diff --git "a/5231.jsonl" "b/5231.jsonl" new file mode 100644--- /dev/null +++ "b/5231.jsonl" @@ -0,0 +1,750 @@ +{"seq_id":"494578883","text":"# coding: utf-8\nfrom sqlalchemy import Column, MetaData, Numeric, String, Table\nfrom geoalchemy2.types import Geometry\n\n\nmetadata = MetaData()\n\n\nt_postcode_germany = Table(\n 'postcode_germany', metadata,\n Column('country_code', String(2)),\n Column('postalcode', String(20)),\n Column('placename', String(180)),\n Column('adminname1', String(100)),\n Column('admincode1', String(20)),\n Column('adminname2', String(100)),\n Column('admincode2', String(20)),\n Column('adminname3', String(100)),\n Column('admincode3', String(20)),\n Column('latitude', Numeric),\n Column('longitude', Numeric),\n Column('geom', Geometry('POINT', 4326), index=True),\n schema='orig_geo_geonames'\n)\n","sub_path":"egoio/db_tables/orig_geo_geonames.py","file_name":"orig_geo_geonames.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"38116732","text":"import csv\nimport matplotlib.pyplot as plt\nfrom VrepHelper import *\nfrom Imitation_Learn import *\nfrom Manipulator_commands import *\nimport vrep\nfrom evaluate_results import Evaluation\n\ndef main():\n\n filename = 'readdatalog.csv'\n # Create objects\n Vp = VrepHelper()\n Il = Imitation_Learn()\n Mc = Manipulator_Commands()\n Eval = Evaluation()\n\n # Initializing the V-REP simulation environment\n Vp.start_vrep(10)\n Vp.initialize_env()\n Vp.simulation_setup()\n Vp.start_simulation()\n\n obtained_joint_angles = []\n\n # Parsing the existing demo file\n playback_cache = Il.parse_demo(filename)\n\n # Playback_cache is a list of lists: read element in the list to extract joint positions\n\n for positions in playback_cache:\n # Set joint value (position[num]) to respective joint handle\n for num,joint_handle in enumerate(Vp.joint_handles):\n Mc.set_joint_angle(joint_handle, positions[num])\n obtained_joint_angles.append(Mc.get_joint_angle(joint_handle)[1])\n\n # print (\"Given angular positions \\n\", positions, \"\\t\", type(positions), \"\\n\" )\n # print (\"Obtained angular positions \\n\", obtained_joint_angles, \"\\t\", type(obtained_joint_angles), \"\\n\")\n\n # Joint domain evaluation\n Eval.main(2, 0,0, positions, obtained_joint_angles)\n obtained_joint_angles = []\n\n # Cartesian domain evaluation - SOME SECTIONS STILL UNFINISHED !!\n # p_tip_obs = Mc.get_link_pos(Vp.top_handle)\n # p_tip_des = somehow from the recorded data\n # Eval.main(1,p_tip_des, p_tip_obs)\n\n # print(\"Setting to joint positions: \", positions)\n\n '''Enables synchronous operation mode'''\n vrep.simxSynchronousTrigger(Vp.clientID)\n\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Simulation_Environment/demo_playback.py","file_name":"demo_playback.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"188378075","text":"import os\nimport zipfile\nfrom collections import namedtuple\nfrom pathlib import Path\nfrom subprocess import call\nfrom typing import NamedTuple\n\nimport docker\nimport pytest\nfrom django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom grandchallenge.challenges.models import Challenge\nfrom tests.factories import UserFactory, ChallengeFactory, MethodFactory\n\n\"\"\" Defines fixtures than can be used across all of the tests \"\"\"\n\n\n@pytest.fixture(scope=\"session\")\ndef django_db_setup(django_db_setup, django_db_blocker):\n \"\"\" Ensure that the main challenge has been created \"\"\"\n with django_db_blocker.unblock():\n # Set the default domain that is used in RequestFactory\n site = Site.objects.get(pk=settings.SITE_ID)\n site.domain = \"testserver\"\n site.save()\n\n # The main project should always exist\n Challenge.objects.create(short_name=settings.MAIN_PROJECT_NAME)\n\n\nclass ChallengeSet(NamedTuple):\n challenge: ChallengeFactory\n creator: UserFactory\n admin: UserFactory\n participant: UserFactory\n participant1: UserFactory\n non_participant: UserFactory\n\n\ndef generate_challenge_set():\n creator = UserFactory()\n challenge = ChallengeFactory(creator=creator)\n admin = UserFactory()\n challenge.add_admin(admin)\n participant = UserFactory()\n challenge.add_participant(participant)\n participant1 = UserFactory()\n challenge.add_participant(participant1)\n non_participant = UserFactory()\n\n try:\n Challenge.objects.get(short_name=settings.MAIN_PROJECT_NAME)\n except ObjectDoesNotExist:\n ChallengeFactory(short_name=settings.MAIN_PROJECT_NAME)\n\n return ChallengeSet(\n challenge=challenge,\n creator=creator,\n admin=admin,\n participant=participant,\n participant1=participant1,\n non_participant=non_participant,\n )\n\n\n@pytest.fixture(name=\"ChallengeSet\")\ndef challenge_set():\n \"\"\" Creates a challenge with creator, 2 participants, and non participant.\n To use this you must mark the test with @pytest.mark.django_db \"\"\"\n return generate_challenge_set()\n\n\n@pytest.fixture(name=\"TwoChallengeSets\")\ndef two_challenge_sets():\n \"\"\" Creates two challenges with combination participants and admins \"\"\"\n TwoChallengeSets = namedtuple(\n \"TwoChallengeSets\",\n [\n \"ChallengeSet1\",\n \"ChallengeSet2\",\n \"admin12\",\n \"participant12\",\n \"admin1participant2\",\n ],\n )\n ChallengeSet1 = generate_challenge_set()\n ChallengeSet2 = generate_challenge_set()\n admin12 = UserFactory()\n ChallengeSet1.challenge.add_admin(admin12)\n ChallengeSet2.challenge.add_admin(admin12)\n participant12 = UserFactory()\n ChallengeSet1.challenge.add_participant(participant12)\n ChallengeSet2.challenge.add_participant(participant12)\n admin1participant2 = UserFactory()\n ChallengeSet1.challenge.add_admin(admin1participant2)\n ChallengeSet2.challenge.add_participant(admin1participant2)\n return TwoChallengeSets(\n ChallengeSet1,\n ChallengeSet2,\n admin12,\n participant12,\n admin1participant2,\n )\n\n\n@pytest.fixture(name=\"EvalChallengeSet\")\ndef challenge_set_with_evaluation(ChallengeSet):\n \"\"\" Creates a challenge with two methods.\n To use this you must mark the test with @pytest.mark.django_db \"\"\"\n EvalChallengeSet = namedtuple(\n \"EvalChallengeSet\", [\"ChallengeSet\", \"method\"]\n )\n ChallengeSet.challenge.use_evaluation = True\n ChallengeSet.challenge.save()\n method = MethodFactory(\n challenge=ChallengeSet.challenge, creator=ChallengeSet.creator\n )\n return EvalChallengeSet(ChallengeSet, method)\n\n\n@pytest.fixture(scope=\"session\")\ndef evaluation_image(tmpdir_factory):\n \"\"\"\n Creates the example evaluation container\n \"\"\"\n client = docker.DockerClient(\n base_url=settings.CONTAINER_EXEC_DOCKER_BASE_URL\n )\n im, _ = client.images.build(\n path=os.path.join(\n os.path.split(__file__)[0],\n \"evaluation_tests\",\n \"resources\",\n \"docker\",\n ),\n tag=\"test_evaluation:latest\",\n )\n assert im.id in [x.id for x in client.images.list()]\n cli = docker.APIClient(base_url=settings.CONTAINER_EXEC_DOCKER_BASE_URL)\n image = cli.get_image(\"test_evaluation:latest\")\n outfile = tmpdir_factory.mktemp(\"docker\").join(\"evaluation-latest.tar\")\n with outfile.open(mode=\"wb\") as f:\n for chunk in image:\n f.write(chunk)\n client.images.remove(image=im.id)\n\n call([\"gzip\", outfile])\n\n assert im.id not in [x.id for x in client.images.list()]\n return f\"{outfile}.gz\", im.id\n\n\n@pytest.fixture(scope=\"session\")\ndef alpine_images(tmpdir_factory):\n client = docker.DockerClient(\n base_url=settings.CONTAINER_EXEC_DOCKER_BASE_URL\n )\n client.images.pull(\"alpine:3.7\")\n client.images.pull(\"alpine:3.8\")\n cli = docker.APIClient(base_url=settings.CONTAINER_EXEC_DOCKER_BASE_URL)\n # get all images and put them in a tar archive\n image = cli.get_image(\"alpine\")\n outfile = tmpdir_factory.mktemp(\"alpine\").join(\"alpine.tar\")\n with outfile.open(\"wb\") as f:\n for chunk in image:\n f.write(chunk)\n return outfile\n\n\n@pytest.fixture(scope=\"session\")\ndef submission_file(tmpdir_factory):\n testfile = tmpdir_factory.mktemp(\"submission\").join(\"submission.zip\")\n z = zipfile.ZipFile(testfile, mode=\"w\")\n\n files = [\n Path(\"evaluation_tests\") / \"resources\" / \"submission.csv\",\n Path(\"cases_tests\") / \"resources\" / \"image10x10x10.mhd\",\n Path(\"cases_tests\") / \"resources\" / \"image10x10x10.zraw\",\n ]\n\n try:\n for file in files:\n if \"cases_tests\" in str(file.parent):\n arcname = Path(\"submission\") / Path(\"images\") / file.name\n else:\n arcname = Path(\"submission\") / file.name\n\n z.write(\n Path(__file__).parent / file,\n compress_type=zipfile.ZIP_DEFLATED,\n arcname=arcname,\n )\n finally:\n z.close()\n\n return testfile\n","sub_path":"app/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"280043395","text":"import os\n\n\ndef run_command(cmd, *args):\n if not cmd:\n return ''\n if args:\n cmd = ' '.join((cmd,) + args)\n try:\n import subprocess\n except ImportError:\n # Python 2.3\n _, rf, ef = os.popen3(cmd)\n else:\n # Python 2.4+\n p = subprocess.Popen(cmd, shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n rf, ef = p.stdout, p.stderr\n errors = ef.read()\n if errors:\n print(\"ERROR: %s\" % errors)\n return rf.read().strip()\n\n\npath = \"hadoop fs -mkdir -p /processed_data/order/\"\ny = \"2015/\"\nm = 1\nd = 1\n\nwhile m < 10:\n d = 1\n while d < 10:\n command = path + y + \"0\" + str(m) + \"/0\" + str(d)\n print(command)\n d += 1\n run_command(command)\n m += 1\n\n","sub_path":"ShenzhouTool/createPath.py","file_name":"createPath.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"317467488","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.5.1\n# kernelspec:\n# display_name: Python 3 (venv)\n# language: python\n# name: python3\n# ---\n\nimport sklearn\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set()\nfrom sklearn.datasets import make_moons, make_circles, make_classification\nimport matplotlib.animation as mpl_animation\nimport matplotlib\nfrom IPython.display import HTML\n\n# # Perceptrón base\n\n# +\nX, y = make_classification(\n n_features=2,\n n_redundant=0,\n n_informative=2,\n random_state=1,\n n_clusters_per_class=1,\n class_sep=0.55,\n)\n\nplt.figure(dpi=150)\nsns.scatterplot(X[:, 0], X[:, 1], hue=y, palette='RdBu')\nplt.show()\n\n# +\nepoch = 1\n\nb = 0.0\nw = np.zeros(2).T\n\nwhile True:\n stable = True\n print(f\"epoch {epoch}\")\n for (Xi, yi) in zip(X, y):\n yhat = max(0.0, np.sign(np.dot(Xi, w) + b))\n\n w += (yi - yhat) * Xi\n b += yi - yhat\n stable &= yi == yhat\n\n if stable:\n break\n\n epoch += 1\n\n\n# +\ndef plot_hiperplane(w, b, X, y):\n plt.figure(dpi=150)\n ax = sns.scatterplot(X[:, 0], X[:, 1], hue=y, palette='RdBu', alpha=1)\n\n G = 500\n\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n\n xx, yy = np.meshgrid(np.linspace(*xlim, G), np.linspace(*ylim, G))\n z = np.dot(np.c_[xx.ravel(), yy.ravel()], w) + b\n z = z.reshape(xx.shape)\n\n ax.contourf(xx, yy, z, alpha=0.1, cmap='RdBu')\n\n x_vals = np.array(xlim)\n y_vals = b - (w[0] / w[1]) * x_vals\n plt.plot(x_vals, y_vals, ':', color='Purple')\n\n plt.ylim(*ylim)\n plt.xlim(*xlim)\n\n plt.show()\n\n\nplot_hiperplane(w, b, X, y)\n# -\n# Que pasa si no es linealmente separable?\n\n# # Learning rate\n\n# +\nX, y = make_classification(\n n_features=2,\n n_redundant=0,\n n_informative=2,\n random_state=1,\n n_clusters_per_class=1,\n class_sep=0.4,\n n_samples=100,\n)\n\nplt.figure(dpi=150)\nsns.scatterplot(X[:, 0], X[:, 1], hue=y, palette='RdBu')\nplt.show()\n\n# +\nfig = plt.figure(dpi=150)\n\n\ndef plot_hiperplane(frame):\n plt.clf()\n\n epoch, b, w = frame\n # print(f\"epoch: {epoch} | bias = {b} weights={w}\")\n\n ax = sns.scatterplot(X[:, 0], X[:, 1], hue=y, palette='RdBu', alpha=1)\n\n G = 500\n\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n\n xx, yy = np.meshgrid(np.linspace(*xlim, G), np.linspace(*ylim, G))\n z = np.dot(np.c_[xx.ravel(), yy.ravel()], w) + b\n z = z.reshape(xx.shape)\n\n ax.contourf(xx, yy, z, alpha=0.2, cmap='RdBu')\n\n x_vals = np.array(xlim)\n y_vals = b - (w[0] / w[1]) * x_vals\n plt.plot(x_vals, y_vals, ':', color='Purple')\n\n plt.ylim(*ylim)\n plt.xlim(*xlim)\n\n return (ax,)\n\n\nmax_epochs = 50\n\nepoch = 1\n\nalpha = 0.1\nb = 0.0\nw = np.zeros(2).T\n\nframes = [(epoch, np.copy(b), np.copy(w))]\n\nwhile True:\n if epoch > max_epochs:\n break\n stable = True\n for (Xi, yi) in zip(X, y):\n yhat = max(0.0, np.sign(np.dot(Xi, w) + b))\n\n w += (yi - yhat) * Xi * alpha\n b += (yi - yhat) * alpha\n stable &= yi == yhat\n\n if stable:\n break\n\n epoch += 1\n frames.append((epoch, np.copy(b), np.copy(w)))\n\n\ndef init_anim():\n last_frame = frames[-1]\n plot_hiperplane(last_frame)\n\n\nanim = mpl_animation.FuncAnimation(\n fig, plot_hiperplane, frames=frames, interval=250, init_func=init_anim\n)\n\nmatplotlib.rc('animation', html='jshtml')\n\nHTML(anim.to_jshtml())\n# -\n\n# # Funciones de activacion\n\n# Que funciones de activacion podemos usar? Cuales son las propiedades que deben cumplir?\n\n# ## Identidad\n#\n# La función identidad está dada por $$f(x) = x$$\n\n# +\nx = np.linspace(-5, 5)\ny = x\n\nplt.figure()\nsns.lineplot(x, y)\nplt.title(\"identidad\")\nplt.ylabel(\"f(x)\")\nplt.xlabel(\"x\")\nplt.show()\n# -\n\n# ## Escalón\n#\n# La función escalón está dada por $$f(x)= \\left\\{ \\begin{array}{lcc}\n# 0 & si & x \\lt 0 \\\\\n# \\\\ 1 & si & x \\geq 0\n# \\end{array}\n# \\right. $$\n\n# +\nx = np.linspace(-5, 5)\ny = np.maximum(0.0, np.sign(x))\n\nplt.figure()\nsns.lineplot(x, y)\nplt.title(\"escalón\")\nplt.ylabel(\"f(x)\")\nplt.xlabel(\"x\")\nplt.show()\n# -\n\n# ## Tangente hiperbólica\n#\n# La función tangente hiperbólica está dada por $$f(x) = \\tanh{x}$$\n\n# +\nx = np.linspace(-5, 5)\ny = np.tanh(x)\n\nplt.figure()\nsns.lineplot(x, y)\nplt.title(\"tanh\")\nplt.ylabel(\"f(x)\")\nplt.xlabel(\"x\")\nplt.show()\n# -\n\n# ## ReLU (Rectified Linear Unit)\n#\n# La función Relu viene dada por $$f(x) = \\max(0, x) = \\left\\{ \\begin{array}{lcc}\n# 0 & si & x \\lt 0 \\\\\n# \\\\ x & si & x \\geq 0\n# \\end{array}\n# \\right. $$\n\n# +\nx = np.linspace(-5, 5)\ny = np.maximum(0, x)\n\nplt.figure()\nsns.lineplot(x, y)\nplt.title(\"ReLU\")\nplt.ylabel(\"f(x)\")\nplt.xlabel(\"x\")\nplt.show()\n# -\n\n# # Perceptrón multicapa\n#\n# Vamos a ver un ejemplo cuado el dataset no es linealmente separable.\n\n# +\nX, y = make_moons(n_samples=1000, random_state=0, noise=0.1)\n\nplt.figure(dpi=150)\nsns.scatterplot(X[:, 0], X[:, 1], hue=y, palette='RdBu')\nplt.show()\n\n# +\nimport keras\n\nin_l = keras.layers.Input(shape=(2,))\nd1 = keras.layers.Dense(128, activation='relu')(in_l)\nout_l = keras.layers.Dense(1, activation='sigmoid')(d1)\n\nm = keras.models.Model(inputs=[in_l], outputs=[out_l])\n\nm.compile('adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nm.fit(X, y, epochs=1000, batch_size=64, verbose=0)\n\n# +\nplt.figure(dpi=150)\n\nxrange = X[:, 0].max() - X[:, 0].min()\nyrange = X[:, 1].max() - X[:, 1].min()\n\nxlim = (X[:, 0].min() - xrange * 0.05, X[:, 0].max() + xrange * 0.05)\nylim = (X[:, 1].min() - yrange * 0.05, X[:, 1].max() + yrange * 0.05)\n\nG = 250\n\nxx, yy = np.meshgrid(np.linspace(*xlim, G), np.linspace(*ylim, G))\nz = m.predict(np.c_[xx.ravel(), yy.ravel()])[:, 0]\nz = z.reshape(xx.shape)\n\nplt.contourf(xx, yy, z, alpha=0.4, cmap='RdBu')\nsns.scatterplot(X[:, 0], X[:, 1], hue=y, palette='RdBu', alpha=1)\n\nplt.show()\n# -\n\n\n# # Funciones de pérdida\n\n\n# # SGD?\n\n\n# # Perceptrón multiclase\n","sub_path":"clases/12_redes_neuronales/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"249247612","text":"# coding: utf-8\nimport datetime\nimport ujson\n\nfrom django.shortcuts import render\n\nfrom mis import models as mismodels\nfrom mis.dao.methods_user import get_user_by\nimport http_msg\n\n# Create your views here.\n\n\ndef list_student_classes(request):\n student = request.GET.get('student', 0)\n sidnumber = request.GET.get('sidnumber', 0)\n course = request.GET.get('course', None)\n if not student:\n student = get_user_by(sidnumber)\n if student or sidnumber:\n entries = mismodels.Classes.objects.filter(flag=0).filter(student=student)\n if course:\n entries = entries.filter(category=course)\n\n entries = entries.order_by('category')\\\n .order_by('start_time')\n return render(request, 'student_timetable.html', dict(entries=entries, current_time=datetime.datetime.now()))\n\n\ndef list_student_speiyou_classes(request):\n uid = request.GET.get('uid', 0)\n claId = request.GET.get('claId', 0)\n entries = http_msg.list_courses(uid, claId)\n entries = sorted(entries, key=lambda x: x.get('classDate'))\n rows = http_msg.attendances_get(uid, claId)\n attendance = []\n if rows.rlt:\n data = ujson.loads(rows.data)\n attendance = sorted(data, key=lambda x: x.get('tbc').get('bcuc_course_date'))\n return render(request, 'student_speiyou_timetable.html', dict(entries=entries, attendance=attendance, uid=uid, claId=claId))\n\n","sub_path":"mis/tal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"423796077","text":"import sys\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QDialog, QFileDialog, QShortcut, QRubberBand, QErrorMessage\nfrom PyQt5.QtGui import QScreen, QPixmap, QKeySequence, QWindow\nfrom qtScreenshooterMainWindow import Ui_qtScreenshooterMainWindow\nfrom qtScreenshooterSaveWindow import Ui_qtScreenshooterSaveWindow\n\n\nclass MainWin(QMainWindow, Ui_qtScreenshooterMainWindow):\n def __init__(self):\n QMainWindow.__init__(self)\n Ui_qtScreenshooterMainWindow.__init__(self)\n self.setupUi(self)\n self.cancelBtn.clicked.connect(self.cancelBtnAction)\n self.startBtn.clicked.connect(self.startBtnAction)\n # Need to keep a reference to QTimer or it will be garbage collected!!!\n # This means that your callback is not called and you will lose\n # 30 minutes troubleshooting it!!!!!!!!!!!!!!\n self.windowTimer = QTimer()\n self.saveWindow = SaveWin()\n\n # Keyboard shortcuts\n # Exit\n self.exitShortcut = QShortcut(QKeySequence(\"Ctrl+Q\"), self)\n self.exitShortcut.activated.connect(self.close)\n\n # Radio Button access\n self.capEntireScreenShortcut = QShortcut(QKeySequence(\"Ctrl+E\"), self)\n self.capEntireScreenShortcut.activated.connect(self.capEntireScrnRadBtn.nextCheckState)\n self.capRgnShortcut = QShortcut(QKeySequence(\"Ctrl+R\"), self)\n self.capRgnShortcut.activated.connect(self.capSelectRgnRadBtn.nextCheckState)\n self.capActiveWinShortcut = QShortcut(QKeySequence(\"Ctrl+W\"), self)\n self.capActiveWinShortcut.activated.connect(self.capActiveWndRadBtn.nextCheckState)\n\n # Start Button\n self.startBtnShortcut = QShortcut(QKeySequence(\"Ctrl+S\"), self)\n self.startBtnShortcut.activated.connect(self.startBtnAction)\n\n self.screenOverlay = QWidget()\n \n def cancelBtnAction(self):\n \"\"\"Close the window when cancel is pressed\"\"\"\n self.close()\n\n def startBtnAction(self):\n if self.capEntireScrnRadBtn.isChecked():\n self.hide()\n # Delay for 500 milliseconds and take screenshot\n self.windowTimer.singleShot(500, self.takeFullScreenshot)\n elif self.capSelectRgnRadBtn.isChecked():\n self.hide()\n self.takeRegionScreenshot()\n print(\"You pressed the button\")\n\n def takeFullScreenshot(self):\n screen = QApplication.primaryScreen()\n screenshot = screen.grabWindow(0)\n self.saveWindow.showMediaPreview(screenshot)\n self.saveWindow.showWin()\n\n def takeRegionScreenshot(self):\n # Access the total size of the desktop\n monitorProperties = QApplication.desktop().screenGeometry()\n\n # Create an exit shortcut for Escape and CTRL+Q\n exitSelectionWindowShortcutQ = QShortcut(QKeySequence(\"Ctrl+Q\"), self.screenOverlay)\n exitSelectionWindowShortcutQ.activated.connect(self.closeTransparentSelectionWindow)\n exitSelectionWindowShortcutEsc = QShortcut(QKeySequence(QKeySequence.Cancel), self.screenOverlay)\n exitSelectionWindowShortcutEsc.activated.connect(self.closeTransparentSelectionWindow)\n\n # Set window opacity, size, focus and display the widget\n self.screenOverlay.setWindowOpacity(0.4)\n self.screenOverlay.setFixedSize(monitorProperties.width(), monitorProperties.height())\n self.screenOverlay.show()\n self.screenOverlay.setFocus()\n\n def closeTransparentSelectionWindow(self):\n self.screenOverlay.close()\n self.show()\n\n\nclass SaveWin(QDialog, Ui_qtScreenshooterSaveWindow):\n def __init__(self):\n QDialog.__init__(self)\n Ui_qtScreenshooterSaveWindow.__init__(self)\n self.setupUi(self)\n self.cancelBtn.clicked.connect(self.saveWinCancelBtn)\n self.acceptBtn.clicked.connect(self.acceptBtnHandler)\n\n def saveWinCancelBtn(self):\n self.close()\n\n def showWin(self):\n self.show()\n\n def showMediaPreview(self, media):\n self.image = QPixmap(media)\n self.mediaPreviewLabel.setPixmap(self.image.scaled(361, 230))\n\n def acceptBtnHandler(self):\n if(self.saveCheckbox.isChecked()):\n fileName = QFileDialog.getSaveFileName(self, \"Save File\", \"\", \"Images (*.jpg, *.png)\")\n if(fileName[0] != \"\"):\n if(fileName[0].endswith(\".jpg\")):\n self.image.save(fileName[0], \"jpg\")\n else:\n self.image.save(fileName[0].join(\".jpg\"), \"jpg\")\n else:\n errorMsg = QErrorMessage.showMessage(\"Please enter a name for the file!\")\n \n\ndef main():\n app = QApplication(sys.argv)\n mainWindow = MainWin()\n mainWindow.show()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"qtScreenshooter.py","file_name":"qtScreenshooter.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"450228535","text":"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nimport scipy.stats as stats\nwarnings.filterwarnings(\"ignore\")\n\n# reading cryptocurrency files\nbtc = pd.read_csv(\"crypto_data/bitcoin_price.csv\")\nether = pd.read_csv(\"crypto_data/ethereum_price.csv\")\nltc = pd.read_csv(\"crypto_data/litecoin_price.csv\")\nmonero = pd.read_csv(\"crypto_data/monero_price.csv\")\nneo = pd.read_csv(\"crypto_data/neo_price.csv\")\nquantum = pd.read_csv(\"crypto_data/qtum_price.csv\")\nripple = pd.read_csv(\"crypto_data/ripple_price.csv\")\n\n\"\"\"\n## 1. Correct Statements\nQ1) Combine all the datasets by merging on the date column and create a dataframe with only the closing prices \nfor all the currencies. Next, create a pair plot with all these columns and choose the correct statements \nfrom the given ones:\n\nI)There is a good trend between litecoin and monero, one increases as the other\n\nII)There is a weak trend between bitcoin and neo.\n\n$\\color{green} {a) I}$\n\nb) II\n\nc)Both I and II\n\nd) None of the above.\n\"\"\"\n\n# putting a suffix with column names so that joins are easy\nbtc.columns = btc.columns.map(lambda x: str(x) + '_btc')\nether.columns = ether.columns.map(lambda x: str(x) + '_et')\nltc.columns = ltc.columns.map(lambda x: str(x) + '_ltc')\nmonero.columns = monero.columns.map(lambda x: str(x) + '_mon')\nneo.columns = neo.columns.map(lambda x: str(x) + '_neo')\nquantum.columns = quantum.columns.map(lambda x: str(x) + '_qt')\nripple.columns = ripple.columns.map(lambda x: str(x) + '_rip')\n\n# merging all the files by date\nm1 = pd.merge(btc, ether, how=\"inner\", left_on=\"Date_btc\", right_on=\"Date_et\")\nm2 = pd.merge(m1, ltc, how=\"inner\", left_on=\"Date_btc\", right_on=\"Date_ltc\")\nm3 = pd.merge(m2, monero, how=\"inner\", left_on=\"Date_btc\", right_on=\"Date_mon\")\nm4 = pd.merge(m3, neo, how=\"inner\", left_on=\"Date_btc\", right_on=\"Date_neo\")\nm5 = pd.merge(m4, quantum, how=\"inner\", left_on=\"Date_btc\", right_on=\"Date_qt\")\ncrypto = pd.merge(m5, ripple, how=\"inner\", left_on=\"Date_btc\", right_on=\"Date_rip\")\n\n# Subsetting only the closing prices column for plotting\ncurr = crypto[[\"Close_btc\", \"Close_et\", 'Close_ltc', \"Close_mon\", \"Close_neo\", \"Close_qt\"]]\ncurr.head()\n\nsns.pairplot(curr)\n\"\"\"\nAs you can see the corelation between Close_ltc and Close_mon is positive and a good trend\n\nAnd Close_btc and Close_neo also show a strong trend positive line\n\"\"\"\nprint(plt.show())\n\n\"\"\"\n## 2. Heatmap\nQ2)As mentioned earlier, Heat Maps are predominantly utilised for analysing Correlation Matrix. \nA high positive correlation (values near 1) means a good positive trend - if one increases, \nthen the other also increases. A negative correlation on the other hand(values near -1) indicate good negative trend\n - if one increases, then the other decreases. \nA value near 0 indicates no correlation, as in one variable doesn’t affect the other. \n\"\"\"\ncor = curr.corr()\nround(cor, 3)\nsns.heatmap(cor, cmap=\"Greens\", annot=True)\n\n\"\"\"\nClose_et and Close_qt have high corr (0.79)\n\nClose_neo and Close_btc have a high corr (0.73)\n\nClose_et and Close_ltc have corr of (0.49)\n\nClose_et and Close_neo have a corr of (0.48)\n\"\"\"\nprint(plt.show())","sub_path":"machine_learning/data_visualization/practice/Practice Questions Session 2- Student Version/crypto_data/crypto_pratice.py","file_name":"crypto_pratice.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"297895679","text":"import os\nimport sys\nimport unittest\n\nfrom gooddataclient.connection import Connection\nfrom gooddataclient.exceptions import DashboardExportError\nfrom gooddataclient.project import Project\nfrom gooddataclient.dashboard import Dashboard\n\n\nfrom tests.credentials import (\n password, username, user_id, test_dashboard_id,\n test_tab_id, test_dashboard_name,\n test_dashboard_project_id\n)\nfrom tests import logger\n\nlogger.set_log_level(debug=('-v' in sys.argv))\n\n\nclass TestDashboard(unittest.TestCase):\n common_filters = [{\"object_id\": 126, \"constraint\": {\"type\": \"floating\", \"from\": -3, \"to\": -1}}]\n wildcard_filter = {\n 'attribute': 'label.page.page_name',\n 'value': 'fake_page'\n }\n output_path = './fake_page.pdf'\n\n def setUp(self):\n self.connection = Connection(username, password)\n self.project = Project(self.connection)\n self.project.load(test_dashboard_project_id)\n self.dashboard = Dashboard(\n self.project, user_id, test_dashboard_id,\n test_tab_id, test_dashboard_name\n )\n\n def test_get_execution_context(self):\n expected_answer = '/gdc/projects/%(project_id)s/users/%(user_id)s/executioncontexts/' % {\n 'project_id': test_dashboard_project_id,\n 'user_id': user_id\n }\n self.dashboard._get_execution_context(self.common_filters)\n self.assertIn(expected_answer, self.dashboard.execution_context_response_uri)\n\n\n common_filters = [{\"wrong_object_id\": 126, \"constraint\": {\"type\": \"floating\", \"from\": -3, \"to\": -1}}]\n self.assertRaises(DashboardExportError, self.dashboard._get_execution_context, common_filters)\n\n def test_get_client_export(self):\n expected_answer = '/gdc/projects/%(project_id)s/clientexport/' % {\n 'project_id': test_dashboard_project_id\n }\n self.dashboard._get_client_export(self.common_filters, self.wildcard_filter)\n self.assertIn(expected_answer, self.dashboard.client_export_response_uri)\n\n def test_poll_for_dashboard_data(self):\n self.dashboard._poll_for_dashboard_data(self.common_filters, self.wildcard_filter)\n self.assertIsNotNone(self.dashboard.pdf_data)\n\n def test_save_as_pdf(self):\n self.dashboard.save_as_pdf(self.common_filters, self.wildcard_filter, self.output_path)\n try:\n os.remove(self.output_path)\n except:\n self.fail('pdf should be found')\n\n def test_saved_dashboard_is_empty(self):\n self.dashboard.save_as_pdf(self.common_filters, self.wildcard_filter, self.output_path)\n self.dashboard.EMPTY_SIZE = 10 # fake pdf size\n self.assertFalse(self.dashboard.saved_dashboard_is_empty(self.output_path))\n self.dashboard.EMPTY_SIZE = 13109 # real pdf size\n self.assertTrue(self.dashboard.saved_dashboard_is_empty(self.output_path))\n os.remove(self.output_path)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_dashboard.py","file_name":"test_dashboard.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"240178328","text":"import sys\nimport copy\nfrom pathlib import Path\nimport numpy as np\nimport scipy.signal\nimport scipy.ndimage\nimport sunpy.io.fits\nimport matplotlib.pyplot as plt\n\n\n# write_path = Path('/Users/harshmathur/Documents/CourseworkRepo/Kodai Visit/20200207')\n# write_path = Path('/Users/harshmathur/Documents/CourseworkRepo/Level-1')\n# write_path = Path('/Volumes/Harsh 9599771751/Kodai Visit Processed/20200208')\n# write_path = Path('/Volumes/Harsh 9599771751/Kodai Visit Processed/20200210')\nwrite_path = Path('/Volumes/Harsh 9599771751/Kodai Visit Processed/20190419')\n\n\ndef generate_master_dark(dark_filename, write_path):\n data, header = sunpy.io.fits.read(dark_filename)[0]\n average_data = np.average(data, axis=0)\n smoothed_data = scipy.signal.medfilt2d(average_data, kernel_size=3)\n smoothed_data[np.where(smoothed_data == 0)] = np.mean(smoothed_data)\n smoothed_data[\n np.where(\n np.abs(\n smoothed_data - smoothed_data.mean()\n ) > 4 * smoothed_data.std()\n )\n ] = smoothed_data.mean()\n save_path = write_path / dark_filename.name\n sunpy.io.fits.write(save_path, smoothed_data, header)\n\n\ndef generate_fringe_flat(fringe_filename, dark_master, write_path):\n data, header = sunpy.io.fits.read(fringe_filename)[0]\n\n fringe_data = np.mean(data, axis=0)\n\n dark_data, _ = sunpy.io.fits.read(dark_master)[0]\n\n fringe_data -= dark_data\n\n no_of_points = 50\n\n plt.imshow(fringe_data, cmap='gray', origin='lower')\n\n plt.title(\n 'Select {} points in bright fringe in top beam across the image'\n .format(\n no_of_points\n )\n )\n\n points = plt.ginput(no_of_points)\n\n intensity = np.zeros(no_of_points)\n\n x_position = np.zeros(no_of_points)\n\n x_bin, y_bin = 2, 2\n\n for i, point in enumerate(points):\n x_beg, x_end = int(point[0] - x_bin), int(point[0] + x_bin)\n y_beg, y_end = int(point[1] - y_bin), int(point[1] + y_bin)\n intensity[i] = np.median(fringe_data[y_beg:y_end, x_beg:x_end])\n x_position[i] = point[0]\n\n intensity = intensity / np.max(intensity)\n\n c = np.polyfit(x_position, intensity, 3, w=intensity)\n\n x = np.arange(fringe_data.shape[1])\n\n intensity_fit = c[0] * x**3 + c[1] * x**2 + c[2] * x + c[3]\n\n intensity_mask = np.ones(fringe_data.shape) * np.array([intensity_fit])\n\n intensity_mask = intensity_mask / intensity_mask.max()\n\n fringe_corrected = fringe_data / intensity_mask\n\n fringe_write_path = write_path / (\n fringe_filename.name.split('.')[-2] + 'FRINGEFLAT.fits'\n )\n\n sunpy.io.fits.write(fringe_write_path, fringe_corrected, header)\n\n\ndef get_y_shift(x_corrected_flat):\n max_shift, extent, up_sampling = 50, 20, 10\n\n no_of_vertical_pixels = x_corrected_flat.shape[0]\n\n vertical_indices = np.arange(no_of_vertical_pixels)\n\n shift_horizontal = np.zeros(no_of_vertical_pixels)\n\n shift_horizontal_fit = np.zeros(no_of_vertical_pixels)\n\n weights = np.ones(no_of_vertical_pixels)\n\n display = copy.deepcopy(x_corrected_flat)\n\n plt.figure('Click on the line profile to trace')\n\n plt.imshow(display, cmap='gray', origin='lower')\n\n point = plt.ginput(1)\n\n plt.clf()\n\n plt.cla()\n\n point_as_a_list = list(map(int, point[0]))\n\n reference_row = int(point_as_a_list[1])\n\n x_beg = int(point_as_a_list[0] - extent / 2)\n\n x_end = int(point_as_a_list[0] + extent / 2)\n\n slit_reference = np.mean(\n display[\n reference_row - 10:reference_row + 10, x_beg:x_end\n ],\n axis=0\n )\n\n normalised_slit = (\n slit_reference - slit_reference.mean()\n ) / slit_reference.std()\n\n for j in vertical_indices:\n this_slit = display[j, x_beg - max_shift:x_end + max_shift]\n\n weights[j] = np.sqrt(this_slit.mean()**2)\n\n this_slit_normalised = (this_slit - this_slit.mean()) / this_slit.std()\n\n correlation = np.correlate(\n scipy.ndimage.zoom(this_slit_normalised, up_sampling),\n scipy.ndimage.zoom(normalised_slit, up_sampling),\n mode='valid'\n )\n\n shift_horizontal[j] = np.argmax(correlation)\n\n shift_horizontal = shift_horizontal / up_sampling - max_shift\n\n valid_x_points = np.argwhere(np.abs(shift_horizontal) < max_shift)\n\n shifts_for_valid_points = shift_horizontal[valid_x_points]\n\n c = np.polyfit(\n valid_x_points.ravel(),\n shifts_for_valid_points.ravel(),\n 2,\n w=np.nan_to_num(weights)[valid_x_points].ravel()\n )\n\n shift_horizontal_fit = c[0] * vertical_indices**2 + \\\n c[1] * vertical_indices + c[2]\n\n shift_horizontal_apply = -shift_horizontal_fit\n\n plt.plot(\n valid_x_points,\n shifts_for_valid_points,\n 'k-',\n shift_horizontal_fit,\n 'k-'\n )\n\n plt.show()\n\n return shift_horizontal_apply\n\n\ndef get_x_shift(dark_corrected_flat):\n max_shift, extent, up_sampling = 50, 20, 10\n\n no_of_horizontal_pixels = dark_corrected_flat.shape[1]\n\n horizontal_indices = np.arange(no_of_horizontal_pixels)\n\n shift_vertical = np.zeros(no_of_horizontal_pixels)\n\n shift_vertical_fit = np.zeros(no_of_horizontal_pixels)\n\n weights = np.ones(no_of_horizontal_pixels)\n\n display = copy.deepcopy(dark_corrected_flat)\n\n plt.figure('Click on the slit profile to trace')\n\n plt.imshow(display, cmap='gray', origin='lower')\n\n point = plt.ginput(1)\n\n plt.clf()\n\n plt.cla()\n\n point_as_a_list = list(map(int, point[0]))\n\n reference_column = int(point_as_a_list[0])\n\n y_beg = int(point_as_a_list[1] - extent / 2)\n\n y_end = int(point_as_a_list[1] + extent / 2)\n\n slit_reference = display[y_beg:y_end, reference_column]\n\n normalised_slit = (\n slit_reference - slit_reference.mean()\n ) / slit_reference.std()\n\n for j in horizontal_indices:\n this_slit = display[y_beg - max_shift:y_end + max_shift, j]\n\n weights[j] = np.sqrt(this_slit.mean()**2)\n\n this_slit_normalised = (this_slit - this_slit.mean()) / this_slit.std()\n\n correlation = np.correlate(\n scipy.ndimage.zoom(this_slit_normalised, up_sampling),\n scipy.ndimage.zoom(normalised_slit, up_sampling),\n mode='valid'\n )\n\n shift_vertical[j] = np.argmax(correlation)\n\n shift_vertical = shift_vertical / up_sampling - max_shift\n\n valid_x_points = np.argwhere(np.abs(shift_vertical) < max_shift)\n\n shifts_for_valid_points = shift_vertical[valid_x_points]\n\n c = np.polyfit(\n valid_x_points.ravel(),\n shifts_for_valid_points.ravel(),\n 1,\n w=np.nan_to_num(weights)[valid_x_points].ravel()\n )\n\n shift_vertical_fit = c[0] * horizontal_indices + c[1]\n\n shift_vertical_apply = -shift_vertical_fit\n\n plt.plot(\n valid_x_points,\n shifts_for_valid_points,\n 'k-',\n shift_vertical_fit,\n 'k-'\n )\n\n plt.show()\n\n return shift_vertical_apply\n\n\ndef apply_x_shift(dark_corrected_flat, shifts):\n result = np.zeros_like(dark_corrected_flat)\n\n for i in np.arange(dark_corrected_flat.shape[1]):\n scipy.ndimage.shift(\n dark_corrected_flat[:, i],\n shifts[i],\n result[:, i],\n mode='nearest'\n )\n\n # plt.imshow(result, cmap='gray', origin='lower')\n\n # plt.show()\n\n return result\n\n\ndef apply_y_shift(dark_corrected_flat, shifts):\n result = np.zeros_like(dark_corrected_flat)\n\n for i in np.arange(dark_corrected_flat.shape[0]):\n scipy.ndimage.shift(\n dark_corrected_flat[i, :],\n shifts[i],\n result[i, :],\n mode='nearest'\n )\n\n # plt.imshow(result, cmap='gray', origin='lower')\n\n # plt.show()\n\n return result\n\n\ndef remove_line_profile(inclination_corrected_flat):\n rows_1 = np.arange(100, 400)\n rows_2 = np.arange(600, 900)\n profile = np.append(\n inclination_corrected_flat[rows_1], inclination_corrected_flat[rows_2],\n axis=0\n )\n line_median = np.median(profile, 0)\n normalised_median = line_median / line_median.max()\n filtered_line = scipy.ndimage.gaussian_filter1d(normalised_median, 2)\n result = np.divide(inclination_corrected_flat, filtered_line)\n\n return result, normalised_median\n\n\ndef get_master_flat_x_y_inclinations_and_line_profile(\n flat_filename, dark_master, fringe_master, write_path\n):\n flat_data, flat_header = sunpy.io.fits.read(flat_filename)[0]\n dark_data, dark_header = sunpy.io.fits.read(dark_master)[0]\n fringe_data, fringe_header = sunpy.io.fits.read(fringe_master)[0]\n\n mean_flat = np.mean(flat_data, axis=0)\n\n dark_corrected_flat = mean_flat - dark_data\n\n shift_vertical_apply = get_x_shift(dark_corrected_flat)\n\n x_corrected_flat = apply_x_shift(dark_corrected_flat, shift_vertical_apply)\n\n x_corrected_fringe = apply_x_shift(fringe_data, shift_vertical_apply)\n\n shift_horizontal_apply = get_y_shift(x_corrected_flat)\n\n y_corrected_flat = apply_y_shift(\n x_corrected_flat, shift_horizontal_apply\n )\n\n y_corrected_fringe = apply_y_shift(\n x_corrected_fringe, shift_horizontal_apply\n )\n\n _, line_median = remove_line_profile(y_corrected_flat / y_corrected_fringe)\n\n flat_master = y_corrected_flat / line_median\n\n flat_master_name = flat_filename.name.split('.')[-2] + 'FLATMASTER.fits'\n\n write_path_flat_master = write_path / flat_master_name\n\n sunpy.io.fits.write(\n write_path_flat_master,\n flat_master,\n flat_header,\n overwrite=True\n )\n\n np.savetxt(write_path / 'x_inclinations.txt', shift_vertical_apply)\n\n np.savetxt(write_path / 'y_inclinations.txt', shift_horizontal_apply)\n\n np.savetxt(write_path / 'flat_profile.txt', line_median)\n\n\n\n\n# if __name__ == '__main__':\n# dark_filename = Path(\n# '/Volumes/Harsh 9599771751/Spectropolarimetric ' +\n# 'Data Kodaikanal/2019/20190413/Darks/083651_DARK.fits'\n# )\n\n# flat_filename = Path(\n# '/Volumes/Harsh 9599771751/Spectropolarimetric ' +\n# 'Data Kodaikanal/2019/20190413/Flats/083523_FLAT.fits'\n# )\n\n\n# fringe_filename = Path(\n# '/Volumes/Harsh 9599771751/Kodai Visit ' +\n# '31 Jan - 12 Feb/20200207/Flats/082259_FLAT.fits'\n# )\n\n# fringe_master = Path(\n# '/Users/harshmathur/Documents/CourseworkRepo' +\n# '/Kodai Visit/20200204/103556_FLATFRINGEFLAT.fits'\n# )\n\n\n# dark_master = Path(\n# '/Volumes/Harsh 9599771751/Kodai Visit ' +\n# 'Processed/20190419/083651_DARK.fits'\n# )\n\n","sub_path":"dark_master_generate.py","file_name":"dark_master_generate.py","file_ext":"py","file_size_in_byte":10548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"228243346","text":"from app import app\nfrom database.models import IbmUser, Config\nfrom database import DB\nimport requests\nimport json\nimport time\n\n@app.route('/original', methods=['POST'])\ndef add_user():\n \n config = Config.query.filter_by().first()\n ibm_user_index = config.ibm_user_index\n\n user = IbmUser.query.filter_by(id=ibm_user_index).first()\n if user is None:\n config.ibm_user_index = config.ibm_user_index + 1\n DB.session.commit()\n return add_user()\n new_id = req_url(user.tel)\n if new_id == 0 or new_id is None:\n config.ibm_user_index = config.ibm_user_index + 1\n DB.session.commit()\n return add_user()\n \n DB.session.commit()\n hidata_reg(new_id, user.tel)\n return {\n \"tel\": user.tel,\n \"index\": config.ibm_user_index\n }\n\n@app.route('/count')\ndef get_count():\n \n config = Config.query.filter_by().first()\n ibm_user_index = config.ibm_user_index\n return {\n \"index\": ibm_user_index,\n \"total\": 280262\n }\n\ndef req_url(m):\n kw = {\n 'm': m\n }\n headers = {\n 'client': 'h5',\n 'version': '2.2.6'\n }\n response = requests.put(\n app.config['RDHY_GEN_URL'], params=kw, headers=headers\n )\n response_datas = json.loads(response.text)\n return response_datas['data']\n\ndef hidata_reg(user_id, tel):\n data = {\n \"common\":{\n \"ip\": \"0.0.0.0\",\n \"port\": \"80\",\n \"appId\": app.config['HIDATA_APPID'],\n \"platformId\": \"2\",\n \"appVersion\": \"V1.0\",\n \"eventLogVersion\": \"V1.0\",\n \"deviceId\": \"\",\n \"deviceType\": \"1\",\n \"deviceModel\": \"PC\",\n \"operateSystem\": \"Mac\",\n \"operateSystemVersion\": \"MacIntel\",\n \"screenSize\": \"2560*1440\",\n \"browserName\": \"chrome/90.0.4430.85\",\n \"browserVersion\": \"90\",\n \"logType\": \"2\"\n },\n \"event\":{\n \"sourceId\":\"10001\",\n \"eventId\": \"3\",\n \"eventTime\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n\t\t\t\"userId\": user_id,\t\t\t # 用户id \n\t\t\t\"account\": tel, \t\t # 注册账号\n\t\t\t\"passwd\": \"\", # 注册密码\n\t\t\t\"name\": \"\", \t\t # 注册姓名\n\t\t\t\"nickname\": \"\", \t # 注册别名\n\t\t\t\"registerType\": \"2\", \t\t\t # 注册方式(1:工号;2:手机;3:微信;4:qq;5:微博6:邮箱)\n\t\t\t\"img\": \"\",\t # 注册头像 \n\t\t\t\"age\": \"0\",\t\t\t\t\t\t # 注册年龄 \n\t\t\t\"sex\": \"0\",\t\t\t\t\t\t # 性别:0:无;1:男;2:女; \n\t\t\t\"birthday\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), # 生日 \n\t\t\t\"trade\": \"123\"\n }\n }\n \n response = requests.post(app.config['HIDATA_URL'], data=json.dumps(data), headers={\n 'Content-Type': 'application/json;charset=UTF-8'\n })\n # response_datas = json.loads(response.text)\n return bool(response.text)\n \n ","sub_path":"routes/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"169866698","text":"from __future__ import absolute_import\n\nimport logging\nfrom datacube_ows.wms_utils import GetLegendGraphicParameters\nimport io\nfrom PIL import Image\nimport numpy as np\nfrom flask import make_response\nimport requests\n\n_LOG = logging.getLogger(__name__)\n\n\ndef legend_graphic(args):\n params = GetLegendGraphicParameters(args)\n img = None\n product = params.product\n style = params.style_name\n legend_config = getattr(product, 'legend', None)\n if legend_config is not None:\n if legend_config.get('url', None):\n img_url = legend_config.get('url')\n r = requests.get(img_url, timeout=1)\n if r.status_code == 200 and r.headers['content-type'] == 'image/png':\n img = make_response(r.content)\n img.mimetype = 'image/png'\n elif legend_config.get('styles', []):\n if style in legend_config.get('styles', []):\n img = create_legends_from_styles([style])\n elif set(legend_config.get('styles', [])) == set(product.style_index.keys()):\n # We want all the styles, and all the styles have legends\n styles = [product.style_index[s] for s in legend_config.get('styles', [])]\n img = create_legends_from_styles(styles)\n return img\n\n\ndef create_legend_for_style(product, style_name):\n if style_name not in product.style_index:\n return None\n style = product.style_index[style_name]\n return create_legends_from_styles([style])\n\n\ndef create_legends_from_styles(styles):\n # Run through all values in style cfg and generate\n imgs = []\n for s in styles:\n url = s.legend_override_with_url()\n if url:\n img = get_image_from_url(url)\n if img:\n imgs.append(img)\n else:\n bytesio = io.BytesIO()\n s.legend(bytesio)\n bytesio.seek(0)\n imgs.append(Image.open(bytesio))\n\n min_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1]\n imgs_comb = np.vstack((np.asarray(i.resize(min_shape)) for i in imgs))\n imgs_comb = Image.fromarray(imgs_comb)\n b = io.BytesIO()\n imgs_comb.save(b, 'png')\n legend = make_response(b.getvalue())\n legend.mimetype = 'image/png'\n b.close()\n return legend\n\n\ndef get_image_from_url(url):\n r = requests.get(url, timeout=1)\n if r.status_code == 200 and r.headers['content-type'] == 'image/png':\n bytesio = io.BytesIO()\n bytesio.write(r.content)\n bytesio.seek(0)\n return Image.open(bytesio)\n return None\n","sub_path":"datacube_ows/legend_generator.py","file_name":"legend_generator.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"242590802","text":"import os\nimport subprocess\n\n\ndef create_folder(directory):\n try:\n if not os.path.isfile(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n else:\n os.remove(directory)\n os.makedirs(directory)\n return True, None\n except OSError as e:\n return False, e.message\n\n\ndef call_ffmpeg(input, number_segment, folder_output):\n sfileName = os.path.splitext(os.path.basename(input))[0]\n folder_content = folder_output + '/piece'\n output = folder_content + '/' + sfileName + '_%4d.mkv'\n Result_Create_Folder, error_create = create_folder(folder_content)\n if Result_Create_Folder == False:\n return {'e': 1, 'Error': 801, 'Description': error_create}\n\n cmnd = ['ffmpeg', '-i', input, '-vcodec', 'copy',\n '-map_metadata', '-1', '-map', '0:v', '-segment_time', number_segment,\n '-f', 'segment', '-y', output]\n p = subprocess.Popen(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n exitCode = p.returncode\n # error occurs at ffprobe\n # print out\n # part = 'parts:' + argv[3] + 's-' + argv[4] + 's'\n # cmnd = [\n # 'mkvmerge', '-o', argv[5], '--split', part, '--no-audio', '--no-global-tags', '--no-buttons', '--no-track-tags',\n # '--no-chapters', '--no-subtitles', argv[2]\n # ]\n # result = utils.run_command(cmnd, False)\n if exitCode == 0:\n result = []\n for entry in os.listdir(folder_content):\n file = folder_content + '/' + entry\n if os.path.isfile(file):\n result.append(file)\n\n else:\n result = {'e': 1, 'Error': 650, 'Description': 'Split File Error'}\n return result\n\n # return info\n\n\ndef probe_video_file(filename):\n try:\n cmnd = ['ffprobe', '-select_streams', 'v', '-show_streams', '-show_format',\n '-loglevel', 'quiet', '-print_format', 'json', filename]\n p = subprocess.Popen(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate()\n # error occurs at ffprobe\n return out\n except OSError as e:\n return None","sub_path":"source/CeleryWorkers/libraries/Split.py","file_name":"Split.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"119789772","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 27 12:49:15 2018\r\n\r\n@author: Frantz\r\n\"\"\"\r\n\r\nclass Solution:\r\n def plusOne(self, digits):\r\n \"\"\"\r\n :type digits: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n flag = 1\r\n for i in range((len(digits)-1), -1,-1):\r\n if digits[i] + flag == 10:\r\n digits[i] = 0\r\n flag = 1\r\n else:\r\n digits[i] += flag\r\n flag = 0\r\n if flag == 1:\r\n digits.insert(0,1)\r\n return digits\r\n\r\n \r\nsol = Solution()\r\ndigits = [9]\r\nresutl = sol.plusOne(digits)\r\nprint(resutl)\r\na = range(10,-1,-1)","sub_path":"LeetCode/66PlusOne.py","file_name":"66PlusOne.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"316474035","text":"import argparse\nimport glob\nimport skimage\nfrom skimage import io \nfrom skimage import transform as tf\nimport os\n\n\nparser = argparse.ArgumentParser(\"Prepares a set of images to be used for trainning/testing with cycle-GAN and similar methods, \")\nparser.add_argument('-r', dest='r', type=float, default=0.8, help='rate of training data')\nparser.add_argument('-A', dest='A', type=str, required=True, help='path where the images from the domain A should be found')\nparser.add_argument('-B', dest='B', type=str, required=True, help='path where the images from the domain B should be found')\nparser.add_argument('-wi', dest='width', type=int, default=256, help='width required for the images to be created')\nparser.add_argument('-he', dest='height', type=int, default=256, help='height required for the images to be created')\nparser.add_argument('-o', dest='out',type=str, default='/tmp/', help='the output folder where to put everything')\n\n\nargs = parser.parse_args() \nprint(args)\n\nlA = glob.glob(args.A+'scene*.png')\nlB = glob.glob(args.B+'*.jpg')\n\n# split the images in the different datasets\nlA_train = lA[0:int(args.r*len(lA))]\nlA_test = lA[int(args.r*len(lA)):]\nlB_train = lB[0:int(args.r*len(lB))]\nlB_test = lB[int(args.r*len(lB)):]\nll = [lA_train, lB_train, lA_test, lB_test]\nletters = ['A','B','A','B']\n\n# create the output folders\noutput_folders = [args.out+'trainA', args.out+'trainB', args.out+'testA', args.out+'testB']\nfor folder in output_folders:\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n# fill the images resizing them if neccessary\nH = args.height\nW = args.width\nfor l, out_folder, letter in zip(ll, output_folders, letters):\n print(\"filling \"+out_folder)\n for i,path in enumerate(l):\n img = io.imread(path)\n Hp, Wp, _ = img.shape\n if Hp > Wp:\n img = np.swapaxes(img, 0, 1)\n Hp, Wp, _ = img.shape\n\n if H >= W:\n h = Hp\n w = W/H*Hp\n else:\n w = Wp\n h = H/W*Wp\n\n # crop\n crop_h = int((Hp-h)/2)\n crop_w = int((Wp-w)/2)\n img2 = skimage.util.crop(img,[(crop_h, crop_h),(crop_w, crop_w),(0,0)])\n\n # resize\n img3 = tf.resize(img2, (H,W), mode = 'reflect')\n\n # view\n # from skimage.viewer import ImageViewer\n # viewer = ImageViewer(img3)\n # viewer.show()\n\n path = out_folder + \"/\" + str(i+1) +\"_\"+letter+'.jpg'\n io.imsave(path, (img3*255).astype('uint8'))\n\n \n\n\n","sub_path":"dataset_creator.py","file_name":"dataset_creator.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"483857436","text":"def rankAndFile(rowsAndColumns):\n result = []\n counts = {}\n for rowOrColumn in rowsAndColumns:\n for n in rowOrColumn.split():\n actualN = int(n)\n if actualN in counts:\n counts[actualN] = counts[actualN] + 1\n #print counts\n else:\n counts[actualN] = 1\n #print counts\n for key in sorted(counts.keys()):\n #print key\n if counts[key] % 2 != 0:\n result.append(str(key))\n return \" \".join(result)\n\n##print rankAndFile([[\"1 2 3\"],\n##[\"2 3 5\"],\n##[\"3 5 6\"],\n##[\"2 3 4\"],\n##[\"1 2 3\"]])\n\nreadFile = open(\"B-large.in\")\nwriteFile = open(\"B-large.out\", \"a\")\n\nnumberOfTestCases = -1\nN = -1\ncaseNumber = 1\nrowsAndColumns = []\nfor line in readFile.readlines():\n if(numberOfTestCases == -1):\n numberOfTestCases = int(line)\n continue\n if N == -1:\n N = int(line) * 2 - 1\n #print N\n continue\n else:\n rowsAndColumns.append(line)\n if N == 1:\n writeFile.write(\"Case #\" + str(caseNumber) + \": \" + rankAndFile(rowsAndColumns) + \"\\n\")\n caseNumber = caseNumber + 1\n\n N = -1\n #print N\n rowsAndColumns = []\n else:\n N = N - 1\n #print N\n \n\nreadFile.close()\nwriteFile.close()\n","sub_path":"solutions_5630113748090880_1/Python/aniketshah/rank_and_file.py","file_name":"rank_and_file.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"460169381","text":"import sys\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom .PlotWindow import Ui_PlotWindow\nfrom .FFTWindowLogic import FFTWindowLogic\nfrom numpy import sin, arange, pi, savetxt\n\nfrom scipy.signal import square, sawtooth, gausspulse\n\nfrom pyqtgraph import LinearRegionItem, SignalProxy\nfrom pyqtgraph import mkPen\n\n\nclass PlotWindowLogic(Ui_PlotWindow):\n def __init__(self, PlotWindowLogic):\n Ui_PlotWindow.__init__(self)\n\n def initBindings(self):\n # self.pushButtonAddSignal.clicked.connect(self.addSignal)\n self.pushButtonViewFFT.clicked.connect(self.showFFT)\n self.pushButtonExportCSV.clicked.connect(self.exportDataset)\n self.FFTwindow = None\n\n def PlotSin(self, amp, freq, phase):\n\n self.Fs = 44100\n self.x = arange(0, 1, 1/self.Fs)\n self.y = (amp/10)*sin(2 * pi * freq * self.x + (phase*pi))\n self.plot = self.PlotView.plotItem\n self.vBox = self.plot.vb\n self.vBox.setLimits(xMin=-0, yMin=-2, xMax=1.3, yMax=2)\n self.vBox.setBackgroundColor(\"w\")\n # self.vBox.setBackgroundColor(\"white\")\n self.plot.addLegend()\n self.plot.showGrid(x=True, y=True)\n self.plot.plot(self.x, self.y, pen=mkPen('b', width=1),\n name=str(amp)+\"Sin(2π\"+str(freq)+\"+\"+str(phase))\n proxy = SignalProxy(self.plot.scene().sigMouseMoved, rateLimit=60, slot=self.MouseMoved)\n\n def MouseMoved(self):\n pass\n\n\n def plotSawtooth(self, amp, freq):\n self.Fs: int = 44100\n self.x = arange(0, 1, 1/self.Fs)\n self.y = (amp/10)*sawtooth(2*pi*freq*self.x)\n self.plot = self.PlotView.plotItem\n self.vBox = self.plot.vb\n self.vBox.setLimits(xMin=-0, yMin=-2, xMax=1.3, yMax=2)\n self.vBox.setBackgroundColor(\"w\")\n\n self.plot.addLegend()\n self.plot.showGrid(x=True, y=True)\n self.plot.plot(self.x, self.y, pen=mkPen('b', width=1),\n name=str(amp)+\"Sawtooth(2π\"+str(freq))\n\n def plotSquare(self, amp, freq):\n self.Fs: int = 48000\n self.x = arange(0, 1, 1/self.Fs)\n self.y = (amp/10)*square(2*pi*freq*self.x)\n self.plot = self.PlotView.plotItem\n self.vBox = self.plot.vb\n self.vBox.setLimits(xMin=-0, yMin=-2, xMax=1.3, yMax=2)\n self.vBox.setBackgroundColor(\"w\")\n\n self.plot.addLegend()\n self.plot.showGrid(x=True, y=True)\n self.plot.plot(self.x, self.y, pen=mkPen('b', width=1),\n name=str(amp)+\"Sawtooth(2π\"+str(freq))\n\n def plotGpulse(self, amp, freq):\n self.Fs: int = 44100\n self.x = arange(0, 1, 1/self.Fs)\n self.y = (amp/10)*gausspulse((self.x,freq))\n self.plot = self.PlotView.plotItem\n self.vBox = self.plot.vb\n self.vBox.setLimits(xMin=-0, yMin=-2, xMax=1.3, yMax=2)\n self.vBox.setBackgroundColor(\"w\")\n\n self.plot.addLegend()\n self.plot.showGrid(x=True, y=True)\n self.plot.plot(self.x, self.y, pen=mkPen('b', width=1),\n name=str(amp)+\"Gaussian Pulse(2π\"+str(freq))\n\n # def addSignal(self):\n # # abre un nuevo dialogo\n # self.AddSignalWindow = QtWidgets.QDialog()\n # self.ui = Ui_AddSignalDialog()\n # self.ui.setupUi(self.AddSignalWindow)\n # self.AddSignalWindow.show()\n # self.AddSignalWindow.activateWindow()\n # self.AddSignalWindow.raise_\n # self.AddSignalWindow.accepted.connect(self.Addplot)\n\n # def Addplot(self):\n # amp = self.ui.horizontalSliderAmplitude.value()\n # freq = self.ui.horizontalSliderFrequency.value()\n # phase = self.ui.horizontalSliderPhase.value()\n # func = 'Sin'\n # self.y = self.y+(amp/10)*sin(2*pi*freq*self.x+phase*pi)\n # if(self.ui.radioButtonCos.isChecked() == True):\n # self.y = self.y+(amp/10)*cos(2*pi*freq*self.x+phase*pi)\n # func = 'Cos'\n\n # self.plot.clearPlots()\n # self.plot.plot(self.x, self.y, pen='r', name=str(\n # amp/10)+' ('+func+' 2π '+str(freq)+'*t)')\n\n def showFFT(self):\n self.FFTwindow = QtWidgets.QWidget()\n self.ui = FFTWindowLogic(self, self.y, self.Fs)\n self.ui.setupUi(self.FFTwindow)\n self.ui.PlotFFT()\n self.FFTwindow.activateWindow()\n self.FFTwindow.show()\n self.FFTwindow.raise_()\n\n\n def exportDataset(self):\n savetxt('file.csv',[self.x,self.y],delimiter=\",\")\n","sub_path":"src/main/python/utils/PlotWindowLogic.py","file_name":"PlotWindowLogic.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"621077434","text":"#! /usr/bin/env python3\nimport numpy\n\nclass TicTacToe:\n\n \"\"\"\n Tic Tac Toe\n\n Initial Grid Configuration:\n -1 -1 -1\n -1 -1 -1\n -1 -1 -1\n\n Winnning Grid Configurations:\n X X X\n O O X\n O O -1\n\n ....\n\n X O O\n O X X\n O -1 X\n \"\"\"\n\n def __init__(self):\n self.DIMENSIONS = 3\n self.GRID = numpy.empty((self.DIMENSIONS, self.DIMENSIONS,))\n self.GRID[:] = 0\n\n def isDone(self):\n return self.isWinningGrid(self.GRID) or self.isWinningGrid(self.GRID.transpose()) or numpy.where(self.GRID == 0)[0].size == 0\n\n def isWinningGrid(self, grid):\n for anchor in range(self.DIMENSIONS):\n if self.isWinningConfiguration(grid[anchor]):\n return True\n\n return self.isWinningConfiguration(grid.diagonal()) or self.isWinningConfiguration(numpy.fliplr(grid).diagonal())\n\n def isWinningConfiguration(self, configuration):\n if numpy.absolute(numpy.sum(configuration)) == self.DIMENSIONS:\n return True\n\n return False\n\n def getBestScore(self, grid, maximizingPlayer):\n bestValue = -10 if maximizingPlayer else 10\n for rowIdx in range(self.DIMENSIONS):\n value = sum(grid[rowIdx])\n bestValue = max(bestValue, value) if maximizingPlayer else min(bestValue, value)\n\n return bestValue\n\n def play(self):\n self.GRID[1][1] = -1\n\n value, position = self.minimax(self.GRID, True)\n self.GRID[position[0]][position[1]] = 1\n\n value, position = self.minimax(self.GRID, False)\n self.GRID[position[0]][position[1]] = -1\n\n value, position = self.minimax(self.GRID, True)\n self.GRID[position[0]][position[1]] = 1\n\n value, position = self.minimax(self.GRID, False)\n self.GRID[position[0]][position[1]] = -1\n\n print(self.GRID)\n\n def minimax(self, currentGrid, maximizingPlayer):\n newGrid = numpy.copy(currentGrid)\n bestValue = -10 if maximizingPlayer else 10\n bestChoice = ()\n\n for rowIdx in range(self.DIMENSIONS):\n for colIdx in range(self.DIMENSIONS):\n if newGrid[rowIdx][colIdx] == 0:\n newGrid[rowIdx][colIdx] = 1 if maximizingPlayer else -1\n currentValue = bestValue\n value = max(self.getBestScore(newGrid, maximizingPlayer), self.getBestScore(newGrid.transpose(), maximizingPlayer)) if maximizingPlayer else min(self.getBestScore(newGrid, maximizingPlayer), self.getBestScore(newGrid.transpose(), maximizingPlayer))\n bestValue = max(bestValue, value) if maximizingPlayer else min(bestValue, value)\n\n if bestValue != currentValue:\n bestChoice = (rowIdx, colIdx)\n\n newGrid[rowIdx][colIdx] = 0\n\n return bestValue, bestChoice\n\n\ntictactoe = TicTacToe()\ntictactoe.play()\n","sub_path":"samples/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"284861874","text":"from chrome_driver import create_driver, quit_driver\nfrom bs4 import BeautifulSoup\nimport re\nimport regex\nimport json\nfrom database import Database\n\n\ndef scrap_undergrad():\n url = \"https://www.concordia.ca/academics/undergraduate/calendar/current/courses-quick-links.html\"\n\n driver = create_driver()\n driver.get(url)\n\n #Selenium hands the page source to Beautiful Soup\n soup=BeautifulSoup(driver.page_source, 'lxml')\n all_faculties = soup.findAll(\"span\", {\"class\": \"large-text\"})\n\n info = {}\n list_of_faculties = []\n\n for faculty in all_faculties:\n faculty_link = faculty.findAll(\"a\")\n if(len(faculty_link) >0):\n if(len(faculty_link)>1):\n number_of_faculties_in_tag = len(faculty_link)\n count = 0\n array_faculty_names = re.split('\\s+', faculty.text)\n while count0 and paragraph.startswith(pattern1[0])) or (len(pattern2)>0 and paragraph.startswith(pattern2[0]))):\n return True\n else:\n return False\n\ndef get_course_number_and_descrption(array_undergrad_info,paragraph):\n array = re.split('\\s+', paragraph)\n count = 0\n course_code = \"\"\n for element in array:\n if count<2:\n course_code = course_code+\" \"+element\n count=count+1\n course_code = course_code[1:]\n try:\n title_and_description_array = re.split(\"\\xa0\", paragraph)\n title_and_description = title_and_description_array[len(title_and_description_array)-1].replace(\"\\xa0\",\"\")[0:]\n except IndexError:\n title_and_description_index = paragraph.index(\"\\xa0\")\n title_and_description_temp = paragraph[title_and_description_index:]\n title_and_description = re.split(course_code, title_and_description_temp)[0].replace(\"\\xa0\",\"\")[0:]\n\n title_and_description_array = re.split(\"\\n\", title_and_description)\n title = title_and_description_array[0]\n credit = \"In description\"\n try:\n description = title_and_description_array[1]\n except IndexError:\n description = \"No description\"\n try:\n credits_index = title.index(\"credit\")-2\n credit = title[credits_index]\n title = title[:credits_index-2]\n info = {\n \"course\": course_code,\n \"credits\": credit,\n \"title\": title,\n \"description\": description\n }\n array_undergrad_info.append(info)\n except ValueError:\n info = {\n \"course\": course_code,\n \"credits\": credit,\n \"title\": title,\n \"description\": description\n }\n array_undergrad_info.append(info)\n return array_undergrad_info\n\ndef save_in_json(array):\n with open('./undergraduate-info.json', 'w') as outfile:\n json.dump(array, outfile)\n\ndef save_in_db(array_of_courses):\n db = Database(\"courses.sqlite\")\n db.drop('courses')\n db.add_table(\"courses\", course=\"text\", credits=\"text\", title=\"text\", description=\"text\", graduate_level=\"text\")\n\n for course_object in array_of_courses:\n course = course_object.get('course')\n credits = course_object.get('credits')\n title = course_object.get('title')\n description = course_object.get('description')\n\n db.insert(\"courses\",course,credits,title,description,\"undergraduate\")\n\n db.close_connection()\n\n\n\nif __name__ == \"__main__\":\n list_of_faculties, info = scrap_undergrad()\n # print(\"faculties: \\n\")\n array_undergrad_info = []\n for faculty in info:\n # print(faculty)\n href =info[faculty].get('href')\n link = \"https://www.concordia.ca{}\".format(href,sep='')\n # print(link)\n array_undergrad_info = scrap_faculty_courses(link,array_undergrad_info)\n # array_undergrad_info = scrap_faculty_courses(\"https://www.concordia.ca/academics/undergraduate/calendar/current/sec81/81-100.html#jazz\",array_undergrad_info)\n save_in_json(array_undergrad_info)\n save_in_db(array_undergrad_info)","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":8703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"86681813","text":"import argparse\n\nimport torch\nimport torchvision\nfrom PIL import Image\n\nimport utils\nfrom model import Darknet\n\nto_image = torchvision.transforms.ToTensor()\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"YOLOv4 inference\")\n\n parser.add_argument(\"--img-file\", metavar=\"origin-img\", default=\"./image/demo.png\",\n help=\"the image to predict (default: %(default)s)\")\n\n parser.add_argument(\"--weight\", required=True, metavar=\"/path/to/yolov4.weights\", help=\"the path of weight file\")\n\n parser.add_argument(\"--save-img\", metavar=\"predicted-img\", help=\"the path to save predicted image\")\n\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n img: Image.Image = Image.open(args.img_file)\n img = img.resize((608, 608))\n\n # C*H*W\n img_data = to_image(img)\n\n net = Darknet(img_data.size(0))\n net.load_weights(args.weight)\n net.eval()\n\n with torch.no_grad():\n boxes, confs = net(img_data.unsqueeze(0))\n\n idxes_pred, boxes_pred, probs_pred = utils.post_processing(boxes, confs, 0.4, 0.6)\n\n utils.plot_box(boxes_pred, args.img_file, args.save_img)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"276632628","text":"import sys\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nimport engine\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nDEBUG = False\nimport networkx as nx\n\n\nclass MplCanvas(FigureCanvasQTAgg):\n\n def __init__(self, parent=None, fig=None):\n if not fig:\n fig = Figure(figsize=(4, 5), dpi=100)\n self.axes = fig.add_subplot(111)\n super(MplCanvas, self).__init__(fig)\n\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n self.gp = engine.GraphPlanVis()\n\n self.fig_width = 5\n self.fig_height = 4\n self.mpl = MplCanvas(parent=self, fig=Figure())\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n self.setWindowTitle(\"GraphPlan Visualization by Almog Dubin\")\n\n if DEBUG:\n # self.domain_file_path = \"examples/gripper/domain.pddl\"\n # self.problem_file_path = \"examples/gripper/p01.pddl\"\n self.domain_file_path = \"examples/blocksworld/domain.pddl\"\n self.problem_file_path = \"examples/blocksworld/p01.pddl\"\n else:\n self.domain_file_path = None\n self.problem_file_path = None\n\n self._construct_top_menu()\n self._construct_main_menu()\n cid = self.mpl.figure.canvas.mpl_connect('button_press_event', self._onclick)\n\n self.show()\n if DEBUG:\n self._try_start_graph_plan()\n self.action_expand_level()\n # self.gp.draw_no_op = False\n\n self.mutex_mode = False\n\n def _onclick(self, event):\n if not self.mutex_mode:\n return\n\n clicked = min(self.gp.pos.items(),\n key=lambda x: pow(x[1][0]-event.xdata, 2) + pow(x[1][1]-event.ydata, 2))\n clicked = clicked[0]\n\n mutexes = self.gp.get_nx_node_mutexes(self.mpl.axes, clicked)\n\n self._after_mutex_press(clicked, mutexes)\n\n def _after_mutex_press(self, clicked, mutexes):\n self._refresh_graph_view()\n\n nx.draw_networkx_nodes(self.gp.nx_graph, self.gp.pos, [clicked],\n node_shape=\"s\", node_color=\"yellow\", ax=self.mpl.axes)\n\n nx.draw_networkx_nodes(self.gp.nx_graph, self.gp.pos, mutexes,\n node_shape=\"s\", node_color=\"orange\", ax=self.mpl.axes)\n self._refresh_figure()\n\n def _construct_main_menu(self, fig=None):\n\n self.mpl = MplCanvas(self, fig)\n\n # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second.\n toolbar = NavigationToolbar(self.mpl, self)\n\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(toolbar)\n layout.addWidget(self.mpl)\n\n # Create a placeholder widget to hold our toolbar and canvas.\n widget = QtWidgets.QWidget()\n widget.setLayout(layout)\n self.setCentralWidget(widget)\n\n def _construct_top_menu(self):\n # File menu\n self.file_menu = QtWidgets.QMenu('&File', self)\n self.file_menu.addAction('&Load Domain', lambda: self.file_load_pddl(\"domain\"))\n self.file_menu.addAction('&Load problem', lambda: self.file_load_pddl(\"problem\"))\n\n self.file_menu.addAction('&Quit', self.file_quit,\n QtCore.Qt.CTRL + QtCore.Qt.Key_Q)\n self.menuBar().addMenu(self.file_menu)\n\n # Action menu\n self.menuBar().addSeparator()\n self.action_menu = QtWidgets.QMenu('&Action', self)\n self.action_menu.addAction('&Expand level', self.action_expand_level,\n QtCore.Qt.CTRL + QtCore.Qt.Key_E)\n self.action_menu.addAction('&Solve', self.action_solve,\n QtCore.Qt.CTRL + QtCore.Qt.Key_S)\n self.action_menu.addAction('&Expand and solve', self.action_expand_and_solve,\n QtCore.Qt.CTRL + QtCore.Qt.Key_X)\n self.action_menu.addAction('&Reset', self.action_reset_graph,\n QtCore.Qt.CTRL + QtCore.Qt.Key_R)\n self.action_menu.addAction('&Change stopping condition', self.action_change_max_depth)\n\n self.action_menu.setDisabled(True)\n\n self.menuBar().addMenu(self.action_menu)\n\n # View menu\n self.menuBar().addSeparator()\n self.view_menu = QtWidgets.QMenu('&View', self)\n self.view_menu.addAction('&Show mutexes', self.view_mutexes,\n QtCore.Qt.CTRL + QtCore.Qt.Key_M)\n self.view_menu.addAction('&Show no-op', self.show_no_ops,\n QtCore.Qt.CTRL + QtCore.Qt.Key_P)\n self.menuBar().addMenu(self.view_menu)\n self.view_menu.setDisabled(True)\n\n # Help menu\n self.menuBar().addSeparator()\n self.help_menu = QtWidgets.QMenu('&Help', self)\n self.menuBar().addMenu(self.help_menu)\n\n self.help_menu.addAction('&About', self.about)\n\n def closeEvent(self, ce):\n self.file_quit()\n\n def file_quit(self):\n self.close()\n\n def file_load_pddl(self, file_type):\n if file_type == \"domain\":\n self.domain_file_path = self._load_file()\n else:\n self.problem_file_path = self._load_file()\n\n if self.problem_file_path and self.domain_file_path:\n self._try_start_graph_plan()\n\n def about(self):\n # TODO this\n QtWidgets.QMessageBox.about(self, \"About\", \"e\")\n\n def action_expand_level(self):\n if not self.gp.is_ready:\n return\n self.gp.expand_level()\n self._refresh_graph_view()\n\n def action_solve(self):\n if not self.gp.is_ready:\n return\n solution = self.gp.solve(with_expanding=False)\n solution_string = self.gp.format_solution(solution)\n ms = QtWidgets.QMessageBox()\n ms.setText(solution_string)\n ms.exec_()\n\n def action_expand_and_solve(self):\n if not self.gp.is_ready:\n return\n solution = self.gp.solve()\n self.gp._create_nx_graph()\n self._set_empty_plot()\n solution_nodes = self.gp.get_solution_nx_nodes(solution)\n\n self.gp.draw_graph(self.mpl.axes, alpha=0.2)\n self.gp.draw_graph(self.mpl.axes, draw_list=solution_nodes, keep_old_layout=True)\n self._refresh_figure()\n # solution_string = self.gp.format_solution(solution)\n # ms = QtWidgets.QMessageBox()\n # ms.setText(solution_string)\n # ms.exec_()\n\n def action_reset_graph(self):\n\n self.gp = engine.GraphPlanVis()\n self._set_empty_plot()\n self._try_start_graph_plan()\n\n def action_change_max_depth(self):\n i, okPressed = QtWidgets.QInputDialog.getInt(self, \"Please set the maximal number of equal level\\n\" +\n \"before the algorithm fails\", \"Maximal equal levels:\",\n 2, 2, 100, 1)\n if okPressed:\n self.gp.max_depth_checking = i\n def view_mutexes(self):\n if not self.gp.is_ready:\n return\n # self.gp.draw_graph_mutexes(self.mpl.axes)\n self.mutex_mode = not self.mutex_mode\n\n def show_no_ops(self):\n self.gp.draw_no_op = not self.gp.draw_no_op\n self._refresh_graph_view()\n\n def _try_start_graph_plan(self):\n try:\n self.gp.create_problem(self.domain_file_path, self.problem_file_path)\n self.action_menu.setDisabled(False)\n self.view_menu.setDisabled(False)\n\n except Exception as e:\n self.gp = engine.GraphPlanVis()\n error_dialog = QtWidgets.QErrorMessage()\n error_dialog.showMessage(str(e))\n\n def _load_file(self):\n options = QtWidgets.QFileDialog.Options()\n options |= QtWidgets.QFileDialog.DontUseNativeDialog\n file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, \"QFileDialog.getOpenFileName()\",\n \"examples/block-world\", \"pddl plan files (*.pddl)\", options=options)\n if not file_path.endswith(\".pddl\"):\n error_dialog = QtWidgets.QErrorMessage()\n error_dialog.showMessage('file is not a .pddl format!')\n return file_path\n\n def _set_empty_plot(self):\n self.mpl.axes.cla()\n self._refresh_figure()\n\n def _refresh_figure(self):\n\n self.mpl.figure.canvas.draw()\n self.mpl.figure.canvas.flush_events()\n\n def _refresh_graph_view(self):\n self.mpl.axes.cla()\n self.gp.visualize(self.mpl.axes, alpha=1)\n self._refresh_figure()\n\n\napp = QtWidgets.QApplication(sys.argv)\nw = MainWindow()\napp.exec_()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"638768033","text":" #!/usr/bin/env python\n#\n# -*- coding: utf-8 -*-\n#\n# default.py\n#\n# Copyright 2013 Jelle Smet \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 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n#\n#\n\nfrom wishbone.tools import QLogging\nfrom wishbone.tools import WishboneQueue\nfrom wishbone.tools import LoopContextSwitcher\nfrom wishbone.errors import QueueMissing, QueueOccupied, SetupError, QueueFull, QueueLocked\nfrom gevent import spawn, sleep, signal, joinall, kill, Greenlet\nfrom gevent.event import Event\nfrom uuid import uuid4\nfrom time import time\nfrom os.path import basename\nfrom gevent import socket\n\nclass Default():\n '''The default Wishbone router.\n\n A router is responsible to:\n\n - Forward the events from one queue to the other.\n - Forward the logs from all modules to the logging module\n - Forward the metrics from all modules to the metrics module.\n\n SIGINT is intercepted and initiates a proper shutdown sequence.\n\n Parameters:\n\n - interval(int): The interval metrics are polled from each module\n\n - context_switch(int): When looping over blocking code a context switch\n is done every X iterations.\n Default: 100\n\n - rescue(bool): Whether to extract any events stuck in one of\n the queues and write that to a cache file. Next\n startup the events are read from the cache and\n inserted into the same queue again.\n\n - uuid(bool): If True, adds a uuid4 value in the header of each\n event if not present when forwarded from one queue\n to the other. (default False)\n\n - throttle(bool): If True, scans every second for modules which\n overflow child modules with messages and thus have\n to be throttled.\n default: False\n\n - throttle_threshold(int): When is True, start to throttle\n start to throttle when a module has more\n than messages.\n default: 5000\n\n '''\n\n def __init__(self, interval=1, context_switch=100, rescue=False, uuid=False, throttle=True, throttle_threshold=15000):\n self.interval=interval\n self.context_switch=context_switch\n self.rescue=rescue\n\n signal(2, self.__signal_handler)\n self.logging=QLogging(\"Router\")\n self.logs=WishboneQueue()\n self.metrics=WishboneQueue()\n\n if uuid == True:\n self.__UUID = self.__doUUID\n else:\n self.__UUID = self.__noUUID\n\n self.__throttle=throttle\n self.__throttle_threshold=throttle_threshold\n\n # Forward router's logs to logging queue.\n #########################################\n spawn (self.__forwardEvents, self.logging.logs, self.logs)\n\n self.__modules = {}\n self.__logmodule = None\n self.__metricmodule = None\n self.__map=[]\n\n self.__block=Event()\n self.__block.clear()\n self.__exit=Event()\n self.__exit.clear()\n\n self.__runConsumers=Event()\n self.__runConsumers.clear()\n\n self.__runLogs=Event()\n self.__runLogs.clear()\n\n self.hostname=socket.gethostname()\n\n self.loop_context_switcher=LoopContextSwitcher(self.loop)\n\n def getContextSwitcher(self, cycles):\n return self.loop_context_switcher.get(cycles)\n\n def block(self):\n ''' A convenience function which blocks untill all registered\n modules are in a stopped state.\n\n Becomes unblocked when stop() is called and finisehd.\n '''\n\n self.__exit.wait()\n\n def connect(self, producer, consumer):\n '''Connects a producing queue to a consuming queue.\n\n A separate greenthread consumes the events from the consumer queue and\n submits these to the producer queue. When a non existing queue is\n defined, it is autocreated.\n\n The syntax of queue names is:\n\n module_instance_name.queuename\n\n Parameters:\n\n - producer(str): The name of the producing module queue.\n\n - consumer(str): The name of the consuming module queue.\n\n '''\n\n try:\n (producer_module, producer_queue) = producer.split(\".\")\n except ValueError:\n raise Exception(\"A queue name should have format 'module.queue'. Got '%s' instead\"%(producer))\n\n try:\n (consumer_module, consumer_queue) = consumer.split(\".\")\n except ValueError:\n raise Exception(\"A queue name should have format 'module.queue'. Got '%s' instead\"%(consumer))\n\n try:\n self.__modules[producer_module]\n except:\n raise Exception (\"There is no module registered with name %s\"%(producer_module))\n\n try:\n self.__modules[consumer_module]\n except:\n raise Exception (\"There is no module registered with name %s\"%(consumer_module))\n\n self.__modules[producer_module][\"children\"].append(consumer_module)\n self.__modules[consumer_module][\"parents\"].append(producer_module)\n\n if not self.__modules.has_key(producer_module):\n raise Exception(\"There is no Wishbone module registered with name '%s'\"%(producer_module))\n if not self.__modules.has_key(consumer_module):\n raise Exception(\"There is no Wishbone module registered with name '%s'\"%(consumer_module))\n\n while True:\n try:\n producer_queue_instance = getattr(self.__modules[producer_module][\"instance\"].queuepool, producer_queue)\n break\n except:\n self.logging.info(\"Queue %s does not exist in module %s. Autocreate queue.\"%(producer_queue, producer_module))\n self.__modules[producer_module][\"instance\"].createQueue(producer_queue)\n\n while True:\n try:\n consumer_queue_instance = getattr(self.__modules[consumer_module][\"instance\"].queuepool, consumer_queue)\n break\n except :\n self.logging.info(\"Queue %s does not exist in module %s. Autocreate queue.\"%(consumer_queue, consumer_module))\n self.__modules[consumer_module][\"instance\"].createQueue(consumer_queue)\n\n if self.__modules[consumer_module][\"connections\"].has_key(consumer_queue):\n raise QueueOccupied(\"Queue %s of module %s is already connected.\"%(consumer_queue, consumer_module))\n\n if self.__modules[producer_module][\"connections\"].has_key(producer_queue):\n raise QueueOccupied(\"Queue %s of module %s is already connected.\"%(producer_queue, producer_module))\n\n self.__modules[consumer_module][\"connections\"]={}\n\n self.__modules[consumer_module][\"connections\"][consumer_queue]=producer_queue\n self.__modules[producer_module][\"connections\"][producer_queue]=consumer_queue\n\n #self.__modules[producer_module][\"instance\"].queuepool.outbox=self.__modules[consumer_module][\"instance\"].queuepool.inbox\n setattr(self.__modules[producer_module][\"instance\"].queuepool, producer_queue, consumer_queue_instance)\n\n\n def getChildren(self, instance):\n children=[]\n\n def getChild(instance, children):\n if len(self.__modules[instance][\"children\"]) > 0:\n for child in self.__modules[instance][\"children\"]:\n if child not in children:\n children.append(child)\n getChild(child, children)\n\n\n getChild(instance, children)\n return children\n\n def getParents(self, instance):\n parents=[]\n\n def getParent(instance, parents):\n if len(self.__modules[instance][\"parents\"]) > 0:\n for parent in self.__modules[instance][\"parents\"]:\n if parent not in parents:\n parents.append(parent)\n getParent(parent, parents)\n\n getParent(instance, parents)\n return parents\n\n def doRescue(self):\n '''Runs over each queue to extract any left behind messages.\n '''\n\n for module in reversed(self.__modules):\n for queue in module.queuepool.messagesLeft():\n for blah in module.queuepool.dump(queue):\n print (blah)\n\n def loop(self):\n\n '''Convenience funtion which returns a bool indicating the router is in running or stop state.'''\n\n return not self.__runConsumers.isSet()\n\n def register(self, module, name, *args, **kwargs):\n '''Registers a Wishbone actor into the router.\n\n Parameters:\n\n module(module) A wishbone module.\n name(string) The name to assign to the module insance.\n args(list) Positional arguments to pass to the module.\n kwargs(dict) Named arguments to pass to the module.\n '''\n\n self.__modules[name] = {\"instance\":None, \"fwd_logs\":None, \"fwd_metrics\":None, \"connections\":{}, \"children\":[], \"parents\":[]}\n self.__modules[name][\"instance\"]=module(name, *args, **kwargs)\n self.__modules[name][\"instance\"].getContextSwitcher=self.getContextSwitcher\n\n self.__modules[name][\"fwd_logs\"] = spawn (self.__forwardLogs, self.__modules[name][\"instance\"].logging.logs, self.logs)\n self.__modules[name][\"fwd_metrics\"] = spawn (self.__gatherMetrics, self.__modules[name][\"instance\"])\n\n def registerLogModule(self, module, name, *args, **kwargs):\n '''Registers and connects the module to the router's log queue.\n\n If this method is not called (no module connected to it) the queue is\n automatically connected to a Null module.\n\n Parameters:\n\n module(module) A wishbone module.\n name(string) The name to assign to the module insance.\n args(list) Positional arguments to pass to the module.\n kwargs(dict) Named arguments to pass to the module.\n '''\n\n self.__logmodule = name\n\n self.__modules[name] = {\"instance\":None, \"fwd_logs\":None, \"fwd_metrics\":None, \"connections\":{}, \"children\": [], \"parents\":[]}\n self.__modules[name][\"instance\"]=module(name, *args, **kwargs)\n self.__modules[name][\"instance\"].getContextSwitcher=self.getContextSwitcher\n\n self.__modules[name][\"fwd_logs\"] = spawn (self.__forwardLogs, self.__modules[name][\"instance\"].logging.logs, self.logs)\n self.__modules[name][\"fwd_metrics\"] = spawn (self.__gatherMetrics, self.__modules[name][\"instance\"])\n\n self.__modules[name][\"connections\"][\"inbox\"] = spawn (self.__forwardEvents, self.logs, self.__modules[name][\"instance\"].queuepool.inbox)\n\n def registerMetricModule(self, module, name, *args, **kwargs):\n '''Registers and connects the module to the router's log queue.\n\n If this method is not called (no module connected to it) the queue is\n automatically connected to a Null module.\n\n Parameters:\n\n module(module) A wishbone module.\n name(string) The name to assign to the module insance.\n args(list) Positional arguments to pass to the module.\n kwargs(dict) Named arguments to pass to the module.\n '''\n\n self.__metricmodule = name\n self.__modules[name] = {\"instance\":None, \"fwd_logs\":None, \"fwd_metrics\":None, \"connections\":{}, \"children\": [], \"parents\": []}\n self.__modules[name][\"instance\"]=module(name, *args, **kwargs)\n self.__modules[name][\"instance\"].getContextSwitcher=self.getContextSwitcher\n\n self.__modules[name][\"fwd_logs\"] = spawn (self.__forwardLogs, self.__modules[name][\"instance\"].logging.logs, self.logs)\n self.__modules[name][\"fwd_metrics\"] = spawn (self.__gatherMetrics, self.__modules[name][\"instance\"])\n self.__modules[name][\"connections\"][\"inbox\"] = spawn (self.__forwardEvents, self.metrics, self.__modules[name][\"instance\"].queuepool.inbox)\n\n def start(self):\n '''Starts the router and all registerd modules.\n\n Executes following steps:\n\n - Starts the registered logging module.\n - Starts the registered metrics module.\n - Calls each registered module's start() function.\n '''\n\n if self.__logmodule == None:\n from wishbone.module import Null\n self.registerLogModule(Null, \"__null_logs\")\n\n if self.__metricmodule == None:\n from wishbone.module import Null\n self.registerMetricModule(Null, \"__null_metrics\")\n\n for module in self.__modules:\n try:\n self.__modules[module][\"instance\"].preHook()\n self.logging.debug(\"Prehook found for module %s and executed.\"%(module))\n except AttributeError:\n self.logging.debug(\"Prehook not found for module %s.\"%(module))\n\n self.__modules[module][\"instance\"].start()\n\n if self.__throttle == True:\n self.logging.info(\"Throttling enabled. Starting throttle monitor.\")\n spawn(self.throttleMonitor)\n\n def stop(self):\n '''Stops the router and all registered modules.\n\n It stops all the modules except the modules connected\n to the logs or metrics endpoint to ensure these event\n streams survive untill the end. All other modules\n are shutdown in the order they have been registered.\n '''\n\n self.logging.info('Stopping.')\n\n for module in self.__modules.keys():\n if module in [self.__logmodule, self.__metricmodule]+self.getChildren(self.__logmodule)+self.getChildren(self.__metricmodule):\n continue\n else:\n try:\n self.__modules[module][\"instance\"].postHook()\n self.logging.debug(\"Posthook found for module %s and executed.\"%(module))\n except AttributeError:\n self.logging.debug(\"Posthook not found for module %s.\"%(module))\n\n self.__modules[module][\"instance\"].stop()\n while self.__modules[module][\"instance\"].logging.logs.size() > 0:\n sleep(0.5)\n\n while self.__modules[self.__logmodule][\"instance\"].queuepool.inbox.size() > 0 or self.logs.size() > 0:\n sleep(0.5)\n\n self.__runConsumers.set()\n\n if self.rescue:\n self.doRescue()\n\n self.__exit.set()\n\n def __forwardEvents(self, source, destination):\n\n '''The background greenthread which continuously consumes the producing\n queue and dumps that data into the consuming queue.'''\n\n #todo(smetj): make this cycler setup more dynamic? Auto adjust the amount\n #cycles before context switch to achieve sweetspot?\n\n switcher = self.getContextSwitcher(self.context_switch)\n while switcher():\n try:\n event = source.get()\n except QueueLocked:\n source.waitUntilGetAllowed()\n else:\n if self.__checkIntegrity(event):\n event=self.__UUID(event)\n try:\n destination.put(event)\n except QueueLocked:\n source.putLock()\n source.rescue(event)\n destination.waitUntilPutAllowed()\n source.putUnlock()\n except QueueFull:\n source.putLock()\n source.rescue(event)\n destination.waitUntilFreePlace()\n source.putUnlock()\n else:\n self.logging.warn(\"Invalid event format.\")\n self.logging.debug(\"Invalid event format. %s\"%(event))\n\n\n def __gatherMetrics(self, module):\n\n '''A background greenlet which periodically gathers the metrics of all\n queues in all registered modules. These metrics are then forwarded to\n the registered metrics module.\n\n\n Metrics have following format:\n\n (time, type, source, name, value, unit, (tag1, tag2))\n '''\n\n while not self.__runConsumers.isSet():\n now = time()\n if hasattr(module, \"metrics\"):\n for fn in module.metrics:\n metric=(now, \"wishbone\", self.hostname, \"function.%s.%s.total_time\"%(module.name, fn), module.metrics[fn][\"total_time\"], '',())\n self.metrics.put({\"header\":{}, \"data\":metric})\n metric=(now, \"wishbone\", self.hostname, \"function.%s.%s.hits\"%(module.name, fn), module.metrics[fn][\"hits\"], '',())\n self.metrics.put({\"header\":{}, \"data\":metric})\n\n for queue in module.queuepool.listQueues():\n stats = getattr(module.queuepool, queue).stats()\n for item in stats:\n metric=(now, \"wishbone\", self.hostname, \"queue.%s.%s.%s\"%(module.name, queue, item), stats[item], '', ())\n self.metrics.put({\"header\":{}, \"data\":metric})\n sleep(self.interval)\n\n def __forwardLogs(self, source, destination):\n\n '''The background greenthread which continuously consumes the producing\n queue and dumps that data into the consuming queue.'''\n\n switcher = self.getContextSwitcher(10)\n while switcher():\n try:\n event = source.get()\n except:\n sleep(0.1)\n else:\n if self.__checkIntegrity(event):\n try:\n destination.put(event)\n except:\n source.rescue(event)\n else:\n self.logging.warn(\"Invalid event format.\")\n self.logging.debug(\"Invalid event format. %s\"%(event))\n\n def __signal_handler(self):\n\n '''Intercepts the SIGINT signal and initiates a proper shutdown\n sequence.'''\n\n self.logging.info(\"Received SIGINT. Shutting down.\")\n self.stop()\n\n def __doUUID(self, event):\n try:\n event[\"header\"][\"uuid\"]\n except:\n event[\"header\"][\"uuid\"] = str(uuid4())\n return event\n\n def __noUUID(self, event):\n return event\n\n def __checkIntegrity(self, event):\n '''Checks the integrity of the messages passed over the different queues.\n\n The format of the messages should be\n\n { 'headers': {}, data: {} }\n '''\n try:\n event[\"header\"]\n event[\"data\"]\n return True\n except:\n return False\n\n def throttleMonitor(self):\n \"\"\"Sweeps over all registered modules and tries to detect modules with problematic flow rates.\n Once found a moduleMonitor greenthread is spawned which is reponsible for enabling and disabling\n throttling.\"\"\"\n\n active_module_monitors={}\n\n while self.loop():\n for module in self.__modules:\n for queue in self.__modules[module][\"instance\"].queuepool.listQueues():\n if getattr(self.__modules[module][\"instance\"].queuepool, queue).size() > self.__throttle_threshold:\n parents = self.getParents(module)\n if len(parents) == 0:\n #simple, the module is flooding itself.\n if module in active_module_monitors and active_module_monitors[module].ready():\n active_module_monitors[module] = spawn(self.moduleMonitor, module, module, getattr(self.__modules[module][\"instance\"].queuepool, queue).size)\n else:\n #We have to find the upstream culprit responsible for flooding.\n #A parent module with a queue with the highest out_rate\n if parents[0] not in active_module_monitors or parents[0] in active_module_monitors and active_module_monitors[parents[0]].ready():\n active_module_monitors[parents[0]] = spawn(self.moduleMonitor, parents[0], module, getattr(self.__modules[module][\"instance\"].queuepool, queue).size)\n sleep(1)\n\n def moduleMonitor(self, module, child_name, child_size):\n \"\"\"A moduleMonitor is a greenthread which monitors the state of a module and triggers the expected\n throttling functions. It exits when no more throttling is required.\n \"\"\"\n\n if \"enableThrottling\" in dir(self.__modules[module][\"instance\"]) and \"disableThrottling\" in dir(self.__modules[module][\"instance\"]):\n self.logging.debug(\"Module %s is identified to overflow module %s. Enable throttling.\"%(module, child_name))\n while self.loop():\n if child_size() > self.__throttle_threshold:\n try:\n self.__modules[module][\"instance\"].enableThrottling()\n except Exception as err:\n self.logging.err(\"Executing enableThrottling() in module %s generated an error. Reason: %s.\"%(module, err))\n break\n else:\n try:\n self.__modules[module][\"instance\"].disableThrottling()\n self.logging.debug(\"Throttling on module %s is not required anymore. Exiting.\"%(module))\n except Exception as err:\n self.logging.err(\"Executing disableThrottling() in module %s generated an error. Reason: %s.\"%(module, err))\n break\n sleep(1)\n","sub_path":"wishbone/router/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":22549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"317655376","text":"\"\"\"Given a singly linked list, the task is to rearrange it in a way that all odd position nodes are together and all even positions node are together.\nAssume the first element to be at position 1 followed by second element at position 2 and so on.\n\nExample 1:\n\nInput:\nLinkedList: 1->2->3->4\nOutput: 1 3 2 4\nExplanation:\nOdd elements are 1, 3 and even elements are\n2, 4. Hence, resultant linked list is\n1->3->2->4.\nExample 2:\n\nInput:\nLinkedList: 1->2->3->4->5\nOutput: 1 3 5 2 4\nExplanation:\nOdd elements are 1, 3, 5 and even elements are\n2, 4. Hence, resultant linked list is\n​1->3->5->2->4.\"\"\"\n\n# class Solution:\ndef rearrangeEvenOdd(head):\n if head == None:\n return None\n\n odd = head\n even = head.next\n\n evenfirst = even\n\n while(1==1):\n if (odd==None or even == None or (even.next) == None):\n odd.next = evenfirst\n break\n\n odd.next = even.next\n odd = even.next\n\n if (odd.next == None):\n even.next = None\n odd.next = evenfirst\n break\n\n even.next = odd.next\n even = odd.next\n\n return head\n\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def append(self, data):\n new_node = Node(data)\n if self.head == None:\n self.head = new_node\n self.tail = new_node\n return\n else:\n self.tail.next = new_node\n self.tail = new_node\n\n def newNode(self, key):\n temp = Node(key)\n self.next =None\n return temp\n\n def printList(self, node):\n while(node):\n print(node.data, end= \" \")\n node = node.next\n\n # def push(self, new_data):\n # new_node = Node(new_data)\n # new_node.next = self.head\n # self.head = new_node\n\n\nt = int(input())\nfor i in range(t):\n n = int(input())\n a = list(map(int, input().strip().split()))\n l = LinkedList()\n for j in a:\n l.append(j)\n # Solution().rearrangeEvenOdd(l.head)\n # Solution().rearrangeEvenOdd(l.head)\n rearrangeEvenOdd(l.head)\n l.printList(l.head)\n print()\n","sub_path":"Linked_List/rearrange_linked_list.py","file_name":"rearrange_linked_list.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"565856025","text":"import inspect\n\nimport pytest\nimport requests\nfrom urllib3.util.retry import Retry\nfrom requests.adapters import HTTPAdapter\nfrom test.integration.utils import ergo\n\n\n# HTTP requests need to retry on ConnectionError while the Flask server boots.\nsession = requests.Session()\nretries = Retry(connect=5, backoff_factor=0.1)\nsession.mount('http://', HTTPAdapter(max_retries=retries))\n\n\ndef product(x, y):\n return float(x) * float(y)\n\n\ndef test_product():\n \"\"\"tests the example function from the ergo README\"\"\"\n with ergo(\"http\", f\"{__file__}:product\"):\n resp = session.get(\"http://localhost?x=4&y=5\")\n assert resp.status_code == 200\n result = resp.json()\n assert result == 20.0\n\n\ndef test_product__post_request():\n with ergo(\"http\", f\"{__file__}:product\"):\n resp = session.post(\"http://localhost?x=4&y=5\")\n assert resp.status_code == 200\n result = resp.json()\n assert result == 20.0\n\n\ndef test_product__ergo_start():\n manifest = {\n \"func\": f\"{__file__}:product\"\n }\n namespace = {\n \"protocol\": \"http\",\n }\n with ergo(\"start\", manifest=manifest, namespace=namespace):\n resp = session.get(\"http://localhost\", params={\"x\": 2.5, \"y\": 3})\n assert resp.status_code == 200\n result = resp.json()\n assert result == 7.5\n\n\ndef get_dict():\n return {\n \"string\": \"🌟\",\n \"float\": 1.234,\n }\n\n\ndef get_one_dict():\n return [get_dict()]\n\n\ndef get_two_dicts():\n return [get_dict(), get_dict()]\n\n\ndef get_none():\n return None\n\n\ndef yield_one_dict():\n yield get_dict()\n\n\ndef yield_two_dicts():\n yield get_dict()\n yield get_dict()\n\n\n@pytest.mark.parametrize(\"getter\", [\n get_dict,\n get_one_dict,\n get_two_dicts,\n get_none,\n yield_one_dict,\n yield_two_dicts,\n])\ndef test_get_data(getter):\n \"\"\"assert that ergo flask response data preserves the type and dimensionality of the component function's return\n value\"\"\"\n manifest = {\n \"func\": f\"{__file__}:{getter.__name__}\"\n }\n namespace = {\n \"protocol\": \"http\",\n }\n with ergo(\"start\", manifest=manifest, namespace=namespace):\n resp = session.get(\"http://localhost\")\n assert resp.ok\n actual = resp.json()\n if inspect.isgeneratorfunction(getter):\n expected = [i for i in getter()]\n else:\n expected = getter()\n\n assert actual == expected\n","sub_path":"test/integration/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"425577110","text":"import time\nimport os\n\nimport bluesky.plan_stubs as bps\nimport bluesky_darkframes\nimport bluesky_darkframes.sim\nfrom bluesky.plans import count\nfrom event_model import RunRouter, Filler\nfrom ophyd.sim import NumpySeqHandler\nimport pytest\nfrom suitcase.tiff_series import Serializer\n\n\n# This is some simulated hardware for demo purposes.\ndet = bluesky_darkframes.sim.DiffractionDetector(name='det')\ndet.exposure_time.put(0.01)\nshutter = bluesky_darkframes.sim.Shutter(name='shutter', value='open')\n\n\ndef dark_plan():\n yield from bps.mv(shutter, 'closed')\n yield from bps.trigger(det, group='darkframe-trigger')\n yield from bps.wait('darkframe-trigger')\n snapshot = bluesky_darkframes.SnapshotDevice(det)\n yield from bps.mv(shutter, 'open')\n return snapshot\n\n\ndef test_one_dark_event_emitted(RE):\n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n dark_plan=dark_plan, detector=det, max_age=3)\n RE.preprocessors.append(dark_frame_preprocessor)\n\n def verify_one_dark_frame(name, doc):\n if name == 'stop':\n doc['num_events']['dark'] == 1\n\n RE(count([det]), verify_one_dark_frame)\n RE(count([det], 3), verify_one_dark_frame)\n\n\ndef test_mid_scan_dark_frames(RE):\n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n dark_plan=dark_plan, detector=det, max_age=0)\n RE.preprocessors.append(dark_frame_preprocessor)\n\n def verify_four_dark_frames(name, doc):\n if name == 'stop':\n doc['num_events']['dark'] == 4\n\n RE(count([det], 3), verify_four_dark_frames)\n\n\ndef test_max_age(RE):\n \"\"\"\n Test the a dark frame is reused until it expires, and then re-taken.\n \"\"\"\n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n dark_plan=dark_plan, detector=det, max_age=1)\n RE.preprocessors.append(dark_frame_preprocessor)\n # The first executation adds something to the cache.\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 1\n state, = dark_frame_preprocessor.cache\n # A second execution reuses the cache entry, adds nothing.\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 1\n dark_frame_preprocessor.get_snapshot(state)\n # Wait for it to age out.\n time.sleep(1.01)\n with pytest.raises(bluesky_darkframes.NoMatchingSnapshot):\n dark_frame_preprocessor.get_snapshot(state)\n\n\ndef test_locked_signals(RE):\n \"\"\"\n Test that if a 'locked signal' is changed, a new dark frame is taken, but\n if the locked signal goes back to the original value, the original dark\n frame is reused.\n \"\"\"\n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n dark_plan=dark_plan, detector=det, max_age=100,\n locked_signals=[det.exposure_time])\n RE.preprocessors.append(dark_frame_preprocessor)\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 1\n RE(bps.mv(det.exposure_time, 0.02))\n # This should take a new dark frame.\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 2\n # This should reuse the first one.\n RE(bps.mv(det.exposure_time, 0.01))\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 2\n\n\ndef test_limit(RE):\n \"\"\"\n Test that if a 'locked signal' is changed, a new dark frame is taken, but\n if the locked signal goes back to the original value, the original dark\n frame is reused.\n \"\"\"\n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n dark_plan=dark_plan, detector=det, max_age=100,\n locked_signals=[det.exposure_time],\n limit=1)\n RE.preprocessors.append(dark_frame_preprocessor)\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 1\n state, = dark_frame_preprocessor.cache\n previous_state = state\n RE(bps.mv(det.exposure_time, 0.02))\n # This should take a new dark frame and evict the last one.\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 1\n state, = dark_frame_preprocessor.cache\n assert state != previous_state\n previous_state = state\n # This should take a new dark frame and evict the last one.\n RE(bps.mv(det.exposure_time, 0.01))\n RE(count([det]))\n assert len(dark_frame_preprocessor.cache) == 1\n state, = dark_frame_preprocessor.cache\n assert state != previous_state\n previous_state = state\n\n\n@pytest.mark.parametrize('pedestal', [None, 0, 100])\ndef test_streaming_export(RE, tmp_path, pedestal):\n \"\"\"\n Test that DarkSubtractor generates files when subscribed to RE.\n \"\"\"\n def factory(name, doc):\n # The problem this is solving is to store documents from this run long\n # enough to cross-reference them (e.g. light frames and dark frames),\n # and then tearing it down when we're done with this run.\n kwargs = {}\n if pedestal is not None:\n kwargs['pedestal'] = pedestal\n subtractor = bluesky_darkframes.DarkSubtraction('det_image', **kwargs)\n serializer = Serializer(tmp_path)\n filler = Filler({'NPY_SEQ': NumpySeqHandler}, inplace=False)\n\n # Here we push the run 'start' doc through.\n subtractor(name, doc)\n serializer(name, doc)\n filler(name, doc)\n\n # And by returning this function below, we are routing all other\n # documents *for this run* through here.\n def fill_subtract_and_serialize(name, doc):\n name, doc = filler(name, doc)\n name, doc = subtractor(name, doc)\n serializer(name, doc)\n\n return [fill_subtract_and_serialize], []\n\n rr = RunRouter([factory])\n RE.subscribe(rr)\n\n dark_frame_preprocessor = bluesky_darkframes.DarkFramePreprocessor(\n dark_plan=dark_plan, detector=det, max_age=100)\n RE.preprocessors.append(dark_frame_preprocessor)\n\n RE(count([det]))\n exported_files = os.listdir(tmp_path)\n\n assert len(exported_files) == 2\n\n\ndef test_no_dark_frames(RE, tmp_path):\n \"\"\"\n Test that a readable error is raised if no 'dark' frame is received.\n \"\"\"\n def factory(name, doc):\n # The problem this is solving is to store documents from this run long\n # enough to cross-reference them (e.g. light frames and dark frames),\n # and then tearing it down when we're done with this run.\n subtractor = bluesky_darkframes.DarkSubtraction('det_image')\n serializer = Serializer(tmp_path)\n filler = Filler({'NPY_SEQ': NumpySeqHandler}, inplace=False)\n\n # Here we push the run 'start' doc through.\n subtractor(name, doc)\n serializer(name, doc)\n filler(name, doc)\n\n # And by returning this function below, we are routing all other\n # documents *for this run* through here.\n def fill_subtract_and_serialize(name, doc):\n name, doc = filler(name, doc)\n name, doc = subtractor(name, doc)\n serializer(name, doc)\n\n return [fill_subtract_and_serialize], []\n\n rr = RunRouter([factory])\n RE.subscribe(rr)\n\n # We intentionally 'forget' to set up a dark_frame_preprocessor for this\n # test.\n\n with pytest.raises(bluesky_darkframes.NoDarkFrame):\n RE(count([det]))\n","sub_path":"bluesky_darkframes/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"319745771","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\nwho = pd.read_csv(\"BIO465_Vaccine/data/WHO-SIMPLE.csv\")\n\n#apply any filters worth analyzing\nfilter = who[\"Year\"] >= 2000\nfilter2 = who[\"Country Code\"] == \"USA\"\nwho = who[filter]\n#who = who[filter2]\n\n#Select which factors you would like to analyze\n#who = who[[\"Country_Year\", \"MDG_0000000001\", \"PCV3\", \"ROTAC\", \"WHS4_100\", \"WHS4_117\", \"WHS4_129\", \"WHS4_543\", \"WHS4_544\", \"WHS8_110\", \"MCV2\", \"NUTRITION_564\", \"WHS4_128\", \"LBW_NUMBER\", \"LBW_PREVALENCE\", \"NUTRITION_HA_2\", \"NUTRITION_WA_2\", \"NUTRITION_WH2\", \"NUTRITION_WH_2\", \"WHOSIS_000005\", \"WHOSIS_000006\", \"MDG_0000000026\", \"WHS9_95\", \"WHS_PBR\", \"WSH_2\", \"WSH_3\", \"WSH_SANITATION_SAFELY_MANAGED\", \"M_Est_smk_curr\", \"M_Est_smk_daily\", \"TOBACCO_0000000192\", \"GHED_CHEGDP_SHA2011\", \"WHS9_85\"]]\nwho = who[[\"Country_Year\", \"MDG_0000000001\", \"LBW_PREVALENCE\", \"GHED_CHEGDP_SHA2011\", \"GDP\"]]\nwho = who.set_index(\"Country_Year\")\n#Drop rows with NA values\nwho.dropna(axis=0,how=\"any\",inplace=True)\n\n\n#Conduct PCA\nimr_column = who.loc[:,\"MDG_0000000001\"]\nimr = imr_column.values\n\ncategory = pd.qcut(who.MDG_0000000001,q=4, labels=[\"low imr\", \"moderately low imr\", \"moderately high imr\", \"high imr\"])\nlength = len(who.columns)\nwho.insert(length, \"IMR Category\", category)\n#Remove continous variables for imr\ndel who[\"MDG_0000000001\"]\n\nfeatures = [\"LBW_PREVALENCE\", \"GHED_CHEGDP_SHA2011\", \"GDP\"]\n# Separating out the features\nx = who.loc[:, features].values\n# Separating out the target\ny = who.loc[:,['IMR Category']].values\n# Standardizing the features\nx = StandardScaler().fit_transform(x)\n\n#switch index to allow for join with PCs 1 and 2\nwho['rows'] = np.arange(len(who))\nwho = who.set_index('rows')\n\npca = PCA(n_components=2)\nprincipalComponents = pca.fit_transform(x)\nprincipalDf = pd.DataFrame(data = principalComponents, columns = ['principal component 1', 'principal component 2'])\nfinalDf = pd.concat([principalDf, who[['IMR Category']]], axis = 1)\n\n#print(finalDf)\n\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = ['high imr', 'moderately high imr', 'moderately low imr', 'low imr']\ncolors = ['r', 'g', 'b', 'c']\nfor target, color in zip(targets,colors):\n indicesToKeep = finalDf['IMR Category'] == target\n ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']\n , finalDf.loc[indicesToKeep, 'principal component 2']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()\n\n#This ratio tells you the amount of variance explained by PC1 and PC2\nprint(pca.explained_variance_ratio_)\nplt.show()\n\n\n\n\n","sub_path":"code/Exploration and Prototyping Code/whoPCA.py","file_name":"whoPCA.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"320835484","text":"'''outpt function definition'''\n\nimport numpy\nfrom numba import jit, int64, float64, complex128\n\n\n@jit(int64[:](float64, int64, int64, int64, int64, float64[:], complex128[:],\n float64, int64, float64[:], float64[:, :]), nopython=True)\ndef outpt(r, mdr, ndr, ndz, tlc, f3, u, _dir, ir, tll, tlg):\n\n '''Output transmission loss'''\n\n eps = 1e-20\n\n mdr += 1\n if mdr == ndr:\n mdr = 0\n tlc += 1\n ur = (1 - _dir) * f3[ir] * u[ir] + \\\n _dir * f3[ir + 1] * u[ir + 1]\n temp = 10 * numpy.log10(r + eps)\n tll[tlc] = -20 * numpy.log10(numpy.abs(ur) + eps) + temp\n\n for i in range(tlg.shape[0]):\n j = (i + 1) * ndz\n ur = u[j] * f3[j]\n tlg[i, tlc] = \\\n -20 * numpy.log10(numpy.abs(ur) + eps) + temp\n\n return numpy.array([mdr, tlc], dtype=numpy.int64)\n","sub_path":"pyram/outpt.py","file_name":"outpt.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"36005541","text":"'''\nCreated on 2016. 02.24\n@author: Logan K.\n'''\nfrom __future__ import print_function\n\nfrom PIL import Image\n\nif __name__ == '__main__':\n print ('PIL_Version: ' + Image.VERSION)\n print ('PILLOW_Version: ' + Image.PILLOW_VERSION)\n\ndef histo(image):\n data = image.histogram()\n for i in range(0, len(data), 3):\n print (i / 3, \" R: \", data[i], \" G:\", data[i + 1], \" B:\", data[i + 2])\n\n\nimage = Image.open(\"sample.jpg\")\nwidth, height = image.size\n\nhalf_width = width / 2\nhalf_height = height / 2\nhalf_half_width = half_width / 2\nhalf_half_height = half_height / 2\n\nlu_center = (0 + (half_width / 2), 0 + half_half_height)\nld_center = (0 + (half_width / 2), half_height + half_half_height)\nru_center = (half_width + half_half_width, 0 + half_half_height)\nrd_center = (half_width + half_half_width, half_height + half_half_height)\n\nlu_box = (0, 0, half_width, half_height)\nld_box = (0, half_height, half_width, height)\nru_box = (half_width, 0, width, half_height)\nrd_box = (half_width, half_height, width, height)\n\nlu_image = image.crop(lu_box)\nld_image = image.crop(ld_box)\nru_image = image.crop(ru_box)\nrd_image = image.crop(rd_box)\n\n\n","sub_path":"beautya/image/sample/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"138662365","text":"# Pyrogram - Telegram MTProto API Client Library for Python\n# Copyright (C) 2017-2018 Dan Tès \n#\n# This file is part of Pyrogram.\n#\n# Pyrogram is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Pyrogram is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Pyrogram. If not, see .\n\nimport logging\nimport threading\nimport time\nfrom datetime import timedelta, datetime\nfrom hashlib import sha1, sha256\nfrom io import BytesIO\nfrom os import urandom\nfrom queue import Queue\nfrom threading import Event, Thread\n\nimport pyrogram\nfrom pyrogram import __copyright__, __license__, __version__\nfrom pyrogram.api import functions, types, core\nfrom pyrogram.api.all import layer\nfrom pyrogram.api.core import Message, Object, MsgContainer, Long, FutureSalt, Int\nfrom pyrogram.api.errors import Error, InternalServerError\nfrom pyrogram.connection import Connection\nfrom pyrogram.crypto import AES, KDF\nfrom .internals import MsgId, MsgFactory, DataCenter\n\nlog = logging.getLogger(__name__)\n\n\nclass Result:\n def __init__(self):\n self.value = None\n self.event = Event()\n\n\nclass Session:\n INITIAL_SALT = 0x616e67656c696361\n NET_WORKERS = 1\n WAIT_TIMEOUT = 15\n MAX_RETRIES = 5\n ACKS_THRESHOLD = 8\n PING_INTERVAL = 5\n\n notice_displayed = False\n\n BAD_MSG_DESCRIPTION = {\n 16: \"[16] msg_id too low, the client time has to be synchronized\",\n 17: \"[17] msg_id too high, the client time has to be synchronized\",\n 18: \"[18] incorrect two lower order msg_id bits, the server expects client message msg_id to be divisible by 4\",\n 19: \"[19] container msg_id is the same as msg_id of a previously received message\",\n 20: \"[20] message too old, it cannot be verified by the server\",\n 32: \"[32] msg_seqno too low\",\n 33: \"[33] msg_seqno too high\",\n 34: \"[34] an even msg_seqno expected, but odd received\",\n 35: \"[35] odd msg_seqno expected, but even received\",\n 48: \"[48] incorrect server salt\",\n 64: \"[64] invalid container\"\n }\n\n def __init__(self,\n client: pyrogram,\n dc_id: int,\n auth_key: bytes,\n is_media: bool = False,\n is_cdn: bool = False):\n if not Session.notice_displayed:\n print(\"Pyrogram v{}, {}\".format(__version__, __copyright__))\n print(\"Licensed under the terms of the \" + __license__, end=\"\\n\\n\")\n Session.notice_displayed = True\n\n self.client = client\n self.dc_id = dc_id\n self.auth_key = auth_key\n self.is_media = is_media\n self.is_cdn = is_cdn\n\n self.connection = None\n\n self.auth_key_id = sha1(auth_key).digest()[-8:]\n\n self.session_id = Long(MsgId())\n self.msg_factory = MsgFactory()\n\n self.current_salt = None\n\n self.pending_acks = set()\n\n self.recv_queue = Queue()\n self.results = {}\n\n self.ping_thread = None\n self.ping_thread_event = Event()\n\n self.next_salt_thread = None\n self.next_salt_thread_event = Event()\n\n self.net_worker_list = []\n\n self.is_connected = Event()\n\n def start(self):\n while True:\n self.connection = Connection(DataCenter(self.dc_id, self.client.test_mode), self.client.proxy)\n\n try:\n self.connection.connect()\n\n for i in range(self.NET_WORKERS):\n self.net_worker_list.append(\n Thread(\n target=self.net_worker,\n name=\"NetWorker#{}\".format(i + 1)\n )\n )\n\n self.net_worker_list[-1].start()\n\n Thread(target=self.recv, name=\"RecvThread\").start()\n\n self.current_salt = FutureSalt(0, 0, self.INITIAL_SALT)\n self.current_salt = FutureSalt(0, 0, self._send(functions.Ping(0)).new_server_salt)\n self.current_salt = self._send(functions.GetFutureSalts(1)).salts[0]\n\n self.next_salt_thread = Thread(target=self.next_salt, name=\"NextSaltThread\")\n self.next_salt_thread.start()\n\n if not self.is_cdn:\n self._send(\n functions.InvokeWithLayer(\n layer,\n functions.InitConnection(\n api_id=self.client.api_id,\n app_version=self.client.app_version,\n device_model=self.client.device_model,\n system_version=self.client.system_version,\n system_lang_code=self.client.lang_code,\n lang_code=self.client.lang_code,\n lang_pack=\"\",\n query=functions.help.GetConfig(),\n )\n )\n )\n\n self.ping_thread = Thread(target=self.ping, name=\"PingThread\")\n self.ping_thread.start()\n\n log.info(\"Connection inited: Layer {}\".format(layer))\n except (OSError, TimeoutError, Error):\n self.stop()\n except Exception as e:\n self.stop()\n raise e\n else:\n break\n\n self.is_connected.set()\n\n log.debug(\"Session started\")\n\n def stop(self):\n self.is_connected.clear()\n\n self.ping_thread_event.set()\n self.next_salt_thread_event.set()\n\n if self.ping_thread is not None:\n self.ping_thread.join()\n\n if self.next_salt_thread is not None:\n self.next_salt_thread.join()\n\n self.ping_thread_event.clear()\n self.next_salt_thread_event.clear()\n\n self.connection.close()\n\n for i in range(self.NET_WORKERS):\n self.recv_queue.put(None)\n\n for i in self.net_worker_list:\n i.join()\n\n self.net_worker_list.clear()\n\n for i in self.results.values():\n i.event.set()\n\n if not self.is_media and callable(self.client.disconnect_handler):\n try:\n self.client.disconnect_handler(self.client)\n except Exception as e:\n log.error(e, exc_info=True)\n\n log.debug(\"Session stopped\")\n\n def restart(self):\n self.stop()\n self.start()\n\n def pack(self, message: Message):\n data = Long(self.current_salt.salt) + self.session_id + message.write()\n padding = urandom(-(len(data) + 12) % 16 + 12)\n\n # 88 = 88 + 0 (outgoing message)\n msg_key_large = sha256(self.auth_key[88: 88 + 32] + data + padding).digest()\n msg_key = msg_key_large[8:24]\n aes_key, aes_iv = KDF(self.auth_key, msg_key, True)\n\n return self.auth_key_id + msg_key + AES.ige256_encrypt(data + padding, aes_key, aes_iv)\n\n def unpack(self, b: BytesIO) -> Message:\n assert b.read(8) == self.auth_key_id, b.getvalue()\n\n msg_key = b.read(16)\n aes_key, aes_iv = KDF(self.auth_key, msg_key, False)\n data = BytesIO(AES.ige256_decrypt(b.read(), aes_key, aes_iv))\n data.read(8)\n\n # https://core.telegram.org/mtproto/security_guidelines#checking-session-id\n assert data.read(8) == self.session_id\n\n message = Message.read(data)\n\n # https://core.telegram.org/mtproto/security_guidelines#checking-sha256-hash-value-of-msg-key\n # https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n # 96 = 88 + 8 (incoming message)\n assert msg_key == sha256(self.auth_key[96:96 + 32] + data.getvalue()).digest()[8:24]\n\n # https://core.telegram.org/mtproto/security_guidelines#checking-msg-id\n # TODO: check for lower msg_ids\n assert message.msg_id % 2 != 0\n\n return message\n\n def net_worker(self):\n name = threading.current_thread().name\n log.debug(\"{} started\".format(name))\n\n while True:\n packet = self.recv_queue.get()\n\n if packet is None:\n break\n\n try:\n data = self.unpack(BytesIO(packet))\n\n messages = (\n data.body.messages\n if isinstance(data.body, MsgContainer)\n else [data]\n )\n\n log.debug(data)\n\n for msg in messages:\n if msg.seq_no % 2 != 0:\n if msg.msg_id in self.pending_acks:\n continue\n else:\n self.pending_acks.add(msg.msg_id)\n\n if isinstance(msg.body, (types.MsgDetailedInfo, types.MsgNewDetailedInfo)):\n self.pending_acks.add(msg.body.answer_msg_id)\n continue\n\n if isinstance(msg.body, types.NewSessionCreated):\n continue\n\n msg_id = None\n\n if isinstance(msg.body, (types.BadMsgNotification, types.BadServerSalt)):\n msg_id = msg.body.bad_msg_id\n elif isinstance(msg.body, (core.FutureSalts, types.RpcResult)):\n msg_id = msg.body.req_msg_id\n elif isinstance(msg.body, types.Pong):\n msg_id = msg.body.msg_id\n else:\n if self.client is not None:\n self.client.updates_queue.put(msg.body)\n\n if msg_id in self.results:\n self.results[msg_id].value = getattr(msg.body, \"result\", msg.body)\n self.results[msg_id].event.set()\n\n if len(self.pending_acks) >= self.ACKS_THRESHOLD:\n log.info(\"Send {} acks\".format(len(self.pending_acks)))\n\n try:\n self._send(types.MsgsAck(list(self.pending_acks)), False)\n except (OSError, TimeoutError):\n pass\n else:\n self.pending_acks.clear()\n except Exception as e:\n log.error(e, exc_info=True)\n\n log.debug(\"{} stopped\".format(name))\n\n def ping(self):\n log.debug(\"PingThread started\")\n\n while True:\n self.ping_thread_event.wait(self.PING_INTERVAL)\n\n if self.ping_thread_event.is_set():\n break\n\n try:\n self._send(functions.PingDelayDisconnect(\n 0, self.WAIT_TIMEOUT + 10\n ), False)\n except (OSError, TimeoutError, Error):\n pass\n\n log.debug(\"PingThread stopped\")\n\n def next_salt(self):\n log.debug(\"NextSaltThread started\")\n\n while True:\n now = datetime.now()\n\n # Seconds to wait until middle-overlap, which is\n # 15 minutes before/after the current/next salt end/start time\n dt = (self.current_salt.valid_until - now).total_seconds() - 900\n\n log.debug(\"Current salt: {} | Next salt in {:.0f}m {:.0f}s ({})\".format(\n self.current_salt.salt,\n dt // 60,\n dt % 60,\n now + timedelta(seconds=dt)\n ))\n\n self.next_salt_thread_event.wait(dt)\n\n if self.next_salt_thread_event.is_set():\n break\n\n try:\n self.current_salt = self._send(functions.GetFutureSalts(1)).salts[0]\n except (OSError, TimeoutError, Error):\n self.connection.close()\n break\n\n log.debug(\"NextSaltThread stopped\")\n\n def recv(self):\n log.debug(\"RecvThread started\")\n\n while True:\n packet = self.connection.recv()\n\n if packet is None or len(packet) == 4:\n if packet:\n log.warning(\"Server sent \\\"{}\\\"\".format(Int.read(BytesIO(packet))))\n\n if self.is_connected.is_set():\n Thread(target=self.restart, name=\"RestartThread\").start()\n break\n\n self.recv_queue.put(packet)\n\n log.debug(\"RecvThread stopped\")\n\n def _send(self, data: Object, wait_response: bool = True, timeout: float = WAIT_TIMEOUT):\n message = self.msg_factory(data)\n msg_id = message.msg_id\n\n if wait_response:\n self.results[msg_id] = Result()\n\n payload = self.pack(message)\n\n try:\n self.connection.send(payload)\n except OSError as e:\n self.results.pop(msg_id, None)\n raise e\n\n if wait_response:\n self.results[msg_id].event.wait(timeout)\n result = self.results.pop(msg_id).value\n\n if result is None:\n raise TimeoutError\n elif isinstance(result, types.RpcError):\n Error.raise_it(result, type(data))\n elif isinstance(result, types.BadMsgNotification):\n raise Exception(self.BAD_MSG_DESCRIPTION.get(\n result.error_code,\n \"Error code {}\".format(result.error_code)\n ))\n else:\n return result\n\n def send(self, data: Object, retries: int = MAX_RETRIES, timeout: float = WAIT_TIMEOUT):\n self.is_connected.wait(self.WAIT_TIMEOUT)\n\n try:\n return self._send(data, timeout=timeout)\n except (OSError, TimeoutError, InternalServerError) as e:\n if retries == 0:\n raise e from None\n\n (log.warning if retries < 3 else log.info)(\n \"{}: {} Retrying {}\".format(\n Session.MAX_RETRIES - retries,\n datetime.now(), type(data)))\n\n time.sleep(0.5)\n return self.send(data, retries - 1, timeout)\n","sub_path":"ENV/lib/python3.5/site-packages/pyrogram/session/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":14436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"509234759","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom class_attendance_register_db import Students, Classes, users, Attendance, Base\nimport dbcreate\nimport datetime\nfrom tabulate import tabulate\nfrom colorama import init, Fore\nfrom sqlalchemy.sql import select\nfrom termcolor import colored\n\n\nengine = create_engine('sqlite:///class_attendance_register.db')\nBase.metadata.engine = engine\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\n\n\n\nstudent_logs =[]\nstudents_in_class = {}\nactive_classes = {}\nchecked_in_students=[]\n\ndef start_class(classid):\n\tstart_time = datetime.datetime.now()\n\n\tq = session.query(Classes).filter(Classes.class_id == classid)\n\tif not session.query(q.exists()).scalar():\n\t\tprint (\"The class \" + str(classid) + \"does not exist in the database.\")\n\telse:\n\t\tactive_classes[classid] = start_time\n\t\tprint (\"The Class with ID \" +str(classid) + \" starting time was \") \n\t\tprint(start_time )\n\n\n\ndef end_class(classid):\n\tendingtime = datetime.datetime.now()\n\tif classid in active_classes.keys():\n\t\tactive_classes.pop(classid)\n\t\tprint(\"The Class ID: \" +str(classid) + \" terminated at \")\n\t\tprint(endingtime)\n\telse:\n\t\tprint(\"Class ID: \" + str(classid) + \" not in session!\")\n\t\t\t\n\n\ndef all_classes():\n\t\n\tallclasses = select([Classes])\n\tq = session.execute(allclasses)\n\tclass_list=[]\n\n\t#orders the result to enable tabulation\n\tfor class_item in q.fetchall():\n\t\tclass_list.append(class_item)\n\tsession.close()\n\n\tif len(class_list) > 0:\n\t\tprint(colored(tabulate(class_list,tablefmt = \"grid\", headers = [\"class_id\",\"class_code\",\"class_name\",\"session_status\",\"tutor\"]),\"green\"))\n\telse:\n\t\tprint(colored(\"Table empty\",\"yellow\"))\n\t\n\n\ndef all_students():\n\tallstudents = select([Students])\n\tq = session.execute(allstudents)\n\tstudent_list=[]\n\n\t#orders the result to enable tabulation\n\tfor student_item in q.fetchall():\n\t\tstudent_list.append(student_item)\n\tsession.close()\n\n\tif len(student_list) > 0:\n\t\tprint(colored(tabulate(student_list,tablefmt = \"grid\", headers = [\"student_id\",\"reg_no\",\"student_name\"]),'green'))\n\telse:\n\t\tprint(colored(\"Table empty\",\"yellow\"))\n\ndef activeclasses():\n\tif active_classes.keys():\n\t\tfor classid in active_classes.keys():\n\t\t\tallclasses = session.query(Classes).all()\n\t\t\tfor classdet in allclasses:\n\t\t\t\tprint(\"Active Class: \")\n\t\t\t\tprint(classdet)\n\n\t\t\tstart_time = active_classes[classid]\n\t\t\tprint(\"Starting time is: \")\n\t\t\tprint (start_time)\n\t\t\t\n\telse:\n\t\tprint (\"There are no active classes at the moment, check later\")\n\t\n\n\ndef check_in_student(student_id, class_id):\n\tstudents = session.query(Students).all()\n\tid_found = False\n\tfor student in students:\n\t\tif student.student_id == student_id:\n\t\t\tid_found = True\n\t\t\tbreak\n\tif not id_found:\n\t\tprint('Student not present')\n\t\treturn\n\tif class_id in students_in_class:\n\t\tif student_id in students_in_class[class_id]:\n\t\t\tprint('Student already checked into this class')\n\t\t\treturn\n\t\tif student_id in checked_in_students:\n\t\t\tprint('Student already checked in another class')\n\t\t\treturn\n\t\tchecked_in_students.append(student_id)\n\t\tstudents_in_class[class_id].append(student_id)\n\t\tcheck_student_att = session.query(Attendance).all()\n\t\tattending = False\n\t\tif check_student_att:\n\t\t\tfor csa in check_student_att:\n\t\t\t\tif csa.st_id == student_id and csa.cl_id == class_id:\n\t\t\t\t\tsession.query(Attendance).filter_by(st_id=student_id).filter_by(cl_id=class_id).update({'inclass_status':True})\n\t\t\t\t\tattending=True\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tattending_stud = Attendance()\n\t\t\tattending_stud.cl_id = class_id\n\t\t\tattending_stud.st_id = student_id\n\t\t\tattending_stud.inclass_status = True\n\t\t\tsession.add(attending_stud)\n\t\t\tsession.commit()\n\telse:\n\t\tprint(colored('The class Id is not available',\"red\"))\n\t\treturn\n\n\navailable_classes = session.query(Classes).all()\nif available_classes:\n\tfor cls in available_classes:\n\t\tstudents_in_class[cls.class_id]=[]\ncheck_in_student(3,2)\ncheck_in_student(4,2)\n\n\ndef check_out_student(studentid,classid):\n\trea_son = input(\"What reason did student give? \")\n\tif classid in students_in_class:\n\t\tfor student in students_in_class[classid]:\n\t\t\tif studentid == student:\n\t\t\t\tprint(str(studentid) + \"just checked out\")\n\t\t\t\tprint(colored(\"Reason cited: \" + rea_son,\"green\"))\n\t\t\t\tstudents_in_class[classid].remove(studentid)\n\telse:\n\t\tprint (\"This Class ID \" + str(classid) + \" is not in session at the moment\")\n","sub_path":"activity.py","file_name":"activity.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"440396633","text":"\nimport pandas as pd\nfrom agora_lib import ml, prep\nfrom scipy.signal import savgol_filter\nfrom sklearn.preprocessing import StandardScaler\nimport sklearn as sk\nimport numpy as np\nfrom sklearn.cross_decomposition import PLSRegression\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor\n\nfrom sklearn.model_selection import validation_curve\nimport random\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom scipy import stats\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# num_cpus=psutil.cpu_count(False)\n# ray.init(num_cpus=psutil.cpu_count(logical=False),ignore_reinit_error=True) #initialize ray\nfrom sklearn.preprocessing import RobustScaler\n\n# @ray.remote\nclass Individual:\n fitness = 0;\n\n # ml method\n ml_method = 'SVR'\n # hyperparameter ranges\n svr_C = list(np.logspace(-1, 9, base=2, num=11))\n\n svr_gamma = list(np.logspace(-8, -2, base=2, num=7))\n pls_range=np.arange(1,15,1)\n\n nMut=1\n lam_range=[4,5,6,7,8]\n p_range=[3,5,7,9]\n\n w_range=[5,7,9,11,13,15,17]\n or_range=[2,3,4]\n d_range=[0,1,2]\n sc_range=[0,1,2,3]\n\n\n ml_params = {'C': random.choice(svr_C), 'gamma': random.choice(svr_gamma)}\n\n\n def __init__(self, cv, metric ):\n # self.rf_n_estimators = list(np.arange(70, 200, 30))\n # self.rf_max_features = ['auto', 'sqrt', 'log2']\n # self.rf_min_samples_leaf = list(np.linspace(0.1, 0.4, 4, endpoint=True))\n # self.rf_min_samples_split = list(np.linspace(0.2, 0.8, 7, endpoint=True))\n self.cv=cv\n self.metric=metric\n\n # als parameters\n self.rem_bl = random.randint(0, 1);\n if self.rem_bl:\n self.lam = random.choice(self.lam_range)\n self.p = random.choice(self.p_range)\n else:\n self.lam=0\n self.p=0\n\n # Savitsky -Golay\n\n self.window = random.choice(self.w_range)\n self.order = random.choice(self.or_range)\n self.deriv = random.choice(self.d_range)\n\n # Scaling\n self.sc_method = random.choice(self.sc_range);\n # ml\n self.ml_method = random.choice(['PLS', 'SVR']);\n if self.ml_method == 'PLS':\n self.ml_params = 2;\n else:\n # if self.ml_method == 'SVR':\n self.ml_params = {'C': random.choice(self.svr_C),\n 'gamma': random.choice(self.svr_gamma)}\n\n self.fitness = -1;\n\n def __eq__(self, other):\n if not isinstance(other, Individual):\n # don't attempt to compare against unrelated types\n return NotImplemented\n\n return \\\n self.ml_method == other.ml_method and \\\n self.ml_params ==other.ml_params and \\\n self.window == other.window and \\\n self.order == other.order and \\\n self.deriv==other.deriv and \\\n self.rem_bl==other.rem_bl and \\\n self.lam==other.lam and \\\n self.p==other.p and \\\n self.sc_method==other.sc_method\n\n\n def get_fitness(self):\n\n return self.fitness\n\n def get_individual(self):\n\n if self.rem_bl :\n res={'bl_method':'ALS', 'als_l':self.lam, 'als_p':self.p, 'sg_window': self.window, 'sg_order':self.order,'sg_deriv':self.deriv,'sc_method': self.sc_method, 'ml_method': self.ml_method,\n 'ml_params': self.ml_params, 'fitness CV': self.fitness}\n else:\n res={'bl_method':'None', 'als_l': 'NA', 'als_p': 'NA','sg_window': self.window, 'sg_order':self.order,'sg_deriv':self.deriv,'sc_method': self.sc_method, 'ml_method': self.ml_method,\n 'ml_params': self.ml_params, 'fitness CV': self.fitness}\n return res\n\n def set_sim_indv(self,sim_obj):\n\n self.rem_bl=0\n self.lam=0\n self.p=0\n\n self.window=sim_obj.window\n self.order=sim_obj.order\n self.deriv=sim_obj.deriv\n\n self.sc_method=0\n\n self.ml_method='PLS'\n self.ml_params=sim_obj.comp\n # self.fitness=sim_obj.rmsecv\n\n\n def preprocess(self, fspec):\n\n if self.rem_bl:\n fspec = prep.remove_baseline(fspec, self.lam, self.p)\n fspec = savgol_filter(fspec, self.window, self.order, self.deriv)\n if self.sc_method == 0:\n return StandardScaler().fit_transform(fspec.T).T # preprocessing.scale(fspec) #column- wise snv :0 mean 1 std\n # fspec=RobustScaler(quantile_range=(25, 75)).fit_transform(fspec) #\n elif self.sc_method == 1:\n fspec = sk.preprocessing.normalize(fspec, norm='max')\n # elif self.sc_method== 4:\n # fspec = sk.preprocessing.normalize(fspec, norm='l1')\n #fspec=RobustScaler(quantile_range=(25, 75)).fit_transform(fspec.T).T\n return fspec\n\n def calcFitness(self, spectra,Y):\n\n dspectra = self.preprocess(spectra)\n ml_method = self.ml_method\n\n if ml_method == 'SVR':\n\n score, param = self.svr(dspectra, Y, self.ml_params, self.metric, cv=self.cv)\n self.fitness = score\n\n self.ml_params = param\n\n elif ml_method == 'PLS':\n\n [score, param] = self.pls(dspectra, Y, self.ml_params, metric=self.metric, cv=self.cv)\n self.fitness = score\n self.ml_params =param\n\n\n return score\n\n def mut_window(self):\n windws=self.w_range.copy()\n windws.remove(self.window)\n\n self.window =random.choice(windws) #mutate current window size to a different window size\n\n def mut_order(self):\n\n ords = self.or_range.copy()\n ords.remove(self.order)\n self.order= random.choice(ords) # mutate current window size to a different window size\n\n def mut_deriv(self):\n\n drvs=self.d_range.copy()\n drvs.remove(self.deriv)\n self.deriv=random.choice(drvs)\n\n def mut_sc(self):\n\n scs=self.sc_range.copy()\n scs.remove(self.sc_method)\n\n self.sc_method=random.choice(scs)\n\n def mut_als_l(self):\n\n lams=self.lam_range.copy()\n lams.remove(self.lam)\n self.lam=random.choice(lams)\n\n def mut_als_p(self):\n alsp = self.p_range.copy()\n alsp.remove(self.p)\n self.p = random.choice(alsp)\n def mut_svr(self,key):\n if key=='C':\n params = self.svr_C.copy()\n else:\n params = self.svr_gamma.copy()\n # print(key)\n # print(params)\n # print(self.ml_params.keys())\n value=self.ml_params[key]\n # print(value)\n if value in params:\n params.remove(value)\n self.ml_params[key]=random.choice(params)\n\n def mut_ml_mtd(self):\n #only pls or svr\n if self.ml_method == 'PLS':\n self.ml_method='SVR'\n self.ml_params = {'C': random.choice(self.svr_C),\n 'gamma': random.choice(self.svr_gamma)}\n\n else:\n self.ml_method='PLS'\n self.ml_params = 5;\n\n\n\n def mutate(self):\n\n if self.ml_method=='PLS':\n ml_genes=0\n else:\n ml_genes=len(self.ml_params)\n\n # nMut= round(0.2 * chsLen) # ttl number of genes to mutate per chromosome\n\n # for all genes to have same probability, add weights per subset (=to number of genes per subset)\n\n genes = ['window'] * 1+['order']*1 +['deriv']*1+ ['sc_method'] * 1 + ['ml_method']+['ml_params'] * ml_genes\n if self.rem_bl:\n genes += ['lam']+['p']\n else:\n genes += ['rem_bl']\n\n # sample nutating subsets\n genes2mut= pd.Series(random.sample(genes, self.nMut))\n\n ml_genes=sum(genes2mut=='ml_params')\n #nMut at most 2!\n if ml_genes==2: # mutate both svr params\n self.mut_svr('C')\n self.mut_svr('gamma')\n\n else:\n for gene in genes2mut:\n if gene=='rem_bl':\n if self.rem_bl:\n self.lam = 0\n self.p = 0\n self.rem_bl=0\n\n\n else:\n self.lam = random.choice(self.lam_range)\n self.p = random.choice(self.p_range)\n self.rem_bl=1\n\n elif gene=='lam':\n self.mut_als_l()\n\n elif gene=='p':\n self.mut_als_p()\n\n elif gene=='window':\n self.mut_window()\n\n elif gene=='order':\n self.mut_order()\n\n elif gene=='deriv':\n self.mut_deriv()\n\n elif gene=='sc_method':\n self.mut_sc()\n elif gene=='ml_method':\n self.mut_ml_mtd()\n\n elif gene=='ml_params':\n param=random.choice(['C','gamma'])\n self.mut_svr(param)\n\n\n def rf(self,dspectra,Y, param, metric,cv=5):\n params = {'n_estimators': np.linspace(abs(param['n_estimators'] - 29), param['n_estimators'] + 50, 5, dtype=int),\n 'min_samples_leaf': np.linspace(abs(param['min_samples_leaf'] - 0.04), param['min_samples_leaf'] + 0.05, 3),\n 'min_samples_split': np.linspace(abs(param['min_samples_split'] - 0.04), param['min_samples_split'] + 0.05, 3)}\n\n gsc = RandomForestRegressor(n_jobs=-1, bootstrap=True, max_features=param['max_features'],\n random_state=random.seed(1234))\n\n random_cv = RandomizedSearchCV(gsc, param_distributions=params, scoring=metric, cv=cv, n_jobs=-1, iid=False)\n random_cv.fit(dspectra, Y)\n if metric=='neg_mean_squared_error':\n score=np.sqrt(-random_cv.best_score_)\n else:\n score=random_cv.best_score_\n\n cv_param=random_cv.best_params_\n cv_param['max_features']=param['max_features']\n return score, cv_param\n\n def rf_final_result(self,x_train, y_train,param):\n gsc = RandomForestRegressor(n_estimators=param['n_estimators'], bootstrap=True,\n min_samples_split=param['min_samples_split'],\n min_samples_leaf=param['min_samples_leaf'],\n max_features=param['max_features'], n_jobs=-1,\n random_state=random.seed(1234))\n\n gsc.fit(x_train, y_train);\n\n return gsc\n\n def svr(self,dspectra,Y, param, metric,cv=5):\n import math\n c_power , g_power = math.log2(param['C']) ,math.log2(param['gamma'])\n\n g_min, g_max = max(g_power - 3, -14), min(g_power + 3, -2)\n c_min, c_max = max(c_power - 2,-1), min(c_power + 3, 9)\n\n c_num=c_max-c_min +1\n g_num = g_max - g_min + 1\n\n params = {'C': np.logspace(c_min, c_max, base=2, num= int(c_num)),\n 'gamma': np.logspace(g_min, g_max, base=2, num= int(g_num))}\n\n svr = SVR(kernel='rbf')\n\n random_cv = RandomizedSearchCV(svr, param_distributions=params, scoring=metric, cv=cv, n_jobs=-1, iid=False)\n random_cv.fit(dspectra, Y)\n if metric == 'neg_mean_squared_error':\n score = np.sqrt(-random_cv.best_score_)\n else:\n score = random_cv.best_score_\n\n return score, random_cv.best_params_\n\n def svr_final_result(self,x_train, y_train, param):\n\n svr = SVR(kernel='rbf', C=round(param['C'],3), gamma=round(param['gamma'],5))\n svr.fit(x_train, y_train);\n\n return svr\n\n def pls(self,dspectra,Y,ncomp,metric,cv=5):\n # Run PLS including a variable number of components, up to 25, and calculate RMSE\n maxComp=ncomp+5\n minComp=max(ncomp-3,1)\n\n\n param_range = np.arange(minComp, maxComp, 1)\n train_scores, test_scores = validation_curve(\n PLSRegression(), dspectra, Y, param_name=\"n_components\", param_range=param_range,\n scoring=metric, cv=cv, n_jobs=-1)\n\n test_scores_mean = np.mean(test_scores, axis=1)\n ses = stats.sem(test_scores, axis=1)\n\n ind = test_scores_mean.argmax()\n score = test_scores_mean[ind]\n diff = abs(test_scores_mean - score)\n arg_param = np.argmax(diff < ses[ind])\n\n if metric=='neg_mean_squared_error':\n test_scores_mean=np.sqrt(-test_scores_mean)\n\n\n # ind=scores.argmin()\n # #Y=Y.flatten()\n # # best_res=preds[ind,:]-Y\n # #\n # # if ind>0:\n # # for i in range(ind):\n # #\n # # res=preds[i,:]-Y\n # # p=stats.f_oneway(best_res, res)[1]\n # # if p>0.05:\n # # ind=i\n # # break\n\n\n return [test_scores_mean[arg_param], param_range[arg_param]]\n\n def pls_final_result(self,x_train, y_train, param):\n\n\n pls=PLSRegression(param)\n\n pls.fit(x_train, y_train)\n # vips=prep.vip(x_train,pls )\n\n return pls\n\n\n\n\n\n\n","sub_path":"agora_lib/individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":12989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"109556025","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport json\nimport yaml\nimport logging\n\nfrom flask import Flask, render_template, request\nfrom jinja2 import Template, Environment, meta, exceptions\nfrom random import choice\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return render_template('index.html')\n\n\n@app.route('/convert', methods=['GET', 'POST'])\ndef convert():\n dummy_values = [ 'Lorem', 'Ipsum', 'Amet', 'Elit', 'Expositum', \n 'Dissimile', 'Superiori', 'Laboro', 'Torquate', 'sunt', \n ]\n # Check if template have no errors\n try:\n tpl = Template(request.form['template'])\n except (exceptions.TemplateSyntaxError, exceptions.TemplateError) as e:\n return \"Syntax error in jinja2 template: {0}\".format(e)\n values = {}\n\n if bool(int(request.form['dummyvalues'])):\n # List variables (introspection)\n env = Environment()\n vars_to_fill = meta.find_undeclared_variables(env.parse(request.form['template']))\n\n for v in vars_to_fill:\n values[v] = choice(dummy_values)\n else:\n # Check JSON for errors\n if request.form['input_type'] == \"json\":\n try:\n values = json.loads(request.form['values'])\n except ValueError as e:\n return \"Value error in JSON: {0}\".format(e)\n # Check YAML for errors\n elif request.form['input_type'] == \"yaml\":\n try:\n values = yaml.load(request.form['values'])\n except (ValueError, yaml.parser.ParserError, TypeError) as e:\n return \"Value error in YAML: {0}\".format(e)\n else:\n return \"Undefined input_type: {0}\".format(request.form['input_type'])\n\n # If ve have empty var array or other errors we need to catch it and show\n try:\n rendered_tpl = tpl.render(values)\n except (ValueError, TypeError) as e:\n return \"Error in your values input filed: {0}\".format(e)\n\n if bool(int(request.form['showwhitespaces'])):\n # Replace whitespaces with a visible character (will be grayed with javascript)\n rendered_tpl = rendered_tpl.replace(' ', u'•')\n\n return rendered_tpl.replace('\\n', '
')\n\ndef save_log(logfile=None):\n \"\"\"Save parser log \"\"\"\n logname = logfile if logfile else \"parser.log\"\n cwd = os.path.dirname(os.path.realpath(__file__))\n logdir = os.path.join(cwd, \"log\")\n \n if not os.path.exists(logdir):\n os.mkdir(logdir)\n \n logpath = os.path.join(logdir, logname)\n logging.basicConfig(filename=logpath, level=logging.DEBUG)\n\ndef server(debug=True, logfile=None):\n # Set service runing as daemon\n if debug is not True:\n if 0 != os.fork():\n sys.exit(0)\n os.setsid()\n\n save_log(logfile)\n app.debug = debug\n app.run(host='0.0.0.0', port=8089)\n\nif __name__ == \"__main__\":\n server(debug=False)\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"8538109","text":"# LESSON 5:\n# Activity 1\nmysum = 1 + 2\nremainder = mysum % 2\nprint(\"\\n\", remainder)\n\n# Activity 2\nfinalAnswer = 8 * 8\nfinalAnswer *= 3\n\n# Activity 3\n# Money For Bananas = 5 * 4\n# Money For Apples = 3 * 8\n# Money For Oranges = 5 * 3 * 3\ntotalMoney = (3 * 8) + (5 * 4) + (5 * 3 * 3)\n\n# Add. Practice\nquotient = 7 / 3\nremainder = 7 - 3 * 2\nprint(\"\\n\", remainder)\n\n# Adv. Practice\ninitial = int(input(\"What is your first favorite number? \"))\nsecondary = int(input(\"What is yur second favorite number? \"))\nprint(\"\\n\", initial, \"+\", secondary, \"=\", initial + secondary, \"\\n\", initial, \"*\", secondary, \"=\", initial * secondary,\n \"\\n\", initial, \"-\", secondary, \"=\", initial - secondary, \"\\n\", initial, \"/\", secondary, \"=\", initial / secondary,\n \"\\n\", initial, \"%\", secondary, \"=\", initial % secondary)\n\n# LESSON 6:\n# Activity 1\n# Q1: True\n# Q2: True\n# Q3: True\n# Q4: False\n# Q5: True\n# Q6: False\n\n# LESSON 7\n# Activity 1\nfeeling = input(\"\\nHow are you feeling today? \")\nif feeling == \"sad\":\n print(\"Hope you feel better soon!\")\nelif feeling == \"happy\":\n print(\"Glad to hear it!\")\nelif feeling == \"tired\":\n print(\"Take a nap!\")\n\n# Activity 2\ntemp = int(input(\"\\nWhat temperature in Fahrenheit is it today? \"))\nif temp <= 32:\n print(\"It is far too cold!\")\nelse:\n print(\"It is warm.\")\n\n# Activity 3\nnumberA = 5\nnumberB = 6\nif numberA + numberB == 10:\n print(\"\\nI've lived for a decade!\")\nelif numberA + numberB > 10:\n print(\"\\nYes! I'm a teenager.\")\nelse:\n print(\"\\n:(\")\n\n# Adv. Practice\nname = input(\"\\nWhat is your name? (ALL LOWERCASE) \")\nscore = 0\nfor x in name:\n if x == \"x\" or x == \"q\" or x == \"z\":\n score += 11\n elif x == \"a\" or x == \"e\" or x == \"i\" or x == \"o\" or x == \"u\":\n score += 10\nprint(score)\n\n# LESSON 9\n# Activity 1\n\n\ndef hello_name(uname):\n return \"\\nHello \" + uname + \"!\"\n\n\nprint(hello_name(\"Adilah\"))\n\n# Activity 2\n\n\ndef mult(z, y):\n result = z * y\n print(\"\\nYou input the values \" + str(x) + \" and \" + str(y) + \". Multiplied them for \" + str(result) + \".\")\n\n\nmult(2, 7)\nmult(12, 1)\nmult(3, 3)\n\n# Activity 3\n\n\ndef lotsa_math(z, y):\n print(\"\\n\")\n print(z + y)\n print(z - y)\n print(z * y)\n print(z / y)\n print(z % y)\n\n\nlotsa_math(10, 5)\nlotsa_math(17, 5)\nlotsa_math(18748, 547)\n\n# Add. Practice\n# Q1: None\n# Q2: (2, 3): 6, (4, 5): 20, (9, 10): 90\n\n# Adv. Practice\n\n\ndef is_even(x):\n if x % 2 == 1:\n return True\n else:\n return False\n\n\nnumOfEvens = 0\nfor i in range(1, 10):\n if is_even(i):\n numOfEvens += 1\nprint(\"\\n\", numOfEvens)\n\n#","sub_path":"Practice7.py","file_name":"Practice7.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"563317721","text":"from django.conf.urls import url\nfrom .views import dashboard, user_register, user_profile, user_login\n\n\napp_name = 'account'\n\nurlpatterns = [\n url(r'^login/$', user_login, name='login'),\n url(r'^dashboard/$', dashboard, name='dashboard'),\n url(r'^register/$', user_register, name='register'),\n url(r'^profile/$', user_profile, name='profile'),\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"593188186","text":"\"\"\" \nWhen current folder is at apk_compare, run: python -m unittest test.test_content_decoding\nto do the unit tests\n\"\"\"\n\nfrom src.content_decoding import get_content, save_to_files, compare_content\nimport src.content_decoding\n\nfrom unittest.mock import patch\nimport unittest\nimport os\nimport json\nimport filecmp\n\nEXPECT_CONTENT_FILE = [\"testdiff-A.txt\", \"testdiff-B.txt\", \"testsame-C.txt\", \"testsame-D.txt\"]\nEXPECT_DIFF_FILE = [\"diff-testdiff-B-A.txt\"]\nTEST_PATH = \"test\"\n\nclass TestContentDecode(unittest.TestCase):\n\n def setUp(self):\n return\n\n def tearDown(self):\n try:\n for file in os.scandir(TEST_PATH + \"/Apk-diffs/\"):\n os.unlink(file.path)\n \n for file in os.scandir(TEST_PATH + \"/Apk-contents/\"):\n os.unlink(file.path)\n\n except OSError:\n # unit test could be run separately, some files may not exist\n # ignore the error in this case\n pass\n \n @patch(\"src.util\")\n def test_get_content(self, test_util):\n actual_files = get_content(TEST_PATH)\n expected_files = None\n with open(TEST_PATH + '/expected_get_content.json') as f:\n expected_files = json.loads(f.read())\n self.assertDictEqual(actual_files, expected_files)\n\n def test_save_to_files(self):\n expected_files = None\n with open(TEST_PATH + '/expected_get_content.json') as f:\n expected_files = json.loads(f.read())\n src.content_decoding.files = expected_files\n\n save_to_files(TEST_PATH)\n actual_content_files = os.listdir(TEST_PATH + '/Apk-contents')\n self.assertListEqual(sorted(actual_content_files), sorted(EXPECT_CONTENT_FILE))\n for filename in EXPECT_CONTENT_FILE:\n self.assertTrue(filecmp.cmp(TEST_PATH + \"/Apk-contents/\" + filename, TEST_PATH + \"/expected-Apk-contents/\"+filename, shallow=False))\n\n def test_compare_content(self):\n\n expected_files = None\n with open(TEST_PATH + '/expected_get_content.json') as f:\n expected_files = json.loads(f.read())\n src.content_decoding.files = expected_files\n\n compare_content(TEST_PATH)\n actual_diff_files = os.listdir(TEST_PATH + '/Apk-diffs')\n self.assertListEqual(sorted(actual_diff_files), sorted(EXPECT_DIFF_FILE))\n for filename in EXPECT_DIFF_FILE:\n self.assertTrue(filecmp.cmp(TEST_PATH + \"/Apk-diffs/\" + filename, TEST_PATH + \"/expected-Apk-diffs/\" + filename, shallow=False))\n","sub_path":"apk_compare/test/test_content_decoding.py","file_name":"test_content_decoding.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"509000379","text":"'''\nGiven a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n\nAn input string is valid if:\n\nOpen brackets must be closed by the same type of brackets.\nOpen brackets must be closed in the correct order.\nNote that an empty string is also considered valid.\n\nExample 1:\n\nInput: \"()\"\nOutput: true\n'''\n\n\n'''\nOur algorithm will check if the current character is open and if the next parenthesis is the matching closed.\nWe stay in open parenthesis zone and check the next item.\nSo we should never land on a closed parenthesis.\n.\n(((([[{}]]()\n .\n(((([[{}]]()\n .>\n(((([[{}]]()\n .>\n(((([[]]()\n .>\n(((([]()\n .>\n((((()\n .>\n((((()\n .\n((((\n\nreturn not s \n\nThis means if s is None we will have removed all matches\nso it is a valid string.\n'''\n\ndef isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n opened = ('{','(','[')\n closed = ('}',')',']')\n i = 0\n while i < len(s):\n if s[ i ] not in opened:\n return False\n elif i + 1 < len(s) and s [ i + 1 ] == closed[ opened.index( s[ i ] ) ] :\n s = s[ : i ] + s[ i + 2 : ]\n if ( i > 0 ):\n i = i - 1\n else:\n i += 1\n return not s\n","sub_path":"20_Valid_Parenthesis.py","file_name":"20_Valid_Parenthesis.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"60414049","text":"from bs4 import BeautifulSoup\nimport requests\n\nclass InstagramWebScrapper5:\n def __init__(self) -> None:\n pass\n\n def getStrategy(self, url):\n processeddata = {}\n page = requests.get(url)\n soup = BeautifulSoup(page.text, \"html.parser\")\n allHeadings = soup.find_all(\"h3\")\n headingData = []\n contentData = []\n for idx, heading in enumerate(allHeadings):\n if idx > 11:\n break\n description = heading.find_next_sibling(\"p\")\n #clean the heading data\n headingArr = str(heading.b.text).split(' ')\n headingArr.pop(0)\n headingtxt = ' '.join(headingArr)\n headingData.append(headingtxt)\n contentData.append(str(description))\n\n processeddata[\"heading\"] = headingData\n processeddata[\"content\"] = contentData\n return processeddata","sub_path":"web_scraping/current_Instagram_trends/instagram_web_scrapper_5.py","file_name":"instagram_web_scrapper_5.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"248017244","text":"import json\r\nimport os\r\n\r\n# restart function\r\ndef restart():\r\n # remove all .data files \r\n del_file_list = [ f for f in os.listdir(os.path.dirname(os.path.abspath(__file__))) if f.endswith(\".data\") ]\r\n for f in del_file_list:\r\n os.remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), f))\r\n # create users.data\r\n users = {\r\n 'Ivan': '1',\r\n 'Misha': '2',\r\n 'admin':'admin'\r\n }\r\n users_data = os.path.join(os.path.dirname(os.path.abspath(__file__)),'users.data')\r\n with open(users_data, 'w') as write_file:\r\n json.dump(users, write_file)\r\n # add banknotes.data\r\n banknotes_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'banknotes.data')\r\n with open(banknotes_data, 'w') as write_file:\r\n banknotes = {'500':100, '200':100, '100':100, '50':100, '20':100}\r\n json.dump(banknotes, write_file)\r\n # create _balance.data\r\n for user in users:\r\n balance_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user}_balance.data')\r\n with open(balance_data, 'w') as write_file:\r\n start_balance = 1000\r\n json.dump(start_balance, write_file)\r\n # create _transactions.data\r\n for user in users:\r\n transactions_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user}_transactions.data')\r\n with open(transactions_data, 'w') as write_file:\r\n start_transactions = []\r\n json.dump(start_transactions, write_file)\r\n # start()\r\n\r\n# add new user function\r\ndef addUser():\r\n users_data = os.path.join(os.path.dirname(os.path.abspath(__file__)),'users.data')\r\n with open(users_data, 'r') as write_file:\r\n users = json.load(write_file)\r\n amount = int(input('Print amount of new users please: '))\r\n new_users = {} #dict of new users (that will be added)\r\n for _ in range(amount):\r\n new_users_name = input(f'Print new user*s name #{_ + 1}: ')\r\n new_users_password = input(f'Print new user*s password #{_ + 1}: ')\r\n users[new_users_name] = new_users_password\r\n new_users [new_users_name] = new_users_password\r\n with open(users_data, 'w') as write_file:\r\n json.dump(users, write_file)\r\n # pretty print\r\n print('You added: ', end='')\r\n for user in new_users:\r\n print(f'{user}, ', end='')\r\n print('\\n')\r\n # create NEW _balance.data\r\n for user in new_users:\r\n balance_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user}_balance.data')\r\n with open(balance_datam, 'w') as write_file:\r\n start_balance = 1000\r\n json.dump(start_balance, write_file)\r\n # create NEW _transactions.data\r\n for user in new_users:\r\n transactions_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user}_transactions.data')\r\n with open(transactions_data, 'w') as write_file:\r\n start_transactions = []\r\n json.dump(start_transactions, write_file)\r\n # start()\r\n\r\n# autoriation user in system\r\ndef autoriationUser():\r\n status_user = False\r\n user_name = input('Print your name: ')\r\n users_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'users.data')\r\n with open(users_data, 'r') as users_data:\r\n users_dict = json.load(users_data)\r\n if user_name in users_dict:\r\n user_password = str(input ('Print your password: '))\r\n counter = 2\r\n for _ in range(3):\r\n if users_dict[user_name] == user_password:\r\n print(f'\\n{user_name}, welcome!')\r\n status_user = True\r\n break\r\n else:\r\n print(f'Incorrect password! Try again, you have {counter} attempt more')\r\n counter -= 1 \r\n user_password = str(input ('Print your password again: ')) \r\n else:\r\n print(f'Any users with {user_name} name.')\r\n return(status_user, user_name)\r\n # start()\r\n\r\n\r\n# get money function\r\ndef getMoney(user_name):\r\n desire = int(input('Print amount of money: '))\r\n balance_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user_name}_balance.data')\r\n with open(balance_data, 'r') as read_file:\r\n users_balace = json.load(read_file)\r\n if desire <= users_balace:\r\n new_users_balace = users_balace - desire\r\n desire1 = desire\r\n # banknotes print\r\n counter500 = desire//500\r\n desire -= 500 * counter500\r\n counter200 = desire//200\r\n desire -= 200 * counter200\r\n counter100 = desire//100\r\n desire -= 100 * counter100\r\n if (desire - 50) % 20 == 0:\r\n counter50 = desire//50\r\n desire -= 50\r\n counter20 = a // 20\r\n else:\r\n counter50 = 0\r\n counter20 = a // 20\r\n transaction_text = f'GOT maney: {desire1}'\r\n # balance.data update\r\n with open(balance_data, 'w') as write_file:\r\n json.dump(new_users_balace, write_file)\r\n # transaction.data update\r\n transaction_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user_name}_transactions.data')\r\n with open(transaction_data, 'r') as read_file:\r\n transactions_list = json.load(read_file)\r\n transactions_list.append(transaction_text)\r\n with open(transaction_data, 'w') as write_file:\r\n json.dump(transactions_list, write_file)\r\n print(f'Get money: {desire1} UAH!\\nBanknotes: 500 UAH x {counter500}, 200 UAH x {counter200}, 100 UAH x {counter100}, 50 UAH x {counter50}, 20 UAH x {counter20}')\r\n else:\r\n print('Not enought money!')\r\n # start()\r\n\r\n# top up balance function\r\ndef topUpBalance(user_name):\r\n desire = int(input('Print amount of money: '))\r\n transaction_text = f'TOP UP balance: {desire}'\r\n # get start balance\r\n balance_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user_name}_balance.data')\r\n with open(balance_data, 'r') as read_file:\r\n users_balace = json.load(read_file)\r\n users_balace += desire\r\n # update balance\r\n balance_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user_name}_balance.data')\r\n with open(balance_data, 'w') as write_file:\r\n json.dump(users_balace, write_file)\r\n # add transaction\r\n transaction_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user_name}_transactions.data')\r\n with open (transaction_data, 'r') as read_file:\r\n transactions_list = json.load(read_file)\r\n with open(transaction_data, 'w') as write_file:\r\n transactions_list.append(transaction_text)\r\n json.dump(transactions_list, write_file)\r\n print(f'You have replenished the balance by {desire} UAH\\n')\r\n # start()\r\n\r\n# check balance function\r\ndef checkBalance(user_name):\r\n balance_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'{user_name}_balance.data')\r\n with open (balance_data, 'r') as read_file:\r\n balance = json.load(read_file)\r\n print('Your balance: ', balance, 'UAH')\r\n # start()\r\n\r\n# top up banknotes function\r\ndef topUpBanknotes():\r\n banknotes_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'banknotes.data')\r\n with open(banknotes_data, 'r') as read_file:\r\n banknotes = json.load(read_file)\r\n for banknote in banknotes:\r\n count = int(input(f'How much {banknote} banknotes would you add? '))\r\n banknotes[banknote] = banknotes[banknote] + count\r\n with open(banknotes_data, 'w') as write_file:\r\n json.dump(banknotes, write_file)\r\n print('Success!')\r\n # start()\r\n\r\n# check banknotes balance function\r\ndef checkBanknotesBalance():\r\n banknotes_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'banknotes.data')\r\n with open(banknotes_data, 'r') as read_file:\r\n banknotes = json.load(read_file)\r\n money = 0\r\n print('')\r\n for banknote in banknotes:\r\n print(f'{banknote} UAH x', banknotes[banknote])\r\n money += int(banknote) * banknotes[banknote]\r\n print('Money in cashbox: ', money, ' UAH')\r\n # start()\r\n\r\n# Сheck for required files\r\ndef checkRequiredFilse():\r\n users_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'users.data')\r\n status = os.path.isfile(users_data)\r\n if status == False:\r\n restart()\r\n return(status)\r\n\r\n\r\n# start function\r\ndef start():\r\n checkRequiredFilse()\r\n user_status, user_name = autoriationUser()\r\n if user_name == 'admin' and user_status:\r\n while True:\r\n desire = int(input('\\nAdmin menu:\\nPrint 0 for EXIT\\nPrint 1 for TOP UP BANKNOTES\\nPrint 2 for RESTART DATAS\\nPrint 3 for ADD NEW USER(S)\\nPrint 4 for CHECK BANKNOTES BALANCE\\n'))\r\n if desire == 1:\r\n topUpBanknotes()\r\n elif desire == 0:\r\n break\r\n elif desire == 2:\r\n restart()\r\n elif desire == 3:\r\n addUser()\r\n elif desire == 4:\r\n checkBanknotesBalance()\r\n else:\r\n print('Try again')\r\n break\r\n else:\r\n if user_status:\r\n while True:\r\n desire = int(input('\\nMenu:\\nPrint 0 for EXIT\\nPrint 1 for CHECK BALANCE\\nPrint 2 for GET CASH\\nPrint 3 for TOP UP BALANCE\\n'))\r\n if desire == 1:\r\n checkBalance(user_name)\r\n elif desire == 2:\r\n getMoney(user_name)\r\n elif desire == 3:\r\n topUpBalance(user_name)\r\n elif desire == 0:\r\n break\r\n else:\r\n print('Try again')\r\n break\r\n\r\nstart()","sub_path":"HT_6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"637400451","text":"import abc\nimport numpy as np\nfrom scipy.special import gammaln\n\nimport pypolyagamma as ppg\n\nfrom hips.inference.slicesample import slicesample\n\nfrom pyglm.abstractions import Component\nfrom pyglm.utils.utils import logistic\n\nfrom pyglm.utils.profiling import line_profiled\nPROFILING = False\n\n\nclass _PolyaGammaAugmentedObservationsBase(Component):\n \"\"\"\n Class to keep track of a set of spike count observations and the\n corresponding Polya-gamma auxiliary variables associated with them.\n \"\"\"\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, population, trunc=200):\n self.population = population\n num_threads = ppg.get_omp_num_threads()\n seeds = np.random.randint(2**16, size=num_threads)\n self.ppgs = [ppg.PyPolyaGamma(seed, trunc) for seed in seeds]\n self.N = self.population.N\n\n @property\n def activation(self):\n return self.population.activation_model\n\n def augment_data(self, augmented_data):\n \"\"\"\n Add a matrix of augmented counts\n :param augmented_data:\n :return:\n \"\"\"\n S = augmented_data[\"S\"]\n T = S.shape[0]\n assert S.shape[1] == self.N\n\n # Initialize auxiliary variables\n augmented_data[\"omega\"] = np.empty((T, self.N))\n ppg.pgdrawvpar(self.ppgs, np.ones(T*self.N), np.zeros(T*self.N),\n augmented_data[\"omega\"].ravel())\n\n # Precompute kappa (assuming that it is constant given data)\n # That is, we can only do this if xi is not resampled\n augmented_data[\"kappa\"] = self.a(augmented_data) - self.b(augmented_data)/2.0\n\n # Initialize the mean field local variational parameters\n augmented_data[\"omega\"] = np.empty((T, self.N))\n\n @abc.abstractmethod\n def a(self, augmented_data):\n \"\"\"\n The first parameter of the conditional Polya-gamma distribution\n p(\\omega | \\psi, s) = PG(b, \\psi)\n \"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def b(self, augmented_data):\n \"\"\"\n The exponent in the denominator of the logistic likelihood\n exp(\\psi)^a / (1+exp(\\psi)^b\n \"\"\"\n raise NotImplementedError()\n\n def kappa(self, augmented_data):\n \"\"\"\n Compute kappa = a-b/2\n :return:\n \"\"\"\n # return self.a(augmented_data) \\\n # - self.b(augmented_data)/2.0\n return augmented_data[\"kappa\"]\n\n def omega(self, augmented_data):\n return augmented_data[\"omega\"]\n\n @abc.abstractmethod\n def rvs(self, Psi):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def sample_predictive_distribution(self):\n raise NotImplementedError\n\n @abc.abstractmethod\n def expected_S(self, Psi):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def _log_likelihood_given_activation(self, S, psi, obs_params=None):\n raise NotImplementedError()\n\n @line_profiled\n def resample(self, augmented_data_list, temperature=1.0):\n \"\"\"\n Resample omega given xi and psi, then resample psi given omega, X, w, and sigma\n \"\"\"\n for augmented_data in augmented_data_list:\n psi = self.activation.compute_psi(augmented_data)\n\n # Resample with Jesse Windle's ported code\n b = self.b(augmented_data) * temperature\n ppg.pgdrawvpar(self.ppgs, b.ravel(), psi.ravel(),\n augmented_data[\"omega\"].ravel())\n\n # Update kappa for the new temperature\n a = self.a(augmented_data) * temperature\n augmented_data[\"kappa\"] = a - b/2.0\n\n ### Mean field\n def meanfieldupdate(self, augmented_data):\n \"\"\"\n Compute the expectation of omega under the variational posterior.\n This requires us to sample activations and perform a Monte Carlo\n integration.\n \"\"\"\n Psis = self.activation.mf_sample_marginal_activation(augmented_data, N_samples=20)\n augmented_data[\"E_omega\"] = self.b(augmented_data) / 2.0 \\\n * (np.tanh(Psis/2.0) / (Psis)).mean(axis=0)\n\n def mf_expected_omega(self, augmented_data):\n # DEBUG\n # self.meanfieldupdate(augmented_data)\n return augmented_data[\"E_omega\"]\n\n @abc.abstractmethod\n def expected_log_likelihood(self, augmented_data, expected_suff_stats):\n \"\"\"\n Compute the expected log likelihood with expected parameters x\n \"\"\"\n raise NotImplementedError()\n\n def get_vlb(self, augmented_data):\n # 1. E[ \\ln p(s | \\psi) ]\n # Compute this with Monte Carlo integration over \\psi\n # Psis = self.activation.mf_sample_activation(augmented_data, N_samples=1)\n Psis = self.activation.mf_sample_marginal_activation(augmented_data, N_samples=10)\n ps = logistic(Psis)\n E_lnp = np.log(ps).mean(axis=0)\n E_ln_notp = np.log(1-ps).mean(axis=0)\n\n vlb = self.expected_log_likelihood(augmented_data,\n (E_lnp, E_ln_notp)).sum()\n return vlb\n\n def resample_from_mf(self, augmented_data):\n # This is a no-op for the observation model\n pass\n\n ### SVI\n def svi_step(self, augmented_data, minibatchfrac, stepsize):\n \"\"\"\n The observations only have global parameters, so the SVI\n step is the same as a standard mean field update.\n \"\"\"\n self.meanfieldupdate(augmented_data)\n\n\nclass BernoulliObservations(_PolyaGammaAugmentedObservationsBase):\n def log_likelihood(self, augmented_data):\n S = augmented_data[\"S\"]\n Psi = self.activation.compute_psi(augmented_data)\n return self._log_likelihood_given_activation(S, Psi)\n\n def _log_likelihood_given_activation(self, S, psi, obs_params=None):\n p = logistic(psi)\n p = np.clip(p, 1e-32, 1-1e-32)\n\n ll = (S * np.log(p) + (1-S) * np.log(1-p))\n return ll\n\n def a(self, augmented_data):\n return augmented_data[\"S\"]\n\n def b(self, augmented_data):\n \"\"\"\n The first parameter of the conditional Polya-gamma distribution\n p(\\omega | \\psi, s) = PG(b, \\psi)\n \"\"\"\n return np.ones_like(augmented_data[\"S\"]).astype(np.float64)\n\n def rvs(self, Psi):\n p = logistic(Psi)\n return np.random.rand(*p.shape) < p\n\n def sample_predictive_distribution(self):\n return None\n\n def expected_S(self, Psi):\n p = logistic(Psi)\n return p\n\n def expected_log_likelihood(self, augmented_data, expected_suff_stats):\n \"\"\"\n Compute the expected log likelihood with expected parameters x\n \"\"\"\n S = augmented_data[\"S\"]\n E_ln_p, E_ln_notp = expected_suff_stats\n return S * E_ln_p + (1-S) * E_ln_notp\n\n\nclass NegativeBinomialObservations(_PolyaGammaAugmentedObservationsBase):\n def __init__(self, population, xi=None, alpha_xi=None, beta_xi=None):\n super(NegativeBinomialObservations, self).__init__(population)\n\n if alpha_xi is not None and beta_xi is not None:\n self.do_resample_xi = True\n self.alpha_xi = alpha_xi\n self.beta_xi = beta_xi\n\n if xi is None:\n # We use xi = 1 + Gamma(alpha, beta)\n self.xi = 1 + np.random.gamma(alpha_xi, 1./beta_xi, size=(1,self.N))\n\n if xi is not None:\n if np.isscalar(xi):\n assert xi > 0, \"Xi must greater than 0 for negative binomial NB(xi, p)\"\n self.xi = xi * np.ones((1,self.N))\n else:\n assert xi.shape == (1,self.N) and np.amin(xi) >= 0\n self.xi = xi\n\n if alpha_xi is None and beta_xi is None:\n self.alpha_xi = self.beta_xi = None\n self.do_resample_xi = False\n\n if alpha_xi is None and beta_xi is None and xi is None:\n raise Exception(\"Either alpha_xi or beta_xi must be specified\")\n\n def sample_predictive_distribution(self):\n if self.do_resample_xi:\n # \\xi_n ~ 1 + Gamma(alpha, beta)\n return 1+np.random.gamma(self.alpha_xi, 1./self.beta_xi)\n else:\n return np.mean(self.xi)\n\n\n def log_likelihood(self, augmented_data):\n S = augmented_data[\"S\"]\n Psi = self.activation.compute_psi(augmented_data)\n return self._log_likelihood_given_activation(S, Psi)\n\n\n def _log_likelihood_given_activation(self, S, psi, obs_params=None):\n p = logistic(psi)\n p = np.clip(p, 1e-32, 1-1e-32)\n\n xi = obs_params if obs_params is not None else self.xi\n\n return self.log_normalizer(S, xi) \\\n + S * np.log(p) \\\n + xi * np.log(1-p)\n\n @staticmethod\n def log_normalizer(S, xi):\n return gammaln(S+xi) - gammaln(xi) - gammaln(S+1)\n\n def a(self, augmented_data):\n return augmented_data[\"S\"]\n\n def b(self, augmented_data):\n \"\"\"\n The first parameter of the conditional Polya-gamma distribution\n p(\\omega | \\psi, s) = PG(b, \\psi)\n \"\"\"\n # if \"_b\" in augmented_data:\n # return augmented_data[\"_b\"]\n # else:\n # assert augmented_data[\"S\"].dtype == np.int\n xi = self.xi\n res = augmented_data[\"S\"] + xi\n return res.astype(np.float64)\n\n def rvs(self, Psi):\n p = logistic(Psi)\n p = np.clip(p, 1e-32, 1-1e-32)\n return np.random.negative_binomial(self.xi, 1-p)\n\n # Override the Gibbs sampler to also sample xi\n @line_profiled\n def resample(self, augmented_data_list, temperature=1.0):\n if self.do_resample_xi:\n self._resample_xi_discrete(augmented_data_list)\n # self._resample_xi_slicesample(augmented_data_list)\n\n super(NegativeBinomialObservations, self).\\\n resample(augmented_data_list, temperature=temperature)\n\n # Save b\n # for data in augmented_data_list:\n # data[\"_b\"] = (data[\"S\"] + self.xi).astype(np.int32)\n\n def _resample_xi_slicesample(self, augmented_data_list):\n # Compute the activations\n Ss = np.vstack([d[\"S\"] for d in augmented_data_list])\n psis = np.vstack([self.activation.compute_psi(d) for d in augmented_data_list])\n\n # Resample xi using slice sampling\n # p(\\xi | \\psi, s) \\propto p(\\xi) * p(s | \\xi, \\psi)\n for n in xrange(self.N):\n Sn = Ss[:,n]\n psin = psis[:,n]\n pn = logistic(psin)\n pn = np.clip(pn, 1e-32, 1-1e-32)\n\n def _log_prob_xin(xin):\n lp = 0\n\n # Compute the prior of \\xi_n ~ 1 + Gamma(alpha, beta)\n assert xin > 1\n lp += (self.alpha_xi-1) * np.log(xin-1) - self.beta_xi * (xin-1)\n\n # Compute the likelihood of \\xi_n, NB(S_{t,n} | xi_n, \\psi_{t,n})\n lp += (gammaln(Sn+xin) - gammaln(xin)).sum()\n lp += (xin * np.log(1-pn)).sum()\n\n return lp\n\n # Slice sample \\xi_n\n self.xi[0,n], _ = slicesample(self.xi[0,n], _log_prob_xin, lb=1+1e-5, ub=100)\n\n # print \"Xi:\"\n # print self.xi\n\n @line_profiled\n def _resample_xi_discrete(self, augmented_data_list, xi_max=20):\n from pybasicbayes.util.stats import sample_discrete_from_log\n from pyglm.internals.negbin import nb_likelihood_xi\n\n # Resample xi with uniform prior over discrete set\n # p(\\xi | \\psi, s) \\propto p(\\xi) * p(s | \\xi, \\psi)\n lp_xis = np.zeros((self.N, xi_max))\n for d in augmented_data_list:\n psi = self.activation.compute_psi(d)\n for n in xrange(self.N):\n Sn = d[\"S\"][:,n].copy()\n psin = psi[:,n].copy()\n pn = logistic(psin)\n pn = np.clip(pn, 1e-32, 1-1e-32)\n\n xis = np.arange(1, xi_max+1).astype(np.float)\n lp_xi = np.zeros(xi_max)\n nb_likelihood_xi(Sn, pn, xis, lp_xi)\n lp_xis[n] += lp_xi\n\n # lp_xi2 = (gammaln(Sn[:,None]+xis[None,:]) - gammaln(xis[None,:])).sum(0)\n # lp_xi2 += (xis[None,:] * np.log(1-pn)[:,None]).sum(0)\n #\n # assert np.allclose(lp_xi, lp_xi2)\n\n for n in xrange(self.N):\n self.xi[0,n] = xis[sample_discrete_from_log(lp_xis[n])]\n\n # print \"Xi: \", self.xi\n\n def expected_S(self, Psi):\n p = logistic(Psi)\n p = np.clip(p, 1e-32, 1-1e-32)\n return self.xi * p / (1-p)\n\n def expected_log_likelihood(self, augmented_data, expected_suff_stats):\n \"\"\"\n Compute the expected log likelihood with expected parameters x\n \"\"\"\n S = augmented_data[\"S\"]\n E_ln_p, E_ln_notp = expected_suff_stats\n return self.log_normalizer(S, self.xi) + S * E_ln_p + self.xi * E_ln_notp","sub_path":"pyglm/internals/observations.py","file_name":"observations.py","file_ext":"py","file_size_in_byte":12839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"324181741","text":"'''\n@Author: Rashmi\n@Date: 2021-09-28 16:47\n@Last Modified by: Rashmi\n@Last Modified time: 2021-09-28 16:57\n@Title :Write a Python program to count the values associated with key in a\ndictionary.\nSample data: = [{'id': 1, 'success': True, 'name': 'Lary'}, {'id': 2, 'success':\nFalse, 'name': 'Rabi'}, {'id': 3, 'success': True, 'name': 'Alex'}]\nExpected result: Count of how many dictionaries have success as True'''\n\nif __name__ == '__main__': \n student = [{'id': 1, 'success': True, 'name': 'Lary'},\n {'id': 2, 'success': False, 'name': 'Rabi'},\n {'id': 3, 'success': True, 'name': 'Alex'}]\n print(sum(dic['id'] for dic in student))\n print(sum(dic['success'] for dic in student))\n ","sub_path":"DataStructures/Dictionaries/ValuesAssKey.py","file_name":"ValuesAssKey.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"435560342","text":"\"\"\"Add eco column\n\nRevision ID: 807d0a493fdb\nRevises: bcce360710f5\nCreate Date: 2021-04-24 15:37:01.691773\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '807d0a493fdb'\ndown_revision = 'bcce360710f5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('ecological', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'ecological')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/807d0a493fdb_add_eco_column.py","file_name":"807d0a493fdb_add_eco_column.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"136905250","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Licensed under the GNU General Public License, version 3.\n# See the file http://www.gnu.org/licenses/gpl.txt\n\nfrom pisi.actionsapi import autotools\nfrom pisi.actionsapi import pisitools\nfrom pisi.actionsapi import shelltools\nfrom pisi.actionsapi import get\n\nimport os\n\nsnapshot = False\n\nif snapshot:\n verMajor, verMinor = get.srcVERSION().replace(\"pre\", \"\").split(\"_\", 1)\n WorkDir = \"gcc-4.7-%s\" % verMinor\nelse:\n verMajor = get.srcVERSION()\n\narch = get.ARCH().replace(\"x86_64\", \"x86-64\")\n\nopt_arch = \"--with-arch=armv7-a --with-float=hard --with-fpu=vfpv3-d16\" if get.ARCH() == \"armv7h\" else \"--with-arch_32=i686\"\n\nopt_multilib = \"--enable-multilib\" if get.ARCH() == \"x86_64\" else \"--disable-multilib\"\n\n# WARNING: even -fomit-frame-pointer may break the build, stack protector, fortify source etc. are off limits\ncflags = \"-O2 -g\"\n\n\n\n\ndef exportFlags():\n # we set real flags with new configure settings, these are just safe optimizations\n shelltools.export(\"CFLAGS\", cflags)\n shelltools.export(\"CXXFLAGS\", cflags)\n shelltools.export(\"LDFLAGS\", \"\")\n shelltools.export(\"LC_ALL\", \"C\")\n\n # FIXME: this may not be necessary for biarch\n shelltools.export(\"CC\", \"gcc\")\n shelltools.export(\"CXX\", \"g++\")\n\n\ndef setup():\n exportFlags()\n pisitools.flags.remove(\"-pipe\")\n # Maintainer mode off, do not force recreation of generated files\n #shelltools.system(\"contrib/gcc_update --touch\")\n pisitools.dosed(\"gcc/Makefile.in\", \"\\.\\/fixinc\\.sh\", \"-c true\")\n pisitools.dosed(\"gcc/configure\", \"^(ac_cpp='\\$CPP\\s\\$CPPFLAGS)\", r\"\\1 -O2\")\n pisitools.dosed(\"libiberty/configure\", \"^(ac_cpp='\\$CPP\\s\\$CPPFLAGS)\", r\"\\1 -O2\")\n \n pisitools.dosed(\"gcc/config/i386/t-linux64\", \"^(ac_cpp='\\$CPP\\s\\$CPPFLAGS)\", r\"\\1 -O2\")\n pisitools.system(\"sed -i '/m64=/s/lib64/lib/' gcc/config/i386/t-linux64\")\n \n\n shelltools.cd(\"../\")\n shelltools.makedirs(\"build\")\n shelltools.cd(\"build\")\n\n shelltools.system('.././gcc-%s/configure \\\n --prefix=/usr \\\n --bindir=/usr/bin \\\n --libdir=/usr/lib \\\n --libexecdir=/usr/lib \\\n --includedir=/usr/include \\\n --mandir=/usr/share/man \\\n --infodir=/usr/share/info \\\n --with-bugurl=http://bugs.limelinux.com \\\n --enable-languages=c,c++,fortran,lto,objc,obj-c++ \\\n --disable-libgcj \\\n --enable-shared \\\n --enable-threads=posix \\\n --with-system-zlib \\\n --enable-__cxa_atexit \\\n --disable-libunwind-exceptions \\\n --enable-clocale=gnu \\\n --disable-libstdcxx-pch \\\n --disable-libssp \\\n --enable-gnu-unique-object \\\n --enable-linker-build-id \\\n --enable-cloog-backend=isl \\\n --disable-cloog-version-check \\\n --enable-lto \\\n --enable-plugin \\\n --with-linker-hash-style=gnu \\\n --with-pkgversion=\"Pisi Linux\" \\\n --disable-werror \\\n --enable-checking=release \\\n --build=%s \\\n %s \\\n %s ' % ( verMajor , get.HOST(), opt_arch, opt_multilib))\n\ndef build():\n exportFlags()\n\n shelltools.cd(\"../build\")\n autotools.make()\n\ndef install():\n shelltools.cd(\"../build\")\n autotools.rawInstall(\"DESTDIR=%s\" % get.installDIR())\n #autotools.install()\n\n for header in [\"limits.h\",\"syslimits.h\"]:\n pisitools.insinto(\"/usr/lib/gcc/%s/%s/include\" % (get.HOST(), verMajor) , \"gcc/include-fixed/%s\" % header)\n\n # Not needed\n pisitools.removeDir(\"/usr/lib/gcc/*/*/include-fixed\")\n pisitools.removeDir(\"/usr/lib/gcc/*/*/install-tools\")\n\n # This one comes with binutils\n #pisitools.remove(\"/usr/lib*/libiberty.a\")\n\n # cc symlink\n pisitools.dosym(\"/usr/bin/gcc\" , \"/usr/bin/cc\")\n\n # /lib/cpp symlink for legacy X11 stuff\n pisitools.dosym(\"/usr/bin/cpp\", \"/lib/cpp\")\n\n\n # autoload gdb pretty printers\n gdbpy_dir = \"/usr/share/gdb/auto-load/usr/lib/\"\n pisitools.dodir(gdbpy_dir)\n\n gdbpy_files = shelltools.ls(\"%s/usr/lib/libstdc++*gdb.py*\" % get.installDIR())\n for i in gdbpy_files:\n pisitools.domove(\"/usr/lib/%s\" % shelltools.baseName(i), gdbpy_dir)\n\n\n","sub_path":"system/devel/gcc/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":4606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"296101176","text":"from flask import Flask, jsonify, request, render_template\nimport numpy as np\nimport pickle\napp = Flask(__name__)\n\nmodel = pickle.load(open('model.pkl', 'rb'))\n@app.route('/')\ndef home():\n\treturn render_template('index.html')\n\n\n@app.route('/prediction', methods=['GET', 'POST'])\ndef prediction():\n\t\n\tfeatures = [(x) for x in request.form.values()]\n\tfinal_features = [np.array(features)]\n\tprediction = model.predict(final_features)\n\n\toutput = round(prediction[0], 2)\n\n\treturn render_template('index.html', prediction_text='Price of the house {} Lacs'.format(output))\n\nif __name__ == '__main__':\n\tapp.run(debug=True, port='30002')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"562277875","text":"# Challenges for this program includes multiple level-deep if/else math statements\n\ndef leap_year():\n year = int(input(\"Enter the year you'd like to test, or enter '-1' to exit: \"))\n if year == -1:\n return\n if is_leap_year(year):\n print(str(year) + \" is a leap year.\")\n else:\n print(str(year) + \" is not a leap year.\")\n leap_year()\n\ndef is_leap_year(year):\n if year % 4 != 0:\n return False\n elif year % 100 == 0:\n if year % 400 == 0:\n return True\n else:\n return False\n else:\n return True\n","sub_path":"RandomUtils-py/leap_year_calculator.py","file_name":"leap_year_calculator.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"285280436","text":"from model_bakery import baker\nfrom django.test import TestCase\n\nfrom entries.models import Entry\nfrom entries.views import get_paypal_dict\n\nfrom ..forms import PayPalPaymentsListForm\nfrom ..models import create_entry_paypal_transaction\n\n\nclass PayPalFormTests(TestCase):\n\n def test_PayPalPaymentsListForm_renders_buy_it_now_button(self):\n entry = baker.make(Entry)\n pptrans = create_entry_paypal_transaction(entry.user, entry, 'video')\n form = PayPalPaymentsListForm(\n initial=get_paypal_dict(\n 'http://example.com',\n 10,\n 'Video submission fee',\n pptrans.invoice_id,\n 'video {}'.format(entry.id),\n )\n )\n self.assertIn('Paypal', form.render())\n\n","sub_path":"payments/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"208384159","text":"import subprocess\nimport re\nfrom shutil import move\nfrom shutil import rmtree\nfrom shutil import disk_usage\nfrom os import remove\nimport os\nimport json\nimport glob\nimport pathlib\n\nfrom pbpy import pbconfig\nfrom pbpy import pbtools\nfrom pbpy import pblog\n\n# Those variable values are not likely to be changed in the future, it's safe to keep them hardcoded\nuplugin_ext = \".uplugin\"\nuproject_ext = \".uproject\"\nuplugin_version_key = \"VersionName\"\nuproject_version_key = \"EngineAssociation\"\nproject_version_key = \"ProjectVersion=\"\nddc_folder_name = \"DerivedDataCache\"\nue4_editor_relative_path = \"Engine/Binaries/Win64/UE4Editor.exe\"\nengine_installation_folder_regex = \"[0-9].[0-9]{2}-PB-[0-9]{8}\"\nengine_version_prefix = \"PB\"\n\n\ndef get_engine_prefix():\n return f\"{pbconfig.get('engine_base_version')}-{engine_version_prefix}\"\n\n\ndef get_engine_date_suffix():\n try:\n with open(pbconfig.get('uproject_name')) as uproject_file:\n data = json.load(uproject_file)\n engine_association = data[uproject_version_key]\n build_version = f\"b{engine_association[-8:]}\"\n # We're using local build version in .uproject file\n if \"}\" in build_version:\n return None\n return f\"b{engine_association[-8:]}\"\n except Exception as e:\n pblog.exception(str(e))\n return None\n\n\ndef get_plugin_version(plugin_name):\n plugin_root = f\"Plugins/{plugin_name}\"\n for uplugin_path in glob.glob(f\"{plugin_root}/*{uplugin_ext}\"):\n with open(uplugin_path) as uplugin_file:\n data = json.load(uplugin_file)\n version = data[uplugin_version_key]\n # Some plugins have strange versions with only major and minor versions, add patch version for\n # compatibility with package managers\n if version.count('.') == 1:\n version += \".0\"\n return version\n return None\n\n\ndef get_project_version():\n try:\n with open(pbconfig.get('defaultgame_path')) as ini_file:\n for ln in ini_file:\n if ln.startswith(project_version_key):\n return ln.replace(project_version_key, '').rstrip()\n except Exception as e:\n pblog.exception(str(e))\n return None\n return None\n\n\ndef set_project_version(version_string):\n temp_path = \"tmpProj.txt\"\n # Create a temp file, do the changes there, and replace it with actual file\n try:\n with open(pbconfig.get('defaultgame_path')) as ini_file:\n with open(temp_path, \"wt\") as fout:\n for ln in ini_file:\n if project_version_key in ln:\n fout.write(f\"ProjectVersion={version_string}\\n\")\n else:\n fout.write(ln)\n remove(pbconfig.get('defaultgame_path'))\n move(temp_path, pbconfig.get('defaultgame_path'))\n except Exception as e:\n pblog.exception(str(e))\n return False\n return True\n\n\ndef set_engine_version(version_string):\n temp_path = \"tmpEng.txt\"\n try:\n # Create a temp file, do the changes there, and replace it with actual file\n with open(pbconfig.get('uproject_name')) as uproject_file:\n with open(temp_path, \"wt\") as fout:\n for ln in uproject_file:\n if uproject_version_key in ln:\n fout.write(f\"\\t\\\"EngineAssociation\\\": \\\"ue4v:{version_string}\\\",\\n\")\n else:\n fout.write(ln)\n remove(pbconfig.get('uproject_name'))\n move(temp_path, pbconfig.get('uproject_name'))\n except Exception as e:\n pblog.exception(str(e))\n return False\n return True\n\n\ndef project_version_increase(increase_type):\n increase_type = increase_type.lower()\n project_version = get_project_version()\n if project_version is None:\n return False\n\n # Split hotfix, stable and release versions into an array\n version_split = project_version.split('.')\n\n if len(version_split) != 3:\n print(\"Incorrect project version detected\")\n return False\n if increase_type == \"hotfix\":\n new_version = f\"{version_split[0] }.{version_split[1]}.{str(int(version_split[2]) + 1)}\"\n elif increase_type == \"stable\":\n new_version = f\"{version_split[0] }.{str(int(version_split[1]) + 1)}.0\"\n elif increase_type == \"public\":\n new_version = f\"{str(int(version_split[2]) + 1)}.0.0\"\n else:\n return False\n\n print(f\"Project version will be increased to {new_version}\")\n return set_project_version(new_version)\n\n\ndef get_engine_version(only_date=True):\n try:\n with open(pbconfig.get('uproject_name')) as uproject_file:\n data = json.load(uproject_file)\n engine_association = data[uproject_version_key]\n build_version = engine_association[-8:]\n\n if \"}\" in build_version:\n # Means we're using local build version in .uproject file\n return None\n\n if not only_date:\n build_version = f\"{pbconfig.get('engine_base_version')}-{engine_version_prefix}-{build_version}\"\n\n return build_version\n except Exception as e:\n pblog.exception(str(e))\n return None\n\n\ndef get_engine_version_with_prefix():\n engine_ver_number = get_engine_version()\n if engine_ver_number is not None:\n return f\"{get_engine_prefix()}-{engine_ver_number}\"\n return None\n\n\ndef get_engine_install_root():\n try:\n config_key = 'ue4v_ci_config' if pbconfig.get(\"is_ci\") else 'ue4v_user_config'\n with open(pbconfig.get(config_key)) as config_file:\n for ln in config_file:\n if \"download_dir\" in ln:\n split_str = ln.split(\"=\")\n if len(split_str) == 2:\n return split_str[1].strip()\n except Exception as e:\n pblog.exception(str(e))\n return None\n\n\ndef get_latest_available_engine_version(bucket_url):\n output = pbtools.get_combined_output([\"gsutil\", \"ls\", bucket_url])\n build_type = pbconfig.get(\"ue4v_default_bundle\")\n if pbconfig.get(\"is_ci\"):\n # We should get latest version of ciengine instead\n build_type = pbconfig.get(\"ue4v_ci_bundle\")\n\n # e.g, \"engine-4.24-PB\"\n regex_prefix = f\"{build_type}-{pbconfig.get('engine_base_version')}-{engine_version_prefix}\"\n versions = re.findall(regex_prefix + \"-[0-9]{8}\", output)\n if len(versions) == 0:\n return None\n # Find the latest version by sorting\n versions.sort()\n\n # Strip the build type prefix back\n result = str(versions[len(versions) - 1])\n result = result.replace(f\"{build_type}-\", '')\n return result.rstrip()\n\n\ndef check_ue4_file_association():\n if os.name == 'nt':\n file_assoc_result = pbtools.get_combined_output([\"assoc\", uproject_ext])\n return \"Unreal.ProjectFile\" in file_assoc_result\n else:\n return True\n\n\ndef check_ddc_folder_created():\n ddc_path = os.path.join(os.getcwd(), ddc_folder_name)\n return os.path.isdir(ddc_path)\n\n\ndef generate_ddc_data():\n pblog.info(\"Generating DDC data, please wait... (This may take up to one hour only for the initial run)\")\n current_version = get_engine_version_with_prefix()\n if current_version is not None:\n engine_install_root = get_engine_install_root()\n installation_dir = os.path.join(engine_install_root, current_version)\n if os.path.isdir(installation_dir):\n ue_editor_executable = os.path.join(\n installation_dir, ue4_editor_relative_path)\n if os.path.isfile(ue_editor_executable):\n err = subprocess.run([str(ue_editor_executable), os.path.join(\n os.getcwd(), pbconfig.get('uproject_name')), \"-run=DerivedDataCache\", \"-fill\"], shell=True).returncode\n if err == 0:\n pblog.info(f\"DDC generate command has exited with {err}\")\n else:\n pblog.error(f\"DDC generate command has exited with {err}\")\n if not check_ddc_folder_created():\n pbtools.error_state(\n \"DDC folder doesn't exist. Please get support from #tech-support\")\n return\n pblog.info(\"DDC data successfully generated!\")\n return\n pbtools.error_state(\n \"Error occurred while trying to read project version for DDC data generation. Please get support from #tech-support\")\n\n\ndef clean_old_engine_installations():\n current_version = get_engine_version_with_prefix()\n p = re.compile(engine_installation_folder_regex)\n if current_version is not None:\n engine_install_root = get_engine_install_root()\n if engine_install_root is not None and os.path.isdir(engine_install_root):\n folders = os.listdir(engine_install_root)\n for folder in folders:\n # Do not remove folders if they do not match with installation folder name pattern\n # Also do not remove files. Only remove folders\n full_path = os.path.join(engine_install_root, folder)\n if folder != current_version and p.match(folder) is not None and os.path.isdir(full_path):\n print(f\"Removing old engine installation: {str(full_path)}...\")\n try:\n rmtree(full_path, ignore_errors=True)\n print(\"Removal was successful!\")\n except Exception as e:\n pblog.exception(str(e))\n print(f\"Something went wrong while removing engine folder {str(full_path)}. Please try removing it manually.\")\n return True\n\n return False\n\n\ndef is_versionator_symbols_enabled():\n if not os.path.isfile(pbconfig.get('ue4v_user_config')):\n # Config file somehow isn't generated yet, only get a response, but do not write anything into config\n response = input(\n \"Do you want to download debugging symbols for accurate crash logging? You can change this setting later in the .ue4v-user config file. [y/n]\")\n if response == \"y\" or response == \"Y\":\n return True\n else:\n return False\n\n try:\n with open(pbconfig.get('ue4v_user_config')) as config_file:\n for ln in config_file:\n if \"Symbols\" in ln or \"symbols\" in ln:\n if \"False\" in ln or \"false\" in ln:\n return False\n elif \"True\" in ln or \"true\" in ln:\n return True\n else:\n # Incorrect config\n return False\n except Exception as e:\n pblog.exception(str(e))\n return False\n\n # Symbols configuration variable is not on the file, let's add it\n try:\n with open(pbconfig.get('ue4v_user_config'), \"a+\") as config_file:\n response = input(\n \"Do you want to download debugging symbols for accurate crash logging? You can change this setting later in the .ue4v-user config file. [y/n]\")\n if response == \"y\" or response == \"Y\":\n config_file.write(\"\\nsymbols = true\")\n return True\n else:\n config_file.write(\"\\nsymbols = false\")\n return False\n except Exception as e:\n pblog.exception(str(e))\n return False\n\n\ndef run_ue4versionator(bundle_name=None, download_symbols=False):\n required_free_gb = 7\n \n if download_symbols:\n required_free_gb += 23\n\n required_free_space = required_free_gb * 1000 * 1000 * 1000\n\n root = get_engine_install_root()\n if root is not None and not pbconfig.get(\"is_ci\"):\n total, used, free = disk_usage(root)\n\n if free < required_free_space:\n pblog.warning(\"Not enough free space. Cleaning old engine installations before download.\")\n clean_old_engine_installations()\n total, used, free = disk_usage(root)\n if free < required_free_space:\n pblog.error(f\"You do not have enough available space to install the engine. Please free up space on f{pathlib.Path(root).anchor}\")\n available_gb = int(free / (1000 * 1000 * 1000))\n pblog.error(f\"Available space: {available_gb}GB\")\n pblog.error(f\"Total install size: {required_free_gb}GB\")\n pblog.error(f\"Required space: {int((free - required_free_space) / (1000 * 1000 * 1000))}\")\n pbtools.error_state()\n\n command_set = [\"ue4versionator.exe\"]\n\n if not (bundle_name is None):\n command_set.append(\"-bundle\")\n command_set.append(str(bundle_name))\n\n if download_symbols:\n command_set.append(\"-with-symbols\")\n\n if pbconfig.get(\"is_ci\"):\n # If we're CI, use another config file\n command_set.append(\"-user-config\")\n command_set.append(pbconfig.get(\"ue4v_ci_config\"))\n\n return subprocess.run(command_set, shell=True).returncode\n","sub_path":"pbpy/pbunreal.py","file_name":"pbunreal.py","file_ext":"py","file_size_in_byte":13054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"187744941","text":"def computepay(h,r):\r\n\tif h > 40:\r\n\t\tot = (h - 40) * (0.5 * r)\r\n\t\totPay = ot + (pay)\r\n\t\treturn(otPay)\r\n\telse:\r\n\t\treturn(pay)\r\n\r\nhrs = input(\"Enter Hours:\")\r\nrate = input(\"Enter Rate:\")\r\nr = float(rate)\r\nh = float(hrs)\r\npay = h * r\r\np = computepay(h,r)\r\nprint(p)\r\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"136572120","text":"import os, decimal\nimport numpy as np\nimport csv, math, json, pprint\nfrom sklearn.manifold import TSNE\nimport pandas as pd\nimport string\nfrom operator import itemgetter\n\n\ndef pipeline():\n # raw file : NBA Season Data.csv\n # rawfile = \"../../static/skyflow/data/original/NBA Season Data.csv\"\n # rawfile_rows = read(rawfile)\n\n rows = read('../../static/skyflow/data/original/NBA_redundancy_erased.csv')\n\n # 중복되는 데이터가 있어서 중복 제거 -> NBA_redundancy_erased.csv\n columns_needed = ['Year', 'Player', 'nameID', 'Tm', 'G', 'ORB%', 'DRB%', 'TRB%', 'AST%', 'STL%', 'BLK%', 'Shot%']\n used = set()\n tmp = [row['Year'] for row in rows]\n years = [x for x in tmp if x not in used and (used.add(x) or True)]\n\n # write players.json\n tmp = [row['Player'] for row in rows]\n players = list(set(tmp))\n players.sort()\n for row in rows:\n row['nameID'] = players.index(row['Player'])\n for i, player in enumerate(players):\n players[i] = {'id': i, 'name': player}\n\n playersJson = json.dumps({'players': players}, indent=4)\n with open('players.json', 'w') as f:\n f.write(playersJson)\n f.flush()\n\n # test_years = ['2016']\n\n # Column picked\n selected_rows = pick_column_needed(rows, columns_needed)\n key_modified_rows = list()\n cks = ['year', 'player', 'nameID', 'tm']\n value_origin = ['G', 'ORB%', 'DRB%', 'TRB%', 'AST%', 'STL%', 'BLK%', 'Shot%']\n values = ['g', 'orb', 'drb', 'trb', 'ast', 'stk', 'blk', 'shot']\n joined = list(zip(cks, columns_needed))\n print([(a, b) for a, b in joined])\n for row in selected_rows:\n krow = {a: row[b] for a, b in joined}\n krow['values'] = {a: row[b] for a, b in list(zip(values, value_origin))}\n key_modified_rows.append(krow)\n #\n #\n # Normalize data\n #\n # normalized_rows = get_normalized_data(selected_rows)\n # normalized_list = dict2list(normalized_rows, columns_needed)\n\n for i, row in enumerate(key_modified_rows):\n row['id'] = i\n # Dominance graph build\n #\n # print(selected_list)\n for year in years:\n print(year)\n data_list = [(x['id'], list(map(float, list(x['values'].values())))) for x in\n list(filter(lambda x: x['year'] == year, key_modified_rows))]\n nd_dom, nd_dom_by = find_dominating_list(data_list)\n print(data_list)\n for i, d in enumerate(data_list):\n key_modified_rows[d[0]]['all_dom'] = nd_dom[i]\n key_modified_rows[d[0]]['all_dom_by'] = nd_dom_by[i]\n key_modified_rows[d[0]]['dir_dom'] = [x for x in nd_dom[i]]\n # dominated_by_list = find_dominated_by_list(data_list)\n # dominance_score = find_dominate_score(data_list)\n #\n # for i in dominating_list.keys():\n # selected_rows[i]['dominating'] = dominating_list[i]\n # selected_rows[i]['dominated_by'] = dominated_by_list[i]\n # selected_rows[i]['dominance_score'] = dominance_score[i]\n\n # skylines = classify_skylines(data_list)\n # for i, skyline in enumerate(skylines):\n # for id in skyline:\n # selected_rows[id]['nth-skyline'] = i + 1\n\n for row in key_modified_rows:\n erase_list = list()\n for dom_id in row['dir_dom']:\n l = [True if dom_id in key_modified_rows[d]['dir_dom'] else False for d in row['dir_dom']]\n if any(l):\n erase_list.append(dom_id)\n for i in erase_list:\n row['dir_dom'].remove(i)\n\n for row in key_modified_rows:\n row['dir_dom_by'] = list()\n\n for row in key_modified_rows:\n for dom_id in row['dir_dom']:\n key_modified_rows[dom_id]['dir_dom_by'].append(row['id'])\n\n print()\n # X_embedded = t_SNE(selected_rows, columns_needed)\n\n # 1th skyline\n\n print()\n with open('../../static/skyflow/data/processed/NBA_dominance.json', 'w')as f:\n f.write(json.dumps(key_modified_rows))\n f.flush()\n\n\ndef absent_list():\n rows = readJSON('../../static/skyflow/data/processed/NBA_dominance.json')\n years = list()\n for year in range(1978, 2016):\n years.append([x['nameID'] for x in list(filter(lambda x: int(x['year']) == year, rows))])\n print(years)\n absents = list()\n for year in range(len(years)):\n absents.append(list())\n for year in range(len(years) - 1):\n for x in years[year]:\n if x not in years[year + 1] and x not in absents[year]:\n absents[year + 1].append(x)\n\n for year in range(1, len(years)):\n for x in years[year]:\n if x not in years[year - 1] and x not in absents[year - 1]:\n absents[year - 1].append(x)\n\n print(absents)\n for a in absents:\n print(len(a))\n\n\ndef nth_skyline():\n rows = readJSON('../../static/skyflow/data/processed/NBA_dominance.json')\n already_counted = []\n for row in rows:\n if len(row['all_dom_by']) == 0:\n row['nth-skyline'] = 0\n already_counted.append(row['id'])\n for i in range(1, 8):\n candidate = []\n for row in rows:\n if 'nth-skyline' not in row:\n if all([True if x in already_counted else False for x in row['all_dom_by']]):\n row['nth-skyline'] = i\n candidate.append(row['id'])\n print(i, candidate)\n already_counted.extend(candidate)\n\n for row in rows:\n keys = row['values'].keys()\n for key in keys:\n row['values'][key] = float(row['values'][key])\n row['dominance'] = len(row['all_dom'])\n if row['nth-skyline'] > 3:\n print(row)\n # print(rows.filter(lambda x: x if ))\n with open('../../static/skyflow/data/processed/NBA_nth.json', 'w')as f:\n f.write(json.dumps(rows))\n f.flush()\n print()\n\n # 1 level, 2, 3 level Skyline\n # print('write_process started')\n # list2file(dominating_list, '../data/dominating_list.csv')\n # list2file(dominated_by_list, '../data/dominated_by_list.csv')\n # list2file_1elem(dominance_score, '../data/dominance_score.csv')\n\n # list2jsonfile(dominating_list, '../data/dominating_list.json')\n # list2jsonfile(dominated_by_list, '../data/dominated_by_list.json')\n # list2jsonfile(dominance_score, '../data/dominance_score.json')\n #\n\n # list2file(skylines, '../data/skylines.csv')\n # list2jsonfile(skylines, '../data/skylines.json')\n # print(skylines)\n #\n # then what?\n #\n # t-SNE\n #\n # X_embedded = t_SNE(normalized_rows, columns_needed)\n # write_tsne_coordinate(X_embedded, '../data/tsne.json')\n\n #\n #\n # Measure subspace size\n #\n #\n #\n pass\n\n\ndef compareline_id():\n rows = readJSON('../../static/skyflow/data/processed/NBA_nth.json')\n results = []\n for row in rows:\n id = row['id']\n nth = row['nth-skyline']\n dom = []\n dom_by = []\n conflict = []\n for pid in row['all_dom']:\n nth = rows[pid]['nth-skyline']\n while (len(dom) <= nth):\n dom.append([])\n dom[nth].append(pid)\n for pid in row['all_dom_by']:\n nth = rows[pid]['nth-skyline']\n while (len(dom_by) <= nth):\n dom_by.append([])\n dom_by[nth].append(pid)\n # filtered = list(filter(lambda x: x['year'] == row['year'], rows))\n # for p in filtered:\n # pid = p['id']\n # if pid not in row['all_dom'] and pid not in row['all_dom_by']:\n # nth = rows[pid]['nth-skyline']\n # while (len(conflict) <= nth):\n # conflict.append([])\n # conflict[nth].append(pid)\n results.append({'id': id, 'dom': dom, 'dom_by': dom_by})\n\n # with open('../../static/skyflow/data/processed/NBA_nth')\n\n\ndef layers():\n rows = readJSON('../../static/skyflow/data/processed/NBA_nth.json')\n layers = list()\n for y in range(1978, 2016 + 1):\n layers.append([])\n for row in rows:\n while len(layers[int(row['year']) - 1978]) <= row['nth-skyline']:\n layers[int(row['year']) - 1978].append([])\n layers[int(row['year']) - 1978][row['nth-skyline']].append(row['id'])\n with open('../../static/skyflow/data/processed/NBA_layers.json', 'w') as f:\n f.write(json.dumps(layers))\n f.flush()\n\n\ndef tsne_json():\n file = '../../static/skyflow/data/processed/NBA processed.json'\n output = '../../static/skyflow/data/processed/NBA_tsne.json'\n keys = ['g', 'orb', 'drb', 'trb', 'ast', 'stk', 'blk', 'shot']\n tsne(file, keys, output)\n\n\ndef vector_sum_json():\n file = '../../static/skyflow/data/processed/NBA processed.json'\n output = '../../static/skyflow/data/processed/NBA_vector_sum.json'\n keys = ['g', 'orb', 'drb', 'trb', 'ast', 'stk', 'blk', 'shot']\n vector_sum(file, keys, output)\n\n\n# def vector_sum(file, keys, output):\ndef vector_sum(file, keys, output):\n rows = readJSON(file)['data']\n l = list()\n\n for row in rows:\n l.append([float(row['values'][x]) for x in keys])\n norm_values = get_normalized_data(l)\n print(l)\n print(norm_values)\n vectors = get_vector_sum(norm_values)\n print(vectors)\n for i, row in enumerate(rows):\n row['x'] = vectors[i][0]\n row['y'] = vectors[i][1]\n\n with open(output, 'w') as f:\n f.write(json.dumps({'data': rows}))\n f.flush()\n\n\ndef vector_sum(file, keys, output):\n rows = readJSON(file)['data']\n l = list()\n\n for row in rows:\n l.append([float(row['values'][x]) for x in keys])\n norm_values = get_normalized_data(l)\n print(l)\n print(norm_values)\n vectors = get_vector_sum(norm_values)\n print(vectors)\n for i, row in enumerate(rows):\n row['x'] = vectors[i][0]\n row['y'] = vectors[i][1]\n x = vectors[i][0]\n y = vectors[i][1]\n theta = 0\n if x > 0 and y > 0: # 1사분면\n theta = math.asin(y)\n elif x < 0 and y > 0: # 2사분면\n theta = math.acos(x)\n elif x < 0 and y < 0:\n theta = -math.asin(y) + math.pi\n elif x > 0 and y < 0:\n theta = 2 * math.pi - math.acos(x)\n else:\n print('error', x, y)\n row['theta'] = theta\n # print(vectors[i][0], vectors[i][1], theta * 180 / math.pi)\n\n with open(output, 'w') as f:\n f.write(json.dumps({'data': rows}))\n f.flush()\n\n\ndef tsne(file, keys, output):\n rows = readJSON(file)['data']\n l = list()\n for row in rows:\n l.append([row['values'][x] for x in keys])\n x = np.array(l)\n # print(X)\n x_embedded = TSNE(n_components=2).fit_transform(x)\n for i, row in enumerate(x_embedded):\n rows[i]['x'] = float(row[0])\n rows[i]['y'] = float(row[1])\n\n with open(output, 'w') as f:\n f.write(json.dumps({'data': rows}))\n f.flush()\n\n\ndef test():\n df = pd.read_csv('../../static/skyflow/data/processed/NBA.csv')\n df = df.fillna(0)\n df.to_csv('../../static/skyflow/data/processed/NBA_fillna.csv')\n print(df['3P%'].value_counts(dropna=False))\n\n\ndef skyline_all():\n columns = ['PTS', 'AST', 'STL', 'BLK', 'TRB', 'ORB', 'DRB', '3P%', '3P', 'FG%', 'FG', 'G']\n rows = list()\n with open('../../static/skyflow/data/processed/NBA_fillna.csv', 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n rows.append(row)\n\n # column 조합 nC2 -> nCn\n # tsne location\n # skyline relation\n # abcde.json\n # json : id, nameid, year, x, y, dom, dom_by\n idxs = list(range(0, 12))\n\n r = [x for x in powerset(idxs)]\n # r = [[0, 1, 2, 3, 4, 5, 6, 7]]\n r.sort()\n print(r)\n for l in r:\n if len(l) != len(columns) - 3:\n continue\n print(l)\n # list(map(chr, range(97, 123))) # or list(map(chr, range(ord('a'), ord('z')+1)))\n # [chr(i) for i in range(ord('a'), ord('z') + 1)]\n filename = ''.join(chr(ord('a') + x) for x in l)\n print(filename)\n\n selected_columns = [columns[idx] for idx in l]\n # full_data = []\n for year in range(1978, 2016):\n # output = list()\n adj_matrix = list()\n\n year_list = list(filter(lambda x: int(x['Year']) == year, rows))\n\n year_values = list([float(x[c]) if c.strip() != '' else 0 for c in selected_columns] for x in year_list)\n\n # print(year, year_values)\n x = np.array(year_values)\n x_embedded = TSNE(n_components=2).fit_transform(x)\n # for i, row in enumerate(x_embedded):\n # print(float(row[0]), float(row[1]))\n for i, p in enumerate(year_values):\n adj_matrix.append(list())\n adj_matrix[i].append(float(x_embedded[i][0]))\n adj_matrix[i].append(float(x_embedded[i][1]))\n dom = list()\n dom_by = list()\n # output.append(dict())\n # output[i]['id'] = year_list[i]['id']\n # output[i]['Year'] = year_list[i]['Year']\n # output[i]['PlayerID'] = year_list[i]['PlayerID']\n for idx, v in enumerate(year_values):\n # print(p, v)\n arr = [p[idx] - v[idx] for idx in range(len(l))]\n equal_or_greater = [True if x >= 0 else False for x in arr]\n greater = [True if x > 0 else False for x in arr]\n arr2 = [v[idx] - p[idx] for idx in range(len(l))]\n equal_or_greater2 = [True if x >= 0 else False for x in arr2]\n greater2 = [True if x > 0 else False for x in arr2]\n if all(equal_or_greater) and any(greater):\n # dom.append(year_list[idx]['PlayerID'])\n adj_matrix[i].append(1)\n elif all(equal_or_greater2) and any(greater2):\n # dom_by.append(year_list[idx]['PlayerID'])\n adj_matrix[i].append(-1)\n else:\n adj_matrix[i].append(0)\n\n # print(dom_by)\n # output[i]['dom'] = dom\n # output[i]['dom_by'] = dom_by\n # output[i]['x'] = float(x_embedded[i][0])\n # output[i]['y'] = float(x_embedded[i][1])\n # full_data.extend(output)\n\n with open('./skylines/' + str(year) + '_' + filename + '.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(adj_matrix)\n\n # with open('./skylines/' + year + '_' + filename + '.json', 'w') as f:\n # f.write(json.dumps(full_data, indent=4))\n # f.flush()\n # except ValueError as e:\n # print(selected_columns)\n # print(e)\n\n\ndef column_reduce():\n columns = ['Year', 'Player', 'PlayerID', 'PTS', 'AST', 'STL', 'BLK', 'TRB', 'ORB', 'DRB', '3P%', '3P', 'FG%',\n 'FG', 'G']\n df = pd.read_csv('../../static/skyflow/data/processed/NBA_fillna.csv', sep=',')\n df = df[columns]\n df.info()\n df.index.name = 'id'\n df.to_csv('../../static/skyflow/data/processed/NBA_fillna_reduced.csv', mode='w')\n\n\ndef skyline_final():\n columns = ['PlayerID', 'QoL', 'PP', 'S', 'HC', 'CoL', 'PPI', 'TCT', 'P', 'C']\n rows = list()\n with open('./test.csv', 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n rows.append(row)\n\n tsnes = list()\n dom = list()\n dom_by = list()\n # for year in range(1978, 1979):\n for year in range(2012, 2020):\n # output = list()\n # adj_matrix = list()\n year_list = list(filter(lambda x: int(x['Year']) == year, rows))\n tsne_values = list([float(x[c]) if c.strip() != '' else 0 for c in columns[1:]] for x in year_list)\n year_values = list([(x[c]) if c.strip() != '' else 0 for c in columns] for x in year_list)\n\n # print(year, year_values)\n x = np.array(tsne_values)\n x_embedded = TSNE(n_components=2).fit_transform(x)\n # for i, row in enumerate(x_embedded):\n # print(float(row[0]), float(row[1]))\n for emb in x_embedded:\n tsnes.append([emb[0], emb[1]])\n\n for d_i, d in enumerate(year_values):\n # if A is dominated by B :\n dominance_list = list()\n dominance_by_list = list()\n # dominance_list[A].append(B)\n for j_i, j in enumerate(year_values):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if float(a) > float(b) else False for a, b in zip(d[1:], j[1:])]) and \\\n all([True if float(a) >= float(b) else False for a, b in zip(d[1:], j[1:])]):\n dominance_list.append((j[0]))\n for j_i, j in enumerate(year_values):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if float(a) < float(b) else False for a, b in zip(d[1:], j[1:])]) and \\\n all([True if float(a) <= float(b) else False for a, b in zip(d[1:], j[1:])]):\n dominance_by_list.append((j[0]))\n\n dom.append(dominance_list)\n dom_by.append(dominance_by_list)\n # total.append((dominance_list, dominance_by_list))\n print(len(tsnes), len(dom), len(dom_by))\n\n for i, _ in enumerate(dom):\n rows[i]['dom'] = dom[i]\n rows[i]['dom_by'] = dom_by[i]\n rows[i]['x'] = tsnes[i][0]\n rows[i]['y'] = tsnes[i][1]\n\n with open('./test2.csv', 'w') as f:\n fieldnames = rows[0].keys()\n\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n # for row in rows:\n writer.writeheader()\n writer.writerows(rows)\n # writer.writerow(row)\n for row in rows:\n row['id'] = int(row['id'])\n row['Year'] = int(row['Year'])\n for key in columns[1:]:\n row[key] = float(row[key])\n\n class NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for numpy types \"\"\"\n\n def default(self, obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,\n np.int16, np.int32, np.int64, np.uint8,\n np.uint16, np.uint32, np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32,\n np.float64)):\n return float(obj)\n elif isinstance(obj, (np.ndarray,)): #### This is the fix\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n with open('./test.json', 'w') as f:\n f.write(json.dumps(rows, cls=NumpyEncoder))\n f.flush()\n print(rows)\n\n\ndef setNameID():\n rows = list()\n with open('../../static/skyflow/data/processed/NBA_fillna_reduced_organized.csv', 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n rows.append(row)\n\n names = dict()\n nameID = 0\n for row in rows:\n if row['PlayerID'] not in names:\n names[row['PlayerID']] = nameID\n nameID += 1\n for row in rows:\n row.update({'PlayerID': names[row['PlayerID']]})\n # row['NameID'] = names[row['PlayerID']]\n with open('../../static/skyflow/data/processed/NUMBEO/NUMBEO_nameid.csv', 'w') as f:\n fieldnames = rows[0].keys()\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n # for row in rows:\n writer.writeheader()\n writer.writerows(rows)\n # print(rows)\n # with open('./skylines/' + str(year) + '_' + filename + '.csv', 'w') as f:\n # writer = csv.writer(f)\n # writer.writerows(adj_matrix)\n\n # with open('./skylines/' + year + '_' + filename + '.json', 'w') as f:\n # f.write(json.dumps(full_data, indent=4))\n # f.flush()\n # except ValueError as e:\n # print(selected_columns)\n # print(e)\n\n\ndef powerset(seq):\n \"\"\"\n Returns all the subsets of this set. This is a generator.\n \"\"\"\n if len(seq) <= 1:\n yield seq\n yield []\n else:\n for item in powerset(seq[1:]):\n yield [seq[0]] + item\n yield item\n\n\ndef yearly_tsne(file, output):\n rows = readJSON(file)\n year_idx = 0\n for year in range(1978, 2016):\n print(year, year_idx)\n l = [list(x['values'].values()) for x in list(filter(lambda x: int(x['year']) == year, rows))]\n x = np.array(l)\n # print(X)\n x_embedded = TSNE(n_components=2).fit_transform(x)\n for i, row in enumerate(x_embedded):\n rows[year_idx + i]['x'] = float(row[0])\n rows[year_idx + i]['y'] = float(row[1])\n year_idx += len(l)\n # print(list(filter(lambda x: x['year'] == year, rows)))\n with open(output, 'w') as f:\n f.write(json.dumps(rows))\n f.flush()\n # with open(output, 'w') as f:\n # f.write(json.dumps({'data': rows}))\n # f.flush()\n\n\ndef jsonMerge():\n tsne = readJSON('../data/tsne.json')\n score = readJSON('../data/dominance_score.json')\n skylines = readJSON('../data/skylines.json')\n for i, t in enumerate(tsne):\n t['dominance_count'] = score[i]['values']\n for level, value in enumerate(skylines):\n for idx in value['values']:\n tsne[idx]['level'] = level\n # pprint.pprint(tsne)\n\n with open('../data/tsne_dominance_level.json', 'w') as f:\n f.write(json.dumps(tsne, indent=4))\n f.flush()\n\n\ndef dict2list(normalized_rows, columns):\n normalized_list = list()\n for row in normalized_rows:\n l = list()\n for c in columns:\n l.append(row[c])\n normalized_list.append(l)\n return normalized_list\n\n\ndef t_SNE(rows, values):\n l = list()\n for row in rows:\n l.append([row[x] for x in values])\n\n x = np.array(l)\n # print(X)\n x_embedded = TSNE(n_components=2).fit_transform(x)\n jsonlist = list()\n for i, row in enumerate(x_embedded):\n jsondict = dict()\n jsondict['id'] = i\n jsondict['x'] = float(row[0])\n jsondict['y'] = float(row[1])\n jsonlist.append(jsondict)\n return jsonlist\n\n\ndef get_tsne_kvlist(x_embedded):\n jsonlist = list()\n for i, row in enumerate(x_embedded):\n jsondict = dict()\n jsondict['id'] = i\n jsondict['x'] = float(row[0])\n jsondict['y'] = float(row[1])\n jsonlist.append(jsondict)\n return jsonlist\n\n\ndef write_tsne_coordinate(x_embedded, file):\n jsonlist = list()\n for i, row in enumerate(x_embedded):\n jsondict = dict()\n jsondict['id'] = i\n jsondict['x'] = float(row[0])\n jsondict['y'] = float(row[1])\n jsonlist.append(jsondict)\n with open(file, 'w') as f:\n f.write(json.dumps(jsonlist, indent=4))\n\n\ndef readJSON(file):\n with open(file, 'r') as f:\n data = json.load(f)\n return data\n\n\ndef read(file):\n with open(file, 'r') as csvFile:\n reader = csv.DictReader(csvFile)\n rows = list()\n for row in reader:\n rows.append(row)\n return rows\n\n\n# pick column needed와 겹침\ndef read_columns(rows, columns):\n result = list()\n for row in rows:\n d = dict()\n for column in columns:\n d[column] = row[column]\n result.append(d)\n return result\n\n\ndef count_name(rows):\n d = dict()\n\n for row in rows:\n if row['Player ID'] in d:\n d[row['Player ID']].append(row)\n else:\n d[row['Player ID']] = list()\n d[row['Player ID']].append(row)\n\n print(d)\n\n\n# 한해에 두번씩 써있는 선수들의 뒤에 값을 없앤다.\ndef erase_redundancy(rows):\n d = set()\n l = list()\n\n for i, row in enumerate(rows):\n if (row['Player'], row['Year']) in d:\n l.append(i)\n else:\n d.add((row['Player'], row['Year']))\n\n for l_i in l[::-1]:\n del (rows[l_i])\n\n # with open('../data/NBA_redundancy_erased.csv', 'w') as csvfile:\n # writer = csv.DictWriter(csvfile, fieldnames=rows[0].keys())\n # writer.writeheader()\n #\n # for row in rows:\n # writer.writerow(row)\n return rows\n\n\ndef pick_column_needed(rows, column_needed):\n picks = list()\n for row in rows:\n d = dict()\n for c in column_needed:\n d[c] = row[c]\n picks.append(d)\n\n # with open('../data/NBA_column_picked.csv', 'w') as csvfile:\n # writer = csv.DictWriter(csvfile, fieldnames=picks[0].keys())\n # writer.writeheader()\n #\n # for row in picks:\n # writer.writerow(row)\n return picks\n\n\n# data를 노말라이즈\ndef get_normalized_data(l):\n nparr = np.array(l)\n npmean = np.mean(l, axis=0)\n npmin = np.min(l, axis=0)\n npstd = np.std(l, axis=0)\n npmax = np.max(l, axis=0)\n # pprint.pprint(npmean)\n # pprint.pprint(npmin)\n # pprint.pprint(npmax)\n # pprint.pprint(npstd)\n norm_values = list()\n for r_i, row in enumerate(l):\n norm_values.append([])\n for i, v in enumerate(row):\n norm_values[r_i].append((v - npmean[i]) / npstd[i])\n return norm_values\n\n\ndef get_vector_sum(norm_values):\n result = list()\n vectors = list()\n for row in norm_values:\n # 6차원\n units = np.array(\n [[1, 0],\n [math.sqrt(2) / 2, math.sqrt(2) / 2],\n [0, 1],\n [-math.sqrt(2) / 2, math.sqrt(2) / 2],\n [-1, 0],\n [-math.sqrt(2) / 2, -math.sqrt(2) / 2],\n [0, -1],\n [math.sqrt(2) / 2, -math.sqrt(2) / 2]\n ])\n\n for i in range(8):\n units[i] = row[i] * units[i]\n v = np.sum(units, axis=0)\n vectors.append([v[0], v[1]])\n # print(result)\n # unit vector로 만듬\n for i, d in enumerate(vectors):\n vectors[i] = d / np.linalg.norm(d)\n return vectors\n\n # for row in range(len(data[0])):\n # for\n # column in data:\n # print(column)\n # print(result)\n pass\n\n\ndef list2jsonfile(rows, filepathname):\n jsonlist = list()\n for i, row in enumerate(rows):\n jsondict = dict()\n jsondict['id'] = i\n jsondict['values'] = row\n jsonlist.append(jsondict)\n with open(filepathname, 'w') as f:\n f.write(json.dumps(jsonlist, indent=4))\n f.flush()\n\n\ndef list2file(rows, filepathname):\n with open(filepathname, 'w') as f:\n for i, row in enumerate(rows):\n f.write('{}'.format(i))\n for v in row:\n f.write(',{}'.format(v))\n f.write('\\n')\n f.flush()\n\n\ndef list2file_1elem(rows, filepathname):\n with open(filepathname, 'w') as f:\n for i, v in enumerate(rows):\n f.write('{}'.format(i))\n f.write(',{}'.format(v))\n f.write('\\n')\n f.flush()\n\n\ndef write_vector(rows):\n with open('../data/NBA_vectors.csv', 'w') as f:\n f.write('{},{},{},{}\\n'.format('id', 'year', 'x', 'y'))\n for row in rows:\n f.write('{},{},{},{}\\n'.format(row['Player ID'], row['Year'], row['vectorX'], row['vectorY']))\n\n\ndef find_dominated_by_list(data):\n dominance_list = dict()\n for row in data:\n dominance_list[row[0]] = list()\n for i_d, d in enumerate(data):\n # if A is dominated by B :\n # dominance_list[A].append(B)\n for i_j, j in enumerate(data):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if a > b else False for a, b in zip(d, j)]) and \\\n all([True if a >= b else False for a, b in zip(d, j)]):\n dominance_list[j[0]].append(d[0])\n # print(dominance_list)\n # for i, d in enumerate(dominance_list):\n # print(i, d)\n return dominance_list\n\n\ndef mask(df, key, val):\n return df[df[key] >= val]\n\n\ndef selected_skyline(selected_idx):\n opt = 0\n if opt == 0: # NBA\n # data = list()\n data = pd.read_csv('../../static/skyflow/data/original/nba-players-stats/filtered_tsne.csv', sep=',')\n # with open('../../static/skyflow/data/original/nba-players-stats/filtered_tsne.csv', 'r') as f:\n # csvReader = csv.reader(f, delimiter=',')\n # for r in csvReader:\n # data.append(r)\n # print(data.keys())\n start_idx = 5\n selected_columns = list(map(lambda x: data.columns[x + start_idx], selected_idx))\n # print(data.dtypes)\n print(selected_columns)\n # print(filtered_data)\n year_data = list()\n dominance_dict = dict()\n pd.DataFrame.mask = mask\n for i in range(data.shape[0]):\n dominance_dict[i] = [[], []]\n for year in range(1980, 2017):\n print(year)\n year_data = data[data.Year == year]\n print(year_data.shape[0])\n filtered_data = year_data[['id', ] + selected_columns]\n # print(filtered_data)\n\n # print(filtered_data.shape[0])\n # print(list(range(filtered_data.shape[0] - 1)))\n iter = 0\n\n for idx_a in range(filtered_data.shape[0]):\n cmp = list()\n for column in selected_columns[2:]:\n cmp.append(year_data.iloc[idx_a][column])\n for i, column in enumerate(selected_columns[2:]):\n answer = year_data.mask(column, cmp[i])\n dominance_dict[idx_a] = answer\n # print(answer)\n\n # for idx_a in range(filtered_data.shape[0] - 1): # 마지막꺼 빼고 진행된다\n # # print(idx, row)\n # # fd_slice = filtered_data.ix[idx_a + 1:]\n #\n # for idx_b in range(idx_a + 1, filtered_data.shape[0]):\n # iter += 1\n # # print(idx_a, idx_b)\n # row_a = filtered_data.iloc[idx_a]\n # row_b = filtered_data.iloc[idx_b]\n # # print(row_a['id'], row_b['id'])\n # if all([True if a >= b else False for a, b in zip(row_a[2:], row_b[2:])]):\n # # if a dominate b\n # dominance_dict[idx_a][0].append(row_b['id'])\n # dominance_dict[idx_b][1].append(row_a['id'])\n # test = list(zip(row_a[2:], row_b[2:]))\n # # print(row_a['id'], row_b['id'], test)\n # elif all([True if b >= a else False for a, b in zip(row_a[2:], row_b[2:])]):\n # # elif any([True if b > a else False for a, b in zip(row_a[2:], row_b[2:])]) and all(\n # # [True if b >= a else False for a, b in zip(row_a[2:], row_b[2:])]):\n # # if b dominate a\n # dominance_dict[idx_b][0].append(row_a['id'])\n # dominance_dict[idx_a][1].append(row_b['id'])\n # print(iter, dominance_dict)\n # print(year, dominance_list)\n # columns = data[0]\n\n # print(columns)\n\n # total = dict()\n # for i, year in enumerate(range(1980, 2017)):\n # for d_i, d in enumerate(year_data):\n # dominance_list = list()\n # dominance_by_list = list()\n # # dominance_list[A].append(B)\n # for j_i, j in enumerate(year_data[i]):\n # # skyline 여러 차원 중에서 한차원이라도 커야함\n # if any([True if a > b else False for a, b in zip(d[2:], j[2:])]) and \\\n # all([True if a >= b else False for a, b in zip(d[2:], j[2:])]):\n # dominance_list.append(int(j[0]) - 1)\n #\n # # skyline 여러 차원 중에서 한차원이라도 커야함\n # elif any([True if a < b else False for a, b in zip(d[2:], j[2:])]) and \\\n # all([True if a <= b else False for a, b in zip(d[2:], j[2:])]):\n # dominance_by_list.append(int(j[0]) - 1)\n # total[d[0]] = (dominance_list, dominance_by_list)\n # print(total)\n return ''\n else:\n pass\n\n\n# def find_direct_dominating_list(normalized_rows, start_idx)\ndef get_domrelation():\n data = list()\n with open('../../static/skyflow/data/original/nba-players-stats/filtered_tsne.csv', 'r') as f:\n csvReader = csv.reader(f, delimiter=',')\n for r in csvReader:\n data.append(r)\n columns = ['0', 'Year', 'G', '3PAr', 'ORB%', 'TRB%', 'AST%', 'STL%', 'BLK%', 'TOV%']\n columns_idx = [data[0].index(i) for i in columns]\n\n total = list()\n filtered = list()\n for d in data:\n row = [d[i] for i in columns_idx]\n filtered.append(row)\n print()\n for year in range(1980, 2018):\n year_data = list(filter(lambda x: int(x[1]) == year, filtered[1:]))\n for d_i, d in enumerate(year_data):\n # if A is dominated by B :\n dominance_list = list()\n dominance_by_list = list()\n # dominance_list[A].append(B)\n for j_i, j in enumerate(year_data):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if a > b else False for a, b in zip(d[2:], j[2:])]) and \\\n all([True if a >= b else False for a, b in zip(d[2:], j[2:])]):\n dominance_list.append(int(j[0]) - 1)\n for j_i, j in enumerate(year_data):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if a < b else False for a, b in zip(d[2:], j[2:])]) and \\\n all([True if a <= b else False for a, b in zip(d[2:], j[2:])]):\n dominance_by_list.append(int(j[0]) - 1)\n total.append((dominance_list, dominance_by_list))\n print()\n jsontotal = list()\n for i, row in enumerate(total):\n jsontotal.append({'id': i, 'dom': row[0], 'dom_by': row[1]})\n with open('../../static/skyflow/data/original/nba-players-stats/dom.json', 'w') as f:\n f.write(json.dumps(jsontotal, indent=4))\n f.flush()\n\n\ndef find_dominating_list(data):\n dominance_list = list()\n dominance_by_list = list()\n for i in range(len(data)):\n dominance_list.append(list())\n dominance_by_list.append(list())\n for d_i, d in enumerate(data):\n # if A is dominated by B :\n # dominance_list[A].append(B)\n for j_i, j in enumerate(data):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if a > b else False for a, b in zip(d[1], j[1])]) and \\\n all([True if a >= b else False for a, b in zip(d[1], j[1])]):\n dominance_list[d_i].append(j[0])\n dominance_by_list[j_i].append(d[0])\n # print(dominance_list)\n # for i, d in enumerate(dominance_list):\n # print(i, d)\n return dominance_list, dominance_by_list\n\n\ndef find_dominate_score(normalized_rows, start_idx):\n dominance_list = dict()\n for row in normalized_rows:\n dominance_list[row[0]] = 0\n for i, d in enumerate(normalized_rows):\n # if A is dominated by B :\n # dominance_list[A].append(B)\n for i_j, j in enumerate(normalized_rows):\n # skyline 여러 차원 중에서 한차원이라도 커야함\n if any([True if a > b else False for a, b in zip(d[start_idx:], j[start_idx:])]) and \\\n all([True if a >= b else False for a, b in zip(d[start_idx:], j[start_idx:])]):\n dominance_list[d[0]] += 1\n return dominance_list\n\n\ndef write_score(rows):\n with open('../data/NBA_score.csv', 'w') as f:\n writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))\n writer.writeheader()\n for row in rows:\n writer.writerow(row)\n\n\ndef classify_skylines(normalized_list, start_idx):\n skyline_candidates = [row for row in normalized_list]\n # for i, c in enumerate(skyline_candidates):\n # c.insert(0, i)\n non_skyline = list()\n # for row in rows:\n skylines = list()\n # skyline이 안된애들이 남아있으면 계속 반복\n level = 0\n while skyline_candidates:\n for i, d in enumerate(skyline_candidates):\n # if A is dominated by B :\n # dominance_list[A].append(B)\n for i_j, j in enumerate(skyline_candidates):\n # if i == i_j:\n # continue\n # [zip(d[k], j[k]) for k in keys[4:10]]\n # f = zip(d[keys[4:10]], j[keys[4:10]])\n # skyline 여러 차원 중에서 한차원이라도 커야함\n # if all([True if a <= b else False for a, b in zip(d[start_idx:], j[start_idx:])]):\n if any([True if a > b else False for a, b in zip(d[start_idx:], j[start_idx:])]) and \\\n all([True if a >= b else False for a, b in zip(d[start_idx:], j[start_idx:])]):\n # d에 의해 j가 도미네이트 되었으므로 j는 non-skyline\n if j not in non_skyline:\n non_skyline.append(j[0])\n break\n candidates = list()\n skylines.append(list())\n\n if all(True if a[0] in non_skyline else False for a in skyline_candidates):\n for c in skyline_candidates:\n skylines[level].append(c[0])\n return skylines\n\n for c in skyline_candidates:\n if c[0] in non_skyline:\n candidates.append(c)\n else:\n skylines[level].append(c[0])\n\n skyline_candidates = candidates\n non_skyline = list()\n level += 1\n print(level)\n # if level > 5:\n # break\n # keys = list(skyline_candidates[0].keys())\n # keys = sorted(keys)\n # f.write(\n # '{},{},{},{},{}\\n'.format('Player ID', 'Year', 'vectorX',\n # 'vectorY', 'dominance'))\n # for key in keys:\n # for item in skyline_candidates:\n # f.write(\n # '{},{},{},{},{}\\n'.format(item['Player ID'], item['Year'], item['vectorX'],\n # item['vectorY'], item['dominance']))\n return skylines\n\n\ndef set_floor():\n rows = list()\n with open('../data/NBA_score.csv', 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n rows.append(row)\n floors = dict()\n for row in rows:\n x = round(float(row['vectorX']), 2)\n y = round(float(row['vectorY']), 2)\n if (x, y) not in floors:\n floors[(x, y)] = list()\n floors[(x, y)].append(row)\n for key in floors.keys():\n if len(floors[key]) > 1:\n print(floors[key])\n print(floors)\n with open('../data/NBA_floor.csv', 'w') as f:\n keys = list(floors.keys())\n keys = sorted(keys)\n f.write(\n '{},{},{},{},{}\\n'.format('Player ID', 'Year', 'vectorX',\n 'vectorY', 'dominance'))\n for key in keys:\n for item in floors[key]:\n f.write(\n '{},{},{},{},{}\\n'.format(item['Player ID'], item['Year'], key[0],\n key[1], item['dominance']))\n\n\ndef classify_skyline():\n rows = list()\n with open('../data/NBA_score.csv', 'r') as f:\n reader = csv.DictReader(f)\n for row in reader:\n rows.append(row)\n keys = list(rows[0].keys())\n skyline_candidates = [row for row in rows]\n non_skyline = list()\n # for row in rows:\n\n # skyline이 안된애들이 남아있으면 계속 반복\n level = 1\n while skyline_candidates:\n for i, d in enumerate(skyline_candidates):\n # if A is dominated by B :\n # dominance_list[A].append(B)\n for i_j, j in enumerate(skyline_candidates[:i] + skyline_candidates[i + 1:]):\n # [zip(d[k], j[k]) for k in keys[4:10]]\n # f = zip(d[keys[4:10]], j[keys[4:10]])\n # skyline 여러 차원 중에서 한차원이라도 커야함\n alist = [d[k] for k in keys[4:10]]\n blist = [j[k] for k in keys[4:10]]\n if all([True if a <= b else False for a, b in zip(alist, blist)]):\n # if any([True if a > b else False for a, b in zip(d[1:], j[1:])]) and \\\n # all([True if a >= b else False for a, b in zip(d[1:], j[1:])]):\n if d not in non_skyline:\n non_skyline.append(d)\n break\n\n for n in non_skyline:\n skyline_candidates.remove(n)\n\n with open('../data/skyline/{}_skyline.csv'.format(level), 'w') as f:\n writer = csv.DictWriter(f, fieldnames=skyline_candidates[0].keys())\n writer.writeheader()\n for row in skyline_candidates:\n writer.writerow(row)\n\n skyline_candidates = non_skyline\n non_skyline = list()\n level += 1\n # keys = list(skyline_candidates[0].keys())\n # keys = sorted(keys)\n # f.write(\n # '{},{},{},{},{}\\n'.format('Player ID', 'Year', 'vectorX',\n # 'vectorY', 'dominance'))\n # for key in keys:\n # for item in skyline_candidates:\n # f.write(\n # '{},{},{},{},{}\\n'.format(item['Player ID'], item['Year'], item['vectorX'],\n # item['vectorY'], item['dominance']))\n return\n\n\ndef write_csv(path, rows):\n with open(path, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=rows[0].keys())\n writer.writeheader()\n\n for row in rows:\n writer.writerow(row)\n\n\ndef txt2csv():\n dl = list()\n\n with open('../data/inv_2_int.txt', 'r') as f:\n lines = f.readlines()\n for line in lines:\n arr = line.strip().split(' ')\n d = dict()\n for i, _ in enumerate(arr):\n d[i] = arr[i]\n dl.append(d)\n\n write_csv('../data/inv_2_int.csv', dl)\n\n\ndef non_normalized_vectorsum():\n pass\n\n\ndef get_vector_minmax(rows):\n xs = [float(row['vectorX']) for row in rows]\n ys = [float(row['vectorY']) for row in rows]\n print(min(xs), max(xs))\n print(min(ys), max(ys))\n pass\n\n\ndef modify_realskyline2zero():\n rows = readJSON('../../static/skyflow/data/processed/NBA_vector_sum.json')['data']\n for row in rows:\n if len(row['dominated_by']) == 0:\n print(row)\n row['nth-skyline'] = 0\n\n with open('../../static/skyflow/data/processed/NBA_vector_sum_modified.json', 'w') as f:\n f.write(json.dumps({'data': rows}))\n f.flush()\n\n\ndef delete_redundant_skyline():\n rows = readJSON('../../static/skyflow/data/processed/NBA_vector_sum_modified.json')['data']\n for row in rows:\n erase_list = list()\n for dom_id in row['dominating']:\n l = [True if dom_id in rows[d]['dominating'] else False for d in row['dominating']]\n if any(l):\n erase_list.append(dom_id)\n for i in erase_list:\n row['dominating'].remove(i)\n\n with open('../../static/skyflow/data/processed/NBA_vector_sum_redundant_erased.json', 'w') as f:\n f.write(json.dumps({'data': rows}))\n f.flush()\n\n\ndef tsne_csv():\n lines = list()\n data = list()\n with open('../../static/skyflow/data/original/nba-players-stats/filtered.csv', 'r') as f:\n csvReader = csv.reader(f, delimiter=',')\n idx = 0\n for i, row in enumerate(csvReader):\n if i > 0 and int(row[2]) < 1980:\n continue\n row[0] = idx\n idx += 1\n lines.append(row)\n data.append(row[7:])\n print(lines[0])\n\n l = list()\n for line_i, da in enumerate(data[1:]):\n for i, d in enumerate(da):\n if d == '':\n da[i] = 0\n lines[line_i + 1][i + 7] = 0\n else:\n try:\n da[i] = float(d)\n lines[line_i + 1][i + 7] = float(d)\n except ValueError as e:\n print(e.args)\n\n x = np.array(data[1:])\n # x = x.astype(np.float)\n # print(X)\n x = np.asfarray(x, float)\n lines[0].insert(7, 'tsne_x')\n lines[0].insert(8, 'tsne_y')\n x_embedded = TSNE(n_components=2).fit_transform(x)\n for i, row in enumerate(x_embedded):\n lines[i + 1][0] = int(lines[i + 1][0]) - 1\n lines[i + 1].insert(7, round(float(row[0]), 3))\n lines[i + 1].insert(8, round(float(row[1]), 3))\n\n with open('../../static/skyflow/data/original/nba-players-stats/filtered_tsne.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(lines)\n\n\ndef merge_data():\n dir = '../../static/skyflow/data/original/numbeo/'\n years = range(2012, 2020)\n flag = 0\n result = 0\n for year in years:\n df = pd.read_csv('{}{}{}'.format(dir, year, '.csv'))\n df['Year'] = year\n if flag == 0:\n result = df\n flag = 1\n else:\n result = pd.concat([result, df])\n df.info()\n\n # result['NameID'] = '{}{}'.format(result['City'], result['year'])\n\n # def dosth(x):\n # return x['NameID'].lower()\n y = []\n z = []\n for index, row in result.iterrows():\n z.append('{}{}'.format(row['City'].replace(',', '').replace(' ', '').lower(), row['Year']))\n y.append('{}'.format(row['City'].replace(',', '').replace(' ', '').lower()))\n # result['PlayerID'] = z\n result['PlayerID'] = y\n result.index.name = 'id'\n result = result.fillna(0)\n result = result.drop(columns=['Rank'])\n result.loc[result['Climate Index'] == '-', 'Climate Index'] = 0\n print(result['Climate Index'].unique())\n result = result.rename(index=str, columns={\n \"Quality of Life Index\": \"QoL\",\n \"Purchasing Power Index\": \"PP\",\n \"Safety Index\": \"S\",\n \"Health Care Index\": \"HC\",\n \"Cost of Living Index\": \"CoL\",\n \"Property Price to Income Ratio\": \"PPI\",\n \"Traffic Commute Time Index\": \"TCT\",\n \"Pollution Index\": \"P\",\n \"Climate Index\": \"C\"\n })\n # result.apply(dosth)\n # print(result[['year', 'NameID']])\n\n result.to_csv('test.csv', mode='w')\n\n\ndef baseball_redundant():\n data = pd.read_csv('../../static/skyflow/data/processed/MLB.csv')\n dropped = data.drop_duplicates(['playerID', 'yearID', 'POS'])\n dropped = dropped.reset_index()\n dropped = dropped.drop(\n columns=['index', 'Unnamed: 0', 'PB', 'stint'])\n print(dropped)\n columns = list(dropped.columns)\n info = dropped.info()\n # l = [(dropped.columns[i], dropped.dtypes[i].name) for i in range(dropped.shape[1])]\n # # for i in range(dropped.shape[1]):\n # # dropped\n # # print(sort_list)\n # sorted_list = sorted(l, key=itemgetter(0), reverse=True)\n # sorted_list = sorted(sorted_list, key=itemgetter(1), reverse=True)\n # print(sorted_list)\n # sorted_columns = [x[0] for x in sorted_list]\n # print(sorted_columns)\n print(columns)\n\n idx = columns.index('salary')\n del (columns[idx])\n idx = columns.index('POS')\n del (columns[idx])\n idx = columns.index('yearID')\n del (columns[idx])\n columns.insert(1, 'POS')\n columns.insert(2, 'salary')\n columns.insert(0, 'yearID')\n\n # shows how many nan values in each column?\n for c in dropped.columns:\n print(c, dropped[c].isna().sum())\n dropped = dropped[columns]\n dropped = dropped.rename(columns={'yearID': 'Year'})\n print(dropped)\n dropped.to_csv('../../static/skyflow/data/processed/baseball_redundant.csv', mode='w')\n\n\ndef nba_setting():\n data = pd.read_csv('../../static/skyflow/data/original/NBA Season Data.csv')\n print(data)\n\n\ndef append_column():\n dir = 'skylines'\n for root, dirs, files in os.walk(dir):\n # print(root)\n # print(dirs)\n print(files)\n for file in files:\n with open(dir + '/' + file, 'r') as f:\n lines = f.readlines()\n column_line = 'x,y,'\n for i in range(len(lines) - 1):\n column_line = column_line + str(i) + ','\n column_line = column_line + str(len(lines) - 1)\n with open('skylines_column/' + file, 'w') as fw:\n fw.write(column_line + '\\n')\n for line in lines:\n fw.write(line)\n fw.flush()\n\n\nif __name__ == '__main__':\n # rows = read('../data/NBA_redundancy_erased.csv')\n # column_needed = ['Year', 'Player', 'Player ID', 'Tm', 'ORB%', 'DRB%', 'AST%', 'STL%', 'BLK%', 'Shot%']\n # count_name(rows)\n # erase_redundancy(rows)\n # pick_column_needed(rows, column_needed)\n # picked_rows = read('../data/NBA_column_picked.csv')\n # normalized_rows = get_normalized_data(picked_rows)\n # vector_sum = get_vector_sum(normalized_rows)\n # write_vector(vector_sum)\n #\n # dom_score = dominate_score(vector_sum)\n # write_score(dom_score)\n # print(dom_score)\n # set_floor()\n # classify_skyline()\n # interpolation()\n # spl_interpolation()\n # txt2csv()\n # get_vector_minmax(read('../data/skyline_spread.csv')) # x: -3.73~6.215, y: -3.73~4.51\n # classify_skyline()\n # pipeline()\n # tsne_json()\n # vector_sum_json()\n # modify_realskyline2zero()\n # delete_redundant_skyline()\n # jsonMerge()\n # nth_skyline()\n # compareline_id()\n # layers()\n # yearly_tsne('../../static/skyflow/data/processed/NBA_nth.json',\n # '../../static/skyflow/data/processed/NBA_tsne.json')\n # absent_list()\n # tsne_csv()\n # get_domrelation()\n # selected_skyline([1, 4, 6, 7])\n # baseball_redundant()\n # nba_setting()\n # skyline_all()\n # test()\n # append_column()\n # column_reduce()\n skyline_final()\n # setNameID()\n # merge_data()\n","sub_path":"skyflow/preprocess/NUMBEO/dominance.py","file_name":"dominance.py","file_ext":"py","file_size_in_byte":50154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"70686519","text":"\nimport re\n\n\ndataBaseType = 'dataBaseType'\ndbtype = 'type'\njdbcUrl = 'jdbcUrl'\ncdata = '[CDATA['\ndef getDBType(appDS):\n # for col in appDS.split():\n # if dataBaseType in col:\n # return col.split('=')[1]\n m = re.search(dataBaseType+'=(\\w+)', appDS)\n if m is not None:\n return m.group(1)\n \n m = re.search('value=(\\w+)', appDS)\n \n if m is not None:\n return m.group(1)\n\n raise NameError(appDS)\n\ndef getDBServer(dbUrl):\n if 'mysql' in dbUrl:\n return dbUrl.split(':')[2][2:]\n\n if 'oracle:thin' in dbUrl:\n return dbUrl.split(':')[3][1:]\n\n if 'oracle:oci' in dbUrl:\n m = re.search('\\(host=([^\\(\\)]+)\\)', dbUrl)\n return m.group(1)\n\n if 'http' in dbUrl:\n m = re.search('dataId=(.+)\\]\\]', dbUrl)\n if m is not None:\n return m.group(1)\n\n raise NameError(dbUrl)\nif __name__ == '__main__':\n while True:\n try:\n line = input()\n prod, dbInfo = line.split(',',1)\n \n dbType=''\n for info in dbInfo.split('> '):\n if dataBaseType in info or dbtype in info :\n dbType = getDBType(info)\n \n \n if jdbcUrl in info or cdata in info:\n dbUrl=getDBServer(info)\n print(prod, dbType, dbUrl)\n\n except EOFError:\n break\n","sub_path":"parseZdalDBInfo.py","file_name":"parseZdalDBInfo.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"277771304","text":"import vgg_svhn_model as vgg_mod\nimport custom_svhn_model as cust_mod\nimport data_helper as dh\nimport tensorflow as tf\nimport numpy as np\nimport h5py\n\nclean_data_only = True\nwhich_model = 'custom' # CHOOSE ONE: 'vgg_scratch', 'vgg_transfer', 'custom'\n\nweights_file = which_model+\"_weights.h5\"\n\nselected_optimizer = tf.keras.optimizers.Nadam()\n\n# Lets get the Data:\nif clean_data_only:\n h5f = h5py.File('clean_training_images.h5', 'r')\nelse:\n h5f = h5py.File('all_training_images.h5', 'r')\n\ntraining_images = h5f['training_images'][:]\ntraining_labels = h5f['training_labels'][:]\nvalidation_images = h5f['validation_images'][:]\nvalidation_labels = h5f['validation_labels'][:]\nh5f.close()\nprint('----Data has been Imported----')\n\n\n# The data as it currently stands is ordered. This is because we added to the data from multiple sources\n# including 'train', 'extra' and 'no_number' data. In its current configuration all of the no_number\n# data is at the end. To avoiding making batches of data in training that are all of one type (i.e. all no_numbers)\n# we will shuffle the data\n\n# get the new order\ntraining_shuffle_order = dh.shuffle_data_order(training_labels.shape[0])\nvalidation_shuffle_order = dh.shuffle_data_order(validation_labels.shape[0])\n# perform shuffling on data set.\ntraining_images = training_images[training_shuffle_order]\ntraining_labels = training_labels[training_shuffle_order]\nvalidation_images = validation_images[validation_shuffle_order]\nvalidation_labels = validation_labels[validation_shuffle_order]\n\n\n# We should ensure that the labels match known model output shape\ntrain_labels_trans = np.copy(training_labels).transpose()\ntrain_labels_final = [train_labels_trans[0], train_labels_trans[1], train_labels_trans[2],\n train_labels_trans[3], train_labels_trans[4]]\n\nvalidation_labels_trans = np.copy(validation_labels).transpose()\nvalidation_labels_final = [validation_labels_trans[0], validation_labels_trans[1], validation_labels_trans[2],\n validation_labels_trans[3], validation_labels_trans[4]]\n\n# Now as a pre-processing step we should subtract the mean from each image\ntraining_images_less_mean = dh.less_mean(training_images.astype(np.float64))\nvalidation_images_less_mean = dh.less_mean(validation_images.astype(np.float64))\n\n# Build the selected model\nif which_model == 'vgg_transfer':\n model = vgg_mod.gen_vgg_16(use_these_weights=None, random_weights=False)\nelif which_model == 'vgg_scratch':\n model = vgg_mod.gen_vgg_16(use_these_weights=None, random_weights=True)\nelif which_model == 'custom':\n model = cust_mod.gen_custom_model(use_these_weights=None)\nelse:\n raise Exception('Please select one of the following: vgg_transfer, vgg_scratch, custom')\n\n\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer=selected_optimizer, metrics=['accuracy'])\n\ncallbacks = [tf.keras.callbacks.ModelCheckpoint(filepath=weights_file, monitor='val_loss',\n verbose=1, save_best_only=True),\n\n tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, mode='auto'),\n\n tf.keras.callbacks.TensorBoard(log_dir='checkpoints/'+which_model, histogram_freq=0,\n write_graph=True, write_images=True)]\n\ntraining_stats = model.fit(x=training_images_less_mean, y=train_labels_final,\n validation_data=(validation_images_less_mean, validation_labels_final),\n epochs=3, batch_size=64, verbose=1, callbacks=callbacks)\n\n# Save\nmodel.save_weights(weights_file)\nmodel.save(which_model + '.h5')\n\n","sub_path":"train_models.py","file_name":"train_models.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"249535166","text":"import matplotlib.pyplot as plt\nfrom PIL import Image\nimport torch.nn as nn\nimport numpy as np\nimport os, json\n\nimport torch\nfrom torchvision import models, transforms\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\n\ndef select(test_set, result):\n return None\n\n\ndef do_lime(model, test_set, result):\n images = select(test_set, result)\n do_lime_images(model, images)\n\n\ndef get_input_transform():\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n transf = transforms.Compose([\n transforms.Resize((256, 256)),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize\n ])\n\n return transf\n\n\ndef get_input_tensors(img):\n transf = get_input_transform()\n # unsqeeze converts single image to batch of 1\n return transf(img).unsqueeze(0)\n\n\ndef do_lime_images(images, model):\n for image in images:\n img_t = get_input_tensors(image)\n logits = model(img_t)\n\n\ndef get_pil_transform():\n transf = transforms.Compose([\n transforms.Resize((256, 256)),\n transforms.CenterCrop(224)\n ])\n\n return transf\n\n\ndef get_preprocess_transform():\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n transf = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n\n return transf\n\n\npill_transf = get_pil_transform()\npreprocess_transform = get_preprocess_transform()\n\n\n","sub_path":"do_lime.py","file_name":"do_lime.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"113304231","text":"#!/usr/bin/env python3.6\nimport subprocess\nimport sys\nimport os\nimport secrets\nimport fnmatch\nimport json\nimport argparse\nimport hashlib\nfrom pathlib import Path\nfrom shutil import copyfile, rmtree\nfrom jinja2 import Template\nfrom collections import namedtuple\n\nENV = None\nREPOSITORY_NAME = None\nDEFAULT_MOUNTBASE = None\nNGINX_DYN_CONF_DIR = None\nIMAGE_NAME = None\nBUILD_ENABLED = True\nENVDIR = None\nCIDFILE = None\nSECRET_KEY_FILE = None\nNGINX_CONF_LOCATION_FILE = None\nCMD = None\nCREATE_FLAGS = \"\"\nRUN_FLAGS = \"\"\nEXTRA_OPTIONS = \"\"\n\nBUILD_DIRTY = False\n\nSCRIPT_PATH=os.path.dirname(os.path.realpath(__file__))\nNGINX_TEMPLATE = SCRIPT_PATH + '/' + 'nginx.conf.jn2'\nDOCKERIGNORE_BASEFILE = \".dockerignore_base\"\n\nSERVER_MAP = None\nVOLUMES = None\n\nCONF = None\n\n\ndef pipe(command):\n o = subprocess.run(command, shell=True, stdout=subprocess.PIPE)\n if(o.returncode != 0):\n sys.exit(o)\n return o.stdout.rstrip().decode(\"utf-8\")\n\n\ndef nopipe(command):\n o = subprocess.run(command, shell=True)\n if(o.returncode != 0):\n sys.exit(o)\n\n\ndef load_conf(conf):\n global ENV\n global REPOSITORY_NAME\n global DEFAULT_MOUNTBASE\n global NGINX_DYN_CONF_DIR\n global SERVER_MAP\n global VOLUMES\n global IMAGE_NAME\n\n global BUILD_ENABLED\n global LISTEN_PORT\n global ENVDIR\n global CIDFILE\n global SECRET_KEY_FILE\n global NGINX_CONF_LOCATION_FILE\n global BUILD_DIRTY\n global CMD\n global CREATE_FLAGS\n global RUN_FLAGS\n\n global NGINX_TEMPLATE\n\n c = None\n\n cfile = conf.file\n\n # conf.environment overrides conf.file value\n if conf.environment is not None:\n cfile = \"serverconf.{}.json\".format(conf.environment)\n\n CMD = conf.cmd\n\n if conf.interactive:\n CREATE_FLAGS += \"-t\"\n RUN_FLAGS += \"-a\"\n\n with open(cfile, 'r') as f:\n c = f.read().rstrip()\n jconf = json.loads(c)\n\n global CONF\n CONF = jconf\n\n ENV = jconf['env']\n REPOSITORY_NAME = jconf['repository_name']\n DEFAULT_MOUNTBASE = jconf.get('default_mountbase', None)\n NGINX_DYN_CONF_DIR = jconf.get('nginx_dyn_conf_dir', None)\n SERVER_MAP = jconf.get('server_map', [])\n VOLUMES = jconf.get('volumes', [])\n\n if \"additional_attrs\" in jconf:\n CREATE_FLAGS += \" \" + jconf[\"additional_attrs\"]\n\n if \"build_dirty\" in jconf:\n BUILD_DIRTY = jconf[\"build_dirty\"]\n\n if \"nginx_template\" in jconf:\n NGINX_TEMPLATE = jconf[\"nginx_template\"]\n\n ENVDIR = '.dcm_env_' + ENV + '_' + REPOSITORY_NAME\n CIDFILE = ENVDIR + \"/cidfile\"\n SECRET_KEY_FILE = ENVDIR + \"/s_key\"\n NGINX_CONF_LOCATION_FILE = ENVDIR + \"/nginx_conf_location\"\n\n allowed_host_keywords = [\"pwd\", \"default\", \"\"]\n for v in VOLUMES:\n mountpoint = v.get('host', \"\")\n if not (\n os.path.isabs(mountpoint) or\n mountpoint in allowed_host_keywords\n ):\n sys.exit(\n \"Failed, please provide absolute paths \"\n \"for all volume mountpoints \"\n \"or use a valid keyword\"\n )\n\n if \"existing_tag\" in jconf:\n tag = jconf[\"existing_tag\"]\n IMAGE_NAME = REPOSITORY_NAME + ':' + tag\n BUILD_ENABLED = False\n else:\n githash = pipe(\"git rev-parse --short HEAD\")\n tag = get_version() + '-' + githash\n IMAGE_NAME = REPOSITORY_NAME + ':' + tag\n\n index_diff = pipe(\"git diff-index -U0 HEAD\")\n if index_diff != \"\":\n diff_hash = hashlib.sha1(index_diff.encode())\n short_hash = diff_hash.hexdigest()[0:7]\n IMAGE_NAME += '-ix_' + short_hash\n\n if BUILD_DIRTY:\n IMAGE_NAME += '-dirty'\n\n if \"extra_options\" in jconf:\n EXTRA_OPTIONS = jconf[\"extra_options\"]\n\n\ndef get_version():\n with open('version.txt', 'r') as f:\n return f.read().rstrip()\n\n\ndef get_cid():\n with open(CIDFILE, 'r') as f:\n return f.read()\n\n\ndef get_volume_mountpoint(volume):\n m = namedtuple('path', 'type')\n\n if 'host' in volume:\n if volume['host'] == 'default':\n m.path = \"{}/{}_{}\".format(\n DEFAULT_MOUNTBASE, REPOSITORY_NAME, volume['tag']\n )\n m.type = \"host\"\n elif volume['host'] == 'pwd':\n m.path = os.getcwd()\n m.type = \"host\"\n else:\n m.path = volume['host']\n m.type = \"host\"\n else:\n m.path = volume['tag']\n m.type = \"docker\"\n\n return m\n\n\ndef generate_dockerignore():\n dockerignore_file = \".dockerignore\"\n\n base_ignored_files = \".git*\\n\"\n c = Path(\".gitignore\")\n if c.is_file():\n exclude_list = pipe(\"git ls-files -o --exclude-standard\")\n copyfile(c, dockerignore_file)\n with open(dockerignore_file, 'a') as f:\n f.write(base_ignored_files)\n f.write(exclude_list)\n return\n\n untracked_files = pipe(\"git ls-files -o\")\n with open(dockerignore_file, 'w') as f:\n f.write(base_ignored_files)\n f.write(untracked_files)\n\ndef get_container_name():\n return pipe(\"docker inspect --format='{{.Name}}' \" + get_cid()).lstrip(\"/\")\n\n\ndef get_port_settings():\n ps = pipe(\n \"docker inspect --format='{{json .NetworkSettings.Ports}}' \" +\n get_cid()\n )\n return json.loads(ps)\n\n\ndef get_volume_mountpoint_from_tag(tag):\n for v in VOLUMES:\n if v[\"tag\"] == tag:\n return get_volume_mountpoint(v)\n\n\ndef generate_nginx_conf():\n text = None\n with open(NGINX_TEMPLATE, 'r') as f:\n text = f.read()\n\n forwarded_ports = get_port_settings()\n\n servers = SERVER_MAP\n\n mapped_servers = []\n\n for s in servers:\n container_port = s['c_port']\n host_port = forwarded_ports[container_port][0]['HostPort']\n ms = s.copy()\n ms.update(\n {\n \"h_port\": host_port,\n \"mapped_volumes\": []\n }\n )\n if \"l_port\" not in s:\n ms.update(\n {\n \"l_port\": 80\n }\n )\n for volume in s.get('volumes_served', []):\n mountpoint = get_volume_mountpoint_from_tag(volume['tag'])\n if mountpoint.type == 'docker':\n print(\n \"Warning: cannot serve unmounted docker volume: \" +\n mountpoint.path\n )\n continue\n if not os.path.exists(mountpoint.path):\n print(\n \"Warning: cannot serve unexistent path: \" +\n mountpoint.path\n )\n continue\n\n mv = volume.copy()\n mv.update(\n {\n \"host_dir\": mountpoint.path\n }\n )\n ms['mapped_volumes'].append(mv)\n\n mapped_servers.append(ms)\n\n t = Template(text)\n o = t.render(\n servers=mapped_servers,\n )\n\n container_name = get_container_name()\n\n file_name = ENVDIR + '/' + container_name + '.conf'\n\n with open(file_name, \"w\") as text_file:\n text_file.write(o)\n\n\ndef copy_nginx_conf():\n container_name = get_container_name()\n file_name = container_name + '.conf'\n source = ENVDIR + '/' + file_name\n target = NGINX_DYN_CONF_DIR + '/' + file_name\n\n copyfile(source, target)\n\n with open(NGINX_CONF_LOCATION_FILE, \"w\") as text_file:\n text_file.write(target)\n\n\ndef test_nginx_conf():\n nopipe(\"sudo nginx -t\")\n\n\ndef read_nginx_conf_location():\n with open(NGINX_CONF_LOCATION_FILE, 'r') as f:\n return f.read().rstrip()\n\n\ndef reload_nginx_conf():\n nopipe(\"sudo nginx -s reload\")\n\n\ndef clean_nginx():\n os.remove(read_nginx_conf_location())\n test_nginx_conf()\n reload_nginx_conf()\n os.remove(NGINX_CONF_LOCATION_FILE)\n\n\n# Note: Deployment of only one environment at a time is supported\ndef deploy_nginx():\n generate_nginx_conf()\n copy_nginx_conf()\n test_nginx_conf()\n reload_nginx_conf()\n\n\ndef build_image():\n if BUILD_ENABLED:\n if not BUILD_DIRTY:\n generate_dockerignore()\n command = \"docker build -t {} .\".format(IMAGE_NAME)\n nopipe(command)\n\n\ndef create_host_mountpoints():\n for v in VOLUMES:\n mountpoint = get_volume_mountpoint(v)\n if mountpoint.type != \"docker\" and not os.path.exists(mountpoint.path):\n os.makedirs(mountpoint.path)\n\n\ndef run(port_override=None):\n env = ENV\n if(env is None):\n sys.exit(\"Failed, missing environment parameter\")\n\n if not os.path.exists(ENVDIR):\n os.makedirs(ENVDIR)\n\n envfile = \".\" + env + \".env\"\n\n e = Path(envfile)\n if not e.is_file():\n sys.exit(envfile + \" not found\")\n\n c = Path(CIDFILE)\n if c.is_file():\n sys.exit(\"Failed, CIDFILE present: \" + CIDFILE)\n\n command = \"docker images -q \" + IMAGE_NAME\n matching_images = pipe(command)\n if(matching_images == ''):\n build_image()\n\n secret_key = secrets.token_urlsafe()\n\n with open(SECRET_KEY_FILE, \"w\") as text_file:\n text_file.write(secret_key)\n\n container_name = env + '-' + REPOSITORY_NAME.replace(\"/\", \"-\")\n\n create_host_mountpoints()\n\n port_forwarding = \"\"\n if port_override:\n po = port_override\n for key in po.keys():\n port_forwarding += \"-p {}:{}:{} \".format(\n po[key][0]['HostIp'],\n po[key][0]['HostPort'],\n key\n )\n else:\n port_forwarding = \"-P\"\n\n volstring = \"\"\n for v in VOLUMES:\n mountpoint = get_volume_mountpoint(v)\n volstring += \"--volume={}:{} \".format(mountpoint.path, v['cont'])\n\n command = \" \\\n docker create {} \\\n --name={} \\\n {} \\\n --env-file={} \\\n --env='S_KEY={}' \\\n {} \\\n --cidfile={} \\\n {} \\\n {} {}\".format(\n CREATE_FLAGS,\n container_name,\n port_forwarding,\n envfile,\n secret_key,\n volstring,\n CIDFILE,\n EXTRA_OPTIONS,\n IMAGE_NAME,\n CMD\n )\n\n nopipe(command)\n\n connect_to_docker_networks()\n\n command = \" \\\n docker start {} \\\n {}\".format(\n RUN_FLAGS,\n container_name\n )\n\n nopipe(command)\n\n\ndef deploy():\n run()\n deploy_nginx()\n\n\ndef dismiss():\n clean_nginx()\n clean()\n\n\ndef reload_container():\n p = get_port_settings()\n stop_container()\n remove_container()\n os.remove(CIDFILE)\n run(p)\n\n\ndef start_container():\n nopipe(\"docker start \" + get_cid())\n\n\ndef stop_container():\n nopipe(\"docker stop \" + get_cid())\n\n\ndef inspect_container():\n nopipe(\"docker inspect \" + get_cid())\n\n\ndef remove_container():\n nopipe(\"docker rm \" + get_cid())\n\n\ndef send_sighup():\n nopipe(\"docker exec \" + get_cid() + \" kill -HUP 1\")\n\n\ndef should_clean_volume(volume):\n # Returns true only if `auto_clean` is set to True and\n # current directory is not mounted\n return volume.get('auto_clean', False) and volume.get('host') != 'pwd'\n\n\ndef clean_marked_volumes():\n start_container()\n for v in VOLUMES:\n if should_clean_volume(v):\n command = \"docker exec {} /bin/sh -c 'rm -rf {}/*'\".format(\n get_cid(),\n v['cont']\n )\n nopipe(command)\n\n\ndef clean_marked_mountpoints():\n for v in VOLUMES:\n if should_clean_volume(v):\n m = get_volume_mountpoint(v)\n if m.type == \"host\":\n rmtree(m.path)\n elif m.type == \"docker\":\n nopipe(\"docker volume rm {}\".format(m.path))\n\n\ndef clean():\n p = Path(NGINX_CONF_LOCATION_FILE)\n if p.is_file():\n sys.exit(\n \"Failed, clean nginx installation with './server.py nclean' \"\n \"before proceeding.\"\n )\n clean_marked_volumes()\n stop_container()\n remove_container()\n clean_marked_mountpoints()\n rmtree(ENVDIR)\n\n\ndef logs():\n nopipe(\"docker logs -f \" + get_cid())\n\n\ndef exec_bash():\n nopipe(\"docker exec -it \" + get_cid() + \" bash\")\n\n\ndef connect_to_docker_networks():\n for n in CONF.get('networks', []):\n command = \"docker network connect {} {}\".format(\n n, get_container_name()\n )\n pipe(command)\n\n\ndef update_script():\n print(\n \"Run the following command in your terminal:\\n\"\n \"curl -O https://raw.githubusercontent.com/\"\n \"jrlangford/docker-server-manager/master/install.sh && \"\n \"chmod +x install.sh && sudo ./install.sh\"\n )\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Easily build and deploy docker images'\n )\n\n command_choices = [\n 'build', 'run', 'start', 'stop', 'clean', 'logs', 'bash',\n 'genconf', 'ndeploy', 'nclean', 'dismiss', 'deploy', 'reload',\n 'inspect', 'hup', 'scriptupdate'\n ]\n parser.add_argument(\n 'command',\n action=\"store\",\n choices=command_choices,\n metavar='command',\n help=\"The command to be run, select one from {}\".format(\n command_choices\n )\n )\n\n source_opts = parser.add_mutually_exclusive_group()\n\n source_opts.add_argument(\n '-f', action=\"store\", dest=\"file\",\n help=\"Set serverconf file to be used\", default='serverconf.json'\n )\n\n source_opts.add_argument(\n '-e', action=\"store\", dest=\"environment\",\n help=\"Set serverconf env to be used\", default=None\n )\n\n parser.add_argument(\n '-c', action=\"store\", dest=\"cmd\",\n help=\"Manually docker command to be run\", default=\"\"\n )\n\n parser.add_argument(\n '-i', action=\"store_const\", dest=\"interactive\",\n help=\"Make session interactive and allocate pseudo-tty to container\",\n const=True\n )\n\n p = parser.parse_args()\n\n a1 = p.command\n\n if(a1 == 'scriptupdate'):\n update_script()\n return\n\n load_conf(p)\n\n\n if(a1 == 'build'):\n build_image()\n elif(a1 == 'run'):\n run()\n elif(a1 == 'start'):\n start_container()\n elif(a1 == 'stop'):\n stop_container()\n elif(a1 == 'clean'):\n clean()\n elif(a1 == 'logs'):\n logs()\n elif(a1 == 'bash'):\n exec_bash()\n elif(a1 == 'genconf'):\n generate_nginx_conf()\n elif(a1 == 'ndeploy'):\n deploy_nginx()\n elif(a1 == 'nclean'):\n clean_nginx()\n elif(a1 == 'dismiss'):\n dismiss()\n elif(a1 == 'deploy'):\n deploy()\n elif(a1 == 'reload'):\n reload_container()\n elif(a1 == 'inspect'):\n inspect_container()\n elif(a1 == 'hup'):\n send_sighup()\n else:\n print(\"Unrecognized command\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":14670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"188678452","text":"# helper functions concerning the ANN architecture\n\nimport torch\nfrom torch import nn\n\nfrom neuralpredictors.training import eval_state\nimport numpy as np\nimport random\n\n\ndef get_io_dims(data_loader):\n \"\"\"\n gets the input and output dimensions from the dataloader.\n :Args\n dataloader: is expected to be a pytorch Dataloader object\n each loader should have as first argument the input in the form of\n [batch_size, channels, px_x, px_y, ...]\n each loader should have as second argument the output in the form of\n [batch_size, output_units, ...]\n :return:\n input_dim: input dimensions, expected to be a tuple in the form of input.shape.\n for example: (batch_size, channels, px_x, px_y, ...)\n output_dim: out dimensions, expected to be a tuple in the form of output.shape.\n for example: (batch_size, output_units, ...)\n \"\"\"\n items = next(iter(data_loader))\n return {k: v.shape for k, v in items._asdict().items()}\n\n\ndef get_dims_for_loader_dict(dataloaders):\n \"\"\"\n gets the input and outpout dimensions for all dictionary entries of the dataloader\n\n :param dataloaders: dictionary of dataloaders. Each entry corresponds to a session\n :return: a dictionary with the sessionkey and it's corresponding dimensions\n \"\"\"\n return {k: get_io_dims(v) for k, v in dataloaders.items()}\n\n\ndef get_module_output(model, input_shape):\n \"\"\"\n Gets the output dimensions of the convolutional core\n by passing an input image through all convolutional layers\n\n :param core: convolutional core of the DNN, which final dimensions\n need to be passed on to the readout layer\n :param input_shape: the dimensions of the input\n\n :return: output dimensions of the core\n \"\"\"\n initial_device = \"cuda\" if next(iter(model.parameters())).is_cuda else \"cpu\"\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n with eval_state(model):\n with torch.no_grad():\n input = torch.zeros(1, *input_shape[1:]).to(device)\n output = model.to(device)(input)\n model.to(initial_device)\n return output.shape\n\n\ndef set_random_seed(seed: int, deterministic: bool = True):\n \"\"\"\n Set random generator seed for Python interpreter, NumPy and PyTorch. When setting the seed for PyTorch,\n if CUDA device is available, manual seed for CUDA will also be set. Finally, if `deterministic=True`,\n and CUDA device is available, PyTorch CUDNN backend will be configured to `benchmark=False` and `deterministic=True`\n to yield as deterministic result as possible. For more details, refer to \n PyTorch documentation on reproducibility: https://pytorch.org/docs/stable/notes/randomness.html\n\n Beware that the seed setting is a \"best effort\" towards deterministic run. However, as detailed in the above documentation,\n there are certain PyTorch CUDA opertaions that are inherently non-deterministic, and there is no simple way to control for them.\n Thus, it is best to assume that when CUDA is utilized, operation of the PyTorch module will not be deterministic and thus\n not completely reproducible.\n\n Args:\n seed (int): seed value to be set\n deterministic (bool, optional): If True, CUDNN backend (if available) is set to be deterministic. Defaults to True. Note that if set\n to False, the CUDNN properties remain untouched and it NOT explicitly set to False.\n \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n if deterministic:\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n torch.manual_seed(seed) # this sets both CPU and CUDA seeds for PyTorch\n\n\ndef move_to_device(model, gpu=True, multi_gpu=True):\n \"\"\"\n Moves given model to GPU(s) if they are available\n :param model: (torch.nn.Module) model to move\n :param gpu: (bool) if True attempt to move to GPU\n :param multi_gpu: (bool) if True attempt to use multi-GPU\n :return: torch.nn.Module, str\n \"\"\"\n device = \"cuda\" if torch.cuda.is_available() and gpu else \"cpu\"\n if multi_gpu and torch.cuda.device_count() > 1:\n print(\"Using \", torch.cuda.device_count(), \"GPUs\")\n model = nn.DataParallel(model)\n model = model.to(device)\n return model, device\n\n\ndef find_prefix(keys: list, p_agree: float = 0.66, separator=\".\") -> (list, int):\n \"\"\"\n Finds common prefix among state_dict keys\n :param keys: list of strings to find a common prefix\n :param p_agree: percentage of keys that should agree for a valid prefix\n :param separator: string that separates keys into substrings, e.g. \"model.conv1.bias\"\n :return: (prefix, end index of prefix)\n \"\"\"\n keys = [k.split(separator) for k in keys]\n p_len = 0\n common_prefix = \"\"\n prefs = {\"\": len(keys)}\n while True:\n sorted_prefs = sorted(prefs.items(), key=lambda x: x[1], reverse=True)\n # check if largest count is above threshold\n if sorted_prefs[0][1] < p_agree * len(keys):\n break\n common_prefix = sorted_prefs[0][0] # save prefix\n\n p_len += 1\n prefs = {}\n for key in keys:\n if p_len == len(key): # prefix cannot be an entire key\n continue\n p_str = \".\".join(key[:p_len])\n prefs[p_str] = prefs.get(p_str, 0) + 1\n return common_prefix, p_len - 1\n\n\ndef load_state_dict(\n model,\n state_dict: dict,\n ignore_missing: bool = False,\n ignore_unused: bool = False,\n match_names: bool = False,\n ignore_dim_mismatch: bool = False,\n prefix_agreement: float = 0.66,\n):\n \"\"\"\n Loads given state_dict into model, but allows for some more flexible loading.\n\n :param model: nn.Module object\n :param state_dict: dictionary containing a whole state of the module (result of `some_model.state_dict()`)\n :param ignore_missing: if True ignores entries present in model but not in `state_dict`\n :param match_names: if True tries to match names in `state_dict` and `model.state_dict()`\n by finding and removing a common prefix from the keys in each dict\n :param ignore_dim_mismatch: if True ignores parameters in `state_dict` that don't fit the shape in `model`\n \"\"\"\n\n model_dict = model.state_dict()\n # 0. Try to match names by adding or removing prefix:\n if match_names:\n # find prefix keys of each state dict:\n s_pref, s_idx = find_prefix(list(state_dict.keys()), p_agree=prefix_agreement)\n m_pref, m_idx = find_prefix(list(model_dict.keys()), p_agree=prefix_agreement)\n # switch prefixes:\n stripped_state_dict = {}\n for k, v in state_dict.items():\n if k.split(\".\")[:s_idx] == s_pref.split(\".\"):\n stripped_key = \".\".join(k.split(\".\")[s_idx:])\n else:\n stripped_key = k\n new_key = m_pref + \".\" + stripped_key if m_pref else stripped_key\n stripped_state_dict[new_key] = v\n state_dict = stripped_state_dict\n\n # 1. filter out missing keys\n filtered_state_dict = {k: v for k, v in state_dict.items() if k in model_dict}\n unused = set(state_dict.keys()) - set(filtered_state_dict.keys())\n if unused and ignore_unused:\n print(\"Ignored unnecessary keys in pretrained dict:\\n\" + \"\\n\".join(unused))\n elif unused:\n raise RuntimeError(\n \"Error in loading state_dict: Unused keys:\\n\" + \"\\n\".join(unused)\n )\n missing = set(model_dict.keys()) - set(filtered_state_dict.keys())\n if missing and ignore_missing:\n print(\"Ignored Missing keys:\\n\" + \"\\n\".join(missing))\n elif missing:\n raise RuntimeError(\n \"Error in loading state_dict: Missing keys:\\n\" + \"\\n\".join(missing)\n )\n\n # 2. overwrite entries in the existing state dict\n updated_model_dict = {}\n for k, v in filtered_state_dict.items():\n if v.shape != model_dict[k].shape:\n if ignore_dim_mismatch:\n print(\"Ignored shape-mismatched parameter:\", k)\n continue\n else:\n raise RuntimeError(\n \"Error in loading state_dict: Shape-mismatch for key {}\".format(k)\n )\n updated_model_dict[k] = v\n\n # 3. load the new state dict\n model.load_state_dict(updated_model_dict, strict=(not ignore_missing))\n","sub_path":"nnfabrik/utility/nn_helpers.py","file_name":"nn_helpers.py","file_ext":"py","file_size_in_byte":8386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"420411377","text":"import sys\nimport pandas as pd\nfrom keras import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\nimport os\nfrom time import strftime\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom os.path import exists\nfrom os import makedirs\nfrom config import *\nfrom keras import regularizers\n\n\n# ---------------------- FROM AND TO CSV -------------------------------------------------------------------------------\n\n# Split the columns of the file to returns features and targets\ndef getTrainData(data_path, DimX, DimY, sep):\n startX, endX = DimX.split(':')\n startY, endY = DimY.split(':')\n data = pd.read_csv(data_path, header=None, sep=sep, comment='#')\n print(data.shape)\n X = np.array(data.iloc[:, int(startX):int(endX)])\n Y = np.array(data.iloc[:, int(startY):int(endY)])\n\n return X, Y\n\n\n# Split the columns of the file to returns features of Blind set\ndef getBlindData():\n data = pd.read_csv(BLIND_DATA, header=None, sep=',', comment='#')\n print(data.shape)\n X = np.array(data.iloc[:, 1:11])\n\n return X\n\n\ndef saveOnCSV(results_records, nameResult, Type):\n results = pd.DataFrame(data=results_records)\n filepath = \"../../DATA/\" + Type + \"/\" + nameResult + \".csv\"\n file = open(filepath, mode='w+')\n if Type.lower() != 'monk':\n results = results.sort_values('mee', ascending=True)\n results.to_csv(file, sep=',', header=True, index=False)\n file.close()\n\n\ndef saveResultsOnCSV(results_records, nameResult):\n results = pd.DataFrame(data=results_records)\n filepath = \"../DATA/RESULTS/\" + nameResult + \".csv\"\n file = open(filepath, mode='w+')\n file.write('# Barreca Gabriele, Bertoncini Gioele\\n')\n file.write('# BarBer\\n')\n file.write('# ML-CUP18\\n')\n file.write('# 15/07/2019\\n')\n results.index += 1\n results.to_csv(file, sep=',', header=False, index=True)\n file.close()\n\n\n# Split the an existing date set in 2 new ones, like split_new.py\ndef split_development_set(validation_perc):\n data = pd.read_csv(CUP, header=None, comment='#')\n\n remove_n = int(len(data.index) / validation_perc)\n\n drop_ind = np.random.choice(data.index, remove_n, replace=False)\n\n val_set = data.iloc[drop_ind, :]\n\n file = open(VAL_SET, mode='w')\n val_set.to_csv(file, sep=',', header=False, index=False)\n\n tr_set = data.drop(drop_ind)\n\n file = open(TRAIN_SET, mode='w')\n tr_set.to_csv(file, sep=',', header=False, index=False)\n\n X_train, Y_train = getTrainData(TRAIN_SET, '1:11', '11:13', ',')\n X_val, Y_val = getTrainData(VAL_SET, '1:11', '11:13', ',')\n\n return X_train, Y_train, X_val, Y_val\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# ------------------------------------- UTILS FOR NN -------------------------------------------------------------------\n\n# Model for NN\ndef create_model(input_dim=10, output_dim=2, learn_rate=0.01, units=100, level=5, momentum=0.9, decay=0,\n activation='relu', lamda=0):\n print(units)\n print(level)\n\n model = Sequential()\n model.add(Dense(units=units, input_dim=input_dim, activation=activation, kernel_regularizer=regularizers.l2(lamda),\n # bias_initializer='zeros',\n use_bias=True))\n\n for l in range(level - 1):\n model.add(Dense(units=units, activation=activation, kernel_regularizer=regularizers.l2(lamda),\n # bias_initializer='zeros',\n use_bias=True))\n\n if output_dim == 2:\n actv = 'linear'\n else:\n actv = 'sigmoid'\n\n model.add(\n Dense(output_dim, activation=actv, kernel_regularizer=regularizers.l2(lamda), bias_initializer='zeros',\n use_bias=True))\n\n optimizer = SGD(lr=learn_rate, momentum=momentum, nesterov=False, decay=decay)\n # Compile model\n model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['accuracy'])\n\n return model\n\n\n# one - of - k encoding. From github\ndef one_of_k(data):\n dist_values = np.array([np.unique(data[:, i]) for i in range(data.shape[1])])\n new_data = []\n First_rec = True\n for record in data:\n new_record = []\n First = True\n indice = 0\n for attribute in record:\n new_attribute = np.zeros(len(dist_values[indice]), dtype=int)\n for j in range(len(dist_values[indice])):\n if dist_values[indice][j] == attribute:\n new_attribute[j] += 1\n if First:\n new_record = new_attribute\n First = False\n else:\n new_record = np.concatenate((new_record, new_attribute), axis=0)\n indice += 1\n if First_rec:\n new_data = np.array([new_record])\n First_rec = False\n else:\n new_data = np.concatenate((new_data, np.array([new_record])), axis=0)\n return new_data\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# ------------------------------------ PLOTS ---------------------------------------------------------------------------\n\ndef print_and_saveGrid(grid_result, save=False, plot=False, nameResult=None, Type=None, ):\n # summarize results\n firstScore = 'loss'\n secondScore = 'mee'\n\n splitPlot = ''\n pivot1 = ''\n pivot2 = ''\n pivot3 = 'mee'\n excluded = ['validation_loss']\n\n meanTrainLoss = grid_result.cv_results_['mean_train_' + firstScore]\n meanTestLoss = grid_result.cv_results_['mean_test_' + firstScore]\n meanTrainMee = grid_result.cv_results_['mean_train_' + secondScore]\n meanTestMee = grid_result.cv_results_['mean_test_' + secondScore]\n split0_test_Loss = grid_result.cv_results_['split0_test_' + firstScore]\n split1_test_Loss = grid_result.cv_results_['split1_test_' + firstScore]\n split2_test_Loss = grid_result.cv_results_['split2_test_' + firstScore]\n split0_test_Mee = grid_result.cv_results_['split0_test_' + secondScore]\n split1_test_Mee = grid_result.cv_results_['split1_test_' + secondScore]\n split2_test_Mee = grid_result.cv_results_['split2_test_' + secondScore]\n params = grid_result.cv_results_['params']\n\n # Print on file\n print(Type)\n if save:\n if Type == 'NN':\n results_records = {'n_layers': [], 'hidden_layers_size': [], 'batch_size': [], 'learning_rate': [],\n 'validation_loss': [], 'mee': []}\n elif Type == 'SVR_RBF':\n results_records = {'C': [], 'gamma': [], 'epsilon': [], 'validation_loss': [], 'mee': []}\n splitPlot = ['epsilon']\n pivot2 = 'gamma'\n pivot1 = 'C'\n elif Type == 'SVR_POLY':\n splitPlot = ['epsilon']\n pivot2 = 'degree'\n pivot1 = 'C'\n excluded = ['validation_loss', 'coef0', 'gamma']\n results_records = {'C': [], 'degree': [],\n 'epsilon': [],\n 'gamma': [],\n 'coef0': [],\n 'validation_loss': [], 'mee': []}\n elif Type == 'RFR':\n results_records = {'n_estimators': [], 'max_depth': [],\n 'min_samples_split': [],\n 'max_features': [],\n 'bootstrap': [],\n 'validation_loss': [],\n 'mee': []}\n elif Type == 'ETR':\n results_records = {'n_estimators': [], 'max_depth': [],\n 'min_samples_split': [],\n 'max_features': [],\n 'bootstrap': [],\n 'validation_loss': [],\n 'mee': []}\n splitPlot = ['random_state']\n pivot2 = 'max_depth'\n pivot1 = 'n_estimators'\n elif Type == 'MONK':\n results_records = {'n_layers': [], 'hidden_layers_size': [], 'batch_size': [], 'learning_rate': [],\n 'decay': [],\n 'momentum': [], 'lamda': [], 'activation': [],\n 'validation_loss': [], 'mee': []}\n\n for meanTRL, meanTL, meanTRM, meanTM, S0TL, S1TL, S2TL, S0TM, S1TM, S2TM, param in zip(meanTrainLoss, meanTestLoss,\n meanTrainMee, meanTestMee,\n split0_test_Loss,\n split1_test_Loss,\n split2_test_Loss,\n split0_test_Mee,\n split1_test_Mee,\n split2_test_Mee, params):\n print(\"%f %f %f %f %f %f %f %f %f %f with: %r\" % (meanTRL, meanTL, meanTRM, meanTM, S0TL, S1TL, S2TL, S0TM,\n S1TM, S2TM, param))\n\n if save:\n if Type == 'NN':\n results_records['n_layers'].append(param['level'])\n results_records['hidden_layers_size'].append(param['units'])\n results_records['batch_size'].append(param['batch_size'])\n results_records['learning_rate'].append(param['learn_rate'])\n print(param['level'])\n print(param['batch_size'])\n elif Type == 'SVR_RBF':\n results_records['C'].append(param['reg__estimator__C'])\n results_records['gamma'].append(param['reg__estimator__gamma'])\n results_records['epsilon'].append(param['reg__estimator__epsilon'])\n elif Type == 'SVR_POLY':\n results_records['C'].append(param['reg__estimator__C'])\n results_records['epsilon'].append(param['reg__estimator__epsilon'])\n results_records['degree'].append(param['reg__estimator__degree'])\n results_records['gamma'].append(param['reg__estimator__gamma'])\n results_records['coef0'].append(param['reg__estimator__coef0'])\n elif Type == \"MONK\":\n results_records['n_layers'].append(param['level'])\n results_records['hidden_layers_size'].append(param['units'])\n results_records['batch_size'].append(param['batch_size'])\n results_records['learning_rate'].append(param['learn_rate'])\n results_records['momentum'].append(param['momentum'])\n results_records['activation'].append(param['activation'])\n results_records['decay'].append(param['decay'])\n results_records['lamda'].append(param['lamda'])\n elif Type == 'RFR':\n results_records['n_estimators'].append(param['n_estimators'])\n results_records['max_depth'].append(param['max_depth'])\n results_records['min_samples_split'].append(param['min_samples_split'])\n results_records['bootstrap'].append(param['bootstrap'])\n results_records['max_features'].append(param['max_features'])\n elif Type == 'ETR':\n results_records['n_estimators'].append(param['n_estimators'])\n results_records['max_depth'].append(param['max_depth'])\n results_records['min_samples_split'].append(param['min_samples_split'])\n results_records['bootstrap'].append(param['bootstrap'])\n results_records['max_features'].append(param['max_features'])\n\n results_records['validation_loss'].append(-meanTL)\n results_records['mee'].append(meanTM)\n\n if plot and save and Type != 'NN':\n plotGrid(pd.DataFrame(data=results_records), splitPlot, pivot1, pivot2, pivot3, excluded, Type)\n if save:\n print(results_records)\n saveOnCSV(results_records, nameResult, Type)\n\n\n# Plot grid\ndef plotGrid(dataframe, splitData, pivot1, pivot2, pivot3, excluded, Type):\n for splt in splitData:\n for d in ([x for _, x in dataframe.groupby(dataframe[splt])]):\n splitValue = d[splt].max()\n if splt not in excluded:\n excluded.append(splt)\n hm = d.drop(excluded, 1).sort_values([pivot2, pivot1])\n fig = plt.figure()\n sns.heatmap(hm.pivot(pivot1, pivot2, pivot3), cmap='binary')\n title = splt + \" \" + str(splitValue) + \" with \" + pivot3\n plt.title(title)\n plt.show()\n\n directory = \"../../Image/\" + Type + \"/\"\n t = strftime(\"%H_%M\")\n file = title.replace(\" \", \"_\") + Type + t + \".png\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n fig.savefig(directory + file)\n\n\ndef train_and_plot_MLP(X_tr, Y_tr, X_val, Y_val, n_layers, n_units, learning_rate, momentum, batch_size, epochs, lamda):\n print(\"Training with: lr=%f, batch size=%f, n layers=%f, units=%f, momentum=%f\" % (\n learning_rate, batch_size, n_layers, n_units, momentum))\n\n model = create_model(learn_rate=learning_rate, units=n_units, level=n_layers, momentum=momentum, lamda=lamda)\n history = model.fit(X_tr, Y_tr, shuffle=True, epochs=epochs, verbose=2, batch_size=batch_size,\n validation_data=(X_val, Y_val))\n\n print(\"Min loss:\", min(history.history['val_loss']))\n\n fig = plt.figure()\n\n plt.plot(history.history['loss'], label=\"TR Loss\")\n plt.plot(history.history['val_loss'], label=\"VL Loss\", linestyle='dashed')\n plt.ylim((0, 2))\n plt.legend(loc='upper right')\n plt.show()\n\n directory = \"../../Image/MLP/\"\n file = \"Eta\" + str(learning_rate) + \"batch\" + str(batch_size) + \"m\" + str(momentum) + \"epochs\" + str(\n epochs) + \"lamda\" + str(lamda) + \".png\"\n if not exists(directory):\n makedirs(directory)\n fig.savefig(directory + file)\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# ------------------------------------ UTILS FOR SVM -------------------------------------------------------------------\n\n# The function sorts the dataframe, takes the first two different values and create a list of elements in its range\ndef getIntervalHyperP(dataFrame, hyperp):\n sorted = dataFrame.sort_values('mee')\n\n best_row = dataFrame[dataFrame.mee == dataFrame.mee.min()]\n\n start = best_row.iloc[0][hyperp]\n end = sorted[sorted[hyperp] != float(best_row[hyperp])].iloc[0][hyperp]\n\n End = np.maximum(start, end)\n Start = np.minimum(start, end)\n print(Start)\n print(End)\n tmp = []\n for x in np.arange(Start, (End + abs(End - Start) / 20), abs(End - Start) / 20):\n tmp.append(float('%.3f' % x))\n\n print(tmp)\n return tmp\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# --------------------------------------- UTILS FOR ALL ----------------------------------------------------------------\n\ndef parseArg(arg):\n if arg.lower() == 'grid':\n global GRID\n GRID = True\n elif arg.lower() == 'cv':\n global CV\n CV = True\n # elif arg.lower() == 'predict':\n # global Predict\n # Predict = True\n else:\n sys.exit(\"Argument not recognized\")\n\n# ----------------------------------------------------------------------------------------------------------------------\n","sub_path":"Script/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"105934378","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2014 Vincent Paeder\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 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n\"\"\"\n\n Generic scan event class.\n\n\"\"\"\n \nimport wx\nfrom terapy.core import icon_path\nfrom wx.lib.pubsub import setupkwargs\nfrom wx.lib.pubsub import pub\n\nclass ScanEvent():\n \"\"\"\n \n Generic scan event class.\n \n Properties:\n __extname__ - long name (str)\n \n \"\"\"\n __extname__ = \"Generic event\"\n def __init__(self, parent = None):\n \"\"\"\n \n Initialization.\n \n Parameters:\n parent - parent window (wx.Window)\n \n \"\"\"\n self.is_loop = False\n self.is_display = False\n self.is_save = False\n self.is_axis = False\n self.is_input = False\n self.is_root = False\n self.is_active = True\n self.is_visible = True\n self.can_run = True\n self.host = parent\n self.name = self.__extname__\n self.itmList = []\n self.propNodes = []\n self.propNames = []\n self.m_id = 0\n #self.propFont = wx.Font(8,wx.DECORATIVE,wx.NORMAL,wx.NORMAL)\n #self.propColour = \"#3F3F3F\"\n self.config = [] # variables to be saved in config files\n pub.subscribe(self.stop, \"scan.stop\")\n \n def __del__(self):\n \"\"\"\n \n Actions necessary on scan event deletion.\n \n \"\"\"\n pub.unsubscribe(self.stop, \"scan.stop\")\n \n def run(self, data):\n \"\"\"\n \n Run scan event.\n \n Parameters:\n data - measurement (Measurement)\n \n \"\"\"\n return True\n\n def stop(self, inst=None):\n \"\"\"\n \n Stop scan.\n \n Parameters:\n inst - pubsub event data\n \n \"\"\"\n self.can_run = False\n \n def refresh(self):\n \"\"\"\n \n Refresh scan event.\n \n \"\"\"\n self.can_run = True\n \n def get_operation_count(self):\n \"\"\"\n \n Tell how many \"operations\" this event will generate.\n Normal events do one operation. Loops do one operation per iteration.\n \n Output:\n number of operations (int)\n \n \"\"\"\n return 1\n \n def run_children(self, data):\n \"\"\"\n \n Run scan event children.\n \n Parameters:\n data - measurement (Measurement)\n \n \"\"\"\n for x in self.itmList:\n if self.can_run:\n ev = self.host.GetItemPyData(x)\n if ev.is_active:\n if ev.is_display or ev.is_save:\n ev.run(data)\n elif ev.is_input:\n ev.run(data)\n data.current += 1\n elif ev.is_axis:\n ev.run([])\n elif ev.is_loop:\n data.IncrementScanDimension(self.m_ids)\n ev.run(data)\n return True\n \n def set(self, parent=None):\n \"\"\"\n \n Run scan event configuration procedure.\n \n Parameters:\n parent - parent window (wx.Window)\n \n Output:\n True if successful\n \n \"\"\"\n return True\n \n def get_children(self):\n \"\"\"\n \n Get scan event children. Wrapper to TreeCtrl function.\n \n Output:\n children as list of ScanEvent\n \n \"\"\"\n itm = self.host.FindItem(self)\n return self.host.GetItemChildren(itm,ScanEvent)\n \n def populate(self):\n \"\"\"\n \n Populate host tree structure with properties.\n \n \"\"\"\n if len(self.propNodes)>0:\n self.create_property_root()\n self.set_property_nodes(expand=True)\n \n def create_property_root(self):\n \"\"\"\n \n Create property root in host tree structure.\n \n \"\"\"\n itm = self.host.FindItem(self)\n if self.get_property_node()==None:\n propRoot = self.host.AppendItem(itm,\"Properties\")\n self.host.SetItemPyData(propRoot,PropertyNode())\n else:\n self.host.DeleteChildren(self.get_property_node())\n \n def get_property_node(self, n=-1):\n \"\"\"\n \n Return item corresponding to given property node index\n \n Parameters:\n n - property node index (if n==-1, return property root)\n \n Output:\n tree item (wx.TreeItem)\n \n \"\"\"\n root = self.host.FindItem(self)\n propRoot = self.host.GetItemChildren(root,PropertyNode)\n if n==-1: # return root\n if len(propRoot)==0:\n return None\n else:\n return propRoot[0]\n else: # return property node number n\n itms = self.host.GetItemChildren(propRoot[0])\n return itms[n]\n \n \n def set_property_nodes(self, expand=False):\n \"\"\"\n \n Set property node values.\n \n Parameters:\n expand - if True, expand property folder, collapse if False\n \n \"\"\"\n root = self.get_property_node()\n if root!=None:\n children = self.host.GetItemChildren(root)\n if len(children) != len(self.propNames):\n self.host.DeleteChildren(root)\n for n in range(len(self.propNames)):\n self.host.AppendItem(root,self.propNames[n]+\": \"+str(self.propNodes[n]))\n children = self.host.GetItemChildren(root)\n else:\n for n in range(len(children)):\n self.host.SetItemText(children[n],self.propNames[n]+\": \"+str(self.propNodes[n]))\n \n children.append(root)\n propFont = wx.Font(8,wx.DECORATIVE,wx.NORMAL,wx.NORMAL)\n if wx.Platform == \"__WXMAC__\":\n propFont.SetFaceName(\".LucidaGrandeUI\")\n propColour = \"#3F3F3F\"\n for x in children:\n self.host.SetItemFont(x,propFont)\n self.host.SetItemTextColour(x,propColour)\n if expand:\n self.host.Expand(root)\n \n def set_property(self, pos, val):\n \"\"\"\n \n Set given property to given value.\n \n Parameters:\n pos - property index (int)\n val - value\n \n \"\"\"\n self.propNodes[pos] = val\n \n def edit_label(self, event, pos):\n \"\"\"\n \n Actions triggered by edit tree label event corresponding to given property node.\n \n Parameters:\n event - wx.Event\n pos - property index (int)\n \n \"\"\"\n pass\n \n def check_validity(self, data):\n \"\"\"\n \n Check whether given data can be processed by this event.\n \n Parameters:\n data - data array (DataArray) or measurement (Measurement)\n \n Output:\n True if yes\n \n \"\"\"\n return True\n \n def get_icon(self):\n \"\"\"\n \n Return scan event icon.\n \n Output:\n 16x16 icon (wx.Bitmap)\n \n \"\"\"\n return wx.Image(icon_path + \"empty.png\").ConvertToBitmap()\n \n\nclass PropertyNode():\n \"\"\"\n \n Property node class\n \n Differentiate property nodes from other tree items.\n \n \"\"\"\n def __init__(self):\n \"\"\"\n \n Initialization.\n \n \"\"\"\n self.is_loop = False\n self.is_root = False\n","sub_path":"terapy/scan/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"184637203","text":"import json\nimport logging\nimport requests\nfrom typing import Optional, Any, Union, Tuple, List, Dict\nimport urllib.parse\nimport datetime as dt\nimport re\n\nfrom sqlalchemy.orm.session import Session as SqaSession\n\nfrom assistant.database import Session\nfrom assistant.database import User, StudentsGroup, Faculty, Lesson, SingleLesson, Teacher\n\nlogger = logging.getLogger(__name__)\nfull_name_mask = re.compile(r\"^\\s*?([а-яїєі']+)\\s*?([а-яїєі']+)\\.?\\s*?([а-яїєі']+)\\.?\\s*?$\", re.I)\n\n\nclass TimetableScrapper:\n\n def __init__(self, db_session: Optional[SqaSession] = None):\n if db_session is None:\n db_session = Session()\n self.db = db_session\n\n self.session = requests.Session()\n\n def __del__(self):\n self.session.close()\n\n def run(self):\n self.db.query(SingleLesson).delete()\n\n raw_groups = self.get(\"https://api.mytimetable.live/rest/groups/\", {\"univ\": 1})\n for raw_group in raw_groups[\"results\"]:\n try:\n raw_timetable = self.get(\"https://api.mytimetable.live/rest/timetable/\", {\"group\": raw_group[\"slug\"]})\n if raw_timetable is None or \"lessons\" not in raw_timetable.keys():\n continue\n\n # Get/Create a faculty\n raw_faculty = raw_timetable[\"lessons\"][0][\"faculty\"]\n faculty = self.db.query(Faculty).filter(Faculty.name==raw_faculty[\"name\"]).first()\n if faculty is None:\n faculty = Faculty(\n name=raw_faculty[\"name\"],\n shortcut=raw_faculty[\"short_name\"] or raw_faculty[\"name\"],\n )\n self.db.add(faculty)\n\n # Get/Create a group\n group = self.db.query(StudentsGroup).filter_by(\n name=raw_group[\"name\"],\n course=int(raw_group[\"course_name\"]),\n faculty=faculty,\n ).first()\n if group is None:\n group = StudentsGroup(\n name=raw_group[\"name\"],\n course=int(raw_group[\"course_name\"]),\n faculty=faculty,\n )\n self.db.add(group)\n group_timetable = dict() # {(theme, teachers, subgroup, format): [raw_lessons]}\n\n for raw_lesson in raw_timetable[\"lessons\"]:\n subgroup = (raw_lesson[\"subgroup\"] or \"\").strip() or None\n\n # Unique Lesson key\n lesson_key = (raw_lesson[\"name_full\"], subgroup, raw_lesson[\"format\"])\n if group_timetable.get(lesson_key, None) is None:\n lesson = self.db.query(Lesson).filter_by(\n name=raw_lesson[\"name_full\"],\n students_group=group,\n subgroup=subgroup,\n lesson_format=raw_lesson[\"format\"],\n ).first()\n if lesson is None:\n lesson = Lesson(\n name=raw_lesson[\"name_full\"],\n students_group=group,\n subgroup=subgroup,\n lesson_format=raw_lesson[\"format\"],\n )\n self.db.add(lesson)\n\n # Attach teachers to the lesson\n for raw_teacher in raw_lesson[\"teachers\"]:\n match = full_name_mask.match(raw_teacher[\"full_name\"])\n if match is not None:\n last_name, first_name, middle_name = match.groups()\n else:\n last_name, first_name, middle_name = raw_teacher[\"full_name\"], \"\", \"\"\n teacher = self.db.query(Teacher)\\\n .filter_by(last_name=last_name, first_name=first_name, middle_name=middle_name)\\\n .first()\n if teacher is None:\n teacher = Teacher(\n last_name=last_name,\n first_name=first_name,\n middle_name=middle_name,\n )\n self.db.add(teacher)\n lesson.teachers.append(teacher)\n group_timetable[lesson_key] = lesson\n\n starts_at = None\n ends_at = None\n for lesson_time in raw_timetable[\"lesson_time\"]:\n if lesson_time[\"id\"] == raw_lesson[\"lesson_time\"]:\n starts_at = dt.datetime.strptime(lesson_time[\"start\"], \"%H:%M\").time()\n ends_at = dt.datetime.strptime(lesson_time[\"end\"], \"%H:%M\").time()\n break\n\n for date in raw_lesson[\"dates\"]:\n single_lesson = SingleLesson(\n lesson=group_timetable[lesson_key],\n date=dt.datetime.strptime(date, \"%Y-%m-%d\").date(),\n starts_at=starts_at,\n ends_at=ends_at,\n )\n self.db.add(single_lesson)\n except Exception as e:\n logger.error(\"got error while parsing {}: {}\".format(raw_group.get(\"name\", None), str(e)))\n continue\n else:\n continue\n self.db.commit()\n\n def get(self, url: str, params: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:\n if params is not None and len(params) > 0:\n parts = list(urllib.parse.urlparse(url))\n q = dict(urllib.parse.parse_qsl(parts[4]))\n q.update(params)\n parts[4] = urllib.parse.urlencode(q)\n url = urllib.parse.urlunparse(parts)\n\n response = self.session.get(url)\n if response.status_code < 200 or response.status_code >= 300:\n logger.error(\"got error fetching {} ({}): {}\".format(url, response.status_code, response.content))\n return None\n try:\n body: Dict = response.json()\n # processing multiple pages\n if body.get(\"next\", None) is not None:\n extension = self.get(body[\"next\"])\n if extension is not None:\n # join two responses\n for k, v in extension.items():\n if k in body.keys():\n if isinstance(v, dict):\n for vk, vv in v.items():\n if vk not in body[k].keys():\n body[k][vk] = vv\n elif isinstance(v, list):\n for vv in v:\n if vv not in body[k]:\n body[k].append(vv)\n else:\n body[k] = v\n return body\n except (ValueError, json.JSONDecodeError) as e:\n logger.error(\"got error parsing json {}: {}\".format(url, str(e)))\n return None\n\n\nif __name__ == '__main__':\n # TODO: argparse\n scrapper = TimetableScrapper()\n scrapper.run()\n\n","sub_path":"assistant/timetable_scrapper/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":7585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"199597946","text":"import gzip\nimport json\nfrom pathlib import Path\nfrom subprocess import DEVNULL, STDOUT, check_call\n\nimport pandas as pd\n\nimport feather\nimport statsmodels.api as sm\n\nif __name__ == \"__main__\":\n\n # Config\n DATA_DIR = Path(\".\") / \"data\"\n base_url = \"https://docs.google.com/spreadsheets/d/1CHMArwUdVza-ayOT1aG2tRJJfa1OWvwfMGiCu20X7Ys/export\"\n urls = {\n \"uk\": base_url + \"?gid=1495247060&format=csv\",\n \"london\": base_url + \"?gid=683561754&format=csv\",\n \"scotland\": base_url + \"?gid=1896448771&format=csv\",\n \"wales\": base_url + \"?gid=2059731736&format=csv\",\n \"ni\": base_url + \"?gid=1413308295&format=csv\",\n }\n cutoff_date = \"2017-01-01\"\n\n # RETRIEVE DATA\n print(\"Downloading from Google Sheet\")\n polls = {}\n for geo in urls:\n polls[geo] = pd.read_csv(urls[geo], low_memory=False)\n\n # PROCESS\n # Define parties, respect ordering from Google Doc\n def get_party_names(input_list):\n # Ignore these columns\n cols_to_ignore = [\n \"Company\",\n \"Client\",\n \"Type\",\n \"Method\",\n \"From\",\n \"To\",\n \"Sample Size\",\n \"Source\",\n \"PDF\",\n \"DataSource\",\n ]\n for col_name in cols_to_ignore:\n if col_name in input_list:\n input_list.remove(col_name)\n # Slugify parties\n input_list = [x.lower().replace(\" \", \"_\") for x in input_list]\n return input_list\n\n parties = {}\n for geo in urls:\n parties[geo] = get_party_names(list(polls[geo].columns))\n\n # Formatting\n for geo in parties:\n # Rename columns\n polls[geo].columns = [x.lower().replace(\" \", \"_\") for x in polls[geo].columns]\n\n # Remove cols we don't want\n if \"source\" in polls[geo].columns:\n del polls[geo][\"source\"]\n\n # Format percentages into decimal\n for col in parties[geo]:\n polls[geo][col] = polls[geo][col].apply(lambda x: x / 100)\n\n # Process dates\n polls[geo][\"to\"] = pd.to_datetime(polls[geo][\"to\"])\n polls[geo][\"from\"] = pd.to_datetime(polls[geo][\"from\"])\n\n # Add LOWESS smoothing for 2017 data only\n polls_smoothed = {}\n for geo in parties:\n polls_smoothed[geo] = polls[geo][polls[geo].to >= cutoff_date].groupby(\"to\").mean().reset_index()\n polls_smoothed[geo] = polls_smoothed[geo].ffill(limit=None).bfill(limit=None)\n for party in parties[geo]:\n polls_smoothed[geo][party + \"_smooth\"] = sm.nonparametric.lowess(\n polls_smoothed[geo][party], polls_smoothed[geo][\"to\"], frac=0.15\n )[:, 1]\n polls_smoothed[geo] = polls_smoothed[geo][[\"to\"] + [col + \"_smooth\" for col in parties[geo]]]\n polls_smoothed[geo].columns = [\"date\"] + parties[geo]\n\n # EXPORT\n def multi_format_export(df, filename):\n df.to_json(str(DATA_DIR / (filename + \".json\")), orient=\"records\")\n df.to_csv(DATA_DIR / (filename + \".csv\"), index=False)\n feather.write_dataframe(df, str(DATA_DIR / (filename + \".feather\")))\n\n for geo in parties:\n filename = \"polls_\" + geo if geo != \"uk\" else \"polls\"\n multi_format_export(polls[geo], filename)\n multi_format_export(polls_smoothed[geo], filename + \"_smoothed\")\n\n # Combine polls with polls_smoothed\n combined = [\n json.loads(polls[geo][polls[geo].to > cutoff_date].to_json(orient=\"records\")),\n json.loads(polls_smoothed[geo].to_json(orient=\"records\")),\n ]\n with open(str(DATA_DIR / (filename + \"_tracker\" + \".json\")), \"w\") as f:\n f.write(json.dumps(combined))\n with gzip.open(str(DATA_DIR / (filename + \"_tracker\" + \".json.gz\")), \"w\") as f:\n f.write(json.dumps(combined).encode(\"utf-8\"))\n\n # Upload to S3\n print(\"Uploading to S3...\")\n files_to_upload = []\n for geo in parties:\n filename = \"polls_\" + geo if geo != \"uk\" else \"polls\"\n for file_format in [\".json\", \".csv\", \".feather\"]:\n files_to_upload.append(DATA_DIR / (filename + file_format))\n files_to_upload.append(DATA_DIR / (filename + \"_smoothed\" + file_format))\n files_to_upload.append(DATA_DIR / (filename + \"_tracker.json\"))\n files_to_upload.append(DATA_DIR / (filename + \"_tracker.json.gz\"))\n\n for file_path in files_to_upload:\n print(\"\\t{}\".format(file_path))\n key = file_path.name\n body = str(file_path.resolve())\n acl = \"public-read\"\n check_call(\n [f\"aws s3api put-object --bucket sixfifty --key '{key}' --body '{body}' --acl {acl}\"],\n stdout=DEVNULL,\n stderr=STDOUT,\n shell=True,\n )\n","sub_path":"data/polls/generate_json.py","file_name":"generate_json.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"228679025","text":"import csv\n\ndef lesaskra(skra):\n\twith open(skra) as csvfid:\n\t\t#dialect = csv.Sniffer().sniff(csvfid.read(1024))\n\t\ta = csv.reader(csvfid,delimiter=',')\n\t\treturn {row[0]:row[1:] for row in a}\n\nnofn = lesaskra('diggeroutput.csv')\nprint(nofn)\nprint(nofn['Reykjavík'][0])\n","sub_path":"digger/csvreader.py","file_name":"csvreader.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"469439944","text":"class Print:\n\tdef __init__( self, edition, print_id, partiture ):\n\t\tself.Edition = edition\n\t\tself.print_id = print_id\n\t\tself.Partiture = partiture\n\tdef format( self ):\n\t\tprint(str(self))\n\tdef composition( self ):\n\t\treturn self.Edition.Composition\n\tdef __str__(self):\n\t\tline = \"\"\n\t\tif(self.print_id != None):\n\t\t\tline = line + \"Print Number: \" + str(self.print_id) + \"\\n\"\n\t\tif(self.edition != None):\n\t\t\tline = line + str(self.edition)\n\t\tif(self.partiture != None):\n\t\t\tif(self.partiture):\n\t\t\t\tline = line + \"Partiture: yes\" + \"\\n\"\n\t\t\telse:\n\t\t\t\tline = line + \"Partiture: no\" + \"\\n\"\n\t\treturn line\n\nclass Edition:\n\tdef __init__( self, composition, authors, name ):\n\t\tself.Edition = name\n\t\tself.Composition = composition\n\t\tself.Editor = authors\n\t\t\n\tdef __str__(self):\n\t\tline = \"\"\n\t\tif(self.composition != None):\n\t\t\tline = line + str(self.composition)\n\t\tif(self.name != None):\n\t\t\tline = line + \"Edition: \" + self.name + \"\\n\"\n\t\tif(len(self.authors) > 0):\n\t\t\tline = line + \"Editor: \" + str(self.authors[0]) + \"\\n\"\n\n\t\treturn line\n\t\nclass Composition:\n\tdef __init__( self, name, incipit, key, genre, year, voices, authors ):\n\t\tself.Title = name\n\t\tself.Incipit = incipit\n\t\tself.Key = key\n\t\tself.Genre = genre\n\t\tself.year = year\n\t\tself.Voices = voices\n\t\tself.Composer = authors\n\tdef __str__(self):\n\t\tline = \"\"\n\t\tif(len(self.authors) > 0):\n\t\t\tline = line + \"Composer: \"\n\t\t\tindex = 0\n\t\t\tfor author in self.authors:\n\t\t\t\tif(index > 0):\n\t\t\t\t\tline = line + \"; \" + str(author)\n\t\t\t\telse:\n\t\t\t\t\tline = line + str(author)\n\t\t\t\tindex = index + 1\n\t\t\tline = line + \"\\n\"\n\t\tif(self.name != None):\n\t\t\tline = line + \"Title: \" + self.name + \"\\n\"\n\t\tif(self.genre != None):\n\t\t\tline = line + \"Genre: \" + self.genre + \"\\n\"\n\t\tif(self.key != None):\n\t\t\tline = line + \"Key: \" + self.key + \"\\n\"\n\t\tif(self.year != None):\n\t\t\tline = line + \"Composition Year: \" + str(self.year) + \"\\n\"\n\t\tif(self.incipit != None):\n\t\t\tline = line + \"Incipit: \" + self.incipit + \"\\n\"\n\t\tcounter = 1\n\t\tif(len(self.voices) > 0):\n\t\t\tfor voice in self.voices:\n\t\t\t\tif(voice != None):\n\t\t\t\t\tline = line + \"Voice \" + str(counter) + \": \" + str(voice)\t\t\t\t\t\n\t\t\t\tcounter = counter + 1\n\n\t\treturn line\n\t\t\nclass Voice:\n\tdef __init__( self, name, range ):\n\t\tself.Name = name\n\t\tself.Range = range\n\tdef __str__(self):\n\t\tline = \"\"\n\t\tif(self.range != None):\n\t\t\tline = self.range + \", \" + self.name + \"\\n\"\n\t\telif(self.name != None):\n\t\t\tline = self.name + \"\\n\"\n\t\treturn line\n\t\nclass Person:\n\tdef __init__( self, name, born, died ):\n\t\tself.Name = name\n\t\tself.Born = born\n\t\tself.Died = died\n\tdef __str__(self):\n\t\tcompLine = \"\"\n\t\tb = \"\"\n\t\td = \"\"\n\t\t\n\t\tif(self.born != None):\n\t\t\tb = str(self.born)\n\t\tif(self.died != None):\n\t\t\td = str(self.died)\n\t\t\t\n\t\tif(self.name != None):\n\t\t\tcompLine = compLine + self.name\n\t\tif(b != \"\" or d != \"\"):\n\t\t\tcompLine = compLine + \" (\" + b + \"--\" + d + \")\"\n\t\t\n\t\treturn compLine","sub_path":"04/scorelib.py","file_name":"scorelib.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"77499070","text":"import math\n\nclass Weighting(object):\n\n def __init__(self,data,terms):\n\n '''\n Parameters:\n 1. data ex: = [\"lorem ipsum\",\"dolor sit amet\"]\n 2. terms ex: = [\"ipsum\",\"sit\"]\n '''\n\n self.data = data\n self.terms = terms\n self.raw_tf = {}\n self.log_tf = {}\n self.idf = []\n self.tf_idf = {}\n \n def countWord(self,term, document):\n count = 0\n for word in document.split():\n if term == word:\n count+=1\n return count\n\n def dftCount(self,numbers):\n count = len(self.data)\n for number in numbers:\n if number == 0:\n count-=1\n return count\n\n def get_raw_tf_weighting(self):\n for term in self.terms:\n temp = []\n for data in self.data:\n temp.append(self.countWord(term, data))\n self.raw_tf[term] = temp\n # buatprint = []\n # buatprint.append(term)\n # for t in temp:\n # buatprint.append(str(t))\n # print(\";\".join(buatprint))\n return self.raw_tf\n\n def get_log_tf_weighting(self):\n self.get_raw_tf_weighting()\n for term in self.terms:\n temp = []\n for i in range(len(self.raw_tf[term])):\n tf = 0 if (self.raw_tf[term])[i] == 0 else 1+math.log((self.raw_tf[term])[i],10)\n temp.append(tf)\n self.log_tf[term] = temp\n # buatprint = []\n # buatprint.append(term)\n # for t in temp:\n # if t!= 0 and t!= 1:\n # formatdulu = \"{:.3f}\".format(t)\n # else : \n # formatdulu = t\n # buatprint.append(str(formatdulu))\n # print(\";\".join(buatprint))\n return self.log_tf\n\n def calculate_idf(self):\n for term in self.terms:\n df = self.dftCount(self.raw_tf[term])\n # buatprint = []\n # buatprint.append(term)\n # buatprint.append(str(df))\n # print(\";\".join(buatprint))\n idf_value = math.log(len(self.data)/df,10)\n # print(term+\";\"+str(\"{:.3f}\".format(idf_value)))\n self.idf.append(idf_value)\n return self.idf\n\n def get_idf(self):\n return self.idf\n\n def get_tf_idf_weighting(self):\n self.get_log_tf_weighting()\n self.calculate_idf()\n count = 0\n for term in self.terms:\n temp = []\n for i in range(len(self.data)):\n tfidf_value = self.log_tf[term][i]*self.idf[count]\n temp.append(tfidf_value)\n self.tf_idf[term] = temp\n # buatprint = []\n # buatprint.append(term)\n # for t in temp:\n # if t!= 0 and t!= 1:\n # formatdulu = \"{:.3f}\".format(t)\n # else : \n # formatdulu = t\n # buatprint.append(str(formatdulu))\n # print(\";\".join(buatprint))\n count+=1\n return self.tf_idf\n","sub_path":"Keperluan Sidang/Code - Copy/weighting.py","file_name":"weighting.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"324697255","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-11-12 23:36:32\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\nimport requests\nimport re\nimport json\n#url=\"http://sci.jmu.edu.cn/\"\nurl=\"http://ae.jmu.edu.cn/\"\n\ns=r\"addItem[(]'(.*?)','(.*?)'[)]\"\npattern=re.compile(s)\nstring=requests.get(url)\nnew=pattern.findall(str(string.content,encoding='utf-8'))\nfor n in new:\n\tprint(n[1])\n\n\n['http://arts.jmu.edu.cn/index/xyfc.htm',\n'http://arts.jmu.edu.cn/wszt/xszp.htm',\n'http://arts.jmu.edu.cn/wszt/jszp.htm']","sub_path":"scrapyToText/try/try/re_test.py","file_name":"re_test.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"169069082","text":"# ch21_23.py\nimport bs4\n\nhtmlFile = open('myhtml.html', encoding='utf-8')\nobjSoup = bs4.BeautifulSoup(htmlFile, 'lxml')\nimgTag = objSoup.select('img')\nprint(\"含標籤的串列長度 = \", len(imgTag))\nfor i in range(len(imgTag)): \n print(imgTag[i]) \n\n\n\n \n\n\n\n\n \n","sub_path":"pratice/範例檔案/ch21/ch21_23.py","file_name":"ch21_23.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"113807240","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport os\nimport testtools # noqa\nimport uuid\n\nfrom tempest.api.aflo import base\nfrom tempest import config_aflo as config # noqa\nfrom tempest.lib import exceptions\n\nfrom tempest.api.aflo.fixture import sample_set_catalog_monthly as fixture\nfrom tempest.api.aflo import test_workflowpattern\n\nCONF = config.CONF\nFOLDER_PATH = 'tempest/api/aflo/operation_definition_files/'\n\n\nclass TicketTemplateAdminTest(base.BaseV1AfloAdminTest):\n \"\"\"Aflo Test Class by admin.\"\"\"\n\n @classmethod\n def resource_setup(cls):\n \"\"\"Setup Resources.\"\"\"\n super(TicketTemplateAdminTest, cls).resource_setup()\n\n def test_ticket_template(self):\n \"\"\"Test 'Data Between Created to Deleted'\"\"\"\n # Get contract info ids.\n goods_ids, catalog_ids, contents_ids, scope_ids, price_ids = \\\n get_contract_info_ids(self)\n\n # Get invalid contract info ids.\n i_goods_ids, i_catalog_ids, i_cont_ids, i_scope_ids, i_price_ids = \\\n get_contract_info_ids(self, False)\n\n # Create data.\n workflow_pattern_id = \\\n test_workflowpattern.create_workflow_pattern(\n self,\n [\"workflow_pattern_contents_001.json\",\n \"workflow_pattern_contents_002.json\",\n \"workflow_pattern_contents_003.json\"])\n\n ticket_template_ids = []\n ticket_template_id = create_ticket_template(\n self,\n [\"ticket_template_contents_001\"], '20160627')\n ticket_template_ids.append(ticket_template_id[0])\n # Valid catalog data.\n ticket_template_id = create_ticket_template(\n self,\n [\"ticket_template_contents_002\"],\n '20160627', catalog_ids)\n ticket_template_ids.append(ticket_template_id[0])\n # Invalid catalog data.\n ticket_template_id = create_ticket_template(\n self,\n [\"ticket_template_contents_003\"],\n '20160627', i_catalog_ids)\n ticket_template_ids.append(ticket_template_id[0])\n\n # Get a ticket template.\n self._test_get_ticket_template(ticket_template_ids)\n\n # Delete data.\n delete_ticket_template(self, ticket_template_ids)\n test_workflowpattern.delete_workflow_pattern(\n self, workflow_pattern_id)\n\n delete_contract_info_data(self,\n None,\n goods_ids,\n catalog_ids,\n contents_ids,\n scope_ids,\n price_ids)\n delete_contract_info_data(self,\n None,\n i_goods_ids,\n i_catalog_ids,\n i_cont_ids,\n i_scope_ids,\n i_price_ids)\n\n def _test_get_ticket_template(self, ticket_template_id):\n \"\"\"Test 'Get a list of ticket template'.\n :param ticket_template_id: List of ticket template id.\n \"\"\"\n resp, body = self.aflo_client.list_tickettemplate()\n self._check_template(body, ticket_template_id)\n\n resp, body = self.aflo_client.list_tickettemplate(\n \"ticket_type=New+Contract,request\")\n self._check_template(body, ticket_template_id)\n\n resp, body = self.aflo_client.list_tickettemplate(\n \"sort_key=created_at&sort_key=updated_at\"\n \"&sort_dir=asc&sort_dir=asc&ticket_type=New+Contract\")\n self._check_template(body,\n [ticket_template_id[1],\n ticket_template_id[2]])\n\n resp, body = self.aflo_client.list_tickettemplate(\n \"enable_expansion_filters=false\")\n self._check_template(body, ticket_template_id)\n\n resp, body = self.aflo_client.list_tickettemplate(\n \"enable_expansion_filters=true\")\n self._check_template(body,\n [ticket_template_id[0],\n ticket_template_id[1]])\n\n # Invalid values will be the same as 'False'.\n resp, body = self.aflo_client.list_tickettemplate(\n \"enable_expansion_filters=aaaaaa\")\n self._check_template(body, ticket_template_id)\n\n resp, body = self.aflo_client.get_tickettemplate(\n ticket_template_id[0])\n self.assertEqual(body['id'], ticket_template_id[0])\n\n def _check_template(self, body, ticket_template_id):\n count = 0\n for template in ticket_template_id:\n for db_template in body:\n if template == db_template['id']:\n count = count + 1\n self.assertTrue(count == len(ticket_template_id))\n\n def test_get_tiket_template_irregular_ticket_type(self):\n \"\"\"Test 'List search of ticket template.'\n Test of if you filtering irregular ticket type.\n \"\"\"\n # Create data.\n workflow_pattern_id = \\\n test_workflowpattern.create_workflow_pattern(\n self, [\"workflow_pattern_contents_001.json\"])\n ticket_template_id = create_ticket_template(\n self, [\"ticket_template_contents_001\"], '20160627')\n\n resp, body = self.aflo_client.list_tickettemplate(\n \"ticket_type=aaaaa\")\n\n self.assertTrue(len(body) == 0)\n\n # Delete data.\n delete_ticket_template(self, ticket_template_id)\n test_workflowpattern.delete_workflow_pattern(\n self, workflow_pattern_id)\n\n def test_ticket_template_create_no_data_irreguler(self):\n \"\"\"Test 'Create a ticket template'.\n Test the operation of the parameter without.\n \"\"\"\n field = {}\n\n self.assertRaises(exceptions.BadRequest,\n self.aflo_client.create_tickettemplate,\n field)\n\n def test_ticket_template_delete_no_data_irreguler(self):\n \"\"\"Test 'Delete the ticket template'.\n Test the operation of the parameter without.\n \"\"\"\n id = None\n\n self.assertRaises(exceptions.NotFound,\n self.aflo_client.delete_tickettemplate,\n id)\n\n\nclass TicketTemplateTest(base.BaseV1AfloTest):\n \"\"\"Aflo Test Class.\"\"\"\n\n @classmethod\n def resource_setup(cls):\n \"\"\"Setup Resources.\"\"\"\n super(TicketTemplateTest, cls).resource_setup()\n\n def test_ticket_template_create_no_authority_irreguler(self):\n \"\"\"Test 'Create a ticket template'.\n Test the operation of the Delete API(Not exist authority).\n \"\"\"\n self.assertRaises(exceptions.Forbidden,\n create_ticket_template,\n self,\n [\"ticket_template_contents_001\"], '20160627')\n\n def test_ticket_template_delete_no_authority_irreguler(self):\n \"\"\"Test 'Delete a ticket template'.\n Test the operation of the Delete API(Not exist authority).\n \"\"\"\n id = str(uuid.uuid4())\n\n self.assertRaises(exceptions.Forbidden,\n self.aflo_client.delete_tickettemplate,\n id)\n\n\ndef create_ticket_template(self, files_prefix, version, catalogs=None,\n cancelling_template_id=None):\n \"\"\"Test 'Create a ticket template'.\n :param files_prefix: Create ticket template files prefix.\n :param catalogs: Catalog ids.\n :param cancelling_template_id: Cancelling template id.\n \"\"\"\n id = []\n\n for file_prefix in files_prefix:\n file_name = '%(file_prefix)s_%(version)s.json' \\\n % {'file_prefix': file_prefix, 'version': version}\n obj = open(os.path.join(FOLDER_PATH, file_name)).read()\n contents = json.loads(obj)\n\n if catalogs:\n contents['target_id'] = catalogs\n\n if cancelling_template_id:\n contents['cancelling_template']['id'] = cancelling_template_id\n\n field = {'template_contents': contents}\n\n req, body = self.aflo_client.create_tickettemplate(field)\n ticket_template = body\n\n self.assertTrue(ticket_template['id'] is not None)\n\n id.append(ticket_template['id'])\n\n return id\n\n\ndef delete_ticket_template(self, ticket_template_id):\n \"\"\"Test 'Delete a ticket template'.\n :param workflow_pattern_id: List of workflow pattern id.\n \"\"\"\n for id in ticket_template_id:\n self.aflo_client.delete_tickettemplate(id)\n\n\ndef get_contract_info_ids(self, valid_flag=True):\n \"\"\"Get contract info ids.\n :param valid_flag: It will determine whether valid or.\n \"\"\"\n count = 0\n goods_ids = []\n catalog_ids = []\n contents_ids = []\n catalog_scope_ids = []\n price_ids = []\n\n goods_data_list = fixture.GOODS_DATA_LIST\n for goods_data in goods_data_list:\n # Create goods data.\n req, goods = self.aflo_client.create_goods(goods_data)\n goods_id = goods['goods_id']\n goods_ids.append(goods_id)\n\n # Create catalog data.\n if valid_flag:\n catalog_data = fixture.CATALOG_DATA_LIST[count]\n else:\n catalog_data = fixture.INVALID_CATALOG_DATA_LIST[count]\n catalog_field = {'catalog_name': catalog_data.get('catalog_name'),\n 'lifetime_start': catalog_data.get('lifetime_start'),\n 'lifetime_end': catalog_data.get('lifetime_end')}\n req, catalog = self.aflo_client.create_catalog(catalog_field)\n catalog_id = catalog['catalog_id']\n catalog_ids.append(catalog_id)\n\n # Create catalog contents data.\n cont_data = fixture.CATALOG_CONTENTS_DATA_LIST[count]\n contents_field = {'goods_id': goods_id,\n 'goods_num': cont_data.get('goods_num'),\n 'expansion_key2': cont_data.get('expansion_key2'),\n 'expansion_key3': cont_data.get('expansion_key3')}\n req, contents = self.aflo_client.create_catalog_contents(\n catalog_id,\n contents_field)\n contents_ids.append(contents['seq_no'])\n\n # Create catalog scope data.\n if valid_flag:\n scope_data = fixture.CATALOG_SCOPE_DATA_LIST[count]\n else:\n scope_data = fixture.INVALID_CATALOG_SCOPE_DATA_LIST[count]\n scope_field = {'lifetime_start': scope_data.get('lifetime_start'),\n 'lifetime_end': scope_data.get('lifetime_end')}\n req, catalog_scope = self.aflo_client.create_catalog_scope(\n catalog_id,\n scope_data.get('scope'),\n scope_field)\n catalog_scope_ids.append(catalog_scope['id'])\n\n # Create price data.\n if valid_flag:\n price_data = fixture.PRICE_DATA_LIST[count]\n else:\n price_data = fixture.INVALID_PRICE_DATA_LIST[count]\n price_field = {'price': price_data.get('price'),\n 'lifetime_start': price_data.get('lifetime_start'),\n 'lifetime_end': price_data.get('lifetime_end')}\n req, price = self.aflo_client.create_price(\n catalog_id,\n price_data.get('scope'),\n price_field)\n price_ids.append(price['seq_no'])\n\n count = count + 1\n\n return goods_ids, catalog_ids, contents_ids, catalog_scope_ids, price_ids\n\n\ndef delete_contract_info_data(self,\n contract_id,\n goods_ids,\n catalog_ids,\n contents_ids,\n catalog_scope_ids,\n price_ids):\n \"\"\"Delete contract info data.\n :param contract_id: contract id.\n :param goods_ids: goods ids.\n :param catalog_ids: catalog ids.\n :param contents_ids: catalog contents ids.\n :param catalog_scope_ids: catalog scope ids.\n :param price_ids: price ids.\n \"\"\"\n # Delete contract data.\n if contract_id:\n self.aflo_client.delete_contract(contract_id)\n # Delete goods data.\n for goods_id in goods_ids:\n print(goods_id)\n self.aflo_client.delete_goods(goods_id)\n # Delete catalog data.\n for catalog_id in catalog_ids:\n self.aflo_client.delete_catalog(catalog_id)\n # Delete catalog contents data.\n count = 0\n for contents_id in contents_ids:\n self.aflo_client.delete_catalog_contents(\n catalog_ids[count],\n contents_id)\n count = count + 1\n # Delete catalog scope data.\n for catalog_scope_id in catalog_scope_ids:\n self.aflo_client.delete_catalog_scope(catalog_scope_id)\n # Delete price data.\n count = 0\n price_data_list = fixture.PRICE_DATA_LIST\n for price_id in price_ids:\n self.aflo_client.delete_price(\n catalog_ids[count],\n price_data_list[count].get('scope'),\n price_id)\n count = count + 1\n","sub_path":"contrib/tempest/tempest/api/aflo/test_tickettemplate.py","file_name":"test_tickettemplate.py","file_ext":"py","file_size_in_byte":13514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"609648513","text":"\"\"\"\nTest for gui module\n\"\"\"\n\n\n########### IMPORTS ###########\n# \n\n# packages\nfrom time import sleep\n\n# files from gui\nfrom .gui import GuiMain\n\n# \n########### IMPORTS ###########\n\n\ndef test_calculate(qtbot):\n \"\"\"\n Main test function\n :param qtbot: qtbot object for gui testing\n \"\"\"\n window = GuiMain()\n qtbot.addWidget(window)\n window.show()\n qtbot.waitForWindowShown(window)\n sleep(3)\n\n qtbot.mouseClick(window.comboBox_method)\n\n\nif __name__ == '__main__':\n test_calculate()","sub_path":"code/gui/gui_testing.py","file_name":"gui_testing.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"264525722","text":"import time\n\nimport numpy as np\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport gridcut\n\nPW = 2\nCOST = 8\nSOURCE = np.array([[COST, COST, 0, 0],\n [0, COST, COST, 0],\n [0, 0, COST, COST]], dtype=np.float32)\nSINK = np.array([[0, 0, COST, COST],\n [COST, 0, 0, COST],\n [COST, COST, 0, 0]], dtype=np.float32)\nFIG_SIZE = 4\n\n\ndef test_maxflow_2d_4c_simple(source=SOURCE, sink=SINK, pw=PW):\n edges = np.ones((source.shape), dtype=np.float32) * pw\n result = gridcut.maxflow_2D_4C(source.shape[1], source.shape[0],\n source.ravel(), sink.ravel(),\n edges.ravel(), edges.ravel(),\n edges.ravel(), edges.ravel(),\n n_threads=1, block_size=4)\n assert np.array_equal(result.reshape(source.shape),\n np.array([[0, 0, 1, 1],\n [1, 0, 0, 1],\n [1, 1, 0, 0]]))\n\n result = gridcut.maxflow_2D_4C_potts(source.shape[1], source.shape[0],\n source.ravel(), sink.ravel(), pw,\n n_threads=2, block_size=1)\n assert np.array_equal(result.reshape(source.shape),\n np.array([[0, 0, 1, 1],\n [1, 0, 0, 1],\n [1, 1, 0, 0]]))\n\n\ndef generate_image_unary_term_2cls(width=120, height=80):\n \"\"\" \"\"\"\n annot = np.zeros((height, width))\n annot[int(0.3 * height):int(0.8 * height),\n int(0.2 * width):int(0.7 * width)] = 1\n noise = np.random.randn(height, width) - 0.5\n\n source = (0.5 + (1 - annot) * 2 + noise).astype(np.float32)\n sink = (0.5 + annot * 2 + noise).astype(np.float32)\n\n fig = plt.figure(figsize=(2 * FIG_SIZE, FIG_SIZE))\n plt.subplot(1, 2, 1)\n plt.imshow(source, cmap=\"gray\", interpolation=\"nearest\")\n plt.subplot(1, 2, 2)\n plt.imshow(sink, cmap=\"gray\", interpolation=\"nearest\")\n fig.tight_layout()\n fig.savefig('./images/2cls_grid_unary.png')\n plt.close(fig)\n\n return annot, source, sink\n\n\ndef generate_image_unary_term_3cls(width=120, height=80):\n annot = np.zeros((height, width))\n annot[:, int(0.4 * width)] = 2\n annot[int(0.3 * height):int(0.8 * height),\n int(0.2 * width):int(0.7 * width)] = 1\n img = annot + np.random.randn(100, 100)\n\n unary = np.tile(img[:, :, np.newaxis], [1, 1, 3])\n\n tmp = unary[:, :, 1] - 1\n tmp[annot == 0] *= -1\n unary[:, :, 1] = tmp\n unary[:, :, 2] = 2 - unary[:, :, 2]\n\n fig = plt.figure(figsize=(unary.shape[-1] * FIG_SIZE, FIG_SIZE))\n for i in range(unary.shape[-1]):\n plt.subplot(1, unary.shape[-1], i + 1)\n plt.imshow(unary[:, :, i], cmap=\"gray\", interpolation=\"nearest\")\n fig.tight_layout()\n fig.savefig('./images/3cls_grid_unary.png')\n plt.close(fig)\n\n return annot, unary\n\n\ndef save_results(img, segm, fig_name=''):\n fig = plt.figure(figsize=(2 * FIG_SIZE, FIG_SIZE))\n plt.subplot(1, 2, 1), plt.title('image')\n plt.imshow(img, interpolation=\"nearest\")\n plt.subplot(1, 2, 2), plt.title('solved labeling')\n plt.imshow(segm, interpolation=\"nearest\")\n fig.tight_layout()\n fig.savefig('./images/%s.png' % fig_name)\n plt.close(fig)\n\n\ndef test_maxflow_2d_image(width=120, height=80, pw=PW):\n \"\"\" \"\"\"\n img, source, sink = generate_image_unary_term_2cls(width, height)\n\n t = time.time()\n labels = gridcut.maxflow_2D_4C_potts(img.shape[1], img.shape[0],\n source, sink, pw)\n print ('elapsed time for \"maxflow_2D_4C_potts\": %f' % (time.time() - t))\n\n save_results(img, labels.reshape(img.shape),\n fig_name='2cls_grid_labels_4c')\n\n t = time.time()\n labels = gridcut.maxflow_2D_8C_potts(img.shape[1], img.shape[0],\n source, sink, pw)\n print ('elapsed time for \"maxflow_2D_8C_potts\": %f' % (time.time() - t))\n\n save_results(img, labels.reshape(img.shape),\n fig_name='2cls_grid_labels_8c')\n\n\n# if __name__ == '__main__':\n# test_maxflow_2d_4c_simple()\n# test_maxflow_2d_image()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"375723503","text":"import urllib, ssl, json\nfrom django.shortcuts import render\nfrom django.views.generic.base import ContextMixin, TemplateView\nfrom django.http import HttpResponseRedirect, HttpResponse, JsonResponse\nfrom django.views import View\nfrom django.conf import settings\n# Create your views here.\n\n\nclass MyBaseMixin(ContextMixin):\n\n def jsonrpc(self,url='https://slb.medv.ru/api/v2/', method=\"auth.check\", params={}):\n js = {\"jsonrpc\": \"2.0\", \"method\": method, 'params': params, \"id\": 1}\n params = json.dumps(js).encode('utf8')\n ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\n new_crt = open('n.crt', 'w')\n new_key = open('n.key', 'w')\n new_crt.write(settings.CRT)\n new_key.write(settings.KEY)\n new_key.close()\n new_crt.close()\n\n ssl_context.load_cert_chain('n.crt', keyfile='n.key')\n req = urllib.request.Request(\n url,\n data=params,\n headers={'content-type': 'application/json'}\n )\n response = urllib.request.urlopen(req, context=ssl_context)\n resp = json.loads(response.read().decode('utf8'))\n\n if 'error' in resp:\n result = resp['error']\n elif 'result' in resp:\n result = resp['result']\n return result\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\nclass AuthView(View, MyBaseMixin):\n def get(self,request):\n j = self.jsonrpc()\n return HttpResponse(';)')\n","sub_path":"qualix/Manage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"593759298","text":"import pandas as pd\nimport numpy as np\nfrom math import sin, cos, sqrt, atan2, radians\n\ndef ComputeDistance(row):\n\t# approximate radius of earth in km\n\tR = 6373.0\n\n\tlat1 = row[\"lat_radians\"]\n\tlon1 = row[\"lon_radians\"]\n\tlat2 = row[\"lat_radians1\"]\n\tlon2 = row[\"lon_radians1\"]\n\n\tdlon = lon2 - lon1\n\tdlat = lat2 - lat1\n\n\ta = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2\n\tc = 2 * atan2(sqrt(a), sqrt(1 - a))\n\n\tdistance = R * c\n\treturn distance\n\t\ndistances = pd.read_csv('data_features_clean.csv', usecols=[\"id\",\"latitude\",\"longitude\"]) \t\ndistances[\"id\"] = distances[\"id\"].astype(\"int\")\ndistances[\"lat_radians\"] = distances[\"latitude\"].apply(lambda x:radians(x))\ndistances[\"lon_radians\"] = distances[\"longitude\"].apply(lambda x:radians(x))\ndistances[\"ids\"]=\"\"\ndistances[\"distances\"]=\"\"\n\n","sub_path":"distances2.py","file_name":"distances2.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"237526922","text":"def answer(A):\n # Quick sort\n def quick_sort(nums, low, high):\n \"\"\"\n Sort the array with quicksort\n Pick the last element as pivot\n Sort in place\n Args:\n nums\n low\n high: Included.\n Return:\n None\n \"\"\"\n # Stoping case: Empty\n if low > high:\n return None\n # Stoping case: 1 element\n if low == high:\n return None\n # Stoping case: 2 elements\n if low == high - 1:\n if nums[low] > nums[high]:\n nums[low], nums[high] = nums[high], nums[low]\n return None\n\n pivot = nums[high]\n\n # We try to make the left part of the array is always smaller than\n # pivot. Using a variable to indicate the end of that part. It points\n # to 1st element that larger than pivot\n # j should start from low\n j = low\n\n # Scan the array and put elements smaller than pivot in [0, j-1]\n for i in range(low, high):\n if nums[i] < pivot:\n # Swap. It is Ok to swap a number with itself\n nums[i], nums[j] = nums[j], nums[i]\n j += 1\n # Put the pivot into right position, e.g j\n nums[high], nums[j] = nums[j], nums[high]\n\n # Process left and right part\n quick_sort(nums, low, j - 1)\n quick_sort(nums, j + 1, high)\n return None\n\n quick_sort(A, 0, len(A) - 1)\n return A\n\ndef main():\n case=[\n [[3, 2, 1, 4, 5], [1, 2, 3, 4, 5]],\n [[5, 3, 4, 2], [2, 3, 4, 5]]\n ]\n for i in range(len(case)):\n if answer(case[i][0]) == case[i][1]:\n print ('Case {} passed.'.format(i + 1))\n else:\n print ('Case {} failed.'.format(i + 1))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Lintcode-464-Sort-Integers-II-Beats-94.60%.py","file_name":"Lintcode-464-Sort-Integers-II-Beats-94.60%.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"493472442","text":"from datetime import date, datetime\n\n\nclass Computer:\n def __init__(self, _name=\"\", _dallas_server=None, _root_catalog=\"\",\n _date_in_domain=None, _last_logon_puppet=None,\n _last_logon_windows=None, _type=0, _ad_user_control=None, _crypto_gateway_name=None,\n _last_logon_ad=None, _last_logon_kaspersky=None, _last_logon_local=None,\n _logon_count=None, _dallas_status=None, _local_os=None,\n _kl_ksc_server=None, _kl_ip=None, _kl_os=None, _kl_status=None, _kl_hasDuplicate=False,\n _kl_agent_version=None, _kl_security_version=None, _kl_for_server_version=None,\n _kl_ksc_version=None, _kl_info_updated=False):\n self.date_in_domain = _date_in_domain\n self.ad_user_control = _ad_user_control\n self.logon_count = _logon_count\n self.root_catalog = _root_catalog\n self.name = self.set_name(_name)\n self.type = _type\n self.dallas_server = _dallas_server\n self.dallas_status = _dallas_status\n self.local_os = _local_os\n self.crypto_gateway_name = _crypto_gateway_name\n\n self.last_logon_ad = _last_logon_ad\n self.last_logon_puppet = _last_logon_puppet\n self.last_logon_windows = _last_logon_windows\n self.last_logon_kaspersky = _last_logon_kaspersky\n self.last_logon_local = _last_logon_local\n\n self.kl_ksc_server = _kl_ksc_server\n self.kl_hasDuplicate = _kl_hasDuplicate\n self.kl_ip = _kl_ip\n self.kl_os = _kl_os\n self.kl_status = _kl_status\n self.kl_agent_version = _kl_agent_version\n self.kl_security_version = _kl_security_version\n self.kl_for_server_version = _kl_for_server_version\n self.kl_ksc_version = _kl_ksc_version\n self.kl_info_updated = _kl_info_updated\n\n def set_dallas_server(self, _server_name):\n self.dallas_server = _server_name\n\n def isAD(self):\n if self.date_in_domain:\n return True\n return False\n\n def isDallas(self):\n if self.dallas_server is None:\n return False\n return True\n\n def isPuppet(self):\n if self.last_logon_puppet is None:\n return False\n return True\n\n def isCataloged(self):\n if self.root_catalog is \"\":\n return False\n return True\n\n def isKaspersky(self):\n if self.kl_ksc_server:\n return True\n return False\n\n def isKaspersky_updated(self):\n if self.kl_info_updated:\n return True\n return False\n\n def isWindows(self):\n if self.last_logon_windows is None:\n return False\n return True\n\n def isCG(self):\n if self.crypto_gateway_name is None:\n return False\n return True\n\n def get_dallas_server(self):\n return self.dallas_server\n\n def get_os(self):\n os = 'unkw'\n if self.last_logon_puppet or self.last_logon_windows\\\n or self.last_logon_local or self.last_logon_kaspersky:\n logons = ({\"puppet\": self.last_logon_puppet,\n \"windows\": self.last_logon_windows,\n \"local\": self.last_logon_local,\n \"kaspersky\": self.last_logon_kaspersky\n })\n key_of_max = None\n for key in logons:\n if key_of_max is None:\n if logons[key] is not None:\n key_of_max = key\n continue\n if logons[key] and logons[key_of_max] and logons[key] > logons[key_of_max]:\n key_of_max = key\n if key_of_max == 'puppet':\n os = 'linx'\n elif key_of_max == 'windows':\n os = 'wind'\n elif key_of_max == 'local':\n os = self.local_os\n elif key_of_max == 'kaspersky':\n os = self.kl_os\n elif self.dallas_server is not None:\n os = 'wind'\n elif self.logon_count and self.logon_count == 65535:\n os = 'linx'\n else:\n if self.get_last_logon():\n if self.date_in_domain and self.logon_count and (self.logon_count > 2000 and self.date_in_domain.date() < date(2018, 1, 1) and self.ad_user_control < 5000 or\n self.logon_count < 2000 and self.ad_user_control < 5000):\n os = 'wind'\n elif self.ad_user_control > 60000:\n os = 'linx'\n\n\n return os\n\n def set_name(self, name):\n self.name = name.upper()\n return self.name\n\n def get_name(self):\n return self.name\n\n def get_last_logon(self):\n sources = []\n sources.append(self.last_logon_ad)\n sources.append(self.last_logon_windows)\n sources.append(self.last_logon_puppet)\n sources.append(self.last_logon_kaspersky)\n sources.append(self.last_logon_local)\n sources = list(filter(None, sources))\n if sources == []:\n return None\n return max(sources)\n\n def get_kl_info(self):\n dic = {\n \"server\" : self.kl_ksc_server if self.kl_ksc_server else None,\n \"ip\" : self.kl_ip if self.kl_ip else None,\n \"os\" : self.kl_os if self.kl_os else None,\n \"hasDuplicate\" : self.kl_hasDuplicate,\n \"products\" : {\n \"agent\" : self.kl_agent_version if self.kl_agent_version else None,\n \"security\" : self.kl_security_version if self.kl_security_version else self.kl_for_server_version\n if self.kl_for_server_version else None,\n \"ksc\" : self.kl_ksc_version if self.kl_ksc_version else None\n }\n }\n return dic\n","sub_path":"sc_statistic/Computer.py","file_name":"Computer.py","file_ext":"py","file_size_in_byte":5841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"278646890","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 6 10:28:42 2020\n\n@author: g_dic\n\"\"\"\n\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nimport numpy as np\n#print('numpy: '+np.version.full_version)\nimport matplotlib.animation as animation\nimport matplotlib\n#print('matplotlib: '+matplotlib.__version__)\n#%matplotlib inline\n\n# animation params\nNfrm = 10\nfps = 10\n\n# shape functions\ndef generateSphere():\n '''\n Generates Z data for the points in the X, Y meshgrid and parameter phi.\n '''\n u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\n X= np.cos(u)*np.sin(v)\n Y = np.sin(u)*np.sin(v)\n Z = np.cos(v)\n return X,Y,Z\n\n\n# def sphere(u, v):\n# x = sin(u) * cos(v)\n# y = cos(u)\n# z = -sin(u) * sin(v)\n# return x, y, z\n\ndef generateKlein():\n u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\n x = 3 * np.cos(u) * (1 + np.sin(u)) + (2 * (1 - np.cos(u) / 2)) * np.cos(u) * np.cos(v)\n z = -8 * np.sin(u) - 2 * (1 - np.cos(u) / 2) * np.sin(u) * np.cos(v)\n\n #x = 3 * np.cos(u) * (1 + np.sin(u)) + (2 * (1 - cos(np.u) / 2)) * cos(np.v + np.pi)\n #z = -8 * np.sin(u)\n y = -2 * (1 - np.cos(u) / 2) * np.sin(v)\n return x, y, z\n\n \n\ndef generateMobius():\n theta = np.linspace(0, 2 * np.pi, 30)\n w = np.linspace(-0.25, 0.25, 8)\n w, theta = np.meshgrid(w, theta)\n phi = 0.5 * theta\n # radius in x-y plane\n r = 1 + w * np.cos(phi)\n \n x = r * np.cos(theta)\n y = r * np.sin(theta)\n z = w * np.sin(phi)\n return x,y,z\n\n\ndef generatePlane(Zaxis=0):\n x=np.linspace(-3,3,128) # x goes from -3 to 3, with 256 steps\n y=np.linspace(-3,3,128) # y goes from -3 to 3, with 256 steps\n X,Y=np.meshgrid(x,y)\n Z = np.zeros_like(X) + Zaxis\n return X,Y,Z\n\n\n\ndef generateCube(center=[0,0,0], size=(1.0,1.0,1.0)):\n \"\"\"\n Create a data array for cuboid plotting.\n \n \n ============= ================================================\n Argument Description\n ============= ================================================\n center center of the cuboid, triple\n size size of the cuboid, triple, (x_length,y_width,z_height)\n :type size: tuple, numpy.array, list\n :param size: size of the cuboid, triple, (x_length,y_width,z_height)\n :type center: tuple, numpy.array, list\n :param center: center of the cuboid, triple, (x,y,z)\n \n \n \"\"\"\n \n # suppose axis direction: x: to left; y: to inside; z: to upper\n # get the (left, outside, bottom) point\n o = [a - b / 2 for a, b in zip(center, size)]\n # get the length, width, and height\n l, w, h = size\n x = [[o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in bottom surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in upper surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in outside surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]]] # x coordinate of points in inside surface\n y = [[o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in bottom surface\n [o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in upper surface\n [o[1], o[1], o[1], o[1], o[1]], # y coordinate of points in outside surface\n [o[1] + w, o[1] + w, o[1] + w, o[1] + w, o[1] + w]] # y coordinate of points in inside surface\n z = [[o[2], o[2], o[2], o[2], o[2]], # z coordinate of points in bottom surface\n [o[2] + h, o[2] + h, o[2] + h, o[2] + h, o[2] + h], # z coordinate of points in upper surface\n [o[2], o[2], o[2] + h, o[2] + h, o[2]], # z coordinate of points in outside surface\n [o[2], o[2], o[2] + h, o[2] + h, o[2]]] # z coordinate of points in inside surface\n return np.array(x), np.array(y), np.array(z) \n\n\ndef generateTorus():\n n = 50\n theta = np.linspace(0, 2.*np.pi, n)\n phi = np.linspace(0, 2.*np.pi, n)\n theta, phi = np.meshgrid(theta, phi)\n c, a = 2, 1\n x = (c + a*np.cos(theta)) * np.cos(phi)\n y = (c + a*np.cos(theta)) * np.sin(phi)\n z = a * np.sin(theta)\n return x,y,z\n\ndef generatePringle():\n n_radii = 8\n n_angles = 36\n \n # Make radii and angles spaces (radius r=0 omitted to eliminate duplication).\n radii = np.linspace(0.125, 1.0, n_radii)\n angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)[..., np.newaxis]\n \n radii, angles = np.meshgrid(radii, angles)\n \n # Convert polar (radii, angles) coords to cartesian (x, y) coords.\n # points in the (x, y) plane.\n x = (radii*np.cos(angles))\n y = (radii*np.sin(angles))\n \n # Compute z to make the pringle surface.\n z = np.sin(-x*y)\n return x,y,z\n\ndef test():\n def fun(x, y):\n return x**2 + y\n x = y = np.arange(-3.0, 3.0, 0.05)\n X, Y = np.meshgrid(x, y)\n zs = np.array(fun(np.ravel(X), np.ravel(Y)))\n Z = zs.reshape(X.shape)\n return X,Y,Z\n\ndef generatePyramid(center=[0,0,0], size=(1.0,1.0,1.0)):\n o = [a - b / 2 for a, b in zip(center, size)]\n # get the length, width, and height\n l, w, h = size\n x = [[0, 0, 0, 0, 0], # x coordinate of points in bottom surface\n [o[0], o[0] + l, o[0] + l, o[0], o[0]], # x coordinate of points in upper surface\n [0, 0, 0, 0, 0], # x coordinate of points in outside surface\n [0, 0, 0, 0, 0]] # x coordinate of points in inside surface\n y = [[0,0,0,0,0], # y coordinate of points in bottom surface\n [o[1], o[1], o[1] + w, o[1] + w, o[1]], # y coordinate of points in upper surface\n [0, 0, 0, 0, 0], # y coordinate of points in outside surface\n [0, 0, 0, 0, 0]] # y coordinate of points in inside surface\n z = [[o[2], o[2], o[2], o[2], o[2]], # z coordinate of points in bottom surface\n [o[2] + h, o[2] + h, o[2] + h, o[2] + h, o[2] + h], # z coordinate of points in upper surface\n [o[2], o[2], o[2], o[2], o[2]], # z coordinate of points in outside surface\n [o[2], o[2], o[2], o[2] , o[2]]] # z coordinate of points in inside surface\n return np.array(x), np.array(y), np.array(z) \n \n\n\n# transformation functions\ndef scaleXYZ(X,Y,Z, phi, X_factor=1, Y_factor=1, Z_factor=1):\n return X*(X_factor*phi),Y*(Y_factor*phi),Z*(Z_factor*phi)\n\ndef rotateX(X, Y, Z, deg):\n \"\"\" Rotates this point around the X axis the given number of degrees. Return the x, y, z coordinates of the result\"\"\"\n rad = deg * np.pi / 180\n cosa = np.cos(rad)\n sina = np.sin(rad)\n Y = Y * cosa - Z * sina\n Z = Y * sina + Z * cosa\n return X, Y, Z \n\ndef transpose(X,Y,Z, D, X_factor=0, Y_factor=0, Z_factor=0):\n return X+(X_factor*D),Y+(Y_factor*D),Z+(Z_factor*D)\n\n\ndef wave(X, Y, Z, phi):\n '''\n Generates Z data for the points in the X, Y meshgrid and parameter phi.\n '''\n R = 1 - np.sqrt(X**2 + Y**2)\n return X,Y, np.sinc(2 * np.pi * X + phi) * R\n\ndef wave2(X,Y,Z,phi,func='sin'):\n R = np.sqrt(X**2 + Y**2)\n if func == 'sin':\n Z = np.sin(R) * phi\n if func == 'cos':\n Z = np.cos(R) * phi \n return X,Y, Z\n \n\nfig = plt.figure(figsize=(8,6))\nax = fig.add_subplot(111, projection='3d')\n\n\n# Set the z axis limits so they aren't recalculated each frame.\nax.set_xlim(-3, 3)\nax.set_ylim(-3, 3)\nax.set_zlim(-3, 3)\n\n# Begin plotting.\nwframe = None\n\n# define update routine\ndef update(idx):\n #init shape\n #X,Y,Z = generateSphere()\n #X,Y,Z = generatePlane()\n #X,Y,Z = generateCube() \n #X,Y,Z = generateMobius()\n #X,Y,Z = generateTorus()\n #X,Y,Z = generateKlein()\n #X,Y,Z = generatePringle()\n X,Y,Z = generatePyramid()\n \n phi=phis[idx]\n print(phi)\n global wframe\n # If a line collection is already remove it before drawing.\n if wframe:\n ax.collections.remove(wframe)\n\n # Plot the new wireframe and pause briefly before continuing.\n #X,Y,Z = scaleXYZ(X,Y,Z,phi)\n #X,Y,Z = rotateX(X,Y,Z,phi*180) \n #X,Y,Z = wave(X,Y,Z,phi)\n #X,Y,Z = wave2(X,Y,Z,phi)\n X,Y,Z = transpose(X,Y,Z, phi, 1,0)\n \n \n wframe = ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, color='k', linewidth=0.5)\n #wframe = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, color='k', linewidth=0.5)\n\nphis = np.linspace(0, 3, 5)\nreversePhis = np.linspace(3, 0, 5)\nphis = np.concatenate((phis, reversePhis), axis=0) \nani = animation.FuncAnimation(fig, update, Nfrm, interval=1000/fps)","sub_path":"animatedPlottingExamples/3D_Plot_wireframe_shape_transforms.py","file_name":"3D_Plot_wireframe_shape_transforms.py","file_ext":"py","file_size_in_byte":8503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"445461052","text":"from __future__ import absolute_import, division, print_function\n\nfrom . import ops\nfrom .groupby import DataArrayGroupBy, DatasetGroupBy, DEFAULT_DIMS\nfrom .pycompat import OrderedDict, dask_array_type\n\nRESAMPLE_DIM = '__resample_dim__'\n\n\nclass Resample(object):\n \"\"\"An object that extends the `GroupBy` object with additional logic\n for handling specialized re-sampling operations.\n\n You should create a `Resample` object by using the `DataArray.resample` or\n `Dataset.resample` methods. The dimension along re-sampling\n\n See Also\n --------\n DataArray.resample\n Dataset.resample\n\n \"\"\"\n\n def _upsample(self, method, *args, **kwargs):\n \"\"\"Dispatch function to call appropriate up-sampling methods on\n data.\n\n This method should not be called directly; instead, use one of the\n wrapper functions supplied by `Resample`.\n\n Parameters\n ----------\n method : str {'asfreq', 'pad', 'ffill', 'backfill', 'bfill', 'nearest',\n 'interpolate'}\n Method to use for up-sampling\n\n See Also\n --------\n Resample.asfreq\n Resample.pad\n Resample.backfill\n Resample.interpolate\n\n \"\"\"\n\n upsampled_index = self._full_index\n\n # Drop non-dimension coordinates along the resampled dimension\n for k, v in self._obj.coords.items():\n if k == self._dim:\n continue\n if self._dim in v.dims:\n self._obj = self._obj.drop(k)\n\n if method == 'asfreq':\n return self.mean(self._dim)\n\n elif method in ['pad', 'ffill', 'backfill', 'bfill', 'nearest']:\n kwargs = kwargs.copy()\n kwargs.update(**{self._dim: upsampled_index})\n return self._obj.reindex(method=method, *args, **kwargs)\n\n elif method == 'interpolate':\n return self._interpolate(*args, **kwargs)\n\n else:\n raise ValueError('Specified method was \"{}\" but must be one of'\n '\"asfreq\", \"ffill\", \"bfill\", or \"interpolate\"'\n .format(method))\n\n def asfreq(self):\n \"\"\"Return values of original object at the new up-sampling frequency;\n essentially a re-index with new times set to NaN.\n \"\"\"\n return self._upsample('asfreq')\n\n def pad(self):\n \"\"\"Forward fill new values at up-sampled frequency.\n \"\"\"\n return self._upsample('pad')\n ffill = pad\n\n def backfill(self):\n \"\"\"Backward fill new values at up-sampled frequency.\n \"\"\"\n return self._upsample('backfill')\n bfill = backfill\n\n def nearest(self):\n \"\"\"Take new values from nearest original coordinate to up-sampled\n frequency coordinates.\n \"\"\"\n return self._upsample('nearest')\n\n def interpolate(self, kind='linear'):\n \"\"\"Interpolate up-sampled data using the original data\n as knots.\n\n Parameters\n ----------\n kind : str {'linear', 'nearest', 'zero', 'slinear',\n 'quadratic', 'cubic'}\n Interpolation scheme to use\n\n See Also\n --------\n scipy.interpolate.interp1d\n\n \"\"\"\n return self._interpolate(kind=kind)\n\n def _interpolate(self, kind='linear'):\n raise NotImplementedError\n\n\nclass DataArrayResample(DataArrayGroupBy, Resample):\n \"\"\"DataArrayGroupBy object specialized to time resampling operations over a\n specified dimension\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n self._dim = kwargs.pop('dim', None)\n self._resample_dim = kwargs.pop('resample_dim', None)\n\n if self._dim == self._resample_dim:\n raise ValueError(\"Proxy resampling dimension ('{}') \"\n \"cannot have the same name as actual dimension \"\n \"('{}')! \".format(self._resample_dim, self._dim))\n super(DataArrayResample, self).__init__(*args, **kwargs)\n\n def apply(self, func, shortcut=False, **kwargs):\n \"\"\"Apply a function over each array in the group and concatenate them\n together into a new array.\n\n `func` is called like `func(ar, *args, **kwargs)` for each array `ar`\n in this group.\n\n Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how\n to stack together the array. The rule is:\n 1. If the dimension along which the group coordinate is defined is\n still in the first grouped array after applying `func`, then stack\n over this dimension.\n 2. Otherwise, stack over the new dimension given by name of this\n grouping (the argument to the `groupby` function).\n\n Parameters\n ----------\n func : function\n Callable to apply to each array.\n shortcut : bool, optional\n Whether or not to shortcut evaluation under the assumptions that:\n (1) The action of `func` does not depend on any of the array\n metadata (attributes or coordinates) but only on the data and\n dimensions.\n (2) The action of `func` creates arrays with homogeneous metadata,\n that is, with the same dimensions and attributes.\n If these conditions are satisfied `shortcut` provides significant\n speedup. This should be the case for many common groupby operations\n (e.g., applying numpy ufuncs).\n **kwargs\n Used to call `func(ar, **kwargs)` for each array `ar`.\n\n Returns\n -------\n applied : DataArray or DataArray\n The result of splitting, applying and combining this array.\n \"\"\"\n combined = super(DataArrayResample, self).apply(\n func, shortcut=shortcut, **kwargs)\n\n # If the aggregation function didn't drop the original resampling\n # dimension, then we need to do so before we can rename the proxy\n # dimension we used.\n if self._dim in combined.coords:\n combined = combined.drop(self._dim)\n\n if self._resample_dim in combined.dims:\n combined = combined.rename({self._resample_dim: self._dim})\n\n return combined\n\n def _interpolate(self, kind='linear'):\n \"\"\"Apply scipy.interpolate.interp1d along resampling dimension.\"\"\"\n from .dataarray import DataArray\n from scipy.interpolate import interp1d\n\n if isinstance(self._obj.data, dask_array_type):\n raise TypeError(\n \"Up-sampling via interpolation was attempted on the the \"\n \"variable '{}', but it is a dask array; dask arrays are not \"\n \"yet supported in resample.interpolate(). Load into \"\n \"memory with Dataset.load() before resampling.\"\n .format(self._obj.data.name)\n )\n\n x = self._obj[self._dim].astype('float')\n y = self._obj.data\n\n axis = self._obj.get_axis_num(self._dim)\n\n f = interp1d(x, y, kind=kind, axis=axis, bounds_error=True,\n assume_sorted=True)\n new_x = self._full_index.values.astype('float')\n\n # construct new up-sampled DataArray\n dummy = self._obj.copy()\n dims = dummy.dims\n\n # drop any existing non-dimension coordinates along the resampling\n # dimension\n coords = OrderedDict()\n for k, v in dummy.coords.items():\n # is the resampling dimension\n if k == self._dim:\n coords[self._dim] = self._full_index\n # else, check if resampling dim is in coordinate dimensions\n elif self._dim not in v.dims:\n coords[k] = v\n return DataArray(f(new_x), coords, dims, name=dummy.name,\n attrs=dummy.attrs)\n\n\nops.inject_reduce_methods(DataArrayResample)\nops.inject_binary_ops(DataArrayResample)\n\n\nclass DatasetResample(DatasetGroupBy, Resample):\n \"\"\"DatasetGroupBy object specialized to resampling a specified dimension\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n self._dim = kwargs.pop('dim', None)\n self._resample_dim = kwargs.pop('resample_dim', None)\n\n if self._dim == self._resample_dim:\n raise ValueError(\"Proxy resampling dimension ('{}') \"\n \"cannot have the same name as actual dimension \"\n \"('{}')! \".format(self._resample_dim, self._dim))\n super(DatasetResample, self).__init__(*args, **kwargs)\n\n def apply(self, func, **kwargs):\n \"\"\"Apply a function over each Dataset in the groups generated for\n resampling and concatenate them together into a new Dataset.\n\n `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds`\n in this group.\n\n Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how\n to stack together the datasets. The rule is:\n 1. If the dimension along which the group coordinate is defined is\n still in the first grouped item after applying `func`, then stack\n over this dimension.\n 2. Otherwise, stack over the new dimension given by name of this\n grouping (the argument to the `groupby` function).\n\n Parameters\n ----------\n func : function\n Callable to apply to each sub-dataset.\n **kwargs\n Used to call `func(ds, **kwargs)` for each sub-dataset `ar`.\n\n Returns\n -------\n applied : Dataset or DataArray\n The result of splitting, applying and combining this dataset.\n \"\"\"\n kwargs.pop('shortcut', None) # ignore shortcut if set (for now)\n applied = (func(ds, **kwargs) for ds in self._iter_grouped())\n combined = self._combine(applied)\n\n return combined.rename({self._resample_dim: self._dim})\n\n def reduce(self, func, dim=None, keep_attrs=False, **kwargs):\n \"\"\"Reduce the items in this group by applying `func` along the\n pre-defined resampling dimension.\n\n Parameters\n ----------\n func : function\n Function which can be called in the form\n `func(x, axis=axis, **kwargs)` to return the result of collapsing\n an np.ndarray over an integer valued axis.\n dim : str or sequence of str, optional\n Dimension(s) over which to apply `func`.\n keep_attrs : bool, optional\n If True, the datasets's attributes (`attrs`) will be copied from\n the original object to the new one. If False (default), the new\n object will be returned without attributes.\n **kwargs : dict\n Additional keyword arguments passed on to `func`.\n\n Returns\n -------\n reduced : Array\n Array with summarized data and the indicated dimension(s)\n removed.\n \"\"\"\n if dim == DEFAULT_DIMS:\n dim = None\n\n return super(DatasetResample, self).reduce(\n func, dim, keep_attrs, **kwargs)\n\n def _interpolate(self, kind='linear'):\n \"\"\"Apply scipy.interpolate.interp1d along resampling dimension.\"\"\"\n from .dataset import Dataset\n from .variable import Variable\n from scipy.interpolate import interp1d\n\n old_times = self._obj[self._dim].astype(float)\n new_times = self._full_index.values.astype(float)\n\n data_vars = OrderedDict()\n coords = OrderedDict()\n\n # Apply the interpolation to each DataArray in our original Dataset\n for name, variable in self._obj.variables.items():\n if name in self._obj.coords:\n if name == self._dim:\n coords[self._dim] = self._full_index\n elif self._dim not in variable.dims:\n coords[name] = variable\n else:\n if isinstance(variable.data, dask_array_type):\n raise TypeError(\n \"Up-sampling via interpolation was attempted on the \"\n \"variable '{}', but it is a dask array; dask arrays \"\n \"are not yet supprted in resample.interpolate(). Load \"\n \"into memory with Dataset.load() before resampling.\"\n .format(name)\n )\n\n axis = variable.get_axis_num(self._dim)\n\n # We've previously checked for monotonicity along the\n # re-sampling dimension (in __init__ via the GroupBy\n # constructor), so we can avoid sorting the data again by\n # passing 'assume_sorted=True'\n f = interp1d(old_times, variable.data, kind=kind,\n axis=axis, bounds_error=True,\n assume_sorted=True)\n interpolated = Variable(variable.dims, f(new_times))\n\n data_vars[name] = interpolated\n\n return Dataset(data_vars, coords)\n\n\nops.inject_reduce_methods(DatasetResample)\nops.inject_binary_ops(DatasetResample)\n","sub_path":"xarray/core/resample.py","file_name":"resample.py","file_ext":"py","file_size_in_byte":13037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"291395632","text":"\r\n#A - Part 1s\r\n#==========================================\r\n# Purpose: An object of this class represents an adventurer in a RPG game\r\n# Instance variables:\r\n# name = a string representation for the name of an adventurer object\r\n# level = integer representation for the level of the adventurer object\r\n# strength = integer representation for the strength of the adventurer object\r\n# speed = integer representation for the speed of the adventurer object\r\n# power = integer representation for the power of the adventurer object\r\n# HP = integer representation for the number of hit points (how much damage the adventurer can no longer fight) an adventurer object has\r\n# hidden = boolean representation for whether the adventurer object can be seen or not\r\n# Methods:\r\n# __init__ = initializes all the instance variables of the class listed above\r\n# __repr__ = overrides the __repr__ method to return a string of the object in the format - HP: \r\n# attack = defines the action of an attack - if the target is hidden, the target dodges the attack. if not, the target is hit with 4 times the strength of the attacker\r\n# __lt__ = overrides the __lt__ method to compare the HP of two adventurer objects\r\n#==========================================\r\n\r\nclass Adventurer:\r\n def __init__(self, name='', level=0, strength=0, speed=0, power=0):\r\n self.name = name\r\n self.level = level\r\n self.strength = strength\r\n self.speed = speed\r\n self.power = power\r\n self.HP = self.level * 6\r\n self.hidden = False\r\n def __repr__(self):\r\n return self.name + ' - HP: ' + str(self.HP)\r\n def attack(self, target):\r\n if target.hidden == True:\r\n print(self.name + \" can't see \" + target.name)\r\n else:\r\n attack_damage = self.strength + 4\r\n target.HP -= attack_damage\r\n print(self.name + ' attacks ' + target.name + ' for ' + str(attack_damage) + ' damage')\r\n def __lt__(self, other):\r\n if self.HP < other.HP:\r\n return True\r\n else:\r\n return False\r\n \r\n#A - Part 2\r\n#==========================================\r\n# Purpose: An object of this class represents an Adventurer, specifically a Thief, in a RPG game\r\n# Instance variables:\r\n# name = a string representation for the name of a Thief object\r\n# level = integer representation for the level of the Thief object\r\n# strength = integer representation for the strength of the Thief object\r\n# speed = integer representation for the speed of the Thief object\r\n# power = integer representation for the power of the Thief object\r\n# HP = integer representation for the number of hit points (how much damage the adventurer can no longer fight) an Thief object has\r\n# hidden = boolean representation for whether the Thief object can be seen or not\r\n# Methods:\r\n# __init__ = inherits the initializations from the Adventerur class and changes initial values for the HP and hidden instance variables\r\n# attack = overrides the action of an attack - if the target is hidden, the Thief inherits the Adventurer attack method, if not, the Thief sneak attacks with 5 times the power of its speed and level combined\r\n#==========================================\r\n\r\nclass Thief(Adventurer):\r\n def __init__(self, name='', level=0, strength=0, speed=0, power=0):\r\n super().__init__(name, level, strength, speed, power)\r\n self.HP = self.level * 8\r\n self.hidden = True\r\n def attack(self, target):\r\n if self.hidden == False:\r\n super().attack(target)\r\n else:\r\n sneak_attack = (self.speed + self.level) * 5\r\n target.HP -= sneak_attack\r\n self.hidden = False\r\n target.hidden = False\r\n print(self.name + ' sneak attacks ' + target.name + ' for ' + str(sneak_attack) + ' damage')\r\n\r\n#A - Part 3\r\n#==========================================\r\n# Purpose: An object of this class represents a Ninja, a more powerful version of a Thief, in a RPG game\r\n# Instance variables:\r\n# name = a string representation for the name of a Ninja object\r\n# level = integer representation for the level of the Ninja object\r\n# strength = integer representation for the strength of the Ninja object\r\n# speed = integer representation for the speed of the Ninja object\r\n# power = integer representation for the power of the Ninja object\r\n# HP = integer representation for the number of hit points (how much damage the adventurer can no longer fight) an Ninja object has\r\n# hidden = boolean representation for whether the Ninja object can be seen or not\r\n# Methods:\r\n# attack = overrides the action of an attack - the Ninja attacks similarly as the Thief so it inherits the attack function, but after it attacks, it also hides itself again and gains a regeneration of health equal to its level to \r\n#==========================================\r\n\r\nclass Ninja(Thief):\r\n def attack(self, target):\r\n super().attack(target)\r\n self.hidden = True\r\n self.HP += self.level\r\n \r\n#A - Part 4\r\n#==========================================\r\n# Purpose: An object of this class represents an Adventurer, specifically a Mage, in a RPG game\r\n# Instance variables:\r\n# name = a string representation for the name of a Mage object\r\n# level = integer representation for the level of the Mage object\r\n# strength = integer representation for the strength of the Mage object\r\n# speed = integer representation for the speed of the Mage object\r\n# power = integer representation for the power of the Mage object\r\n# HP = integer representation for the number of hit points (how much damage the adventurer can no longer fight) an Mage object has\r\n# fireballs_left = the number of fireballs the Mage has left to use for attack\r\n# hidden = boolean representation for whether the Mage object can be seen or not\r\n# Methods:\r\n# __init__ = inherits the initializations from the Adventerur class and initializes the fireballs_left instance variable\r\n# attack = overrides the action of an attack - if the number of fireballs left is 0 is hidden, the Mage inherits the Adventurer attack method, if not, the Mage shoots a fireball with 3 times the power of its level\r\n#==========================================\r\n\r\nclass Mage(Adventurer):\r\n def __init__(self, name='', level=0, strength=0, speed=0, power=0):\r\n super().__init__(name, level, strength, speed, power)\r\n self.fireballs_left = self.power\r\n def attack(self, target):\r\n if self.fireballs_left == 0:\r\n super().attack(target)\r\n else:\r\n fireball_damage = self.level * 3\r\n target.HP -= fireball_damage\r\n self.fireballs_left -=1\r\n target.hidden = False\r\n print(self.name + ' casts a fireball on ' + target.name + ' for ' + str(fireball_damage) + ' damage')\r\n\r\n#A - Part 5\r\n#==========================================\r\n# Purpose: An object of this class represents a Wizard, a more powerful version of a Mage, in a RPG game\r\n# Instance variables:\r\n# name = a string representation for the name of a Wizard object\r\n# level = integer representation for the level of the Wizard object\r\n# strength = integer representation for the strength of the Wizard object\r\n# speed = integer representation for the speed of the Wizard object\r\n# power = integer representation for the power of the Wizard object\r\n# HP = integer representation for the number of hit points (how much damage the adventurer can no longer fight) an Wizard object has\r\n# hidden = boolean representation for whether the Wizard object can be seen or not\r\n# fireballs_left = the number of fireballs the Mage has left to use for attack\r\n# Methods:\r\n# __init__ = inherits the initializations from the Wizard class but changes the initializations of HP and fireballs_left instance variables\r\n#==========================================\r\n\r\nclass Wizard(Mage):\r\n def __init__(self, name='', level=0, strength=0, speed=0, power=0):\r\n super().__init__(name, level, strength, speed, power)\r\n self.HP = self.level * 4\r\n self.fireballs_left = self.power * 2\r\n\r\n#B\r\n\r\ndef battle(player_list, enemy_list):\r\n\r\n while len(player_list) >= 1 and len(enemy_list) >= 1:\r\n print('----------Player Turn----------')\r\n print('Your team: ')\r\n for player in player_list:\r\n print(player)\r\n print()\r\n for player in player_list:\r\n for num in range(len(enemy_list)):\r\n print('Enemy ' + str(num + 1) + ' : ' + str(enemy_list[num]))\r\n print()\r\n attack_who = input('Choose a target for ' + player.name + ': ')\r\n enemy_target = enemy_list[int(attack_who)-1]\r\n player.attack(enemy_target)\r\n if enemy_target.HP <= 0:\r\n enemy_list.remove(enemy_target)\r\n print(enemy_target.name + ' was defeated!')\r\n if len(enemy_list) == 0:\r\n print('You Win!')\r\n return player_list\r\n \r\n print('----------Enemy Turn----------')\r\n for enemy in enemy_list:\r\n player_target = min(player_list)\r\n enemy.attack(player_target)\r\n if player_target.HP <= 0:\r\n player_list.remove(player_target)\r\n print(player_target.name + ' was defeated!')\r\n if len(player_list) == 0:\r\n print('You Lose!')\r\n return enemy_list\r\n \r\n print()\r\n","sub_path":"hw12.py","file_name":"hw12.py","file_ext":"py","file_size_in_byte":9493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"90422851","text":"import platform\nfrom datetime import date\nimport shutil\nimport os\nimport json\n\nmy_system = platform.uname()\ntoday = str(date.today())\ntot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])\ndisk = shutil.disk_usage(\"/\")\nkey = 'BUILD_NUMBER'\nbuild = os.getenv(key)\npath = os.getcwd()\n\n\nsystem_info = {\"system\": my_system.system, \"nodeName\": my_system.node, \"Release\": my_system.release,\n\"Version\": my_system.version, \"Machine\": my_system.machine, \"Processor\": my_system.processor, \"Date\": today,\n\"FreeMem\": free_m, \"FreeDisk\": disk.free, \"Build\": build, \"Path\": path}\n\n\njson_object = json.dumps(system_info, indent = 4)\n\n\nprint(json_object)\n","sub_path":"whats_going_on.py","file_name":"whats_going_on.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"550121419","text":"import pathlib\r\n\r\n# Note:\r\n# Changing FRAMES and or RESOULTION will heavily impact load on CPU.\r\n# If you have a powerful enough computer you may set it to 1080p60\r\n\r\n# Secrets\r\n# Twitch Client ID\r\nCLIENT_ID = \"\"\r\n\r\n# Twitch OAuth Token\r\nOAUTH_TOKEN = \"\"\r\n\r\n# Path to the Firefox profile where you are logged into YouTube\r\nROOT_PROFILE_PATH = \"\"\r\n\r\n# Selenium\r\n# How many seconds Firefox should sleep for when uploading\r\nSLEEP = 3\r\n\r\n# If True Firefox will be hidden (True/False)\r\nHEADLESS = True\r\n\r\n# If information when uploading should be printed (True/False)\r\nDEBUG = True\r\n\r\n\r\n# Paths\r\nPATH = str(pathlib.Path().absolute()).replace(\"\\\\\", \"/\")\r\nCLIP_PATH = PATH + \"/clips/{}/{}\"\r\n\r\n\r\n# Video\r\n# Set the mode (game/channel)\r\nMODE = \"game\"\r\n\r\n# If mode is channel put channel names e.g. [\"trainwreckstv\", \"xqcow\"]\r\n# If mode is game put game names e.g. [\"Team Fortress 2\", \"Just Chatting\"]\r\nLIST = [\"Team Fortress 2\", \"Just Chatting\"]\r\n\r\n# If clips should be rendered into one video (True/False)\r\n# If set to False everything else under Video will be ignored\r\nRENDER_VIDEO = True\r\n\r\n# Resoultion of the rendered video (height, width) for 1080p: ((1080, 1920))\r\nRESOLUTION = (720, 1280)\r\n\r\n# Frames per second (30/60)\r\nFRAMES = 30\r\n\r\n# Minumum video length in minutes (doesn't always work)\r\nVIDEO_LENGTH = 10.5\r\n\r\n# Resize clips to fit RESOLUTION (True/False)\r\n# If any RESIZE option is set to False the video might end up having a weird resolution\r\nRESIZE_CLIPS = True\r\n\r\n# Name of the rendered video\r\nFILE_NAME = \"rendered\"\r\n\r\n# Name of downloaded clip (slug/title)\r\nCLIP_TITLE = \"slug\"\r\n\r\n# Enable (True/False)\r\n# Resize (True/False) read RESIZE_CLIPS\r\n# Path to video file (str)\r\nENABLE_INTRO = False\r\nRESIZE_INTRO = True\r\nINTRO_FILE_PATH = PATH + \"/assets/intro.mp4\"\r\n\r\nENABLE_TRANSITION = True\r\nRESIZE_TRANSITION = True\r\nTRANSITION_FILE_PATH = PATH + \"/assets/transition.mp4\"\r\n\r\nENABLE_OUTRO = False\r\nRESIZE_OUTRO = True\r\nOUTRO_FILE_PATH = PATH + \"/assets/outro.mp4\"\r\n\r\n\r\n# Other\r\n# If YouTube stuff should be saved to a separate file e.g. title, description & tags (True/False)\r\nSAVE_TO_FILE = True\r\n\r\n# Name of the file YouTube stuff should be saved to\r\nSAVE_FILE_NAME = \"youtube\"\r\n\r\n# If the rendered video should be uploaded to YouTube after rendering (True/False)\r\nUPLOAD_TO_YOUTUBE = True\r\n\r\n# If the downloaded clips should be deleted after rendering the video (True/False)\r\nDELETE_CLIPS = True\r\n\r\n# How often it should check if it has made a video today (in seconds)\r\nTIMEOUT = 3600\r\n\r\n\r\n# Twitch\r\nRETRIES = 5\r\n\r\n# Twitch API Request Options\r\nHEADERS = {\"Accept\": \"application/vnd.twitchtv.v5+json\", \"Client-ID\": CLIENT_ID}\r\nPARAMS = {\"period\": \"day\", \"language\": \"en\", \"limit\": 100} # 100 is max\r\n\r\n\r\n# YouTube\r\n# If empty, it would take the title of the first clip, and add \"- *category* Highlights Twitch\"\r\nTITLE = \"\"\r\n\r\n# Category\r\n# Not supported yet\r\nCATEGORY = 20 # 20 for gaming\r\n\r\n# Descriptions\r\n# {} will be replaced with a list of streamer names\r\nDESCRIPTIONS = {\r\n \"Just Chatting\": \"Just Chatting twitch clips \\n\\n{}\\n\",\r\n \"Team Fortress 2\": \"TF2 twitch clips\\n\\n{}\\n\",\r\n}\r\n\r\n# Thumbnails\r\nTHUMBNAILS = {\r\n \"Just Chatting\": \"path/to/file.jpg\",\r\n \"Team Fortress 2\": \"path/to/file.jpg\",\r\n}\r\n\r\n# Tags\r\n# Not supported yet\r\nTAGS = {\r\n \"Just Chatting\": \"just chatting, just chatting clips, just chatting twitch clips\",\r\n \"Team Fortress 2\": \"tf2, tf2 twitch, tf2 twitch clips\",\r\n}\r\n","sub_path":"twitchtube/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"393851063","text":"# =======================================================importing libraries=============================================\n\nimport openpyxl\nfrom openpyxl.styles import PatternFill, Border, Side, Alignment, protection, Font\nimport os\n\n\ndef layout(invoice_details):\n # ========================================================initialising workbook==========================================\n\n wb = openpyxl.load_workbook('Experiment.xlsx')\n ws = wb.active\n print(\"Worksheet created\")\n\n customer_details = invoice_details['Customer_details']\n\n # =========================================================styles========================================================\n\n ws.column_dimensions['A'].width = 1\n ws.column_dimensions['B'].width = 7\n ws.column_dimensions['C'].width = 15\n ws.column_dimensions['D'].width = 24\n ws.column_dimensions['E'].width = 8\n ws.column_dimensions['F'].width = 12\n ws.column_dimensions['G'].width = 20\n ws.column_dimensions['H'].width = 2\n ws.row_dimensions[1].height = 42\n ws.row_dimensions[2].height = 16\n ws.row_dimensions[3].height = 16\n ws.row_dimensions[4].height = 22\n ws.row_dimensions[5].height = 19\n ws.row_dimensions[6].height = 19\n ws.row_dimensions[7].height = 16\n ws.row_dimensions[8].height = 16\n ws.row_dimensions[9].height = 16\n ws.row_dimensions[10].height = 16\n ws.row_dimensions[11].height = 16\n ws.row_dimensions[12].height = 29\n for i in range(13, 23):\n ws.row_dimensions[i].height = 28\n\n ws.row_dimensions[23].height = 15\n for i in range(24, 28):\n ws.row_dimensions[i].height = 16\n\n ws.row_dimensions[28].height = 24\n for i in range(29, 33):\n ws.row_dimensions[i].height = 15\n\n ws.row_dimensions[34].height = 42\n ws.row_dimensions[35].height = 16\n ws.row_dimensions[36].height = 16\n ws.row_dimensions[37].height = 22\n ws.row_dimensions[38].height = 19\n ws.row_dimensions[39].height = 19\n ws.row_dimensions[40].height = 16\n ws.row_dimensions[41].height = 16\n ws.row_dimensions[42].height = 16\n ws.row_dimensions[43].height = 16\n ws.row_dimensions[44].height = 16\n ws.row_dimensions[45].height = 29\n for i in range(46, 56):\n ws.row_dimensions[i].height = 28\n\n ws.row_dimensions[56].height = 15\n for i in range(57, 61):\n ws.row_dimensions[i].height = 16\n\n ws.row_dimensions[61].height = 24\n for i in range(62, 66):\n ws.row_dimensions[i].height = 15\n\n thin = Side(border_style=\"thin\", color=\"365194\")\n table_border = Side(border_style=\"thin\", color=\"B2BEB5\")\n thick = Side(border_style=\"thick\", color=\"365194\")\n\n data_heading4 = Font(name='Constantia',\n size=18,\n color=\"365194\")\n data_heading3 = Font(name='Franklin Gothic Book',\n size=10)\n data_heading2 = Font(name='Franklin Gothic Book',\n size=12)\n data_heading1 = Font(name='Constantia',\n size=28)\n table_headings = Font(name='Constantia',\n size=12,\n bold=True,\n color=\"FFFFFF\")\n billing_data_headings = Font(name='Franklin Gothic Book',\n size=11,\n color=\"365194\")\n billing_data = Font(name='Franklin Gothic Book',\n size=11)\n\n ws['B1'].font = data_heading1\n ws['B1'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n ws['B2'].font = data_heading2\n ws['B2'].alignment = Alignment(horizontal='left', vertical='top')\n\n ws['B3'].font = data_heading2\n ws['B3'].alignment = Alignment(horizontal='left', vertical='top')\n\n ws['B4'].font = data_heading2\n ws['B4'].alignment = Alignment(horizontal='left', vertical='top')\n\n ws['B6'].font = data_heading4\n ws['B6'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n ws['F6'].font = data_heading4\n ws['F6'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n ws['F7'].font = data_heading3\n ws['F7'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n for i in range(7, 12):\n search_string = \"B\" + str(i)\n ws[search_string].font = data_heading2\n ws[search_string].alignment = Alignment(vertical='bottom')\n\n #formatting of heading row in table 1\n for i in range(66, 72):\n search_string2 = chr(i) + \"12\"\n ws[search_string2].font = table_headings\n ws[search_string2].alignment = Alignment(horizontal='center', vertical='center')\n ws[search_string2].fill = PatternFill(\"solid\", fgColor=\"365194\")\n ws[search_string2].border = Border(left=table_border, right=table_border, bottom=thin)\n\n #text formatting of table 1\n for i in range(13, 23):\n for j in range(66, 72):\n search_string = chr(j) + str(i)\n ws[search_string].font = data_heading2\n ws[search_string].alignment = Alignment(vertical='center', horizontal='center')\n\n #text formatting of below section of table 1\n for i in range(24, 28):\n search_string6 = \"B\" + str(i)\n ws[search_string6].font = data_heading2\n ws[search_string6].alignment = Alignment(vertical='center', horizontal='left')\n\n search_string3 = \"F\" + str(i)\n ws[search_string3].font = billing_data_headings\n ws[search_string3].alignment = Alignment(vertical='center', horizontal='center')\n\n \"\"\"ws['G24'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G25'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G26'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G27'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G28'].border = Border(left=thin, right=thin)\n ws['G28'].fill = PatternFill(\"solid\", fgColor=\"365194\")\"\"\"\n\n for i in range(24, 28):\n search_string4 = \"G\" + str(i)\n ws[search_string4].font = billing_data\n ws[search_string4].alignment = Alignment(vertical='center', horizontal='center')\n\n ws['G28'].font = Font(name='Franklin Gothic Book',\n size=11,\n color=\"FFFFFF\")\n ws['G28'].alignment = Alignment(vertical='center', horizontal='center')\n\n ws['E28'].font = Font(name='Franklin Gothic Book',\n size=18,\n color=\"365194\")\n ws['E28'].alignment = Alignment(vertical='center', horizontal='center')\n\n for i in range(29, 33):\n search_string = \"B\" + str(i)\n ws[search_string].font = data_heading3\n ws[search_string].alignment = Alignment(vertical='bottom')\n\n for i in range(66, 72):\n for j in range(10):\n search_string5 = chr(i) + str(13 + j)\n if j == (len(invoice_details['Items']) - 1):\n ws[search_string5].border = Border(left=table_border, right=table_border, bottom=thick)\n if ((12 + j) % 2) == 1:\n ws[search_string5].fill = PatternFill(\"solid\", fgColor=\"F5F5F5\")\n else:\n pass\n else:\n ws[search_string5].border = Border(left=table_border, right=table_border, bottom=table_border)\n if ((12 + j) % 2) == 1:\n ws[search_string5].fill = PatternFill(\"solid\", fgColor=\"F5F5F5\")\n else:\n pass\n\n for i in range(66, 72):\n search_string7 = chr(i) + \"22\"\n ws[search_string7].border = Border(left=table_border, right=table_border, bottom=thick)\n\n # ==========================================================page #2=======================================================\n\n ws['B34'].font = data_heading1\n ws['B34'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n ws['B35'].font = data_heading2\n ws['B35'].alignment = Alignment(horizontal='left', vertical='top')\n\n ws['B36'].font = data_heading2\n ws['B36'].alignment = Alignment(horizontal='left', vertical='top')\n\n ws['B37'].font = data_heading2\n ws['B37'].alignment = Alignment(horizontal='left', vertical='top')\n\n ws['B39'].font = data_heading4\n ws['B39'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n ws['F39'].font = data_heading4\n ws['F39'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n ws['F40'].font = data_heading3\n ws['F40'].alignment = Alignment(horizontal='left', vertical='bottom')\n\n for i in range(40, 45):\n search_string = \"B\" + str(i)\n ws[search_string].font = data_heading2\n ws[search_string].alignment = Alignment(vertical='bottom')\n\n for i in range(66, 72):\n search_string2 = chr(i) + \"45\"\n ws[search_string2].font = table_headings\n ws[search_string2].alignment = Alignment(horizontal='center', vertical='center')\n ws[search_string2].fill = PatternFill(\"solid\", fgColor=\"365194\")\n ws[search_string2].border = Border(left=table_border, right=table_border, bottom=thin)\n\n for i in range(46, 56):\n for j in range(66, 72):\n search_string = chr(j) + str(i)\n ws[search_string].font = data_heading2\n ws[search_string].alignment = Alignment(vertical='center', horizontal='center')\n\n for i in range(57, 61):\n search_string6 = \"B\" + str(i)\n ws[search_string6].font = data_heading2\n ws[search_string6].alignment = Alignment(vertical='center', horizontal='left')\n\n search_string3 = \"F\" + str(i)\n ws[search_string3].font = billing_data_headings\n ws[search_string3].alignment = Alignment(vertical='center', horizontal='center')\n\n ws['G57'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G58'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G59'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G60'].border = Border(left=thin, right=thin, bottom=table_border)\n ws['G61'].border = Border(left=thin, right=thin)\n ws['G61'].fill = PatternFill(\"solid\", fgColor=\"365194\")\n\n for i in range(57, 61):\n search_string4 = \"G\" + str(i)\n ws[search_string4].font = billing_data\n ws[search_string4].alignment = Alignment(vertical='center', horizontal='center')\n\n ws['G61'].font = Font(name='Franklin Gothic Book',\n size=11,\n color=\"FFFFFF\")\n ws['G61'].alignment = Alignment(vertical='center', horizontal='center')\n\n ws['E61'].font = Font(name='Franklin Gothic Book',\n size=18,\n color=\"365194\")\n ws['E61'].alignment = Alignment(vertical='center', horizontal='center')\n\n for i in range(62, 66):\n search_string = \"B\" + str(i)\n ws[search_string].font = data_heading3\n ws[search_string].alignment = Alignment(vertical='bottom')\n\n for i in range(66, 72):\n for j in range(len(invoice_details['Items'])-10):\n search_string5 = chr(i) + str(46 + j)\n if j == (len(invoice_details['Items']) - 1):\n ws[search_string5].border = Border(left=table_border, right=table_border, bottom=thick)\n if ((46 + j) % 2) == 1:\n ws[search_string5].fill = PatternFill(\"solid\", fgColor=\"F5F5F5\")\n else:\n pass\n else:\n ws[search_string5].border = Border(left=table_border, right=table_border, bottom=table_border)\n if ((46 + j) % 2) == 1:\n ws[search_string5].fill = PatternFill(\"solid\", fgColor=\"F5F5F5\")\n else:\n pass\n\n for i in range(66, 72):\n row = 46 + (len(invoice_details['Items'])-11)\n search_string8 = chr(i) + str(row)\n ws[search_string8].border = Border(left=table_border, right=table_border, bottom=thick)\n\n # =========================================================values used in invoice========================================\n\n invoice_number = \"Invoice #\" + str(invoice_details['Invoice_number'])\n date = \"Date: \" + invoice_details['Date']\n cgst = invoice_details['CGST'] + \"%\"\n sgst = invoice_details['SGST'] + \"%\"\n igst = invoice_details['IGST'] + \"%\"\n\n total = 0\n for i in invoice_details['Items']:\n product = int(i['Rate']) * int(i['Qty'])\n total += product\n\n cgst_cal = (int(invoice_details['CGST']) / 100) * total\n sgst_cal = (int(invoice_details['SGST']) / 100) * total\n igst_cal = (int(invoice_details['IGST']) / 100) * total\n final = total + cgst_cal + sgst_cal + igst_cal\n\n # =======================================================Values in invoice===============================================\n\n ws['B1'] = \"Firm Name\"\n ws['B2'] = \"Firm Address\"\n ws['B3'] = \"Contact Numbers\"\n ws['B4'] = \"GST No. XXXXX-XXXXX\"\n\n ws['B6'] = \"Bill To\"\n ws['F6'] = invoice_number\n ws['F7'] = date\n ws['B7'] = str(customer_details['Name']) + \" | \" + str(customer_details['Phone'])\n ws['B8'] = \"State: \" + str(customer_details['Address'])\n ws['B9'] = \"StateCode: \" + str(customer_details['Code'])\n ws['B10'] = \"GSTN: \" + str(customer_details['GSTN'])\n\n ws['B12'] = \"S No.\"\n ws['C12'] = \"HSN Code\"\n ws['D12'] = \"Description\"\n ws['E12'] = \"Qty.\"\n ws['F12'] = \"Rate\"\n ws['G12'] = \"Amount\"\n\n ws['B24'] = \"Bank Name: Bank Name\"\n ws['B25'] = \"Account No.: XXXXXXXXXX\"\n ws['B26'] = \"Account Name: Account Name\"\n ws['B27'] = \"IFSC: IFSC Code\"\n\n \"\"\"ws['F24'] = \"Subtotal\"\n ws['G24'] = \"=SUM(G10:G19)\"\n ws['F25'] = \"CGST(\" + cgst + \")\"\n ws['G25'] = cgst_cal\n ws['F26'] = \"SGST(\" + sgst + \")\"\n ws['G26'] = sgst_cal\n ws['F27'] = \"IGST(\" + igst + \")\"\n ws['G27'] = igst_cal\n ws['E28'] = \"Total Cost\"\n ws['G28'] = final\"\"\"\n\n ws['B29'] = \"Make all checks payable to Company Name\"\n ws['B30'] = \"If you have any questions concerning this invoice, use the following contact information:\"\n ws['B31'] = \"Contact Details\"\n ws['B32'] = \"Thank you for your business!\"\n\n ws['B34'] = \"Firm Name\"\n ws['B35'] = \"Firm Details\"\n ws['B36'] = \"Contact Numbers\"\n ws['B37'] = \"GST No. XXXXX-XXXXX\"\n\n ws['B39'] = \"Bill To\"\n ws['F39'] = invoice_number\n ws['F40'] = date\n ws['B40'] = str(customer_details['Name']) + \" | \" + str(customer_details['Phone'])\n ws['B41'] = \"State: \" + str(customer_details['Address'])\n ws['B42'] = \"StateCode: \" + str(customer_details['Code'])\n ws['B43'] = \"GSTN: \" + str(customer_details['GSTN'])\n\n ws['B45'] = \"S No.\"\n ws['C45'] = \"HSN Code\"\n ws['D45'] = \"Description\"\n ws['E45'] = \"Qty.\"\n ws['F45'] = \"Rate\"\n ws['G45'] = \"Amount\"\n\n ws['B57'] = \"Bank Name: Bank Name\"\n ws['B58'] = \"Account No.: XXXXXXXXXX \"\n ws['B59'] = \"Account Name: Account Name\"\n ws['B60'] = \"IFSC: IFSC Code\"\n\n ws['F57'] = \"Subtotal\"\n ws['G57'] = total\n ws['F58'] = \"CGST(\" + cgst + \")\"\n ws['G58'] = cgst_cal\n ws['F59'] = \"SGST(\" + sgst + \")\"\n ws['G59'] = sgst_cal\n ws['F60'] = \"IGST(\" + igst + \")\"\n ws['G60'] = igst_cal\n ws['E61'] = \"Total Cost\"\n ws['G61'] = final\n\n ws['B62'] = \"Make all checks payable to Company Name\"\n ws['B63'] = \"If you have any questions concerning this invoice, use the following contact information:\"\n ws['B64'] = \"Contact Details\"\n ws['B65'] = \"Thank you for your business!\"\n\n # ======================================================Item Details in Table============================================\n start_row = 13\n start_col = 1\n serial_no = 1\n start_character = 69\n\n for i in range(0, 10):\n product_string = \"=PRODUCT(\" + chr(start_character) + str(start_row + i) + \", \" + chr(\n start_character + 1) + str(start_row + i) + \")\"\n ws.cell(row=(start_row + i), column=start_col + 1).value = serial_no\n serial_no += 1\n ws.cell(row=start_row + i, column=start_col + 2).value = int(invoice_details['Items'][i]['HSNCode'])\n ws.cell(row=start_row + i, column=start_col + 3).value = invoice_details['Items'][i]['ItemName']\n ws.cell(row=start_row + i, column=start_col + 4).value = int(invoice_details['Items'][i]['Qty'])\n ws.cell(row=start_row + i, column=start_col + 5).value = int(invoice_details['Items'][i]['Rate'])\n ws.cell(row=start_row + i, column=start_col + 6).value = product_string\n\n start_row2 = 46\n serial_no2 = 11\n\n for i in range(0, len(invoice_details['Items'])-10):\n product_string = \"=PRODUCT(\" + chr(start_character) + str(start_row2 + i) + \", \" + chr(\n start_character + 1) + str(start_row2 + i) + \")\"\n ws.cell(row=(start_row2 + i), column=start_col + 1).value = serial_no2\n serial_no2 += 1\n ws.cell(row=start_row2 + i, column=start_col + 2).value = int(invoice_details['Items'][10+i]['HSNCode'])\n ws.cell(row=start_row2 + i, column=start_col + 3).value = invoice_details['Items'][10+i]['ItemName']\n ws.cell(row=start_row2 + i, column=start_col + 4).value = int(invoice_details['Items'][10+i]['Qty'])\n ws.cell(row=start_row2 + i, column=start_col + 5).value = int(invoice_details['Items'][10+i]['Rate'])\n ws.cell(row=start_row2 + i, column=start_col + 6).value = product_string\n\n # ===============================================merging cells===========================================================\n\n ws.merge_cells('B1:E1')\n ws.merge_cells('B2:E2')\n ws.merge_cells('B3:E3')\n ws.merge_cells('B4:E4')\n\n ws.merge_cells('B6:E6')\n ws.merge_cells('F6:G6')\n ws.merge_cells('B7:E7')\n ws.merge_cells('F7:G7')\n ws.merge_cells('B8:D8')\n ws.merge_cells('B9:E9')\n ws.merge_cells('B10:E10')\n\n for i in range(24, 28):\n merge_range = \"B\" + str(i) + \":D\" + str(i)\n ws.merge_cells(merge_range)\n\n ws.merge_cells('E28:F28')\n\n for i in range(29, 33):\n merge_range = \"B\" + str(i) + \":H\" + str(i)\n ws.merge_cells(merge_range)\n\n ws.merge_cells('B34:E34')\n ws.merge_cells('B35:E35')\n ws.merge_cells('B36:E36')\n ws.merge_cells('B37:E37')\n\n ws.merge_cells('B39:E39')\n ws.merge_cells('F39:G39')\n ws.merge_cells('B40:E40')\n ws.merge_cells('F40:G40')\n ws.merge_cells('B41:D41')\n ws.merge_cells('B42:E42')\n ws.merge_cells('B43:E43')\n\n for i in range(57, 61):\n merge_range = \"B\" + str(i) + \":D\" + str(i)\n ws.merge_cells(merge_range)\n\n ws.merge_cells('E61:F61')\n\n for i in range(62, 66):\n merge_range = \"B\" + str(i) + \":H\" + str(i)\n ws.merge_cells(merge_range)\n\n # ====================================================saving file========================================================\n save_name = invoice_number + \".xlsx\"\n wb.save(save_name)\n os.startfile(save_name, 'print')","sub_path":"pdf_creator_2.py","file_name":"pdf_creator_2.py","file_ext":"py","file_size_in_byte":18798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"512256030","text":"\"\"\"bugs logic\"\"\"\nfrom typing import List, TextIO, Tuple, Union\n\n\ndef get_neighbors(y_pos: int, x_pos: int) -> List[tuple]:\n \"\"\"get neighboring coordinators to a given position\n\n Arguments:\n y_pos {int} -- given y position\n x_pos {int} -- given x position\n\n Returns:\n List[tuple] -- 4 neighboring coordinates\n \"\"\"\n neighbors = []\n # up\n up_coord = (y_pos-1, x_pos)\n neighbors.append(up_coord)\n\n # left\n left_coord = (y_pos, x_pos - 1)\n neighbors.append(left_coord)\n\n # right\n right_coord = (y_pos, x_pos + 1)\n neighbors.append(right_coord)\n\n # down\n down_coord = (y_pos+1, x_pos)\n neighbors.append(down_coord)\n\n return neighbors\n\n\ndef neighbor_bugs(depth: int,\n y_pos: int, x_pos:\n int, bugs: set,\n inner_depth: tuple,\n y_count: int,\n x_count: int) -> Union[int, Tuple[int, int]]:\n \"\"\"get neighbor position that have a bug on it\n if inner_depth is not None it will be depth / recursive aware\n\n Arguments:\n depth {int} -- the current depth\n y_pos {int} -- current y\n x_pos {int} -- current x\n bugs {set} -- current bugs state\n inner_depth {tuple} -- the inner depth location (center cell)\n y_count {int} -- the total y positions available\n x_count {int} -- the total x positions avaiable\n\n Returns:\n Union[int, Tuple[int, int] -- if no inner depth was provided,\n just a count of the total neighboring bugs.\n if inner depth was provided,\n it will return another int that represents the number\n of the neighboring depth that was visited. (+/- 1 from)\n\n \"\"\"\n # set if another depth is found\n recursive_depth = None\n\n neighbors = get_neighbors(y_pos, x_pos)\n\n depth_neighbors = set()\n\n for neighbor in neighbors:\n if inner_depth:\n # check if neighbor is inner recursion\n if neighbor == inner_depth:\n # neighbors vary on position relative to inner recursion\n if y_pos < inner_depth[0]:\n recursive_depth = depth + 1\n recursive_y = 0\n for recursive_x in range(x_count):\n position = (recursive_depth, recursive_y, recursive_x)\n depth_neighbors.add(position)\n elif y_pos > inner_depth[0]:\n recursive_depth = depth + 1\n recursive_y = y_count - 1\n for recursive_x in range(x_count):\n position = (recursive_depth, recursive_y, recursive_x)\n depth_neighbors.add(position)\n elif x_pos < inner_depth[1]:\n recursive_depth = depth + 1\n recursive_x = 0\n for recursive_y in range(y_count):\n position = (recursive_depth, recursive_y, recursive_x)\n depth_neighbors.add(position)\n elif x_pos > inner_depth[1]:\n recursive_depth = depth + 1\n recursive_x = x_count - 1\n for recursive_y in range(y_count):\n position = (recursive_depth, recursive_y, recursive_x)\n depth_neighbors.add(position)\n # check up (outter depth)\n elif neighbor[0] < 0:\n recursive_depth = depth - 1\n position = (recursive_depth,\n inner_depth[0] - 1, inner_depth[1])\n depth_neighbors.add(position)\n # check left\n elif neighbor[1] < 0:\n recursive_depth = depth - 1\n position = (recursive_depth,\n inner_depth[0], inner_depth[1] - 1)\n depth_neighbors.add(position)\n # check down\n elif neighbor[0] >= y_count:\n recursive_depth = depth - 1\n position = (recursive_depth,\n inner_depth[0] + 1, inner_depth[1])\n depth_neighbors.add(position)\n # check right\n elif neighbor[1] >= x_count:\n recursive_depth = depth - 1\n position = (recursive_depth,\n inner_depth[0], inner_depth[1] + 1)\n depth_neighbors.add(position)\n else:\n position = (depth,\n neighbor[0], neighbor[1])\n depth_neighbors.add(position)\n else:\n position = (depth,\n neighbor[0], neighbor[1])\n depth_neighbors.add(position)\n\n intersect = bugs & depth_neighbors\n\n return len(intersect), recursive_depth\n\n\ndef repeat_biodiversity(bugs: set, y_count: int, x_count: int) -> int:\n \"\"\"find the state that repeats and return its \"rating\"\n\n Arguments:\n bugs {set} -- bugs state\n y_count {int} -- total y available\n x_count {int} -- total x available\n\n Returns:\n int -- the rating of the repeated bug state\n \"\"\"\n # historical account of previous patterns\n history = set()\n\n new_bugs = frozenset(bugs)\n while new_bugs not in history:\n\n # update history\n new_bugs = frozenset(new_bugs)\n history.add(new_bugs)\n\n new_bugs = spread(bugs, y_count, x_count)\n\n # update bugs\n bugs = new_bugs\n\n return sum(map(lambda bug: 2 ** (bug[1] * x_count + bug[2]), bugs))\n\n\ndef spread(bugs: set,\n y_count: int,\n x_count: int,\n is_recursive: bool = False,\n min_recursion: int = 0,\n max_recursion: int = 0) -> Union[int, Tuple[int, int, int]]:\n \"\"\"spread bugs to neighboring cells\n\n Arguments:\n bugs {set} -- current bug state\n y_count {int} -- available y\n x_count {int} -- available x\n\n Keyword Arguments:\n is_recursive {bool} -- determines if this process is depth / recursive aware\n (default: {False})\n min_recursion {int} -- min recursion (default: {0})\n max_recursion {int} -- max recusion (default: {0})\n\n Returns:\n Union[int, Tuple[int,int, int] -- if not recursive, just returns new bugs state\n otherwise it will also return the new\n min and max recursive depths\n \"\"\"\n inner_depth = None\n if is_recursive:\n inner_depth = ((y_count - 1) // 2, (x_count - 1) // 2)\n\n depths = list(range(min_recursion, max_recursion + 1))\n new_bugs = set()\n while depths:\n depth = depths.pop()\n for y_position in range(y_count):\n for x_position in range(x_count):\n position = (depth, y_position, x_position)\n\n # skip this position if recursive\n if is_recursive and y_position == inner_depth[0] and x_position == inner_depth[1]:\n continue\n\n neighbor_count, recursive_depth = neighbor_bugs(*position,\n bugs,\n inner_depth,\n y_count,\n x_count)\n is_bug = position in bugs\n\n if is_bug and is_recursive and recursive_depth:\n # if a recursive_depth is reachable that\n # is next to this bug but isn't in our range\n # we need to consider it before compeletion\n if recursive_depth < min_recursion:\n min_recursion = recursive_depth\n depths.append(recursive_depth)\n if recursive_depth > max_recursion:\n max_recursion = recursive_depth\n depths.append(recursive_depth)\n\n if is_bug and neighbor_count == 1:\n # bug lives\n new_bugs.add(position)\n elif not is_bug and neighbor_count in {1, 2}:\n # empty space is now infested\n new_bugs.add(position)\n\n if is_recursive:\n return new_bugs, min_recursion, max_recursion\n else:\n return new_bugs\n\n\ndef spread_minutes(bugs: set, y_count: int, x_count: int, minutes: int) -> set:\n \"\"\"spread bugs over a course of give time in minutes\n\n Arguments:\n bugs {set} -- bugs state\n y_count {int} -- available y\n x_count {int} -- available x\n minutes {int} -- total minutes to spread in\n\n Returns:\n set -- new bug state after x minutes pass\n \"\"\"\n min_recursion = 0\n max_recursion = 0\n for _ in range(minutes):\n bugs, min_recursion, max_recursion = spread(\n bugs, y_count, x_count, True, min_recursion, max_recursion)\n\n return bugs\n\n\ndef read_bugs(file_input: TextIO) -> set:\n \"\"\"read bug input and returns a starting state\n\n depth is 0 for all read inputs\n\n Arguments:\n file_input {TextIO} -- text stream\n\n Returns:\n set -- bug state\n \"\"\"\n bugs = set()\n y_count = 0\n x_count = 0\n for y_position, line in enumerate(file_input):\n y_count += 1\n for x_position, character in enumerate(line.strip()):\n x_count = max(x_position + 1, x_count)\n if character == \"#\":\n # depth starts at 0\n position = (0, y_position, x_position)\n bugs.add(position)\n\n return bugs, y_count, x_count\n","sub_path":"advent_of_code/day_24/bugs.py","file_name":"bugs.py","file_ext":"py","file_size_in_byte":9795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"644753143","text":"\"\"\"\nAuthor: Lili Meng\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom utils import *\n\n\n\n\n\n\ndef resnet_basicblock(x_input, nInputPlane, nOutputPlane, stride, scope_name, is_training, deltaT):\n \"\"\"basic residual with 2 sub layers.\"\"\"\n\n \"\"\" weight tensor. [3,3,3,32],the first two [3,3] are the patch size\n the next is the number of input channels, and the last is the number\n of output channels\n \"\"\"\n\n \"\"\"the first convolution layer with activation function relu\"\"\"\n conv_name1 = scope_name + \"conv1\"\n conv_name2 = scope_name + \"conv2\"\n\n bn_name1 = scope_name + \"bn1\"\n bn_name2 = scope_name + \"bn2\"\n\n bn_name0 = scope_name + \"bn0\"\n\n x_original = x_input\n basic_conv1 = conv2d_new(conv_name1, x_input, 3, 3,\n nInputPlane, nOutputPlane, stride)\n\n # Scale and shift to obtain the final output of the batch normalization\n # this value is fed into the activation function\n basic_bn1 = tf.contrib.layers.batch_norm(basic_conv1,\n center=True, scale=True,\n is_training=is_training,\n scope=bn_name1)\n\n pre_acivations_name1 = \"pre_activations\" + conv_name1\n tf.summary.histogram(pre_acivations_name1, basic_bn1)\n\n basic_h_conv1 = tf.nn.relu(basic_bn1)\n\n after_activations_name1 = \"after_activations\" + conv_name1\n tf.summary.histogram(after_activations_name1, basic_h_conv1)\n\n \"\"\"the second convolution layer\n no relu after the second layer\n the ninputPlane of the second layer is the same as the nOutputPlane of the first layer \n the stride of the second conv layer is [1,1,1,1]\n \"\"\"\n\n basic_conv2 = conv2d_new(conv_name2, basic_h_conv1,\n 3, 3, nOutputPlane, nOutputPlane, 1)\n\n basic_bn2 = tf.contrib.layers.batch_norm(basic_conv2,\n center=True, scale=True,\n is_training=is_training,\n scope=bn_name2)\n\n\n # If the input and output dimensions are not the same, the shortcut still performs\n # identity mapping, with extra zero entries padded for increasing dimensions\n # This option introduces no extra parameter\n if nInputPlane != nOutputPlane: # if nInputPlane!=nOutputPlane, add strided, zero-padded identity shortcut\n x_pool = tf.nn.avg_pool(x_original, ksize=[1, 1, 1, 1],\n strides=[1, stride, stride, 1], padding='SAME')\n\n x_padded = tf.pad(x_pool,\n [[0, 0], [0, 0], [0, 0],\n [(nOutputPlane - nInputPlane) // 2, (nOutputPlane - nInputPlane) // 2]])\n\n # add the output from two convolutional layer and shortcut\n x_output = x_padded + deltaT*basic_bn2\n else:\n # add the output from two convolutional layer and shortcut\n x_output = x_original + deltaT*basic_bn2\n\n pre_acivations_name2 = \"pre_activations\" + conv_name2\n tf.summary.histogram(pre_acivations_name2, x_output)\n\n # relu after adding shortcut\n #x_output = tf.nn.relu(x_output)\n\n return x_output\n\n\ndef resnet_unit_layer(x_input, nInputPlane, nOutputPlane, count, stride, scope_name, is_training, deltaT):\n\n scope_name0 = (scope_name + \"_basicB0\")\n \n resnet_nblocks = resnet_basicblock(\n x_input, nInputPlane, nOutputPlane, stride, scope_name0, is_training, deltaT)\n\n if count > 1:\n for i in range(1, count):\n scope_name_i = scope_name + \"_basicB\" + str(i)\n resnet_nblocks = resnet_basicblock(\n resnet_nblocks, nOutputPlane, nOutputPlane, 1, scope_name_i, is_training, deltaT)\n return resnet_nblocks\n\n\ndef resnet_model(Y, img_height, img_width, in_channels, n_class, num_residual_units, is_training, deltaT):\n \"\"\"Deep residual nerual network with basic block\n details refer to: Deep Residual Learning for Image Recognition \n\n Args:\n images: Batches of images. [batch_size, image_size, image_size, 3]\n in_channels, 3 for RGB images and 1 for gray image\n labels: Batches of labels. [batch_size, num_classes]\n modes: One of 'train' and 'eval'\n n_class: number of classes, for instance 10 for cifar10\n num_residual_units: how many residual units for each unit layer (no feature map size changes)\n \"\"\"\n nChannels = 16\n print(\"before Y.reshape\")\n Y = tf.reshape(Y, [-1, img_height, img_width, in_channels])\n batch_size = tf.shape(Y)[0]\n\n s = conv2d_new('conv1', Y, 3, 3, in_channels, nChannels, 1)\n s = tf.contrib.layers.batch_norm(s,\n center=True, scale=True,\n is_training=is_training,\n scope='bn1')\n s = tf.nn.relu(s)\n\n\n s = resnet_unit_layer(s, nChannels, nChannels, num_residual_units,\n 1, \"unit_1\", is_training, deltaT)\n\n # Downsample again by convolutional layers that have a stride of 2\n # The feature map size is halved, the number of filters is doubled so as to\n # preserve the complexity per layer\n # s = resnet_unit_layer(s, 16, 32, num_residual_units,\n # 2, \"unit_2\", is_training)\n\n # s = resnet_unit_layer(s, 32, 64, num_residual_units,\n # 2, \"unit_3\", is_training)\n\n # average pooling layer\n s = tf.reduce_mean(s, [1, 2])\n\n print(\"no problem after pooling\")\n print(s.shape)\n\n s = tf.reshape(s, [batch_size, -1])\n # Fully connected layer weight\n\n FC_W = tf.get_variable(\n 'DW', [nChannels, n_class],\n initializer=tf.uniform_unit_scaling_initializer(factor=1.0))\n\n variable_summaries('FC_Weights', FC_W)\n\n FC_b = tf.get_variable('FC_b', [n_class],\n initializer=tf.constant_initializer())\n\n variable_summaries('FC_Biases', FC_b)\n\n logits = tf.nn.xw_plus_b(s, FC_W, FC_b)\n\n return logits\n","sub_path":"resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"125314285","text":"from rest_framework.filters import BaseFilterBackend\nfrom django.db.models import Q\nfrom rest_framework.exceptions import ParseError\nfrom django.contrib.gis.geos import Polygon, Point\n\n\nclass InPolygonFilter(BaseFilterBackend):\n polygon_param = 'in_polygon'\n\n def get_filter_bbox(self, request):\n bbox_string = request.data.get(self.polygon_param, None)\n if not bbox_string:\n return None\n try:\n data = [float(n) for n in bbox_string.split(',')]\n except ValueError:\n raise ParseError('Invalid bbox string supplied for parameter {0}'.format(self.polygon_param))\n points = []\n for i in range(0, len(data) - 1, 2):\n points.append((data[i], data[i+1]))\n x = Polygon(tuple(points))\n return x\n\n def filter_queryset(self, request, queryset, view):\n\n filter_field = getattr(view, 'ploygon_filter_field', None)\n include_overlapping = getattr(view, 'ploygon_filter_include_overlapping', False)\n order_field = getattr(view, 'order_by', 'gid')\n if include_overlapping:\n geoDjango_filter = 'bboverlaps'\n else:\n geoDjango_filter = 'contained'\n\n if not filter_field:\n return queryset\n\n bbox = self.get_filter_bbox(request)\n if not bbox:\n return queryset\n return queryset.filter(Q(**{'%s__%s' % (filter_field, geoDjango_filter): bbox})).order_by(order_field)\n\n","sub_path":"bmlife/geolocation/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"407661711","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------\n\nimport six\n\nfrom .models import TextRecord\n\n\ndef _validate_text_records(records):\n if not records:\n raise ValueError(\"Input records can not be empty or None\")\n\n if isinstance(records, six.string_types):\n raise TypeError(\"Input records cannot be a string.\")\n\n if isinstance(records, dict):\n raise TypeError(\"Input records cannot be a dict\")\n\n if not all(isinstance(x, six.string_types) for x in records):\n if not all(\n isinstance(x, (dict, TextRecord))\n for x in records\n ):\n raise TypeError(\n \"Mixing string and dictionary/object record input unsupported.\"\n )\n\n request_batch = []\n for idx, doc in enumerate(records):\n if isinstance(doc, six.string_types):\n record = {\"id\": str(idx), \"text\": doc}\n request_batch.append(record)\n else:\n request_batch.append(doc)\n return request_batch\n","sub_path":"sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_patch.py","file_name":"_patch.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"641000931","text":"\nfrom __future__ import print_function\nimport sys,os\nimport argparse\nfrom azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--file_name',default=None,required=False)\n config = parser.parse_args()\n file_name=config.file_name\n \n\n try:\n connect_str = os.getenv(\"AZURE_STORAGE_CONNECTION_STRING\")\n blob_service_client = BlobServiceClient.from_connection_string(connect_str)\n\n container_name = \"edu\"\n \n # path in azure\n blob_path = \"/parentsvoice_conversion/resource/datasets_for_analy/\"+file_name\n print('blob_path',blob_path)\n pwd=os.getcwd()\n local_path_file=os.path.join(pwd,'datasets',file_name)\n '''\n blob_list = container_client.list_blobs(blob_path)\n # resouces/\n \n\n \n\n \n\n _, tail = os.path.split(\"{}\".format(blob_list.name))\n \n file_path = blob_path + tail\n '''\n # file info in azure\n blob_client = blob_service_client.get_blob_client(container=container_name, blob = \"/parentsvoice_conversion/resource/datasets_for_analy/\"+file_name)\n # local path to save\n\n with open(local_path_file, \"wb\") as my_blob:\n download_stream = blob_client.download_blob()\n my_blob.write(download_stream.readall())\n\n print(\"다운로드 완료.\")\n \n except Exception as ex:\n print('Exception:')\n print(ex)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"resources/azure_download/download_file.py","file_name":"download_file.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"546221423","text":"from django.shortcuts import render, redirect\nfrom django.views.decorators.http import require_POST\n\nfrom .forms import TodoForm\nfrom .models import Task\n\ndef home(request):\n form = TodoForm()\n context = {\n \"title\": Task.objects.all(),\n \"form\": form,\n }\n return render(request, 'index.html', context)\n\n@require_POST\ndef addTask(request):\n form = TodoForm(request.POST)\n if form.is_valid():\n new_todo = Task(title=request.POST['text'])\n new_todo.save()\n return redirect('home')\n\ndef completeTodo(request, task_id):\n todo = Task.objects.get(pk=task_id)\n todo.completed = True\n todo.save()\n return redirect('home')\n\ndef deleteComplete(request):\n Task.objects.filter(completed__exact=True).delete()\n\n return redirect('home')","sub_path":"tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"448269257","text":"import time\r\n#-----------------------------------倉庫----------------------------------------\r\n\r\nclass Bag(): #####倉庫類別#####\r\n def __init__(self,Money,Diamond,Food,Cake,Cookies,Hamburger):\r\n self.Money = Money #金幣\r\n self.Diamond = Diamond #鑽石\r\n self.Food = Food #雞飼料\r\n self.Cake = Cake #蛋糕\r\n self.Cookies = Cookies #餅乾\r\n self.Hamburger = Hamburger #特大麥香雞\r\n \r\n def show(self): #列出資源\r\n print(\"目前身上的物品: \")\r\n print('金幣: ',self.Money,'鑽石: ',self.Diamond,\r\n '\\n有機雞飼料: ',self.Food,'生乳酪蛋糕: ',self.Cake,'餅乾: ',\r\n self.Cookies,'特大麥香雞 ',self.Hamburger)\r\n print(\"\")\r\n#-------------------------------##增減##函式--------------------------------------\r\n def add_money(self,add):\r\n self.Money += add\r\n \r\n def add_diamond(self,add):\r\n self.Diamond += add\r\n\r\n def add_food(self,add):\r\n self.Food += add\r\n\r\n def add_cake(self,add):\r\n self.Cake += add\r\n\r\n def add_cookies(self,add):\r\n self.Cookies += add\r\n\r\n def add_hamburger(self,add):\r\n self.Hamburger += add\r\n#--------------------------------##進食##函式---------------------------------------\r\n def Eat(self,Chicken):\r\n while 1:\r\n Chicken._State(1)\r\n print('0.不吃了',\r\n '\\n1.有機雞飼料: ',self.Food,\r\n '\\n2.生乳酪蛋糕: ',self.Cake,\r\n '\\n3.餅乾: ',self.Cookies,\r\n '\\n4.特大麥香雞: ',self.Hamburger)\r\n print(\"\")\r\n eat = input('請輸入想吃的物品編號: ')\r\n if eat == \"0\":\r\n break\r\n if eat == \"1\" and self.Food > 0:\r\n Chicken._MP(1) #能力值增加\r\n Chicken._Hunger(5)\r\n self.add_food(-1) #食物減少\r\n print(Chicken.Name,' 吃了有機雞飼料 ! ! ')\r\n time.sleep(0.5)\r\n print(Chicken.Name,' 的行動值增加 1 ,飽食度增加 5 ')\r\n time.sleep(0.5)\r\n elif eat == \"1\":\r\n print(\"食物不足\")\r\n if eat == \"2\" and self.Cake > 0:\r\n Chicken._MP(3)\r\n Chicken._Hunger(15)\r\n Chicken._Emotion(15)\r\n self.add_cake(-1)\r\n print(Chicken.Name,' 一臉滿足的吃下了生乳酪蛋糕 ')\r\n time.sleep(0.5)\r\n print(Chicken.Name,' 的行動值增加 3 ,飽食度增加 15 ,心情增加 15 ')\r\n time.sleep(0.5)\r\n elif eat == \"2\":\r\n print(\"食物不足\")\r\n if eat == \"3\" and self.Cookies > 0:\r\n Chicken._MP(8)\r\n Chicken._Hunger(15)\r\n self.add_cookies(-1)\r\n print('喀滋喀滋... ',Chicken.Name,' 優雅的吃完餅乾了 ')\r\n time.sleep(0.5)\r\n print(Chicken.Name,' 的行動值增加 8 ,飽食度增加 15 ')\r\n time.sleep(0.5)\r\n elif eat == \"3\":\r\n print(\"食物不足\")\r\n if eat == \"4\" and self.Hamburger > 0:\r\n Chicken._MP(20)\r\n Chicken._Hunger(20)\r\n Chicken._Emotion(30)\r\n self.add_hamburger(-1)\r\n print('吧唧吧唧... ',Chicken.Name,' 含著眼淚吃完了特大麥香雞... ')\r\n time.sleep(0.5)\r\n print(Chicken.Name,' 的行動值增加 20 ,飽食度增加 20 \\n但是心情減少 30 ')\r\n time.sleep(0.5)\r\n elif eat == \"4\":\r\n print(\"食物不足\")\r\n","sub_path":"雷抗雞/Asset/Bag_System.py","file_name":"Bag_System.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"633545477","text":"import yaml\nimport inflection\nimport re\nimport os\n\n\nclass ContentBuilder(object):\n def __init__(self, sections):\n self.sections = list(sections)\n\n def __iter__(self):\n return self.sections.__iter__()\n\n def get_section(self, requested_section):\n for section in self.sections:\n if section[\"id\"] == requested_section:\n return section\n return None\n\n def get_next_section_id(self, section_id=None, only_editable=False):\n previous_section_is_current = section_id is None\n\n for section in self.sections:\n if only_editable:\n if (\n previous_section_is_current and\n \"editable\" in section and\n section[\"editable\"]\n ):\n return section[\"id\"]\n else:\n if previous_section_is_current:\n return section[\"id\"]\n\n if section[\"id\"] == section_id:\n previous_section_is_current = True\n\n return None\n\n def get_next_editable_section_id(self, section_id=None):\n return self.get_next_section_id(section_id, True)\n\n def filter(self, service_data):\n sections = filter(None, [\n self._get_section_filtered_by(section, service_data)\n for section in self.sections\n ])\n\n return ContentBuilder(sections)\n\n def _get_section_filtered_by(self, section, service_data):\n section = section.copy()\n\n filtered_questions = [\n question for question in section[\"questions\"]\n if self._question_should_be_shown(\n question.get(\"depends\"), service_data\n )\n ]\n\n if len(filtered_questions):\n section[\"questions\"] = filtered_questions\n return section\n else:\n return None\n\n def _question_should_be_shown(self, dependencies, service_data):\n if dependencies is None:\n return True\n for depends in dependencies:\n if not depends[\"on\"] in service_data:\n return False\n if not service_data[depends[\"on\"]] in depends[\"being\"]:\n return False\n return True\n\n\nclass ContentLoader(object):\n def __init__(self, manifest, content_directory):\n manifest_sections = read_yaml(manifest)\n\n self._questions = {\n q: _load_question(q, content_directory)\n for section in manifest_sections\n for q in section[\"questions\"]\n }\n\n self._sections = [\n self._populate_section(s) for s in manifest_sections\n ]\n\n def get_question(self, question):\n return self._questions.get(question, {}).copy()\n\n def get_builder(self):\n return ContentBuilder(self._sections)\n\n def _populate_section(self, section):\n section[\"id\"] = _make_section_id(section[\"name\"])\n section[\"questions\"] = [\n self.get_question(q) for q in section[\"questions\"]\n ]\n\n return section\n\n\ndef _load_question(question, directory):\n question_content = read_yaml(\n directory + question + \".yml\"\n )\n question_content[\"id\"] = _make_question_id(question)\n\n return question_content\n\n\ndef _make_section_id(name):\n return inflection.underscore(\n re.sub(\"\\s\", \"_\", name)\n )\n\n\ndef _make_question_id(question):\n if re.match('^serviceTypes(SCS|SaaS|PaaS|IaaS)', question):\n return 'serviceTypes'\n return question\n\n\ndef read_yaml(yaml_file):\n if not os.path.isfile(yaml_file):\n return {}\n with open(yaml_file, \"r\") as file:\n return yaml.load(file)\n","sub_path":"dmutils/content_loader.py","file_name":"content_loader.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"366724586","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport re\nimport time\nimport pickle\nimport requests\nfrom pathlib import Path\n\nimport pandas as pd\nfrom lxml import etree\n\nSYMBOLS_URL = \"http://app.finance.ifeng.com/hq/list.php?type=stock_a&class={s_type}\"\nCSI300_BENCH_URL = \"http://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.000300&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58&klt=101&fqt=0&beg=19900101&end=20220101\"\nSH600000_BENCH_URL = \"http://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600000&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58&klt=101&fqt=0&beg=19900101&end=20220101\"\n\nCALENDAR_URL_BASE = \"http://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.{bench_code}&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58&klt=101&fqt=0&beg=19900101&end=20220101\"\n\nCALENDAR_BENCH_URL_MAP = {\n \"CSI300\": CALENDAR_URL_BASE.format(bench_code=\"000300\"),\n \"CSI100\": CALENDAR_URL_BASE.format(bench_code=\"000903\"),\n # NOTE: Use the time series of SH600000 as the sequence of all stocks\n \"ALL\": CALENDAR_URL_BASE.format(bench_code=\"600000\"),\n}\n\n_BENCH_CALENDAR_LIST = None\n_ALL_CALENDAR_LIST = None\n_HS_SYMBOLS = None\n_CALENDAR_MAP = {}\n\n# NOTE: Until 2020-10-20 20:00:00\nMINIMUM_SYMBOLS_NUM = 3900\n\n\ndef get_hs_calendar_list(bench_code=\"CSI300\") -> list:\n \"\"\"get SH/SZ history calendar list\n\n Parameters\n ----------\n bench_code: str\n value from [\"CSI300\", \"CSI500\", \"ALL\"]\n\n Returns\n -------\n history calendar list\n \"\"\"\n\n def _get_calendar(url):\n _value_list = requests.get(url).json()[\"data\"][\"klines\"]\n return sorted(map(lambda x: pd.Timestamp(x.split(\",\")[0]), _value_list))\n\n calendar = _CALENDAR_MAP.get(bench_code, None)\n if calendar is None:\n calendar = _get_calendar(CALENDAR_BENCH_URL_MAP[bench_code])\n _CALENDAR_MAP[bench_code] = calendar\n return calendar\n\n\ndef get_hs_stock_symbols() -> list:\n \"\"\"get SH/SZ stock symbols\n\n Returns\n -------\n stock symbols\n \"\"\"\n global _HS_SYMBOLS\n\n def _get_symbol():\n _res = set()\n for _k, _v in ((\"ha\", \"ss\"), (\"sa\", \"sz\"), (\"gem\", \"sz\")):\n resp = requests.get(SYMBOLS_URL.format(s_type=_k))\n _res |= set(\n map(\n lambda x: \"{}.{}\".format(re.findall(r\"\\d+\", x)[0], _v),\n etree.HTML(resp.text).xpath(\"//div[@class='result']/ul//li/a/text()\"),\n )\n )\n return _res\n\n if _HS_SYMBOLS is None:\n symbols = set()\n _retry = 60\n # It may take multiple times to get the complete\n while len(symbols) < MINIMUM_SYMBOLS_NUM:\n symbols |= _get_symbol()\n time.sleep(3)\n\n symbol_cache_path = Path(\"~/.cache/hs_symbols_cache.pkl\").expanduser().resolve()\n symbol_cache_path.parent.mkdir(parents=True, exist_ok=True)\n if symbol_cache_path.exists():\n with symbol_cache_path.open(\"rb\") as fp:\n cache_symbols = pickle.load(fp)\n symbols |= cache_symbols\n with symbol_cache_path.open(\"wb\") as fp:\n pickle.dump(symbols, fp)\n\n _HS_SYMBOLS = sorted(list(symbols))\n\n return _HS_SYMBOLS\n\n\ndef symbol_suffix_to_prefix(symbol: str, capital: bool = True) -> str:\n \"\"\"symbol suffix to prefix\n\n Parameters\n ----------\n symbol: str\n symbol\n capital : bool\n by default True\n Returns\n -------\n\n \"\"\"\n code, exchange = symbol.split(\".\")\n if exchange.lower() in [\"sh\", \"ss\"]:\n res = f\"sh{code}\"\n else:\n res = f\"{exchange}{code}\"\n return res.upper() if capital else res.lower()\n\n\ndef symbol_prefix_to_sufix(symbol: str, capital: bool = True) -> str:\n \"\"\"symbol prefix to sufix\n\n Parameters\n ----------\n symbol: str\n symbol\n capital : bool\n by default True\n Returns\n -------\n\n \"\"\"\n res = f\"{symbol[:-2]}.{symbol[-2:]}\"\n return res.upper() if capital else res.lower()\n\n\nif __name__ == '__main__':\n assert len(get_hs_stock_symbols()) >= MINIMUM_SYMBOLS_NUM\n","sub_path":"scripts/data_collector/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"165110359","text":"# -*- coding: utf-8 -*-\n# @Time : 18-6-22 上午9:10\n# @Author : BlvinDon\n# @Email : wenbingtang@hotmail.com\n# @File : Test.py\n# @Software: PyCharm\nimport re\ndef Weight():\n with open('DT.dot', 'r') as fp:\n temp = ''\n for line in fp.readlines():\n line = line.strip('\\n')\n temp = temp + line\n pattern = re.compile(r'\\[\\d+, \\d+\\]') # 查找数字\n result1 = pattern.findall(temp)\n result2 = []\n for r in result1:\n if ', 0]' not in r:\n if '[0, ' not in r:\n # print(r)\n result2.append(r)\n # print(result2)\n pattern = re.compile(r'\\d+') # 查找数字\n result3 = pattern.findall(str(result2))\n # print(result3)\n sum = 0\n oushu = 0\n jishu = 0\n for i in range(len(result3)):\n sum = sum + int(result3[i])\n if i % 2 == 0:\n oushu = oushu + int(result3[i])\n else:\n jishu = jishu + int(result3[i])\n maj_sup = oushu / float(sum)\n min_sup = jishu / float(sum)\n return maj_sup, min_sup\n\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"591801725","text":"# Copyright 2017 - Red Hat\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom glare.common import exception as exc\nfrom glare.tests.unit import base\n\n\nclass TestArtifactShow(base.BaseTestArtifactAPI):\n\n def test_show_basic(self):\n # Create an artifact and get its info back\n vals = {'name': 'art1', 'version': '0.0.1', 'string_required': 'str1',\n 'int1': 5, 'float1': 5.0, 'bool1': 'yes'}\n art = self.controller.create(self.req, 'sample_artifact', vals)\n\n # Read info about created artifact\n show_art = self.controller.show(self.req, 'sample_artifact', art['id'])\n\n self.assertEqual(art, show_art)\n\n # Test that the artifact is not accessible from other non-metatype type\n self.assertRaises(exc.ArtifactNotFound,\n self.controller.show, self.req, 'images', art['id'])\n\n # Test that the artifact is accessible from 'all' metatype\n show_art = self.controller.show(self.req, 'all', art['id'])\n\n self.assertEqual(art['id'], show_art['id'])\n\n def test_show_basic_negative(self):\n # If there is no artifact with given id glare raises ArtifactNotFound\n self.assertRaises(\n exc.ArtifactNotFound,\n self.controller.show, self.req, 'images', 'wrong_id')\n\n # If there is no artifact type glare raises TypeNotFound\n self.assertRaises(\n exc.TypeNotFound,\n self.controller.show, self.req, 'wrong_type', 'wrong_id')\n","sub_path":"glare/tests/unit/api/test_show.py","file_name":"test_show.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"444661270","text":"from selenium.webdriver.common.by import By\nfrom selenium import webdriver\n\nchrome = webdriver.Chrome()\n\nchrome.get(\"https://yandex.ru\")\n\n# search_input это объект типа WebElement\nsearch_input = chrome.find_element(By.CSS_SELECTOR, \"input#text\")\n\nprint(type(search_input))\n\nchrome.close()\n","sub_path":"1_webelement/1_webelement.py","file_name":"1_webelement.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"432357501","text":"import json\nimport logging\nimport os\nimport subprocess\nimport time\nfrom shutil import move\n\nfrom ModelAnalyzer.settings import (\n COMPILED_DUMP,\n PROFILING_DUMP,\n TIMES_EACH_PROGRAM_IS_RUN,\n SRC_FILES, ALWAYS_COMPILE,\n)\n\n\nclass ProgramCompilerAndRunner:\n def __init__(self, file_names):\n self._log = logging.getLogger(self.__class__.__name__)\n self._program_paths = self._find_programs_paths(file_names)\n\n @staticmethod\n def _find_programs_paths(file_names):\n found_paths = []\n for root, dirs, files in os.walk(SRC_FILES):\n for file in files:\n if file in file_names:\n found_paths.append((root, file))\n return found_paths\n\n def perform_test(self, test_spec):\n executables_data = self._find_executables(test_spec)\n return self._run_programs(test_spec, executables_data)\n\n def _find_executables(self, test_spec):\n executables_data = []\n for root, name in self._program_paths:\n new_file_name = f\"{name.split('.')[0]}_\" + \"_\".join(\n [str(value) for value in test_spec.values() if not isinstance(value, list)]\n )\n output_path = os.path.join(COMPILED_DUMP, new_file_name)\n exit_code = 0\n if os.path.isfile(output_path) and not ALWAYS_COMPILE:\n self._log.info(f\"Found '{new_file_name}'. No need to compile.\")\n else:\n exit_code = self._compile_file(root, name, output_path)\n executables_data.append(\n {\n \"src_name\": name,\n \"executable_name\": new_file_name,\n \"compiling_exit_code\": exit_code,\n }\n )\n return executables_data\n\n def _compile_file(self, root, name, output_path):\n if name.endswith(\".c\"):\n return self._compile_c_file(root, name, output_path)\n elif name.endswith(\".cu\"):\n return self._compile_cu_file(root, name, output_path)\n else:\n self._log.warning(f\"Could not compile. Unknown extension: {name}\")\n return -1\n\n def _compile_c_file(self, root, name, output_path):\n self._log.info(f\"Compiling using 'make': '{name}'.\")\n subprocess.run(\n [\n \"cmake\",\n f\"-B{root}\",\n f\"-H{root}\",\n \"-DCMAKE_BUILD_TYPE=Release\",\n \"-DCMAKE_MODULE_PATH=/nfshome/aderango/git/opencal/cmake\",\n \"-DOpenCL_LIBRARY=/opt/cuda/targets/x86_64-linux/lib/libOpenCL.so\",\n \"-DOpenCL_INCLUDE_DIR=/opt/cuda/targets/x86_64-linux/include\",\n ]\n )\n exit_code = subprocess.run([\"make\", \"-C\", root]).returncode\n if exit_code == 0:\n move(os.path.join(root, name.split(\".\")[0]), output_path)\n return exit_code\n\n def _compile_cu_file(self, root, name, output_path):\n self._log.info(f\"Compiling using 'nvcc': '{name}'.\")\n return subprocess.run(\n [\"nvcc\", os.path.join(root, name), \"-o\", output_path]\n ).returncode\n\n def _run_programs(self, test_spec, executables_data):\n results_paths = []\n for executable_data in executables_data:\n if executable_data[\"compiling_exit_code\"] == 0:\n result_path = self._run_program(\n {**executable_data, **test_spec}\n )\n results_paths.append(result_path)\n return results_paths\n\n def _run_program(self, executable_data):\n self._log.info(f\"Testing '{executable_data['executable_name']}'.\")\n runs_times = []\n exit_code = 0\n for i in range(TIMES_EACH_PROGRAM_IS_RUN):\n run_start_time = time.time()\n exit_code = subprocess.run(\n [f\"{COMPILED_DUMP}/{executable_data['executable_name']}\"]\n ).returncode\n run_elapsed_time = time.time() - run_start_time\n self._log.info(\n f\"Test {i + 1}/{TIMES_EACH_PROGRAM_IS_RUN} has \"\n f\"been run in {run_elapsed_time // 60:.0f}m\"\n f\"{run_elapsed_time % 60:.0f}s\"\n )\n runs_times.append(run_elapsed_time)\n return self._save_test_summary(\n executable_data, min(runs_times), exit_code\n )\n\n def _save_test_summary(self, executable_data, elapsed_time, exit_code):\n results_object = {\n **executable_data,\n \"datastamp\": round(time.time()),\n \"elapsed_time\": elapsed_time,\n \"run_exit_code\": exit_code,\n }\n result_file_path = os.path.join(\n PROFILING_DUMP, executable_data[\"executable_name\"]\n )\n self._log.debug(f\"Intermediate result save to '{result_file_path}'\")\n with open(result_file_path, \"w\") as result_file:\n json.dump(results_object, result_file, indent=4)\n return result_file_path\n","sub_path":"tests/ModelAnalyzer/test_steps/ProgramCompilerAndRunner.py","file_name":"ProgramCompilerAndRunner.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"301456518","text":"\nimport pytest\nimport gpmap\nfrom epistasis import models\n\nimport numpy as np\nimport pandas as pd\n\nimport os\n\ndef test__genotypes_to_X(test_data):\n\n # Make sure function catches bad genotype passes\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n # Duplicated\n g = list(gpm.genotype)\n g.extend(g)\n\n # not in gpmap\n b = list(gpm.genotype)\n b.append(\"stupid\")\n bad_genotypes = [g,b]\n for bad in bad_genotypes:\n with pytest.raises(ValueError):\n models.base._genotypes_to_X(bad,gpm,order=1,model_type=\"local\")\n\n # Sample through various model comobos\n allowed = {\"local\":set([0,1]),\n \"global\":set([-1,1])}\n\n for d in test_data:\n\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n for i in range(1,gpm.length+1,1):\n for model_type in [\"local\",\"global\"]:\n X = models.base._genotypes_to_X(gpm.genotype,\n gpm,\n order=i,\n model_type=model_type)\n assert X.shape[0] == len(gpm.genotype)\n assert set(np.unique(X)).issubset(allowed[model_type])\n\n\ndef test_arghandler_decorator():\n\n class Yo:\n\n def _a(self,data=5,method=None):\n return data\n\n def _b(self,data=None,method=None):\n return 6\n\n @models.base.arghandler\n def test_method(self,a=None,b=None,**kwargs):\n\n return a, b\n\n @models.base.arghandler\n def bad_method(self,c=None,d=None,**kwargs):\n\n return c, d\n\n yo = Yo()\n assert yo.test_method() == (None,6)\n assert yo.test_method(a=5) == (5,6)\n assert yo.test_method(a=10) == (10,6)\n assert yo.test_method(b=10) == (None,6)\n\n with pytest.raises(AttributeError):\n yo.bad_method()\n\n\n### Tests for AbstractModel:\n# AbstractModel cannot be instantiated on its own, as it is designed to be a\n# mixin with sklearn classes. Many methods have to be defined in subclass\n# (.fit, .predict, etc.) These will not be tested here, but instead in the\n# subclass tests. For methods defined here that are never redefined in subclass\n# (._X, .add_gpm, etc.) we test using the simplest mixed/subclass\n# (EpistasisLinearRegression).\n\ndef test_abstractmodel_predict_to_df(test_data):\n \"\"\"\n Test basic functionality. Real test of values will be done on .predict\n for subclasses.\n \"\"\"\n\n m = models.linear.EpistasisLinearRegression()\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n m.add_gpm(gpm)\n\n # This should fail -- no fit run\n with pytest.raises(Exception):\n df = m.predict_to_df()\n\n m.fit()\n\n # This should work\n df = m.predict_to_df()\n assert type(df) is type(pd.DataFrame())\n assert len(df) == len(d[\"genotype\"])\n\n # Create and fit a new model.\n m = models.linear.EpistasisLinearRegression()\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n # No gpm added -- should fail\n with pytest.raises(RuntimeError):\n m.predict_to_df()\n\n m.add_gpm(gpm)\n m.fit()\n\n df = m.predict_to_df(genotypes=d[\"genotype\"][0])\n assert len(df) == 1\n\n bad_stuff = [1,{},[1,2],\"STUPID\",[\"STUPID\",\"IS\",\"REAL\"]]\n for b in bad_stuff:\n with pytest.raises(ValueError):\n print(f\"Trying bad genotypes {b}\")\n m.predict_to_df(genotypes=b)\n\n df = m.predict_to_df(genotypes=d[\"genotype\"][:3])\n assert len(df) == 3\n\ndef test_abstractmodel_predict_to_csv(test_data,tmp_path):\n\n m = models.linear.EpistasisLinearRegression()\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n m.add_gpm(gpm)\n m.fit()\n\n csv_file = os.path.join(tmp_path,\"tmp.csv\")\n\n m.predict_to_csv(filename=csv_file)\n assert os.path.exists(csv_file)\n df = pd.read_csv(csv_file)\n assert len(df) == len(d[\"genotype\"])\n\n # Make sure genotypes pass works\n m.predict_to_csv(filename=csv_file,genotypes=d[\"genotype\"][0])\n assert os.path.exists(csv_file)\n df = pd.read_csv(csv_file)\n assert len(df) == 1\n\ndef test_abstractmodel_predict_to_excel(test_data,tmp_path):\n\n m = models.linear.EpistasisLinearRegression()\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n m.add_gpm(gpm)\n m.fit()\n\n excel_file = os.path.join(tmp_path,\"tmp.xlsx\")\n\n m.predict_to_excel(filename=excel_file)\n assert os.path.exists(excel_file)\n df = pd.read_excel(excel_file)\n assert len(df) == len(d[\"genotype\"])\n\n # Make sure genotypes pass works\n m.predict_to_excel(filename=excel_file,genotypes=d[\"genotype\"][0])\n assert os.path.exists(excel_file)\n df = pd.read_excel(excel_file)\n assert len(df) == 1\n\ndef test_abstractmodel_add_gpm(test_data):\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n m = models.linear.EpistasisLinearRegression()\n\n bad_gpm = [1,None,\"test\",[],{}]\n for b in bad_gpm:\n with pytest.raises(TypeError):\n m.add_gpm(b)\n m.add_gpm(gpm)\n\n # Test genotype_column arg\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n m = models.linear.EpistasisLinearRegression()\n bad_genotype_column = [1,None,[],{},(1,)]\n for b in bad_genotype_column:\n with pytest.raises(TypeError):\n print(f\"trying {b}\")\n m.add_gpm(gpm,genotype_column=b)\n\n with pytest.raises(KeyError):\n m.add_gpm(gpm,genotype_column=\"not_a_column\")\n\n m.add_gpm(gpm,genotype_column=\"genotype\")\n assert m.genotype_column == \"genotype\"\n\n # Test phenotype_column arg\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"])\n\n m = models.linear.EpistasisLinearRegression()\n\n # Shouldn't work b/c no float column\n with pytest.raises(ValueError):\n m.add_gpm(gpm)\n\n # Shouldn't work because there is no column with that name\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n with pytest.raises(KeyError):\n m.add_gpm(gpm,phenotype_column=\"not_real\")\n\n # Shouldn't work because column is not numeric\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"genotype\"])\n with pytest.raises(ValueError):\n m.add_gpm(gpm,phenotype_column=\"phenotype\")\n\n # Make sure it gets right column (first float that is not reserved)\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n coolness=d[\"phenotype\"],\n something_else=d[\"phenotype\"])\n m.add_gpm(gpm)\n assert m.phenotype_column == \"coolness\"\n\n # Test uncertainty_column arg.\n\n # Do default = None\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n m.add_gpm(gpm)\n assert m.uncertainty_column == \"epi_zero_uncertainty\"\n unc = np.array(m.gpm.data.loc[:,\"epi_zero_uncertainty\"])\n assert len(np.unique(unc)) == 1\n assert np.isclose(unc[0],np.min(gpm.data.loc[:,m.phenotype_column])*1e-6)\n\n # pass missing column\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"],\n coolness=d[\"phenotype\"],\n not_float=d[\"genotype\"])\n\n # Send in same as phenotype\n with pytest.raises(ValueError):\n m.add_gpm(gpm,uncertainty_column=\"phenotype\")\n\n # send in not there\n with pytest.raises(KeyError):\n m.add_gpm(gpm,uncertainty_column=\"not_there\")\n\n # send in not float\n with pytest.raises(ValueError):\n m.add_gpm(gpm,uncertainty_column=\"not_float\")\n\n # Shoud work\n m.add_gpm(gpm,uncertainty_column=\"coolness\")\n assert m.uncertainty_column == \"coolness\"\n\n # Check final output\n assert m.gpm is gpm\n assert m.Xcolumns is not None\n assert m.epistasis is not None\n assert m._previous_X is None\n\ndef test_gpm_getter(test_data):\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n m = models.linear.EpistasisLinearRegression()\n assert m.gpm is None\n m.add_gpm(gpm)\n assert m.gpm is gpm\n\ndef test_results_getter(test_data):\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"])\n\n m = models.linear.EpistasisLinearRegression()\n m.add_gpm(gpm)\n\n assert m.results is None\n m.fit()\n assert isinstance(m.results,pd.DataFrame)\n\ndef test_column_getters(test_data):\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"],\n uncertainty=d[\"phenotype\"])\n\n m = models.linear.EpistasisLinearRegression()\n\n assert m.genotype_column is None\n assert m.phenotype_column is None\n assert m.uncertainty_column is None\n\n m.add_gpm(gpm,uncertainty_column=\"uncertainty\")\n\n assert m.genotype_column == \"genotype\"\n assert m.phenotype_column == \"phenotype\"\n assert m.uncertainty_column == \"uncertainty\"\n\ndef test__X_arghandler(test_data):\n\n m = models.linear.EpistasisLinearRegression()\n with pytest.raises(ValueError):\n m._X()\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n phenotype=d[\"phenotype\"],\n uncertainty=d[\"phenotype\"])\n m.add_gpm(gpm)\n\n # Make sure calling _X() naked-ly populates previous_X\n assert m._previous_X is None\n X = m._X()\n assert m._previous_X is X\n\n # If we access after having run, make sure X is the same object\n assert X is m._X()\n\n # Should wipe out previous_X and force recalculation.\n m.add_gpm(gpm)\n assert X is not m._X()\n\n # Get x for single genotype. should work. should not update _previous_X\n X = m._X(d[\"genotype\"][0])\n assert len(X) == 1\n assert X is not m._previous_X\n\n # Get x for two genotypes. should work and not update _previous_X\n X = m._X(d[\"genotype\"][0:2])\n assert len(X) == 2\n assert X is not m._previous_X\n\n # Get x for two genotypes. should work and not update _previous_X\n X = m._X(np.array(d[\"genotype\"][0:2]))\n assert len(X) == 2\n assert X is not m._previous_X\n\n # Just keep the array, do not update previous_X\n hack = np.ones((1,1))\n X = m._X(data=hack)\n assert X is hack\n assert X is not m._previous_X\n\n # pass in bad genotypes\n with pytest.raises(ValueError):\n X = m._X(\"NOT_A_GENOTYPE\")\n with pytest.raises(ValueError):\n X = m._X([d[\"genotype\"][0],\"NOT_A_GENOTYPE\"])\n\n # pass in general badness\n bad_passes = [np.ones((1,1,1)),[],\"stupid\",1,1.1,()]\n for b in bad_passes:\n with pytest.raises(ValueError):\n m._X(b)\n\ndef test__y_arghandler(test_data):\n\n m = models.linear.EpistasisLinearRegression()\n with pytest.raises(ValueError):\n m._y()\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n coolness=d[\"phenotype\"],\n uncertainty=d[\"phenotype\"])\n m.add_gpm(gpm,phenotype_column=\"coolness\")\n assert np.array_equal(m._y(),d[\"phenotype\"])\n\n # pass in general badness\n bad_passes = [np.ones((1,1,1)),[],\"stupid\",1,1.1,()]\n for b in bad_passes:\n with pytest.raises(TypeError):\n print(f\"trying {b}\")\n m._y(b)\n\n y = m._y([1.0])\n assert np.array_equal(y,[1.0])\n\n\ndef test__yerr_arghandler(test_data):\n\n m = models.linear.EpistasisLinearRegression()\n with pytest.raises(ValueError):\n m._yerr()\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n coolness=d[\"phenotype\"],\n uncertainty=d[\"phenotype\"])\n m.add_gpm(gpm,phenotype_column=\"coolness\",uncertainty_column=\"uncertainty\")\n assert np.array_equal(m._yerr(),d[\"phenotype\"])\n\n # pass in general badness\n bad_passes = [np.ones((1,1,1)),[],\"stupid\",1,1.1,()]\n for b in bad_passes:\n with pytest.raises(TypeError):\n print(f\"trying {b}\")\n m._yerr(b)\n\n y = m._yerr([1.0])\n assert np.array_equal(y,[1.0])\n\ndef test__thetas_arghandler(test_data):\n\n m = models.linear.EpistasisLinearRegression()\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n coolness=d[\"phenotype\"],\n uncertainty=d[\"phenotype\"])\n m.add_gpm(gpm,phenotype_column=\"coolness\",uncertainty_column=\"uncertainty\")\n\n # No thetas calcualted yet\n with pytest.raises(RuntimeError):\n m._thetas()\n m.fit()\n\n # Get thetas, calcualted\n t = m._thetas()\n assert len(t) == 4\n\n # pass in general badness\n bad_passes = [np.ones((1,1,1)),[],\"stupid\",1,1.1,()]\n for b in bad_passes:\n with pytest.raises(TypeError):\n print(f\"trying {b}\")\n m._thetas(b)\n\n y = m._thetas([1.0])\n assert np.array_equal(y,[1.0])\n\ndef test__lnprior(test_data):\n\n m = models.linear.EpistasisLinearRegression()\n with pytest.raises(ValueError):\n m._lnprior()\n\n d = test_data[0]\n gpm = gpmap.GenotypePhenotypeMap(genotype=d[\"genotype\"],\n coolness=d[\"phenotype\"],\n uncertainty=d[\"phenotype\"])\n m.add_gpm(gpm,phenotype_column=\"coolness\",uncertainty_column=\"uncertainty\")\n\n x = m._lnprior()\n assert np.array_equal(x,np.zeros(len(d[\"genotype\"])))\n\n # pass in general badness\n bad_passes = [np.ones((1,1,1)),[],\"stupid\",1,1.1,()]\n for b in bad_passes:\n with pytest.raises(TypeError):\n print(f\"trying {b}\")\n m._lnprior(b)\n\n y = m._lnprior([1.0])\n assert np.array_equal(y,[1.0])\n","sub_path":"tests/models/test_models_base.py","file_name":"test_models_base.py","file_ext":"py","file_size_in_byte":14678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"116859984","text":"# noqa: D100\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.utils.validation import check_X_y, check_is_fitted\nfrom sklearn.utils.validation import check_array\nfrom sklearn.utils.multiclass import type_of_target\n\n\nclass OneNearestNeighbor(BaseEstimator, ClassifierMixin):\n \"\"\"Creates a One NearestNeightbor simulator.\"\"\"\n\n def __init__(self): # noqa: D107\n pass\n\n def fit(self, X, y):\n \"\"\"Fit the 1-NN i.e. memorizes the X.\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n The input array.\n\n Returns\n -------\n self : OneNearestNeighbor\n\n \"\"\"\n\n X, y = check_X_y(X, y)\n self.classes_ = np.unique(y)\n\n if type_of_target(y) not in ['binary', 'multiclass', 'unknown']:\n raise ValueError(f\"Unknown label type: {y}\")\n\n self.train_features_ = X\n self.respective_label_ = y\n return self\n\n def predict(self, X):\n \"\"\"Predict the class of X.\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n The input array.\n\n Returns\n -------\n y_pred : ndarray of shape (len(X))\n The output array with predicted classes.\n\n \"\"\"\n\n check_is_fitted(self)\n X = check_array(X)\n y_pred = np.full(shape=len(X), fill_value=self.classes_[0])\n var = np.zeros((len(X)))\n\n for i in range(len(X)):\n var[i] = np.argmin(np.linalg.norm(self.train_features_-X[i],\n axis=1))\n var = var.astype(int)\n\n y_pred = self.respective_label_[var]\n\n return y_pred\n\n def score(self, X, y):\n \"\"\"Calculate the error rate of our predictor.\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n The input array on which we will predict.\n y : ndarray of shape (n_samples)\n The input array with correct classes\n\n Returns\n -------\n score : float\n The predictor score.\n\n \"\"\"\n X, y = check_X_y(X, y)\n y_pred = self.predict(X)\n return np.mean(y_pred == y)\n","sub_path":"sklearn_questions.py","file_name":"sklearn_questions.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"620166811","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import models\r\n\r\nfrom django.utils.translation import gettext as _\r\n\r\nfrom catalogues.models import City, MyModel\r\n\r\nfrom users.models import Users\r\n\r\nfrom shops.models import Shops\r\n\r\nimport os\r\n\r\nclass Stores(MyModel):\r\n\tshop = models.ForeignKey(Shops, on_delete=models.PROTECT, default=None, blank=False, null=False, db_column='shop_id', verbose_name=_('Belongs to shop'))\r\n\tcity = models.ForeignKey(City, on_delete=models.PROTECT, default=None, blank=False, null=False, db_column='city_id', verbose_name=_('City'))\r\n\tadmin = models.ForeignKey(Users, on_delete=models.PROTECT, default=None, blank=False, null=False, db_column='admin_id', verbose_name=_('User admin'))\r\n\r\n\tname = models.CharField(max_length=255, default=None, blank=False, null=False, verbose_name=_('Store name'))\r\n\t\r\n\taddress_line1 = models.CharField(max_length=1024, default=None, blank=False, null=False, verbose_name=_('Address line 1'))\r\n\taddress_line2 = models.CharField(max_length=1024, default=None, blank=True, null=True, verbose_name=_('Address line 2'))\r\n\tcell_phone = models.CharField(max_length=10, default=None, blank=False, null=False, verbose_name=_('Cell phone'))\r\n\thome_phone = models.CharField(max_length=10, default=None, blank=True, null=True, verbose_name=_('Home phone'))\r\n\tother_phone = models.CharField(max_length=10, default=None, blank=True, null=True, verbose_name=_('Other phone'))\r\n\r\n\t@property\r\n\tdef store_with_shop_name(self):\r\n\t\tresult = self.name + ' [' + _('Belongs to shop')\r\n\t\tresult += '=' + self.shop.name \r\n\t\tresult += '; ' + _('User admin') + '='\r\n\t\tresult += self.admin.first_name + ' '\r\n\t\tresult += self.admin.last_name + ' ('\r\n\t\tresult += self.admin.email + ')]'\r\n\t\treturn result\r\n\t\r\n\tdef save(self):\r\n\t\tsuper(Stores, self).save()\r\n\t\t# We must to create its upload dir...\r\n\t\tpath = os.getcwd() + '/static/uploads/shops/shop-' + str(self.shop.id) + '/stores/store-' + str(self.id)\r\n\t\ttry:\r\n\t\t\tos.makedirs(path)\r\n\t\texcept OSError: \r\n\t\t\tprint(\"Creation of the directory %s failed\" % path)\r\n\t\telse: \r\n\t\t\tprint (\"Successfully created the directory %s \" % path)\r\n\r\n\tclass Meta:\r\n\t\t# In MySQL, with utf8 encoding for tables, the max key size for varchar is 255\r\n\t\t#unique_together = ('name', 'shop', 'city', 'address_line1')\r\n\t\tunique_together = ('created_by_user', 'shop', 'name', 'city')\r\n\t\tpermissions = (\r\n\t\t\t(_('Find') + ' [action=#/stores/find]', _('Find')),\r\n\t\t\t(_('Add') + ' [action=#/stores/add]', _('Add')),\r\n\t\t\t(_('Edit') + ' [action=#/stores/edit]', _('Edit')),\r\n\t\t\t(_('Delete') + ' [action=#/stores/delete]', _('Delete')),\r\n\t\t)","sub_path":"stores/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"634819959","text":"\"\"\"Provides a basic example of destroying a friendship on StockTwits.\"\"\"\n\nimport pytwits\n\n\ndef main():\n\n access_token = 'TOKEN'\n stocktwits = pytwits.StockTwits(access_token=access_token)\n\n user = stocktwits.friendships(path='destroy', id='1511554')\n print(user.name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"docs/examples/destroy_friendship.py","file_name":"destroy_friendship.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"139669657","text":"from selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nimport os.path\nimport sys\nfrom selenium.webdriver import FirefoxProfile\nfrom browsermobproxy import Client\nfrom framework.framedriver import FrameWebdriver\nfrom framework.exceptions import ProfileNotFound\nfrom selenium.webdriver.chrome.options import Options\n\n\ncap_map = {\n \"firefox\": DesiredCapabilities.FIREFOX.copy(),\n \"internet explorer\": DesiredCapabilities.INTERNETEXPLORER.copy(),\n \"internetexplorer\": DesiredCapabilities.INTERNETEXPLORER.copy(),\n \"iexplorer\": DesiredCapabilities.INTERNETEXPLORER.copy(),\n \"ie\": DesiredCapabilities.INTERNETEXPLORER.copy(),\n \"chrome\": DesiredCapabilities.CHROME.copy(),\n \"opera\": DesiredCapabilities.OPERA.copy(),\n \"phantomjs\": DesiredCapabilities.PHANTOMJS.copy(),\n \"htmlunitjs\": DesiredCapabilities.HTMLUNITWITHJS.copy(),\n \"htmlunit\": DesiredCapabilities.HTMLUNIT.copy(),\n \"iphone\": DesiredCapabilities.IPHONE.copy(),\n \"ipad\": DesiredCapabilities.IPAD.copy(),\n \"android\": DesiredCapabilities.ANDROID.copy(),\n \"edge\": DesiredCapabilities.EDGE.copy(),\n \"safari\": DesiredCapabilities.SAFARI.copy()\n}\n\nos_map = {\n \"Windows\": \"WINDOWS\",\n \"Windows 2000\": \"XP\",\n \"Windows 2003\": \"XP\",\n \"Windows XP\": \"XP\",\n \"Windows Vista\": \"VISTA\",\n \"Windows 2008\": \"VISTA\",\n \"Windows 7\": \"VISTA\",\n \"Windows 8\": \" WIN8\",\n \"Windows 8.1\": \"WIN8_1\",\n \"Windows 10\": \"WIN10\",\n \"Mac\": \"MAC\",\n \"Android\": \"ANDROID\",\n}\n\nclass Browser(object):\n\n def __init__(self, br_conf, all_conf):\n self.browser_config = br_conf\n self.c = all_conf\n profile = None\n caps = cap_map[br_conf[\"type\"]]\n\n if br_conf[\"type\"] == \"firefox\":\n s = sys.platform\n if s in br_conf[\"profiles\"].keys() and br_conf[\"profiles\"][s]:\n profile_path=os.path.join(self.c[\"sframe\"][\"base\"],\"support\",\"profiles\",br_conf[\"profiles\"][s])\n elif br_conf[\"profiles\"][\"profile\"]:\n profile_path=os.path.join(self.c[\"sframe\"][\"base\"],\"support\",\"profiles\",br_conf[\"profiles\"][\"profile\"])\n else:\n profile_path = None\n\n if profile_path:\n if os.path.isdir(profile_path):\n profile = FirefoxProfile(profile_path)\n else:\n raise ProfileNotFound(\"Profile not found at %s\" % profile_path)\n\n if \"on_error\" in all_conf[\"sframe\"][\"screenshots\"]:\n if not all_conf[\"sframe\"][\"screenshots\"][\"on_error\"]:\n caps[\"webdriver.remote.quietExceptions\"] = True\n\n if \"headless\" in br_conf[\"profiles\"].keys() and br_conf[\"profiles\"][\"headless\"]:\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n caps = chrome_options.to_capabilities()\n print(\"added headless to chrome\")\n\n if \"type\" in all_conf[\"selenium\"][\"proxy\"]\\\n and all_conf[\"selenium\"][\"proxy\"][\"type\"] == \"browsermob\":\n self.proxy = Client(all_conf[\"selenium\"][\"proxy\"][\"url\"])\n self.proxy.add_to_capabilities(caps)\n\n if \"grid\" in all_conf[\"selenium\"][\"executor\"]\\\n and all_conf[\"selenium\"][\"executor\"][\"is grid\"]:\n if br_conf[\"grid filters\"][\"platform\"]:\n caps[\"platform\"] = br_conf[\"grid filters\"][\"platform\"].upper()\n if br_conf[\"grid filters\"][\"version\"]:\n caps[\"version\"] = str(br_conf[\"grid filters\"][\"version\"])\n\n com_exe = \"http://%s:%s/wd/hub\" % (self.c[\"selenium\"][\"executor\"][\"host\"], self.c[\"selenium\"][\"executor\"][\"port\"])\n\n self.driver = FrameWebdriver(desired_capabilities=caps,command_executor=com_exe,browser_profile=profile)\n","sub_path":"framework/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"391040942","text":"from sys import argv as args\r\n\r\ninput = \"110201\"\r\nrecipes = [3,7]\r\n\r\n\r\ndef solve1():\r\n\tglobal recipes, input\r\n\t\r\n\tend = int(input)\r\n\tworkers = [i for i in range(2)]\r\n\twhile len(recipes) < end + 10:\r\n\t\trecipes += [int(c) for c in str(sum(recipes[workers[i]] for i in range(len(workers))))]\r\n\t\tfor i in range(len(workers)):\r\n\t\t\tworkers[i] = (workers[i] + recipes[workers[i]]+1) % len(recipes)\r\n\tprint(\"\".join([str(x) for x in recipes[end:]]))\r\n\treturn\r\n\r\n\r\ndef solve2():\r\n\tglobal recipes, input\r\n\t\r\n\tilen = len(input)\r\n\tinput = [int(c) for c in input]\r\n\tworkers = [i for i in range(2)]\r\n\tstop = False\r\n\tcounter = 0\r\n\twhile not stop:\r\n\t\tfor v in [int(c) for c in str(sum(recipes[workers[i]] for i in range(len(workers))))]:\r\n\t\t\tif recipes[-ilen:] == input:\r\n\t\t\t\tstop = True\r\n\t\t\t\tbreak\r\n\t\t\trecipes.append(v)\r\n\t\tfor i in range(len(workers)):\r\n\t\t\tworkers[i] = (workers[i] + recipes[workers[i]]+1) % len(recipes)\r\n\tprint(len(recipes)-ilen)\r\n\treturn\r\n\r\n\r\ndef main():\r\n\tif len(args) > 1:\r\n\t\tif args[1] == \"1\":\r\n\t\t\tsolve1()\r\n\t\telif args[1] == \"2\":\r\n\t\t\tsolve2()\r\n\r\nmain()\r\n","sub_path":"14/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"13627193","text":"import logging\nimport aerospike\nfrom config_reader_production import ConfigurationReader\nimport ipaddress\n\n\nclass AerospikeClient:\n\n # Configure the client\n def __init__(self):\n ip_address, port, namespace, db_set = ConfigurationReader.databaseConfiguration()\n self.config = {'hosts': [(ip_address, port)]}\n self.ip_address = ip_address\n self.port = port\n self.namespace = namespace\n self.db_set = db_set\n self.logger = logging.getLogger(__name__)\n\n # Create a client and connect it to the cluster\n def connect(self):\n try:\n self.client = aerospike.client(self.config).connect()\n except Exception as e:\n import sys\n self.logger.error(\n 'Failed to connect to the cluster with ' + str(self.config['hosts']) + 'Exception message: ' + str(e))\n\n def put_ip_table(self, dictionary):\n for keyDict, value in dictionary.items():\n bins = {\n 'IP': keyDict,\n 'Count': value\n }\n key = (self.namespace, self.db_set, keyDict)\n try:\n self.client.put(key, bins)\n except Exception as e:\n self.logger.error('Inserting value failed with host: ' + str(self.config['hosts']) + ', KEY=' + str(\n key) + 'Exception message: ' + str(e))\n\n def put_data(self, hrpi_time, prediction, hrpi, counter):\n bins = {\n 'HRPI': hrpi,\n 'Prediction': prediction,\n 'Counter': counter\n }\n key = (self.namespace, self.db_set, hrpi_time)\n try:\n self.client.put(key, bins)\n except Exception as e:\n self.logger.error('Inserting value failed with host: ' + str(self.config['hosts']) + ', KEY=' + str(\n key) + 'Exception message: ' + str(e))\n\n def loadData(self, timeStamp, hrpi, eval, attack):\n namespace = \"firewall\"\n set = \"graph\"\n hrpiDict = \"data\"\n evalDict = \"eval\"\n print(\"timeStamp=\", timeStamp, \"hrpi=\", hrpi)\n if eval == 1:\n eval += attack\n try:\n self.client.put((namespace, set, timeStamp), {\n hrpiDict: hrpi, evalDict: eval\n },\n policy={'key': aerospike.POLICY_KEY_SEND})\n except Exception as e:\n import sys\n # print(\"error: {0}\".format(e), file=sys.stderr)\n\n def incrementData(self, set, key, dict):\n namespace = \"firewall\"\n set = \"ip_table\"\n # print(\"Incrementing: \", key, \" : \", dict)\n try:\n # print(\"Set=\",set,\"Key=\",key,\"Dict=\",dict)\n self.client.increment((namespace, set, key), dict, 1,\n policy={'key': aerospike.POLICY_KEY_SEND})\n # test = self.client.get((namespace, set, key))\n # print(test)\n except Exception as e:\n import sys\n # print(\"error: {0}\".format(e), file=sys.stderr)\n\n def getData(self, timeFrom, timeTo):\n try:\n keys = []\n for time in range(timeFrom, timeTo):\n keys.append(('firewall', 'graph', time))\n records = self.client.get_many(keys)\n\n return records\n except Exception as e:\n import sys\n self.logger.error(\n 'Error loading batch HRPI data from host: ' + str(self.config['hosts'])\n + '. Exception message: ' + str(e))\n\n def getDataIP(self, timeFrom, timeTo):\n try:\n keys = []\n for time in range(timeFrom, timeTo + 1):\n key = ('firewall', 'ip_table', time)\n keys.append(key)\n records = self.client.get_many(keys)\n return records\n except Exception as e:\n import sys\n self.logger.error(\n 'Error loading batch HRPI data from host: ' + str(self.config['hosts'])\n + '. Exception message: ' + str(e))\n\n def getHistoryData(self, timeFrom, timeTo):\n try:\n keys = []\n for time in range(timeFrom, timeTo):\n # print(time)\n key = ('firewall', 'graph', time)\n # print(key)\n keys.append(key)\n # print(key)\n records = self.client.get_many(keys)\n return records\n except Exception as e:\n import sys\n self.logger.error(\n 'Error loading batch HRPI data from host: ' + str(self.config['hosts']) + '. Exception message: ' + str(\n e))\n","sub_path":"AeroSpike_production.py","file_name":"AeroSpike_production.py","file_ext":"py","file_size_in_byte":4634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"534351312","text":"##\n# COS 429 Final Project\n# Sharon Zhang\n#\n# This module estimates the actual camera path.\n#\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport sys\n\nclass Window():\n \"\"\"\n A pop-up window with the video frame for user to select crop window\n \"\"\"\n \n def __init__(self, img):\n self.count = 0\n self.img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n self.points = []\n\n def getCoords(self):\n if self.count >= 2:\n plt.close()\n return\n fig = plt.figure()\n plt.title('Select crop box')\n plt.imshow(self.img)\n cid = fig.canvas.mpl_connect('button_press_event', self.__onclick__)\n plt.show()\n return self.points\n\n def __onclick__(self,click):\n self.points.append((click.xdata, click.ydata))\n self.count += 1\n\ndef estimateTransforms(orig_frames):\n \"\"\"\n Given a sequence of video frames, estimate the camera path transforms between\n each consecutive pair of frames\n\n orig_frames: an array of images\n \"\"\"\n\n # extract SIFT features and compute optical flow\n sift_fg = cv2.xfeatures2d.SIFT_create(50)\n sift_bg = cv2.xfeatures2d.SIFT_create(150)\n bf = cv2.BFMatcher()\n transforms = []\n\n for num in range(1, len(orig_frames)):\n if (num % 10 is 1):\n print(\"frame\", num-1, \"-> frame\", num, \"(of {})\".format(count-1))\n\n # get current and previous frame\n f_curr = cv2.cvtColor(orig_frames[num], cv2.COLOR_BGR2GRAY)\n f_prev = cv2.cvtColor(orig_frames[num-1], cv2.COLOR_BGR2GRAY)\n\n # get foreground/background masks\n _, fg_mask1 = cv2.threshold(f_prev, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n _, bg_mask1 = cv2.threshold(f_prev, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n\n _, fg_mask2 = cv2.threshold(f_curr, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n _, bg_mask2 = cv2.threshold(f_curr, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n\n # compute SIFT features in foreground and background\n kp2, des2 = sift_fg.detectAndCompute(f_curr, fg_mask2)\n kp1, des1 = sift_fg.detectAndCompute(f_prev, fg_mask1)\n\n kp2_bg, des2_bg = sift_bg.detectAndCompute(f_curr, bg_mask2)\n kp1_bg, des1_bg = sift_bg.detectAndCompute(f_prev, bg_mask1)\n\n if len(kp2) > 0 and len(kp2_bg) > 0:\n kp2 = np.concatenate((kp2,kp2_bg), axis=0)\n elif not kp2:\n kp2 = kp2_bg\n\n if len(kp1) > 0 and len(kp1_bg) > 0:\n kp1 = np.concatenate((kp1,kp1_bg), axis=0)\n elif not kp1:\n kp1 = kp1_bg\n\n if des2 is not None and des2_bg is not None:\n des2 = np.concatenate((des2,des2_bg), axis=0)\n elif not des2:\n des2 = des2_bg\n\n if des1 is not None and des1_bg is not None:\n des1 = np.concatenate((des1,des1_bg), axis=0)\n elif not des1:\n des1 = des1_bg\n\n # extract good feature matches\n matches = bf.knnMatch(des1, des2, k=2)\n\n # print('Before filtering:', len(matches))\n good = []\n for m,n in matches:\n if m.distance < 0.25*n.distance:\n good.append(m)\n # print('After filtering:', len(good))\n\n pts_dst = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)\n pts_src = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)\n\n # calculate optical flow\n if len(pts_dst) > 0 and len(pts_src) > 0:\n M = cv2.estimateRigidTransform(pts_src, pts_dst, fullAffine=False)\n\n if M is not None:\n transforms.append(M)\n else:\n if num > 1:\n transforms.append(transforms[-1])\n else:\n CONST_TRANSFORM = np.zeros((2,3))\n CONST_TRANSFORM[0,0] = 1\n CONST_TRANSFORM[1,1] = 1\n transforms.append(CONST_TRANSFORM)\n\n print(\"Finished analyzing {} frames\".format(num))\n return transforms\n\n# store original frames\nvideoname = sys.argv[1]\n\nvidcap = cv2.VideoCapture(videoname)\nsuccess, img = vidcap.read()\nheight, width, ch = img.shape\n\n# input bounding box\nwin = Window(img)\nul, lr = win.getCoords()\n\ncount = 0\nsuccess = True\norig_frames = []\nwhile success:\n orig_frames.append(img)\n count += 1\n success, img = vidcap.read()\n if not success:\n print ('Failed on frame', count)\n\nprint('Finished reading {} frames'.format(count-1))\n\n# estimate camera path transforms\ntransforms = estimateTransforms(orig_frames)\n\n# record video information\nf = open('{}_info.txt'.format(videoname.split('.')[0]), 'w')\nf.write('{}\\n'.format(count-1)) # total frames\nf.write('{} {}\\n'.format(width, height)) # video dimensions\nf.write('{} {}\\n'.format( int(ul[0]), int(ul[1]) )) # ul\nf.write('{} {}\\n'.format( int(lr[0]), int(lr[1]) )) # lr\n\n# write estimated transforms to file\nf = open('{}_estTransforms.txt'.format(videoname.split('.')[0]), 'w')\nfor i in range(len(transforms)):\n cp = transforms[i]\n f.write('{} {} {} {} {} {}\\n'.format(cp[0,2], cp[1,2], cp[0,0], cp[0,1], cp[1,0], cp[1,1]))\n\n# plot estimated camera path\nCt = np.identity(3)\nmotion = np.zeros((len(transforms),2))\nfor i in range(len(transforms)):\n Ct = Ct @ np.concatenate((transforms[i], [[0,0,1]]), axis=0)\n motion[i,:] = Ct[:2,2]\n\nplt.figure()\nplt.plot([i for i in range(len(transforms))], motion[:,0])\nplt.title(\"x motion\")\nplt.show()\n\nplt.figure()\nplt.plot([i for i in range(len(transforms))], motion[:,1])\nplt.title(\"y motion\")\nplt.show()\n","sub_path":"estimateCameraPath.py","file_name":"estimateCameraPath.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"680567","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport argparse\nimport ipaddress\nimport os\nimport re\n\nfrom lib.core.Config import *\nfrom lib.utils.ArgParseUtils import LineWrapRawTextHelpFormatter\nfrom lib.utils.NetUtils import NetUtils\n\n\nclass ArgumentsParser:\n\n formatter_class = lambda prog: LineWrapRawTextHelpFormatter(\n prog, max_help_position=100)\n\n def __init__(self, settings):\n self.settings = settings\n\n self.parser = argparse.ArgumentParser(\n formatter_class=ArgumentsParser.formatter_class)\n self.parser.add_argument('-t', '--target', type=self.check_arg_target, \n dest='target', help='Target IP:PORT or URL')\n self.parser.add_argument('-s', '--ssl', dest='ssl', default=False,\n help='Enable SSL/TLS')\n self.parser.add_argument('-e', '--exploit', type=self.check_arg_exploit,\n dest='exploit', help='Exploit to use')\n self.parser.add_argument('-l', '--list', dest='list', action='store_true', default=False,\n help='Display list of exploits')\n\n self.args = self.parser.parse_args()\n self.check_args()\n\n\n def check_arg_target(self, target):\n # Case where URL is provided\n if target.lower().startswith('http'):\n self.check_arg_url(target)\n\n # Otherwise consider format is IP:PORT\n else:\n if ':' in target:\n self.check_arg_ip_port(target)\n else:\n raise argparse.ArgumentTypeError('Invalid format. Must be either URL or IP:PORT')\n\n return target\n\n\n def check_arg_url(self, url):\n url = str(url)\n regex = re.compile(\n r'^https?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+'\n r'(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|' # ...or ipv4\n r'\\[?[A-F0-9]*:[A-F0-9:]+\\]?)' # ...or ipv6\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n if not regex.match(url):\n raise argparse.ArgumentTypeError('Invalid URL submitted')\n # Add http:// prefix if necessary\n if not url.startswith('http://') and not url.startswith('https://'):\n url = 'http://{0}'.format(url)\n # Remove potential ending slash at end of URL\n while url.endswith('/'):\n url = url[:-1]\n return url\n\n\n def check_arg_ip_port(self, ip_port):\n ip, port = ip_port.split(':', maxsplit=1)\n if not NetUtils.is_valid_port(port):\n raise argparse.ArgumentTypeError('Invalid port number')\n if not NetUtils.is_valid_ip(ip):\n raise argparse.ArgumentTypeError('Invalid IP address')\n\n return ip, port\n\n\n def check_arg_exploit(self, exploit):\n if self.settings.get_exploit(exploit) is None:\n raise argparse.ArgumentTypeError('Unsupported exploit. Check --list')\n return exploit\n\n def check_args(self):\n if self.args.list is False:\n if self.args.target is None:\n self.parser.error('Target is required (--target)')\n elif self.args.exploit is None:\n self.parser.error('Exploit name is required (--exploit)')\n return","sub_path":"lib/core/ArgumentsParser.py","file_name":"ArgumentsParser.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"534141408","text":"\"\"\"\nhttps://leetcode.com/problems/wiggle-subsequence/\n\n1). Two dp array.\nup[i] -> max length ending with nums[i] and wiggle up.\ndown[i] -> max length ending with nums[i] and wiggle down.\n\nFor a nums[i], to get up[i] and down[i] we need to check all 0 <= j < i.\n\nTime complexity: O(n^2), n = len(nums)\n\n2). We don't need to check every j < i.\nup[i] -> max length for nums[:i+1], ending with nums[i], last one wiggle up.\ndown[i] -> max length for nums[:i+1], ending with nums[i], last one wiggle down.\n\nIf nums[i] > nums[i-1]\na. nums[i-1] is the last element of down[i-1] sub sequence, then up[i] = down[i-1] + 1\nb. nums[i-1] is not the last element of down[i-1] sub sequence. That means nums[i] > k, where k is the last element of the down[i-1] sub sequence. Hence, we can still add nums[i] to the subsequence to build a longer wiggle up sequence. up[i] = down[i-1] + 1\n\nNo matter what, down[i] = down[i-1]\n\nFor nums[i] < nums[i-1], just flip up/down dp array around.\nFor nums[i] == nums[i-1], up[i] = up[i-1], down[i] = down[i-1].\n\nTime complexity: O(n), n = len(nums)\n\"\"\"\nclass Solution:\n def wiggleMaxLength(self, nums) -> int:\n n = len(nums)\n if n == 0:\n return 0\n up, down = [1] * n, [1] * n\n for i in range(1, n):\n if nums[i-1] < nums[i]:\n up[i] = down[i-1] + 1\n down[i] = down[i-1]\n elif nums[i-1] < nums[i]:\n down[i] = up[i-1] + 1\n up[i] = up[i-1]\n else:\n up[i] = up[i-1]\n down[i] = down[i-1]\n return max(up[-1], down[-1])\n\n def wiggleMaxLength_n2(self, nums) -> int:\n n = len(nums)\n if n == 0:\n return 0\n up, down = [1] * n, [1] * n\n ans = 1\n for i in range(1, n):\n j = i - 1\n while j >= 0:\n if nums[j] > nums[i]:\n up[i] = max(up[i], down[j] + 1)\n elif nums[j] < nums[i]:\n down[i] = max(down[i], up[j] + 1)\n j -= 1\n ans = max(up[i], down[i])\n return ans\n\nsol = Solution()\nassert sol.wiggleMaxLength([1,7,4,9,2,5]) == 6\nassert sol.wiggleMaxLength([1,17,5,10,13,15,10,5,16,8]) == 7\nassert sol.wiggleMaxLength([1,2,3,4,5,6,7,8,9]) == 2\n","sub_path":"0376_WiggleSubsequence.py","file_name":"0376_WiggleSubsequence.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"181528376","text":"'''\r\n超参数调优\r\n参考网址“https://blog.csdn.net/Amy_mm/article/details/79902477”\r\n网格搜索\r\n主要思想:\r\n暴风搜索法,首先为不同的超参数设定一个值列表,然后计算机会遍历每个超参数的组合进行性能评估,选出性能最佳的参数组合。\r\n'''\r\nfrom sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.pipeline import make_pipeline\r\nimport numpy as np\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\n#引入鸢尾花数据\r\niris = datasets.load_iris()\r\nX = iris.data#特征数据\r\ny = iris.target#分类结果\r\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,stratify=y,random_state=1)\r\n\r\n\r\npipe_svc = make_pipeline(StandardScaler(),\r\n SVC(random_state = 1))\r\n\r\nparam_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0]\r\n \r\nparam_grid = [{'svc__C' : param_range,\r\n 'svc__kernel' : ['linear']},\r\n {'svc__C' : param_range,\r\n 'svc__kernel': ['rbf'],\r\n 'svc__gamma' : param_range}]\r\n\r\n\r\ngs=GridSearchCV(estimator=pipe_svc,\r\n param_grid=param_grid,\r\n scoring='accuracy',\r\n cv=2)\r\n\r\nscores=cross_val_score(gs,X_train,y_train,scoring='accuracy',cv=5)\r\nprint(\"CV Accuracy in Train Phase: %.3f +/- %.3f\" % (np.mean(scores),np.std(scores)))\r\n\r\ngs.fit(X_train,y_train)\r\n#输出最优超参数及其分数\r\nprint(gs.best_score_)\r\nprint(gs.best_params_)\r\n","sub_path":"320180941370-liujunjiao/超参数调优.py","file_name":"超参数调优.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"27214882","text":"import random\r\nfrom NeuralNetwork.utils import defaults\r\nfrom NeuralNetwork.NEAT.Node import node\r\n\r\n\r\nclass connectionGene:\r\n def __init__(self, frm: node, to: node, w, in_no, settings=defaults.NEAT_default):\r\n self.fromNode = frm\r\n self.toNode = to\r\n self.w = w\r\n self.innovationNo = in_no\r\n self.enabled = True\r\n self.settings = settings\r\n self.weight_mutation_ratio = self.settings[\"weight_mutation_ratio\"]\r\n\r\n def mutateWeight(self):\r\n r = random.random()\r\n if self.weight_mutation_ratio < r:\r\n self.w = random.uniform(-1, 1)\r\n else:\r\n self.w += random.uniform(-1, 1)/50\r\n if self.w > 1:\r\n self.w = 1\r\n elif self.w < -1:\r\n self.w = -1\r\n\r\n def clone(self, frm: node, to: node):\r\n cln = connectionGene(frm, to, self.w, self.innovationNo, self.settings)\r\n cln.enabled = self.enabled\r\n return cln\r\n\r\n def __repr__(self):\r\n if self.enabled:\r\n s = \"enabled\"\r\n else:\r\n s = \"disabled\"\r\n ino = self.innovationNo\r\n return f\"\"\r\n","sub_path":"NeuralNetworks/NeuralNetwork/NEAT/ConnectionGene.py","file_name":"ConnectionGene.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"348420953","text":"import pygame\n\npygame.init()\n\n# 创建游戏的窗口 480*700\nscree = pygame.display.set_mode((480, 700))\n\n# 绘制背景图像\nbg = pygame.image.load(\"./images/background.png\")\nscree.blit(bg, (0, 0))\npygame.display.update()\n\n# 绘制英雄飞机\nhero = pygame.image.load(\"./images/me1.png\")\nscree.blit(hero, (200, 500))\npygame.display.update()\n\n# 游戏循环\nwhile True:\n event = pygame.event.poll()\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n\n# 游戏结束\npygame.quit()\n\n\n","sub_path":"飞机大战/text_05_绘制英雄图像.py","file_name":"text_05_绘制英雄图像.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"1350120","text":"from flask import render_template, redirect, request, url_for, abort, jsonify\nfrom app import app, post_store, models, member_store\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef home():\n return render_template(\"index.html\", posts=post_store.get_all())\n\n\n@app.route(\"/topic/add\", methods=[\"GET\", \"POST\"])\ndef topic_add():\n if request.method == \"POST\":\n new_post = models.Post(title = request.form[\"title\"], content = request.form[\"content\"], member_id = request.form[\"member_id\"])\n post_store.add(new_post)\n return redirect(url_for(\"home\"))\n\n else:\n return render_template(\"topic_add.html\")\n\n\n@app.route(\"/topic/delete/\")\ndef topic_delete(id):\n try:\n post_store.delete(id)\n except ValueError:\n abort(404)\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/topic/show/\")\ndef topic_show(id):\n showpost = post_store.get_by_id(id)\n if showpost is None:\n abort(404)\n return render_template(\"topic_show.html\", post=showpost)\n\n\n@app.route(\"/topic/edit/\", methods=[\"GET\", \"POST\"])\ndef topic_edit(id):\n updated_post = post_store.get_by_id(id)\n if updated_post is None:\n abort(404)\n if request.method == \"POST\":\n updated_post.title = request.form[\"title\"]\n updated_post.body = request.form[\"body\"]\n post_store.update(updated_post)\n return redirect(url_for(\"home\"))\n\n else:\n updated_post = post_store.get_by_id(id)\n return render_template(\"topic_edit.html\", post=updated_post)\n\n\n@app.route(\"/members\")\ndef members():\n return render_template(\"members.html\", members=member_store.get_all())\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"188423569","text":"\nimport activityio as aio\nimport math\n\nclass AIOWrapper:\n def __init__(self, name, df, idx, last=None):\n self.name = name\n self._df = df\n self._t = df.ix[idx]\n self._last = last\n print(\"AIOWR %r, %r, %r, %r\" % (idx, df.start + df.ix[idx].name, df.start, df.ix[idx].name))\n def hasattr(self, key):\n try:\n v = self.__getattr__(key)\n return True\n except AttributeError:\n return False\n\n def __getattr__(self, key):\n if key in self.__dict__:\n return self.__dict__[key]\n elif key in type(self).__dict__:\n if isinstance(type(self).__dict__[key], property):\n p = type(self).__dict__[key]\n return p.__get__(self, None)\n return type(self).__dict__[key]\n elif key in self._df.columns:\n return getattr(self._t, key)\n else:\n raise AttributeError(key)\n @property\n def hr(self):\n if 'hr' in self._df.columns:\n return self._t.hr\n elif 'value' in self._df.columns:\n # \n # 99\n # \n return self._t.value\n @property\n def time(self):\n return self._df.start + self._t.name\n @property\n def distance(self):\n if 'dist' in self._df.columns:\n if math.isnan(self._t.dist):\n return None\n else:\n return self._t.dist\n else:\n return 0\n @property\n def temperature(self):\n try:\n return self.temp\n except AttributeError:\n return None\n\n @property\n def cadence(self):\n if 'cad' in self._df.columns:\n return self._t.cad\n else:\n return None\n\n @property\n def speed(self):\n if 'speed' in self._df.columns:\n return self._t.speed\n else:\n return None\n # \"\"\" returns km/h \"\"\"\n # if self._last:\n # dist = self.distance - self._last.distance\n # tdelta = self.time - self._last.time\n # elif self._df.start:\n # dist = self.distance\n # tdelta = self.time - self._df.start\n # print(\"Nyerga\", self._df.start, tdelta, dist)\n # return -99.9\n # else:\n # return 0.0\n # if tdelta.seconds == 0:\n # return 0\n # else:\n # return dist * 3600 / tdelta.seconds / 1000\n\n\nclass AIO:\n def __init__(self, name, df):\n self.name = name\n self._df = df\n\n def all(self):\n last = None\n for idx in range(1, self._df.shape[0]):\n v = AIOWrapper(self.name, self._df, idx, last)\n if last and v.time < last.time:\n continue\n last = v\n yield v\n\n def __iter__(self):\n self._g = self.all()\n return self\n\n def __next__(self):\n return next(self._g)\n","sub_path":"trkm/sequencer/activityio.py","file_name":"activityio.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"649741906","text":"import persistent\nfrom . import model\n\nclass Site(persistent.Persistent):\n\n def __init__(self, initial_email):\n from BTrees.OOBTree import BTree\n self.boards = BTree()\n self.users = self.admins = [initial_email] # Future: persistent\n\n def update_users(self, users, admins):\n self.users = list(users)\n self.admins = list(admins)\n for board in self.boards.values():\n board.update_users(self.users, self.admins)\n\n def add_board(self, name, title, description):\n self.boards[name] = model.Kanban(name, title, description)\n self.boards[name].update_users(self.user, self.admins)\n","sub_path":"server/zc/twotieredkanban/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"603787623","text":"from mrjob.job import MRJob\nimport re\n\n\nclass Counter(MRJob):\n def mapper(self, _, line):\n count = int(line.replace(\" \", \"\").split('\"').pop())\n yield ('total', count)\n\n def reducer(self, word, counts):\n yield (word, sum(counts))\n\n\nif __name__ == '__main__':\n Counter.run()\n","sub_path":"lab-1/total_words.py","file_name":"total_words.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"459729116","text":"class Config(object):\n def __init__(self):\n # model params\n self.model = \"MANN\"\n self.nsteps = 10\n self.msteps = self.nsteps * 3 # multiplication of nsteps\n self.attention_size = 128\n self.num_filters = 128\n self.kernel_sizes = [3, 4, 5]\n self.l2_lambda = 1e-3\n self.ar_lambda = 1e-1\n self.ar_g = 1\n\n # data params\n self.data_path = '../data/28339_11_2mins.csv'\n self.nfeatures = 8\n self.x_len = self.nsteps + self.msteps\n self.y_len = 1\n self.foresight = 0\n self.dev_ratio = 0.1\n self.test_ratio = 0.1\n self.seed = None\n\n # train params\n self.lr = 1e-3\n self.num_epochs = 50\n self.batch_size = 256\n self.dropout = 0.5\n self.nepoch_no_improv = 5\n self.clip = 5\n self.desc = self._desc()\n\n def _desc(self):\n desc = \"\"\n for mem, val in self.__dict__.items():\n desc += mem + \":\" + str(val) + \", \"\n return desc\n\n\nif __name__ == \"__main__\":\n config = Config()\n print(config.desc)\n","sub_path":"MANN/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"76201550","text":"\"\"\" workshop 10 \"\"\"\nfrom pyplasm import *\nimport numpy as np\nimport sys, os\n\nsys.setrecursionlimit(1500)\n\npavTexture = \"texture/pav4.jpg\"\nwallTexture = \"texture/wall1.jpg\"\nwallStone = \"texture/wall6.jpg\"\ndoorTexture = \"texture/wood.jpg\"\nmetalTexture = \"texture/metal.jpg\"\nglassTexture = \"texture/glass.jpg\"\nroofTexture = \"texture/roof.png\"\n\nzero = CUBOID([.0,.0,.0])\ninitStruct = STRUCT([zero])\nlevelHeight = [30.0,30.0,20.0,30.0,30.0,20.0]\nheights = [60.0,20.0,3.5,60.0,20.0]\n\ndef countFileDirectory(path):\n i = 0\n for name in os.listdir(path):\n if not name.startswith('.'):\n i = i + 1\n return i\n\ndef readSvg(l,readingLevel,path):\n file = open(\"components/\"+path+\"/lines/level-\"+str(l)+\".lines\",\"r\")\n data = file.read()\n n = countFileDirectory(\"components/\"+path+\"/lines/\")\n file.close()\n d = data.splitlines()\n readingLevel = readingLevel + [d]\n if l!=n-1:\n return readSvg(l+1,readingLevel,path)\n else:\n return readingLevel\n\nlevelBase = readSvg(0,[],\"base\")\nlevelExternal = readSvg(0,[],\"esterno\")\nlevelInternal = readSvg(0,[],\"interno\")\nlevelDoors = readSvg(0,[],\"porte\")\nlevelWindows = readSvg(0,[],\"finestre\")\nlevelStair = readSvg(0,[],\"scale\")\n\ndef parseLines(l,i, params):\n stringLine = params[l][i]\n splitLine = stringLine.split(\",\")\n arrayLine = np.array(splitLine, dtype=float)\n return arrayLine\n\n#Creation first floor\ndef createFloor1(i,s1):\n if i < len(levelBase[0]):\n params = parseLines(0,i,levelBase)\n a_pol = POLYLINE([[params[0],params[1]],[params[2],params[3]]])\n a_off = OFFSET([4.0, 5.5, 2.0])(a_pol)\n s2 = STRUCT([a_off, s1])\n return createFloor1(i+1,s2)\n else:\n s1 = SOLIDIFY(SKEL_2(s1))\n s1 = TEXTURE([pavTexture, TRUE, FALSE, 1, 1, 0, 1, 1])(s1)\n return s1\n\n#Creation external wall\ndef createExternalWalls(l,i,h,s1):\n if l <= len(levelExternal)-1:\n if i < len(levelExternal[l]):\n params = parseLines(l,i,levelExternal)\n a_pol = MKPOL([[[params[0],params[1],0.0],[params[0],params[3],0.0],[params[2],params[1],0.0],[params[2],params[3],0.0]],[[1,2,3,4]],[1]])\n a_off = OFFSET([3.0, 3.0, levelHeight[l]])(a_pol)\n if l==0:\n a_texture = TEXTURE([wallStone, TRUE, FALSE, 1, 1, 0, 2, 1])(a_off)\n else:\n if l==3:\n a_texture = TEXTURE([wallStone, TRUE, FALSE, 1, 1, 0, 6, 1])(a_off)\n else:\n a_texture = TEXTURE([wallTexture, TRUE, FALSE, 1, 1, 0, 6, 1])(a_off)\n a_tras = STRUCT([T(3)(h), a_texture])\n s2 = STRUCT([a_tras, s1])\n return createExternalWalls(l,i+1,h,s2)\n else:\n h = h + levelHeight[l]\n return createExternalWalls(l+1,0,h,s1)\n else:\n return s1\n\n#Creation internal wall\ndef createInternalWalls(l,i,h,s1):\n if l <= len(levelInternal)-1:\n if i < len(levelInternal[l]):\n params = parseLines(l,i,levelInternal)\n a_pol = MKPOL([[[params[0],params[1],0.0],[params[0],params[3],0.0],[params[2],params[1],0.0],[params[2],params[3],0.0]],[[1,2,3,4]],[1]])\n a_off = OFFSET([1.0, 1.0, levelHeight[l]])(a_pol)\n a_texture = TEXTURE([wallTexture, TRUE, FALSE, 1, 1, 0, 2, 1])(a_off)\n a_tras = STRUCT([T(3)(h), a_texture])\n s2 = STRUCT([a_tras, s1])\n return createInternalWalls(l,i+1,h,s2)\n else:\n h = h + levelHeight[l]\n return createInternalWalls(l+1,0,h,s1)\n else:\n return s1\n\n#Creation a door\ndef createDoor(elem, j, h, door):\n if j < 13:\n build = MKPOL([[[elem[0],elem[1],0.0],[elem[2],elem[3],0.0]],[[1,2]],[1]])\n if not j%2:\n buildOffset = OFFSET([3.5, 3.5, 8.5])(build)\n buildTexture = TEXTURE([doorTexture, TRUE, FALSE, 1, 1, 0, 6, 1])(buildOffset)\n buildTras = STRUCT([T([3])([h]), buildTexture])\n h = h + 8.5\n else:\n buildOffset = OFFSET([3.5, 3.5, 0.5])(build)\n buildTexture = TEXTURE([doorTexture, TRUE, FALSE, 1, 1, 0, 1, 1])(buildOffset)\n buildTras = STRUCT([T([3])([h]), buildTexture])\n h = h + 0.5\n door = STRUCT([buildTras,door])\n return createDoor(elem, j+1, h, door)\n else:\n return door\n\n#Creation handle's door\ndef createHandle(elem,s1):\n handle = MKPOL([[[elem[0],elem[1],0.0],[elem[2],elem[3],0.0]],[[1,2]],[1]])\n handle0 = OFFSET([8.0, 1.0, 1.0])(handle)\n if (elem[0]-elem[2]<1.0) & (elem[0]-elem[2]>-1.0):\n handle_0 = STRUCT([T([1,2,3])([-2.0,1.0,31.0]), handle0])\n handle_1 = STRUCT([T([1,2,3])([-2.0,3.0,31.0]), handle0])\n handle1 = OFFSET([1.0, 1.5, 1.0])(handle)\n handle_2 = STRUCT([T([1,2,3])([5.0,1.0,31.0]), handle1])\n handle_3 = STRUCT([T([1,2,3])([5.0,6.0,31.0]), handle1])\n handle_01 = DIFF([handle_0,handle_1])\n handle_23 = DIFF([handle_2,handle_3])\n handle_23_2 = STRUCT([T([1])([-8.0]), handle_23])\n else:\n handle = MKPOL([[[elem[0],elem[1],0.0],[elem[2],elem[3],0.0]],[[1,2]],[1]])\n handle0 = OFFSET([1.0, 8.0, 1.0])(handle)\n handle_0 = STRUCT([T([1,2,3])([1.0,-2.0,31.0]), handle0])\n handle_1 = STRUCT([T([1,2,3])([3.0,-2.0,31.0]), handle0])\n handle1 = OFFSET([1.0, 1.5, 1.0])(handle)\n handle_2 = STRUCT([T([1,2,3])([1.0,5.0,31.0]), handle1])\n handle_3 = STRUCT([T([1,2,3])([6.0,5.0,31.0]), handle1])\n handle_01 = DIFF([handle_0,handle_1])\n handle_23 = DIFF([handle_2,handle_3])\n handle_23_2 = STRUCT([T([2])([-8.0]), handle_23])\n handle_all = STRUCT([handle_01,handle_23,handle_23_2])\n handle_all = TEXTURE([metalTexture, TRUE, FALSE, 1, 1, 0, 1, 1])(handle_all)\n s1 = STRUCT([s1,handle_all])\n return s1\n\n#Creation all doors\ndef createDoors(l,i,h,s1):\n if l <= len(levelDoors)-1:\n if i < len(levelDoors[l]):\n params = parseLines(l,i,levelDoors)\n d = createDoor(params, 0, h, initStruct)\n hand = createHandle(params,initStruct)\n hand = STRUCT([T([3])([h]), hand])\n finalStruct = STRUCT([d, s1, hand])\n return createDoors(l,i+1,h,finalStruct)\n else:\n h = h + 80.0 \n return createDoors(l+1,0,h,s1)\n else:\n return s1\n\n#Creation a window\ndef createWindow(params,h):\n q1 = MKPOL([[[params[0],params[1],0.0],[params[2],params[3],0.0]],[[1,2]],[1]])\n q1 = OFFSET([3.5, 3.5, 30.0])(q1)\n #q1 = STRUCT([T(3)(5.0), q1])\n q1 = TEXTURE([glassTexture, TRUE, FALSE, 1, 1, 0, 1, 1])(q1)\n q1 = MATERIAL([0,1.36,2.55,0.5, 0,1,0,0.5, 0,0,1,0, 0,0,0,0.5, 100])(q1)\n if (params[0]-params[2]<1.0) & (params[0]-params[2]>-1.0):\n if params[1]-1.0):\n if params[0] 1: break\n if stepSize > 5:\n print ('Sufficient local maximum found: ', n)\n break\n if all(i == maxOrder for i in n): \n print('Maximum value of n = [7, 7, 7, 7, 7] reached ... exiting')\n break\n def comparison(a): \n comp = pdn(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS, gammaCal, gammaRec, a)\n return comp\n \n increase = []\n if n[0] + stepSize < maxOrder: increase.append([n[0] + stepSize, n[1], n[2], n[3], n[4]])\n else: increase.append([maxOrder, n[1], n[2], n[3], n[4]])\n if n[1] + stepSize < maxOrder: increase.append([n[0], n[1] + stepSize, n[2], n[3], n[4]])\n else: increase.append([n[0], maxOrder, n[2], n[3], n[4]])\n if n[2] + stepSize < maxOrder: increase.append([n[0], n[1], n[2] + stepSize, n[3], n[4]])\n else: increase.append([n[0], n[1], maxOrder, n[3], n[4]])\n if n[3] + stepSize < maxOrder: increase.append([n[0], n[1], n[2], n[3] + stepSize, n[4]])\n else: increase.append([n[0], n[1], n[2], maxOrder, n[4]])\n if n[4] + stepSize < maxOrder: increase.append([n[0], n[1], n[2], n[3], n[4] + stepSize])\n else: increase.append([n[0], n[1], n[2], n[3], maxOrder])\n \n if iteration % printVals == 0: print('Trying: ', increase)\n m = max(increase, key = comparison) \n \n decrease = []\n if n[0] - stepSize > minOrder: decrease.append([n[0] - stepSize, n[1], n[2], n[3], n[4]])\n else: decrease.append([0, n[1], n[2], n[3], n[4]])\n if n[1] - stepSize > minOrder: decrease.append([n[0], n[1] - stepSize, n[2], n[3], n[4]])\n else: decrease.append([n[0], 0, n[2], n[3], n[4]])\n if n[2] - stepSize > minOrder: decrease.append([n[0], n[1], n[2] - stepSize, n[3], n[4]])\n else: decrease.append([n[0], n[1], 0, n[3], n[4]])\n if n[3] - stepSize > minOrder: decrease.append([n[0], n[1], n[2], n[3] - stepSize, n[4]])\n else: decrease.append([n[0], n[1], n[2], 0, n[4]])\n if n[4] - stepSize > minOrder: decrease.append([n[0], n[1], n[2], n[3], n[4] - stepSize])\n else: decrease.append([n[0], n[1], n[2], n[3], 0])\n \n if iteration % printVals == 0: print('Trying: ', decrease)\n j = max(decrease, key = comparison)\n \n if iteration % printVals == 0: print('Comparing: ', n, m, 'and', j)\n if iteration % printVals == 0: print('Compared values: ', comparison(n), comparison(m), comparison(j))\n print()\n r = max([n, m, j], key = comparison)\n if iteration % printVals == 0: print('Taking: ', r)\n print('Iteration: ', iteration, ' Current n: ', r, 'Value:', comparison(r), 'Step Size:', stepSize)\n print()\n if np.array_equal(n, r): stepSize += 1\n else: n = r\n iteration += 1\n return n\n\nn = orderOptimization('testAntPSD.prn', 'testLoadPSD.prn', 'testNSPSD.prn', 300, 350, 'testCalS11.s1p', 'testRecSparam.s2p')\nprint(n)\n","sub_path":"February Calibration 1/orderOptimizer.py","file_name":"orderOptimizer.py","file_ext":"py","file_size_in_byte":5804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"316046008","text":"from tensorflow.keras.datasets import boston_housing\nfrom tensorflow.keras.layers import Activation, Dense, Dropout\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.layers.advanced_activations import LeakyReLU\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import trange\nfrom random import random, randint, shuffle\n\ndict_data = {}\nall_data = []\nall_labels = []\ntrain_data = []\ntrain_labels = []\ntest_data = []\ntest_labels = []\n\n\nhw = 8\nhw2 = 64\nboard_index_num = 38\ndy = [0, 1, 0, -1, 1, 1, -1, -1]\ndx = [1, 0, -1, 0, 1, -1, 1, -1]\npattern_space = []\nboard_translate = []\n\nconsts = [\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n 62, 63, 0, 8, 16, 24, 32, 40, 48, 56, 1, 9, 17, 25, 33, 41, 49, 57, 2, 10, 18, 26, 34, 42, 50, 58, 3, 11, 19, 27, 35, 43, 51, 59, 4, 12, 20, 28, 36, 44, 52, 60, 5, 13, 21, 29, 37, 45, 53, 61, 6, 14, 22, 30, 38, 46, 54, 62, 7, 15, 23, 31, 39, 47, 55, 63, 5, 14, 23, 4, 13, 22, 31, 3, 12, 21, 30, 39, 2, 11, 20, 29, 38, 47, 1, 10, 19, 28, 37, 46, 55, 0, 9, 18, 27, 36, 45, 54, 63, 8,\n 17, 26, 35, 44, 53, 62, 16, 25, 34, 43, 52, 61, 24, 33, 42, 51, 60, 32, 41, 50, 59, 40, 49, 58, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34, 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 23, 30, 37, 44, 51, 58, 31, 38, 45, 52, 59, 39, 46, 53, 60, 47, 54, 61, 10, 8, 8, 8, 8, 4, 4, 8, 2, 4, 54, 63, 62, 61, 60, 59, 58, 57,\n 56, 49, 49, 56, 48, 40, 32, 24, 16, 8, 0, 9, 9, 0, 1, 2, 3, 4, 5, 6, 7, 14, 14, 7, 15, 23, 31, 39, 47, 55, 63, 54, 3, 2, 1, 0, 9, 8, 16, 24, 4, 5, 6, 7, 14, 15, 23, 31, 60, 61, 62, 63, 54, 55, 47, 39, 59, 58, 57, 56, 49, 48, 40, 32, 0, 1, 2, 3, 8, 9, 10, 11, 0, 8, 16, 24, 1, 9, 17, 25, 7, 6, 5, 4, 15, 14, 13, 12, 7, 15, 23, 31, 6, 14, 22, 30, 63, 62, 61, 60,\n 55, 54, 53, 52, 63, 55, 47, 39, 62, 54, 46, 38, 56, 57, 58, 59, 48, 49, 50, 51, 56, 48, 40, 32, 57, 49, 41, 33, 0, 9, 18, 27, 36, 45, 54, 63, 7, 14, 21, 28, 35, 42, 49, 56, 0, 1, 2, 3, 4, 5, 6, 7, 7, 15, 23, 31, 39, 47, 55, 63, 63, 62, 61, 60, 59, 58, 57, 56, 56, 48, 40, 32, 24, 26, 8, 0\n]\n\nconsts_idx = 0\nfor i in range(board_index_num):\n pattern_space.append(consts[consts_idx])\n consts_idx += 1\nfor i in range(board_index_num):\n board_translate.append([])\n for j in range(pattern_space[i]):\n board_translate[-1].append(consts[consts_idx])\n consts_idx += 1\n\ndef empty(grid, y, x):\n return grid[y][x] == -1 or grid[y][x] == 2\n\ndef inside(y, x):\n return 0 <= y < hw and 0 <= x < hw\n\ndef check(grid, player, y, x):\n res_grid = [[False for _ in range(hw)] for _ in range(hw)]\n res = 0\n for dr in range(8):\n ny = y + dy[dr]\n nx = x + dx[dr]\n if not inside(ny, nx):\n continue\n if empty(grid, ny, nx):\n continue\n if grid[ny][nx] == player:\n continue\n #print(y, x, dr, ny, nx)\n plus = 0\n flag = False\n for d in range(hw):\n nny = ny + d * dy[dr]\n nnx = nx + d * dx[dr]\n if not inside(nny, nnx):\n break\n if empty(grid, nny, nnx):\n break\n if grid[nny][nnx] == player:\n flag = True\n break\n #print(y, x, dr, nny, nnx)\n plus += 1\n if flag:\n res += plus\n for d in range(plus):\n nny = ny + d * dy[dr]\n nnx = nx + d * dx[dr]\n res_grid[nny][nnx] = True\n return res, res_grid\n\ndef pot_canput_line(arr):\n res_p = 0\n res_o = 0\n for i in range(len(arr) - 1):\n if arr[i] == -1 or arr[i] == 2:\n if arr[i + 1] == 0:\n res_o += 1\n elif arr[i + 1] == 1:\n res_p += 1\n for i in range(1, len(arr)):\n if arr[i] == -1 or arr[i] == 2:\n if arr[i - 1] == 0:\n res_o += 1\n elif arr[i - 1] == 1:\n res_p += 1\n return res_p, res_o\n\nclass reversi:\n def __init__(self):\n self.grid = [[-1 for _ in range(hw)] for _ in range(hw)]\n self.grid[3][3] = 1\n self.grid[3][4] = 0\n self.grid[4][3] = 0\n self.grid[4][4] = 1\n self.player = 0 # 0: 黒 1: 白\n self.nums = [2, 2]\n\n def move(self, y, x):\n plus, plus_grid = check(self.grid, self.player, y, x)\n if (not empty(self.grid, y, x)) or (not inside(y, x)) or not plus:\n print('Please input a correct move')\n return 1\n self.grid[y][x] = self.player\n for ny in range(hw):\n for nx in range(hw):\n if plus_grid[ny][nx]:\n self.grid[ny][nx] = self.player\n self.nums[self.player] += 1 + plus\n self.nums[1 - self.player] -= plus\n self.player = 1 - self.player\n return 0\n \n def check_pass(self):\n for y in range(hw):\n for x in range(hw):\n if self.grid[y][x] == 2:\n self.grid[y][x] = -1\n res = True\n for y in range(hw):\n for x in range(hw):\n if not empty(self.grid, y, x):\n continue\n plus, _ = check(self.grid, self.player, y, x)\n if plus:\n res = False\n self.grid[y][x] = 2\n if res:\n #print('Pass!')\n self.player = 1 - self.player\n return res\n\n def output(self):\n print(' ', end='')\n for i in range(hw):\n print(chr(ord('a') + i), end=' ')\n print('')\n for y in range(hw):\n print(str(y + 1) + ' ', end='')\n for x in range(hw):\n print('○' if self.grid[y][x] == 0 else '●' if self.grid[y][x] == 1 else '* ' if self.grid[y][x] == 2 else '. ', end='')\n print('')\n \n def output_file(self):\n res = ''\n for y in range(hw):\n for x in range(hw):\n res += '*' if self.grid[y][x] == 0 else 'O' if self.grid[y][x] == 1 else '-'\n res += ' *'\n return res\n\n def end(self):\n if min(self.nums) == 0:\n return True\n res = True\n for y in range(hw):\n for x in range(hw):\n if self.grid[y][x] == -1 or self.grid[y][x] == 2:\n res = False\n return res\n \n def judge(self):\n if self.nums[0] > self.nums[1]:\n #print('Black won!', self.nums[0], '-', self.nums[1])\n return 0\n elif self.nums[1] > self.nums[0]:\n #print('White won!', self.nums[0], '-', self.nums[1])\n return 1\n else:\n #print('Draw!', self.nums[0], '-', self.nums[1])\n return -1\n\n def pot_canput(self):\n res_p = 0\n res_o = 0\n for i in range(board_index_num):\n arr = []\n for j in board_translate[i]:\n arr.append(self.grid[j // hw][j % hw])\n t1, t2 = pot_canput_line(arr)\n res_p += t1\n res_o += t2\n return res_p, res_o\n\ndef collect_data(s):\n global dict_data\n grids = []\n rv = reversi()\n idx = 2\n while True:\n if rv.check_pass() and rv.check_pass():\n break\n turn = 0 if s[idx] == '+' else 1\n x = ord(s[idx + 1]) - ord('a')\n y = int(s[idx + 2]) - 1\n idx += 3\n if rv.move(y, x):\n print('error')\n break\n pot_canput_p, pot_canput_o = rv.pot_canput()\n pot_canput_p = str(pot_canput_p)\n pot_canput_o = str(pot_canput_o)\n grid_str1 = ''\n for i in range(hw):\n for j in range(hw):\n if rv.grid[i][j] == 0:\n grid_str1 += '1 '\n else:\n grid_str1 += '0 '\n grid_str2 = ''\n for i in range(hw):\n for j in range(hw):\n if rv.grid[i][j] == 1:\n grid_str2 += '1 '\n else:\n grid_str2 += '0 '\n grid_str3 = ''\n for i in range(hw):\n for j in range(hw):\n if rv.grid[i][j] == -1 or rv.grid[i][j] == 2:\n grid_str3 += '1 '\n else:\n grid_str3 += '0 '\n #grids.append([1, grid_str1 + grid_str2])\n #grids.append([-1, grid_str2 + grid_str1])\n grids.append([1, grid_str1 + grid_str2 + pot_canput_p + ' ' + pot_canput_o])\n grids.append([-1, grid_str2 + grid_str1 + pot_canput_o + ' ' + pot_canput_p])\n\n grid_str1 = ''\n for i in range(hw):\n for j in range(hw):\n if rv.grid[j][i] == 0:\n grid_str1 += '1 '\n else:\n grid_str1 += '0 '\n grid_str2 = ''\n for i in range(hw):\n for j in range(hw):\n if rv.grid[j][i] == 1:\n grid_str2 += '1 '\n else:\n grid_str2 += '0 '\n grid_str3 = ''\n for i in range(hw):\n for j in range(hw):\n if rv.grid[j][i] == -1 or rv.grid[j][i] == 2:\n grid_str3 += '1 '\n else:\n grid_str3 += '0 '\n #grids.append([1, grid_str1 + grid_str2])\n #grids.append([-1, grid_str2 + grid_str1])\n grids.append([1, grid_str1 + grid_str2 + pot_canput_p + ' ' + pot_canput_o])\n grids.append([-1, grid_str2 + grid_str1 + pot_canput_o + ' ' + pot_canput_p])\n \n grid_str1 = ''\n for i in reversed(range(hw)):\n for j in reversed(range(hw)):\n if rv.grid[i][j] == 0:\n grid_str1 += '1 '\n else:\n grid_str1 += '0 '\n grid_str2 = ''\n for i in reversed(range(hw)):\n for j in reversed(range(hw)):\n if rv.grid[i][j] == 1:\n grid_str2 += '1 '\n else:\n grid_str2 += '0 '\n grid_str3 = ''\n for i in reversed(range(hw)):\n for j in reversed(range(hw)):\n if rv.grid[i][j] == -1 or rv.grid[i][j] == 2:\n grid_str3 += '1 '\n else:\n grid_str3 += '0 '\n #grids.append([1, grid_str1 + grid_str2])\n #grids.append([-1, grid_str2 + grid_str1])\n grids.append([1, grid_str1 + grid_str2 + pot_canput_p + ' ' + pot_canput_o])\n grids.append([-1, grid_str2 + grid_str1 + pot_canput_o + ' ' + pot_canput_p])\n\n grid_str1 = ''\n for i in reversed(range(hw)):\n for j in reversed(range(hw)):\n if rv.grid[j][i] == 0:\n grid_str1 += '1 '\n else:\n grid_str1 += '0 '\n grid_str2 = ''\n for i in reversed(range(hw)):\n for j in reversed(range(hw)):\n if rv.grid[j][i] == 1:\n grid_str2 += '1 '\n else:\n grid_str2 += '0 '\n grid_str3 = ''\n for i in reversed(range(hw)):\n for j in reversed(range(hw)):\n if rv.grid[j][i] == -1 or rv.grid[j][i] == 2:\n grid_str3 += '1 '\n else:\n grid_str3 += '0 '\n #grids.append([1, grid_str1 + grid_str2])\n #grids.append([-1, grid_str2 + grid_str1])\n grids.append([1, grid_str1 + grid_str2 + pot_canput_p + ' ' + pot_canput_o])\n grids.append([-1, grid_str2 + grid_str1 + pot_canput_o + ' ' + pot_canput_p])\n\n if rv.end():\n break\n rv.check_pass()\n #score = 1 if rv.nums[0] > rv.nums[1] else 0 if rv.nums[0] == rv.nums[1] else -1\n score = rv.nums[0] - rv.nums[1]\n for sgn, grid in grids:\n if grid in dict_data:\n dict_data[grid][0] += sgn * score\n dict_data[grid][1] += 1\n else:\n dict_data[grid] = [sgn * score, 1]\n\ndef reshape_data():\n global all_data, all_labels\n for grid_str in dict_data.keys():\n grid = [int(i) for i in grid_str.split()]\n score = dict_data[grid_str][0] / dict_data[grid_str][1]\n all_data.append(grid)\n all_labels.append(score)\n #all_data = np.array(all_data)\n #all_labels = np.array(all_labels)\n\ndef divide_data(ratio):\n global train_data, train_labels, test_data, test_labels\n test_num = int(len(all_data) * ratio)\n idxes = list(range(len(all_data)))\n shuffle(idxes)\n for i in range(test_num):\n test_data.append(all_data[idxes[i]])\n test_labels.append(all_labels[idxes[i]])\n for i in range(test_num, len(all_data)):\n train_data.append(all_data[idxes[i]])\n train_labels.append(all_labels[idxes[i]])\n train_data = np.array(train_data)\n train_labels = np.array(train_labels)\n test_data = np.array(test_data)\n test_labels = np.array(test_labels)\n mean = train_data.mean(axis=0)\n std = train_data.std(axis=0)\n print('mean', mean)\n print('std', std)\n train_data = (train_data - mean) / std\n test_data = (test_data - mean) / std\n\ndata_num = 1000\nwith open('third_party/xxx.gam', 'rb') as f:\n raw_data = f.read()\ngames = [i for i in raw_data.splitlines()]\nfor i in trange(data_num):\n collect_data(str(games[i]))\nreshape_data()\ndivide_data(0.1)\nprint('train', train_data.shape, train_labels.shape)\nprint('test', test_data.shape, test_labels.shape)\nmodel = Sequential()\nmodel.add(Dense(512, input_shape=(130,)))\nmodel.add(LeakyReLU(alpha=0.01))\nmodel.add(Dropout(0.0625))\nmodel.add(Dense(256))\nmodel.add(LeakyReLU(alpha=0.01))\nmodel.add(Dense(128))\nmodel.add(LeakyReLU(alpha=0.01))\nmodel.add(Dense(128))\nmodel.add(LeakyReLU(alpha=0.01))\nmodel.add(Dense(1))\nmodel.compile(loss='mse', optimizer=Adam(lr=0.001), metrics=['mae'])\nearly_stop = EarlyStopping(monitor='val_loss', patience=20)\nhistory = model.fit(train_data, train_labels, epochs=1000, validation_split=0.2, callbacks=[early_stop])\n'''\nwith open('param/param.txt', 'w') as f:\n for i in (0, 3):\n for item in model.layers[i].weights[1].numpy():\n f.write(str(item) + '\\n')\n for i in (0, 3, 5):\n for arr in model.layers[i].weights[0].numpy():\n for item in arr:\n f.write(str(item) + '\\n')\n'''\n'''\nfor layer_num, layer in enumerate(model.layers):\n print(layer.weights[0].numpy())\n with open('param/w' + str(layer_num + 1) + '.txt', 'w') as f:\n for i in range(len(layer.weights[0].numpy())):\n if len(layer.weights[0].numpy()[i]) > 1:\n f.write('{')\n for j in range(len(layer.weights[0].numpy()[i])):\n if j == len(layer.weights[0].numpy()[i]) - 1 and len(layer.weights[0].numpy()[i]) > 1:\n f.write(str(layer.weights[0].numpy()[i][j]))\n else:\n f.write(str(layer.weights[0].numpy()[i][j]) + ',')\n if len(layer.weights[0].numpy()[i]) > 1:\n if i == len(layer.weights[0].numpy()) - 1:\n f.write('}')\n else:\n f.write('},\\n')\n if layer_num == len(model.layers) - 1:\n break\n print(layer.weights[1].numpy())\n with open('param/b' + str(layer_num + 1) + '.txt', 'w') as f:\n f.write('{')\n for i in range(len(layer.weights[1].numpy())):\n if i == len(layer.weights[1].numpy()) - 1:\n f.write(str(layer.weights[1].numpy()[i]) + '}')\n else:\n f.write(str(layer.weights[1].numpy()[i]) + ',')\n'''\nplt.plot(history.history['loss'], label='train loss')\nplt.plot(history.history['val_loss'], label='val loss')\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='best')\nplt.show()\ntest_loss, test_mae = model.evaluate(test_data, test_labels)\nprint('result', test_loss, test_mae)\ntest_num = 10\ntest_num = min(test_labels.shape[0], test_num)\ntest_predictions = model.predict(test_data[0:test_num]).flatten()\nprint([round(i, 2) for i in test_labels[0:test_num]])\nprint([round(i, 2) for i in test_predictions[0:test_num]])\nfor i in range(5):\n print(list(test_data[i]))\nmodel.save('model_big.h5')","sub_path":"legacy/20210911/learn.py","file_name":"learn.py","file_ext":"py","file_size_in_byte":16499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"164209411","text":"import socket\nimport pickle\nimport subprocess\n\n#||||||||||||||||||||||||||||||CLIENT||||||||||||||||||||||||||\n\nsocket = socket.socket()\nserverAddress = '127.0.0.1', 1111\n\n\ndef popenExecution(data):\n\n if data[:2] == 'cd': \n os.chdir(str(data[3:]))\n\n command = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, \n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n\n return str(command.stdout.read() + command.stderr.read(), \"utf-8\")\n\n\ndef main():\n \n while True:\n try:\n socket.connect(serverAddress)\n #Standard command to identify who this machine is\n socket.send(pickle.dumps(popenExecution(\"who\").split()[0]))\n break\n except:\n socket.close()\n break\n\n\nmain()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"46980180","text":"# 실행시간\n\nfrom itertools import combinations\n\nT=int(input())\nfor tc in range(1,T+1):\n N=int(input())\n sub_N=N//2\n arr=[list(map(int,input().split())) for _ in range(N)]\n row=[sum(i) for i in arr]\n col=[sum(i) for i in zip(*arr)]\n\n new_arr=[i+j for i,j in zip(row,col)] ### 같은 인덱스를 가지는 행과열을 더해주는 것\n\n allstat=sum(new_arr)//2 ### 전체 행렬값을 구해주는 것\n allstat -= new_arr[-1] ### 1,2 vs 3,4 이나 3,4 vs 1,2은 동일한 결과를 나타내므로,\n mins=99999999 ### 1재료를 미리 한팀으로 고정으로 정해줘서,\n ### 연산량을 줄여주기 위한 것.\n ### a b c d\n ### e f g h\n ### i j k l\n ### m n o p 가 있으면\n ### allstat은 a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p 이고,\n ### 1,2재료을 선택하고 new_arr 0,1를 뽑는다고 치면\n ### new_arr[0]=2a+b+c+d+e+i+m\n ### new_arr[1]=b+2f+j+n+e+g+h\n ### 두 개를 더 해주면\n ### 2a+2b+2e+2f+c+d+g+h+i+j+m+n이 되고 allstat에서 빼주면\n ### (k+l+o+p)-(a+b+e+f) 이 되어 결과적으로,\n ### 3,4재료를 선택한 것에서 1,2재료를 선택한것을 빼준것과\n ### 동일 효과가 된다.\n\n\n\n for l in combinations(new_arr[:-1],sub_N-1):\n mins=min(mins,abs(allstat-sum(l)))\n\n if not mins:\n break\n print('#{} {}'.format(tc,mins))","sub_path":"2003/0305/swea 4012 요리사 실행시간.py","file_name":"swea 4012 요리사 실행시간.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"123730855","text":"from typing import Any\n\nimport proto\n\nfrom google.ads.googleads.v14.enums.types.operating_system_version_operator_type import (\n OperatingSystemVersionOperatorTypeEnum,\n)\n\nclass OperatingSystemVersionConstant(proto.Message):\n resource_name: str\n id: int\n name: str\n os_major_version: int\n os_minor_version: int\n operator_type: OperatingSystemVersionOperatorTypeEnum.OperatingSystemVersionOperatorType\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n resource_name: str = ...,\n id: int = ...,\n name: str = ...,\n os_major_version: int = ...,\n os_minor_version: int = ...,\n operator_type: OperatingSystemVersionOperatorTypeEnum.OperatingSystemVersionOperatorType = ...\n ) -> None: ...\n","sub_path":"google-stubs/ads/googleads/v14/resources/types/operating_system_version_constant.pyi","file_name":"operating_system_version_constant.pyi","file_ext":"pyi","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"172226299","text":"#!/usr/bin/env python3\nimport inca\nimport gensim\nimport logging\nimport re\n\nlettersanddotsonly = re.compile(r'[^a-zA-Z\\.]')\n\nPATH = \"/home/anne/tmpanne/\"\n#outlets = ['telegraaf (print)', 'nrc (print)', 'volkskrant (print)', 'ad (print)', 'trouw (print)']\noutlets = ['telegraaf (print)', 'nrc (print)', 'volkskrant (print)', 'ad (print)', 'trouw (print)', 'telegraaf (www)', 'nrc (www)', 'volkskrant (www)', 'ad (www)', 'trouw (www)', 'nu' , 'nos', 'hetlaatstenieuws', 'hetlaatstenieuws (www)','parool (www)', 'tubantia (www)', 'zwartewaterkrant (www)', 'fd (print)']\n\nw2v_params = {\n 'alpha': 0.025,\n 'size': 100,\n # 'window': 15,\n # 'iter': 5,\n 'min_count': 5,\n 'sg': 1,\n 'hs': 0,\n 'negative': 5\n}\n\ndef preprocess(s):\n s = s.lower().replace('!','.').replace('?','.') # replace ! and ? by . for splitting sentences\n s = lettersanddotsonly.sub(' ',s)\n return s\n\nclass train_model():\n\n def __init__(self, doctype, fromdate,todate):\n self.doctype = doctype\n self.fromdate = fromdate\n self.todate = todate\n if type(self.doctype) is str:\n self.query = {\n \"query\": {\n \"bool\": {\n \"filter\": [\n { \"match\": { \"doctype\": self.doctype}},\n { \"range\": { \"publication_date\": { \"gte\": self.fromdate, \"lt\":self.todate }}}\n ]\n }\n }\n }\n elif type(self.doctype) is list:\n self.query = {\n \"query\": {\n \"bool\": {\n \"filter\": [ {'bool': {'should': [{ \"match\": { \"doctype\": d}} for d in self.doctype]}},\n { \"range\": { \"publication_date\": { \"gte\": self.fromdate, \"lt\":self.todate }}}\n ]\n }\n }\n }\n\n\n self.documents = 0\n self.failed_document_reads = 0\n self.model = gensim.models.Word2Vec(**w2v_params)\n\n self.sentences = set()\n for sentence in self.get_sentences():\n self.sentences.add(\" \".join(sentence))\n self.sentences = [s.split() for s in self.sentences]\n \n self.model.build_vocab(self.sentences)\n print('Build Word2Vec vocabulary')\n self.model.train(self.sentences,total_examples=self.model.corpus_count, epochs=self.model.iter)\n print('Estimated Word2Vec model')\n\n\n\n def get_sentences(self):\n for d in inca.core.database.scroll_query(self.query):\n try:\n self.documents += 1\n sentences_as_lists = (s.split() for s in preprocess(d['_source']['text']).split('.'))\n for sentence in sentences_as_lists:\n yield sentence\n except:\n self.failed_document_reads +=1\n continue\n\ndef train_and_save(fromdate,todate,doctype):\n filename = \"{}w2v_all_uniquesentences_{}_{}\".format(PATH,fromdate,todate)\n\n casus = train_model(doctype,fromdate,todate)\n\n with open(filename, mode='wb') as fo:\n casus.model.save(fo)\n print('Saved model')\n print(\"reopen it with m = gensim.models.FastText.load('{}')\".format(filename))\n del(casus)\n\n\nif __name__ == \"__main__\":\n\n logger = logging.getLogger()\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s')\n logging.root.setLevel(level=logging.INFO)\n\n train_and_save(fromdate = \"2000-01-01\", todate = \"2016-12-31\", doctype = outlets)\n","sub_path":"model_training/trainmodel_uniekezinnen.py","file_name":"trainmodel_uniekezinnen.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"589491674","text":"import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'font.size': 24})\n\nM_star = 1.989*10**33\nAU = 1.496*10**13\n\n\nR_c = np.array([20 * AU, 40 * AU, 60 * AU], float)\nM_disk_percentage = np.array([0.02,0.03,0.05,0.1], float)\nn = 1.\ndust_to_gas_ratio = 0.01\n\nM_disk = np.zeros(len(M_disk_percentage))\nfor i in range (0,len(M_disk_percentage)):\n\tM_disk[i] = M_disk_percentage[i] * M_star\n\nR_max = 400 * AU\nR_min = 0.1 * AU\nsize = 10000\n\ndef make_R_array():\n\tR_array = np.zeros(size)\n\tR_step = (R_max - R_min)/size\n\tfor i in range (0,size):\n\t\tR_array[i] = R_min + i * R_step\n\treturn R_array\nR_array = make_R_array()\n\ndef calc_normalization_constant(M_disk, R_c):\n\tc_sigma = (2-n)*dust_to_gas_ratio*M_disk / (2* np.pi * R_c**2)\n\treturn c_sigma\n\nc_sigma_disk = np.zeros(len(M_disk_percentage))\nfor i in range (0,len(M_disk_percentage)):\n\tc_sigma_disk[i] = calc_normalization_constant(M_disk[i], R_c[1])\n\nc_sigma_Rc = np.zeros(len(R_c))\nfor i in range (0,len(R_c)):\n\tc_sigma_Rc[i] = calc_normalization_constant(M_disk[1], R_c[i])\n\n\ndef calc_dust_profile(c_sigma, R_c):\n\tsd_array = np.zeros(size)\n\tfor i in range (0,size):\n\t\tsd_array[i] = c_sigma * (R_array[i]/R_c)**(-n) * np.exp(-(R_array[i]/R_c)**(2-n))\n\treturn sd_array\n\n\t\nsd_array_disk1 = calc_dust_profile(c_sigma_disk[0], R_c[1])\nsd_array_disk2 = calc_dust_profile(c_sigma_disk[1], R_c[1])\nsd_array_disk3 = calc_dust_profile(c_sigma_disk[2], R_c[1])\nsd_array_disk4 = calc_dust_profile(c_sigma_disk[3], R_c[1])\n\nsd_array_Rc1 = calc_dust_profile(c_sigma_Rc[0], R_c[0])\nsd_array_Rc2 = calc_dust_profile(c_sigma_Rc[1], R_c[1])\nsd_array_Rc3 = calc_dust_profile(c_sigma_Rc[2], R_c[2])\n\n# calc R_array in AU\ndef transform_R_array():\n\tR_array_AU = np.zeros(size)\n\tfor i in range (0,size):\n\t\tR_array_AU[i] = R_array[i]/AU\n\treturn R_array_AU\nR_array_AU = transform_R_array()\n\n\ndef plot():\n\tplt.close()\n\tnrow = 1\n\tncol = 2\n\tfig = plt.subplots(nrow, ncol, figsize=(20,10))\n\tax1 = plt.subplot2grid((1,2), (0,0), colspan = 1)\n\tax2 = plt.subplot2grid((1,2), (0,1), colspan = 1)\n\n\tline_width = 2.5\n\n\n\n\tax1.plot(R_array_AU, sd_array_disk1, label = \"$M_{\\mathrm{disk}}=0.02 \\cdot M_{\\mathrm{star}}$\", linewidth=line_width, color = (0.8, 0.016, 0))\n\tax1.plot(R_array_AU, sd_array_disk2, label = \"$M_{\\mathrm{disk}}=0.03 \\cdot M_{\\mathrm{star}}$\", linewidth=line_width, color = (0.675, 0.29, 0.031))\n\tax1.plot(R_array_AU, sd_array_disk3, label = \"$M_{\\mathrm{disk}}=0.05 \\cdot M_{\\mathrm{star}}$\", linewidth=line_width, color = (0.549, 0.439, 0.051))\n\tax1.plot(R_array_AU, sd_array_disk4, label = \"$M_{\\mathrm{disk}}=0.1 \\cdot M_{\\mathrm{star}}$\", linewidth=line_width, color = (0.369, 0.424, 0.059))\n\tax1.set_yscale(\"log\")\n\tax1.set_xscale(\"log\")\n\tax1.set_xlim([R_min/AU,R_max/AU])\n\tax1.set_ylim([10**(-2.),1*10**3])\n\tlegend1 = ax1.legend(loc='best', shadow = False, framealpha = 0)\n\tframe1 = legend1.get_frame()\n\tframe1.set_facecolor('0.90')\n\tax1.set_xlabel(\"$\\mathrm{R [AU]}$\")\n\tax1.set_ylabel(\"$\\Sigma_{\\mathrm{dst}}^{0} \\left[\\\\frac{\\mathrm{g}}{\\mathrm{cm}^2} \\\\right]$\")\n\tax1.set_title(\"$\\mathrm{Initial \\\\ Dust \\\\ Profile \\\\ for } R_{\\mathrm{c}}=40 \\mathrm{AU}$\")\n\t#ax1.grid(b=True, which='minor', color='black', linestyle='--')\n\t#ax1.grid(b=True, which='major', color='black', linestyle='--')\n\tax1.grid(which='minor')\n\tax1.grid(which='major')\n\n\n\tax2.plot(R_array_AU, sd_array_Rc1, label = \"$R_{\\mathrm{c}}=20 \\mathrm{AU}$\", linewidth=line_width, color = (0.8, 0.016, 0))\n\tax2.plot(R_array_AU, sd_array_Rc2, label = \"$R_{\\mathrm{c}}=40 \\mathrm{AU}$\", linewidth=line_width, color = (0.675, 0.29, 0.031))\n\tax2.plot(R_array_AU, sd_array_Rc3, label = \"$R_{\\mathrm{c}}=60 \\mathrm{AU}$\", linewidth=line_width, color = (0.369, 0.424, 0.059))\n\tax2.set_yscale(\"log\")\n\tax2.set_xscale(\"log\")\n\tax2.set_xlim([R_min/AU,R_max/AU])\n\tax2.set_ylim([10**(-2.),1* 10**3])\n\tlegend2 = ax2.legend(loc='best', shadow = False, framealpha = 0)\n\tframe2 = legend2.get_frame()\n\tframe2.set_facecolor('0.90')\n\tax2.set_xlabel(\"$\\mathrm{R [AU]}$\")\n\tax2.set_ylabel(\"$\\Sigma_{\\mathrm{dst}}^{0} \\left[\\\\frac{\\mathrm{g}}{\\mathrm{cm}^2} \\\\right]$\")\n\tax2.set_title(\"$\\mathrm{Initial \\\\ Dust \\\\ Profile \\\\ for} M_\\mathrm{disk} = 0.03 \\cdot M_{\\mathrm{star}}$\")\n\t#ax2.grid(b=True, which='minor', color='black', linestyle='--')\n\t#ax2.grid(b=True, which='major', color='black', linestyle='--')\n\n\tax2.grid(which='minor')\n\tax2.grid(which='major')\n\tplt.tight_layout()\n\tplt.savefig(\"initial_dust_surface_density3\")\n\tplt.close()\n\treturn 0\nplot()\n\n#$\\mathrm{initial \\\\ dust \\\\ surface \\\\ density \\\\ for \\\\} R_{\\mathrm{c}}=40 \\mathrm{AU}$\n#$\\mathrm{initial \\\\ dust \\\\ surface \\\\ density \\\\ for \\\\ } M_{\\mathrm{disk}}=0.03 \\cdot M_{\\mathrm{star}}$","sub_path":"PlotScripts/initialdustprofile.py","file_name":"initialdustprofile.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"252347085","text":"\"\"\"Tests for the simple observer implementation.\"\"\"\n\nimport pytest\n\nfrom hangups import event\n\n\ndef test_event():\n e = event.Event('MyEvent')\n res = []\n a = lambda arg: res.append('a' + arg)\n b = lambda arg: res.append('b' + arg)\n e.add_observer(a)\n e.fire('1')\n e.add_observer(b)\n e.fire('2')\n e.remove_observer(a)\n e.fire('3')\n e.remove_observer(b)\n e.fire('4')\n assert res == ['a1', 'a2', 'b2', 'b3']\n\n\ndef test_already_added():\n e = event.Event('MyEvent')\n a = lambda a: print('A: got {}'.format(a))\n e.add_observer(a)\n with pytest.raises(ValueError):\n e.add_observer(a)\n\n\ndef test_remove_nonexistant():\n e = event.Event('MyEvent')\n a = lambda a: print('A: got {}'.format(a))\n with pytest.raises(ValueError):\n e.remove_observer(a)\n","sub_path":"hangups/test/test_event.py","file_name":"test_event.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"153378895","text":"\"\"\"\nModule for determining Fibonacci numbers\n\"\"\"\n\ndef fib(n):\n result = []\n a, b = 0, 1\n\n while b < n:\n result.append(b)\n a, b = b, a+b\n\n return result\n\n\nif __name__ == '__main__':\n import sys\n\n try:\n index = int(sys.argv[1])\n except:\n index = 25000\n\n result = fib(index)\n print(\"Fibonacci series up to {}\".format(index))\n print(*result)\n\n ","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"335648590","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 18 10:18:23 2016\r\n\r\n@author: huliqun\r\n@email: huliquns@126.com\r\n\"\"\"\r\nfrom wsgiref import simple_server\r\nimport falcon\r\n\r\nfrom workserver.util import DataFormat\r\nfrom workserver.util import LogUtil\r\nfrom workserver.util import SysUtil\r\n\r\nfrom workserver.service import userRegSRV, payMoneySRV, setBaseMoneySRV, getCurrentResultSRV, getGambleResultSRV,\\\r\n getMatchResultSRV, getAccountLogSRV, getdealerSRV, getGameResultSRV, getMatchesSRV, setDealerMatchSRV, getRecommendSRV\r\n\r\n\r\nLogUtil.initLog()\r\nSysUtil.global_init()\r\n# Configure your WSGI server to load \"things.app\" (app is a WSGI callable)\r\napp = falcon.API(middleware=[\r\n DataFormat.JSONTranslator()\r\n])\r\n\r\napp.add_route('/sports/webService/userReg', userRegSRV.userRegResource())\r\napp.add_route('/sports/webService/payMoney', payMoneySRV.payMoneyResource())\r\napp.add_route('/sports/webService/setBaseMoney',\r\n setBaseMoneySRV.setBaseMoneyResource())\r\napp.add_route('/sports/webService/getCurrentResult',\r\n getCurrentResultSRV.getCurrentResultResource())\r\napp.add_route('/sports/webService/getGambleResult',\r\n getGambleResultSRV.getGambleResultResource())\r\n#app.add_route('/sports/webService/getMatchResult', getMatchResultSRV.getMatchResultResource())\r\napp.add_route('/sports/webService/getGameResult',\r\n getGameResultSRV.getGameResultResource())\r\napp.add_route('/sports/webService/getAccountLog',\r\n getAccountLogSRV.getAccountLogResource())\r\n#app.add_route('/sports/webService/getdealer', getdealerSRV.GetDealerSRVResource())\r\napp.add_route('/sports/webService/getRecommend',\r\n getRecommendSRV.GetRecommendSRVResource())\r\napp.add_route('/sports/webService/setDealerMatch',\r\n setDealerMatchSRV.setDealerMatchSRVResource())\r\napp.add_route('/sports/webService/getMatches',\r\n getMatchesSRV.getMatchesResource())\r\n#app.add_route('/sports/webService/dealwithdealer', dealwithdealerSRV.DealWithDealerResource())\r\n\r\n# Useful for debugging problems in your API; works with pdb.set_trace(). You\r\n# can also use Gunicorn to host your app. Gunicorn can be configured to\r\n# auto-restart workers when it detects a code change, and it also works\r\n# with pdb.\r\nif __name__ == '__main__':\r\n httpd = simple_server.make_server('0.0.0.0', 9000, app)\r\n httpd.serve_forever()\r\n\r\n# gunicorn -b 127.0.0.1:9000 MainServer:app\r\n","sub_path":"MainServer.py","file_name":"MainServer.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"339871008","text":"import yaml\nimport csv\nimport os\nfrom tensorboardX import SummaryWriter\n\n\nclass Logger:\n def __init__(self, run_folder, print_logs=True, tensorbard=True):\n\n self._writer = SummaryWriter(run_folder)\n self._run_folder = run_folder\n self._print_logs = print_logs\n self._tensorboard = tensorbard\n\n if not os.path.exists(run_folder):\n os.makedirs(run_folder)\n\n pass\n\n def _print_args(self, args):\n s = '\\nArguments\\n'\n s += '---------------------------------------\\n'\n for key, value in vars(args).items():\n s += f'{key}: {value}\\n'\n s += '---------------------------------------\\n'\n print(s)\n\n def log_args(self, args):\n if self._print_logs:\n self._print_args(args)\n\n args_path = os.path.join(self._run_folder, 'args.yaml')\n yaml.dump(vars(args), open(args_path, 'w'))\n\n def _print_metrics(self, iteration, metrics):\n s = f'{iteration}'\n for key, value in metrics.items():\n s += f' {key} : {value:.3f}'\n print(s)\n\n def log_metrics(self, iteration, metrics):\n if self._print_logs:\n self._print_metrics(iteration, metrics)\n\n if self._tensorboard:\n for key, value in metrics.items():\n self._writer.add_scalar(key, value, global_step=iteration)\n\n csv_path = os.path.join(self._run_folder, 'metrics.csv')\n with open(csv_path, \"a\") as f:\n wr = csv.writer(f)\n # Add header line if file is empty\n if os.path.getsize(csv_path) == 0:\n keys = ['iteration']\n keys.extend(metrics.keys())\n wr.writerow(keys)\n\n values = [iteration]\n values.extend(metrics.values())\n wr.writerow(values)\n","sub_path":"signal/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"80236828","text":"\"\"\"\nExport Math related symbols here\n\"\"\"\nimport os\nimport copy\nimport xlrd\nfrom pdfxml.file_util import load_general, dump_general\nfrom pdfxml.file_util import load_serialization, dump_serialization, test_folder_exist_for_file_path\nfrom pdfxml.path_util import PROJECT_FOLDER, SHARED_FOLDER, infty_cdb_folder, infty_cdb_tmp_folder, infty_cdb_folder\nfrom pdfxml.InftyCDB.data_portal.data_portal_img import fname2shape\n# the im2shape is a pre-build cache of the image size\n# It's useful because the InftyCDB's coordinate is up side down w.r.t. the PDF system\n# im2shape = fname2shape()\nim2shape = None\n\n\n#########\n# utility function\n#########\ndef get_cid2char(elem_list):\n \"\"\"\n from cid to the detail char information\n\n :param elem_list:\n :return:\n \"\"\"\n cid2char = {}\n for elem in elem_list:\n cid2char[elem[\"cid\"]] = elem\n return cid2char\n\n\ndef get_cid2pid(elem_list):\n \"\"\"\n children id to parent id\n\n :param elem_list:\n :return:\n \"\"\"\n cid2pid = {}\n for elem in elem_list:\n cid2pid[elem[\"cid\"]] = elem[\"pid\"]\n return cid2pid\n\n\ndef get_pid2cidset(elem_list):\n \"\"\"\n from parent to set of children id\n\n :param elem_list:\n :return:\n \"\"\"\n pid2cidset = {}\n cid2pid = get_cid2pid(elem_list)\n for cid, pid in cid2pid.items():\n if pid not in pid2cidset:\n pid2cidset[pid] = set()\n pid2cidset[pid].add(cid)\n return pid2cidset\n\n\ndef get_me_idx_list():\n \"\"\"\n get all the me_idx, no matter runnable or not\n\n :return: list[int]\n \"\"\"\n cache_path = \"{}/tmp/me_idx_list.pkl\".format(infty_cdb_folder)\n test_folder_exist_for_file_path(cache_path)\n if os.path.isfile(cache_path):\n return load_serialization(cache_path)\n\n me_xlsx_path = \"{}/InftyCDB-1/resources/me.xlsx\".format(SHARED_FOLDER)\n wb = xlrd.open_workbook(me_xlsx_path)\n sheet_names = wb.sheet_names()\n\n me_idx_list = []\n ws = wb.sheet_by_index(0)\n for r_idx in range(ws.nrows):\n row = ws.row(r_idx)\n me_idx = int(row[20].value)\n me_idx_list.append(me_idx)\n\n me_idx_list = list(set(me_idx_list))\n dump_serialization(me_idx_list, cache_path)\n return me_idx_list\n\n\ndef get_cid2me_idx():\n \"\"\"\n char id to me idx\n :return:\n \"\"\"\n cache = \"{}/cid2me_idx.pkl\".format(infty_cdb_tmp_folder)\n test_folder_exist_for_file_path(cache)\n if os.path.isfile(cache):\n return load_serialization(cache)\n cid2me_idx = {}\n me_xlsx_path = \"{}/InftyCDB-1/resources/me.xlsx\".format(SHARED_FOLDER)\n elem_list = load_me_elems_xlsx(me_xlsx_path)\n for elem in elem_list:\n cid2me_idx[elem['cid']] = elem['me_idx']\n dump_serialization(cid2me_idx, cache)\n return cid2me_idx\n\n\n#############\n# load char information from xlsx file\n#############\ndef load_me_elems_xlsx(infty_cdb_xlsx_path):\n \"\"\"\n\n :param infty_cdb_xlsx_path:\n :return:\n \"\"\"\n global im2shape\n if im2shape is None:\n im2shape = fname2shape()\n\n wb = xlrd.open_workbook(infty_cdb_xlsx_path)\n sheet_names = wb.sheet_names()\n\n me_elems = []\n ws = wb.sheet_by_index(0)\n for r_idx in range(ws.nrows):\n row = ws.row(r_idx)\n # print len(row)\n cid = int(row[0].value)\n font = row[3].value # filter out Accent from horizontal\n code, name, pid, rel = row[4].value, row[5].value, int(row[13].value), row[14].value\n\n code = str(code)\n if code.endswith(\".0\"):\n code = code[:-2]\n\n fname = row[15].value\n me_idx = int(row[20].value)\n #print fname\n h, w = im2shape[fname]\n\n bbox = [float(w.value) for w in row[16:20]]\n\n new_bbox = copy.copy(bbox)\n new_b = h - bbox[3]\n new_t = h - bbox[1]\n new_bbox[1] = new_b\n new_bbox[3] = new_t\n\n me_elems.append({\n 'cid': cid,\n 'code': code,\n 'name': name,\n 'pid': pid,\n 'relation': rel,\n 'raw_bbox': bbox, # upside down\n 'bbox': new_bbox,\n 'fname': fname,\n 'me_idx': me_idx,\n 'shape': im2shape[fname]\n })\n\n return me_elems\n\n\ndef load_char_map(refresh=False):\n \"\"\"\n load mathematical chars from the CSV file\n NOTE: Dec. 10, later use the XLSX file with less noise.\n\n :param refresh:\n :return: the dict from the char id to char info\n \"\"\"\n #cached_path = \"{}/InftyCDB/cache_data/chars.json\".format(PROJECT_FOLDER)\n cached_path = \"{}/tmp/chars.json\".format(infty_cdb_folder)\n test_folder_exist_for_file_path(cached_path)\n if os.path.isfile(cached_path) and not refresh:\n return load_general(cached_path)\n\n print('rebuild cache from the xlsx file')\n me_xlsx_path = \"{}/InftyCDB-1/resources/me.xlsx\".format(SHARED_FOLDER)\n me_elems = load_me_elems_xlsx(me_xlsx_path)\n cid2info = {}\n for me_elem in me_elems:\n cid2info[me_elem['cid']] = me_elem\n\n dump_general(cid2info, cached_path)\n return cid2info\n\n\n#############\n# split the chars at the level of ME\n#############\ndef get_pid2cid_list():\n \"\"\"\n\n :return: map from parent char id to list of children\n \"\"\"\n cache_path = 'pid2cid_list.pkl'\n if os.path.isfile(cache_path):\n return load_serialization(cache_path)\n\n cid2info = load_char_map()\n pid2cid_list = {}\n for cid, info in cid2info.items():\n if info['pid'] == -1:\n continue\n if not pid2cid_list.has_key(info['pid']):\n pid2cid_list[info['pid']] = []\n pid2cid_list[info['pid']].append(cid)\n\n dump_serialization(pid2cid_list, cache_path)\n\n return pid2cid_list\n\n\ndef get_name2code_set():\n \"\"\"\n name is the glyph name,\n code is the unique id for the pair of glyph name & font\n\n one glyph name could have multiple code in different fonts.\n\n :return:\n \"\"\"\n from pdfxml.path_util import SHARED_FOLDER\n #name2code_cache_path = \"{}/tmp/name2code.pkl\".format(infty_cdb_folder)\n name2code_cache_path = \"{}/InftyCDB-1/cache_data/name2code.json\".format(SHARED_FOLDER)\n if os.path.isfile(name2code_cache_path):\n name2code_list = load_general(name2code_cache_path)\n name2code_set = {}\n for name, code_list in name2code_list.items():\n name2code_set[name] = set(code_list)\n return name2code_set\n\n cid2info = load_char_map()\n name2code_set = {}\n for c in cid2info.values():\n if c['name'] not in name2code_set:\n name2code_set[c['name']] = set()\n name2code_set[c['name']].add(c['code'])\n\n name2code_list = {}\n for name, code_set in name2code_set.items():\n name2code_list[name] = list(code_set)\n dump_general(name2code_list, name2code_cache_path)\n\n return name2code_set\n\n\ndef get_code2name():\n \"\"\"\n based on name2code_set to build map from code 2 name\n :return:\n \"\"\"\n name2code_set = get_name2code_set()\n code2name = {}\n for name, code_set in name2code_set.items():\n for code in code_set:\n code2name[code] = name\n return code2name\n\n\n##################\n# batch processing\n##################\n\n# NOTE : the coordinate is with the left-top as the original point\n\ndef filter_me():\n \"\"\"\n InftyCDB-1.csv is the raw data file,\n This script will print the line related to ME to the screen\n and pipe them to another file\n\n :return:\n \"\"\"\n full_infty_cdb_path = \"{}/InftyCDB-1.csv\".format(infty_cdb_folder)\n lines = open(full_infty_cdb_path).readlines()\n for line in lines:\n ws = line.split(\",\")\n if ws[6][1:-1] == \"math\":\n print(line.strip())\n\n\nif __name__ == \"__main__\":\n #infty_cdb_xlsx_path = infty_cdb_folder+\"/tmp/me.xlsx\"\n #load_me_elems_xlsx()\n #load_char_map()\n get_name2code_set()\n","sub_path":"InftyCDB/data_portal/data_portal.py","file_name":"data_portal.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"132089696","text":"from configparser import ConfigParser\nfrom datetime import date, datetime, timedelta\nimport numpy as np\nimport pandas as pd\nfrom pytz import timezone\nfrom scipy import stats\n\nclass DataLoader:\n def __init__(self, parser: ConfigParser):\n self.swiss_cases = pd.read_csv(parser.get(\"urls\", \"swiss_cases\"))\n self.swiss_fatalities = pd.read_csv(parser.get(\"urls\", \"swiss_fatalities\"))\n self.swiss_hospitalizations = pd.read_csv(\n parser.get(\"urls\", \"swiss_hospitalizations\")\n )\n self.swiss_icu = pd.read_csv(parser.get(\"urls\", \"swiss_icu\"))\n self.swiss_releases = pd.read_csv(parser.get(\"urls\", \"swiss_releases\"))\n \n self.swiss_demography = pd.read_csv(\n parser.get(\"urls\", \"swiss_demography\"), index_col=0\n )\n self.world_cases = self.__simplify_world_data(\n pd.read_csv(parser.get(\"urls\", \"world_cases\"))\n )\n self.world_fataltities = self.__simplify_world_data(\n pd.read_csv(parser.get(\"urls\", \"world_fatalities\"))\n )\n self.world_population = self.__get_world_population()\n\n self.swiss_cases_by_date = self.swiss_cases.set_index(\"Date\")\n self.swiss_fatalities_by_date = self.swiss_fatalities.set_index(\"Date\")\n self.swiss_hospitalizations_by_date = self.swiss_hospitalizations.set_index(\n \"Date\"\n )\n\n self.swiss_cases_by_date_filled = self.swiss_cases_by_date.fillna(\n method=\"ffill\", axis=0\n )\n\n self.swiss_cases_by_date_diff = self.swiss_cases_by_date_filled.diff().replace(\n 0, float(\"nan\")\n )\n self.swiss_cases_by_date_diff[\"date_label\"] = [\n date.fromisoformat(d).strftime(\"%d. %m.\")\n for d in self.swiss_cases_by_date_diff.index.values\n ]\n \n self.swiss_fatalities_by_date_diff = self.swiss_fatalities_by_date.diff().replace(\n 0, float(\"nan\")\n )\n \n self.swiss_hospitalizations_by_date_diff = self.swiss_hospitalizations_by_date.diff().replace(\n 0, float(\"nan\")\n )\n\n self.swiss_cases_by_date_filled = self.swiss_cases_by_date.fillna(\n method=\"ffill\", axis=0\n )\n\n self.swiss_fatalities_by_date_filled = self.swiss_fatalities_by_date.fillna(\n method=\"ffill\", axis=0\n )\n \n self.swiss_hospitalizations_by_date_filled = self.swiss_hospitalizations_by_date.fillna(\n method=\"ffill\", axis=0\n )\n\n self.swiss_case_fatality_rates = (\n self.swiss_fatalities_by_date_filled / self.swiss_cases_by_date_filled\n )\n\n self.swiss_cases_by_date_filled_per_capita = (\n self.__get_swiss_cases_by_date_filled_per_capita()\n )\n\n self.latest_date = self.__get_latest_date()\n self.updated_cantons = self.__get_updated_cantons()\n self.new_swiss_cases = self.__get_new_cases()\n self.total_swiss_cases = self.__get_total_swiss_cases()\n self.total_swiss_fatalities = self.__get_total_swiss_fatalities()\n self.swiss_case_fatality_rate = (\n self.total_swiss_fatalities / self.total_swiss_cases\n )\n\n # Put the date at the end\n self.swiss_cases_as_dict = self.swiss_cases.to_dict(\"list\")\n date_tmp = self.swiss_cases_as_dict.pop(\"Date\")\n self.swiss_cases_as_dict[\"Date\"] = date_tmp\n self.swiss_cases_normalized_as_dict = (\n self.__get_swiss_cases_as_normalized_dict()\n )\n\n self.swiss_fatalities_as_dict = self.swiss_fatalities.to_dict(\"list\")\n self.canton_labels = [\n canton\n for canton in self.swiss_cases_as_dict\n if canton != \"AT\" and canton != \"Date\"\n ]\n self.cantonal_centres = self.__get_cantonal_centres()\n \n #\n # Moving average showing development\n #\n\n self.moving_total = self.__get_moving_total(\n self.swiss_cases_by_date.diff()\n ).replace(0, float(\"nan\"))\n \n self.swiss_cases_by_date_diff[\"AT_rolling\"] = np.round(\n self.swiss_cases_by_date_diff[\"AT\"]\n .rolling(7, center=True)\n .mean(),\n 0,\n )\n \n self.swiss_fatalities_by_date_diff[\"AT_rolling\"] = np.round(\n self.swiss_fatalities_by_date_diff[\"AT\"]\n .rolling(7, center=True)\n .mean(),\n 0,\n )\n \n #\n # World related data\n #\n\n self.world_case_fatality_rate = (\n self.world_fataltities.iloc[-1] / self.world_cases.iloc[-1]\n )\n\n self.swiss_world_cases_normalized = self.__get_swiss_world_cases_normalized()\n \n #\n # Some regression analysis on the data\n #\n self.prevalence_density_regression = self.__get_regression(\n self.swiss_demography[\"Density\"],\n self.swiss_cases_by_date_filled_per_capita.iloc[-1],\n )\n\n self.cfr_age_regression = self.__get_regression(\n self.swiss_demography[\"O65\"], self.swiss_case_fatality_rates.iloc[-1]\n )\n\n self.scaled_cases = self.__get_scaled_cases()\n\n def __get_latest_date(self):\n return self.swiss_cases.iloc[len(self.swiss_cases) - 1][\"Date\"]\n\n def __get_updated_cantons(self):\n l = len(self.swiss_cases_by_date)\n return [\n canton\n for canton in self.swiss_cases_by_date.iloc[l - 1][\n self.swiss_cases_by_date.iloc[l - 1].notnull()\n ].index\n ]\n\n def __get_swiss_cases_by_date_filled_per_capita(self):\n tmp = self.swiss_cases_by_date_filled.copy()\n\n for column in tmp:\n tmp[column] = (\n tmp[column] / self.swiss_demography[\"Population\"][column] * 10000\n )\n return tmp\n\n def __get_new_cases(self):\n if (\n date.fromisoformat(self.latest_date)\n != datetime.now(timezone(\"Europe/Kiev\")).date()\n ):\n return 0\n\n return (\n self.swiss_cases_by_date_filled.iloc[-1][\"AT\"]\n - self.swiss_cases_by_date_filled.iloc[-2][\"AT\"]\n )\n\n def __get_total_swiss_cases(self):\n return self.swiss_cases_by_date_filled.iloc[- 1][\"AT\"]\n\n def __get_total_swiss_fatalities(self):\n return self.swiss_fatalities_by_date_filled.iloc[-1][\"AT\"]\n\n def __get_swiss_cases_as_normalized_dict(self):\n tmp = [\n (\n str(canton),\n [\n round(i, 2)\n for i in self.swiss_cases_as_dict[canton]\n / self.swiss_demography[\"Population\"][canton]\n * 10000\n ],\n )\n for canton in self.swiss_cases_as_dict\n if canton != \"Date\"\n ]\n tmp.append((\"Date\", self.swiss_cases_as_dict[\"Date\"]))\n return dict(tmp)\n\n def __simplify_world_data(self, df: pd.DataFrame):\n df.drop(columns=[\"Lat\", \"Long\"], inplace=True)\n df[\"Province/State\"].fillna(\"\", inplace=True)\n df = df.rename(columns={\"Country/Region\": \"Day\"})\n df = df.groupby(\"Day\").sum()\n df = df.T\n df.drop(\n df.columns.difference(\n [\"France\", \"Germany\", \"Italy\", \"Korea, South\", \"Spain\", \"US\", \"United Kingdom\", \"Switzerland\",]\n ),\n 1,\n inplace=True,\n )\n df.index = range(0, len(df))\n return df\n\n def __get_swiss_world_cases_normalized(self, min_prevalence: int = 0.4):\n tmp = self.world_cases.copy()\n # Don't take today, as values are usually very incomplete\n tmp[\"Austria\"] = pd.Series(self.swiss_cases_as_dict[\"AT\"][:-1])\n\n for column in tmp:\n tmp[column] = tmp[column] / self.world_population[column] * 10000\n\n tmp[tmp < min_prevalence] = 0\n for column in tmp:\n while tmp[column].iloc[0] == 0:\n tmp[column] = tmp[column].shift(-1)\n tmp.dropna(how=\"all\", inplace=True)\n\n return tmp\n\n def __get_regression(self, x, y):\n df = pd.DataFrame([x, y])\n df = df.dropna(axis=1, how=\"any\")\n slope, intercept, r_value, p_value, std_err = stats.linregress(\n df.iloc[0], df.iloc[1]\n )\n m = df.iloc[0].min() + (df.iloc[0].max() - df.iloc[0].min()) / 2\n return {\n \"slope\": slope,\n \"intercept\": intercept,\n \"r_value\": r_value,\n \"p_value\": p_value,\n \"std_err\": std_err,\n \"x\": [df.iloc[0].min(), m, df.iloc[0].max()],\n \"y\": [\n slope * df.iloc[0].min() + intercept,\n slope * m + intercept,\n slope * df.iloc[0].max() + intercept,\n ],\n }\n\n def __get_scaled_cases(self):\n cases = self.swiss_cases_by_date_filled.iloc[-1][0:-1]\n min_cases = cases.min()\n max_cases = cases.max()\n scaled_cases = (cases - min_cases) / (max_cases - min_cases) * (20) + 10\n return scaled_cases\n\n def __get_moving_total(self, df, days=7):\n offset = days - 1\n df_moving_total = df[0:0]\n for i in range(0, len(df)):\n start = max(0, i - offset)\n d = pd.Series(df.iloc[start : i + 1].sum().to_dict())\n d.name = df.index[i]\n df_moving_total = df_moving_total.append(d)\n\n # Add the label for the date range (previous week)\n date_labels = []\n for d in df_moving_total.index.values:\n today = date.fromisoformat(d)\n date_labels.append(\n (today - timedelta(days=7)).strftime(\"%d. %m.\")\n + \" – \"\n + today.strftime(\"%d. %m.\")\n )\n\n df_moving_total[\"date_label\"] = date_labels\n\n return df_moving_total\n\n def __get_world_population(self):\n return {\n \"France\": 65273511,\n \"Germany\": 83783942,\n \"Italy\": 60461826,\n \"Spain\": 46754778,\n \"US\": 331002651,\n \"United Kingdom\": 67886011,\n \"Switzerland\": 8654622,\n \"Korea, South\": 51269185,\n \"Austria\": 8902600,\n }\n\n def __get_cantonal_centres(self):\n return {\n \"W\": {\"lat\": 48.2084885, \"lon\": 16.3720798},\n \"K\": {\"lat\": 46.624253, \"lon\": 14.307528},\n \"B\": {\"lat\": 47.54565, \"lon\": 16.52327},\n \"OÖ\": {\"lat\": 48.10639, \"lon\": 13.98611},\n \"NÖ\": {\"lat\": 48.533332, \"lon\": 15.749997},\n \"T\": {\"lat\": 47.26266, \"lon\": 11.39454},\n \"S\": {\"lat\": 47.311195, \"lon\": 13.033229},\n \"ST\": {\"lat\": 47.276668, \"lon\": 14.921371},\n \"V\": {\"lat\": 47.30311, \"lon\": 9.8471},\n }\n","sub_path":"dashcoch/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":10781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"146967898","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom .forms import ProfileForm,ProjectForm,VotesForm\nfrom .models import Project,Profile,Votes\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializer import ProjectSerializer,ProfileSerializer\nfrom rest_framework import status\n\n# Create your views here.\n\ndef index(request):\n project = Project.objects.all()\n\n profile = Profile.objects.all()\n return render(request,'index.html',{\"project\":project,\"profile\":profile})\n\n@login_required(login_url='/accounts/login/')\ndef images(request,project_id):\n project = Project.objects.get(id = project_id) \n votes = Votes.objects.filter(project = project.id).all() \n return render(request,\"pro.html\", {\"project\":project,\"votes\":votes})\n\n@login_required(login_url='/accounts/login/')\ndef myProfile(request,id):\n user = User.objects.get(id = id)\n profiles = Profile.objects.get(user = user)\n \n return render(request,'profile.html',{\"profiles\":profiles,\"user\":user})\n\n@login_required(login_url='/accounts/login/')\ndef profile(request):\n current_user = request.user\n if request.method == 'POST':\n form = ProfileForm(request.POST, request.FILES)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.user = current_user\n profile.save()\n\n return redirect(index)\n\n else:\n form = ProfileForm()\n return render(request, 'pro_form.html', {\"form\": form})\n\ndef project(request):\n current_user = request.user\n if request.method == 'POST':\n form = ProjectForm(request.POST, request.FILES)\n if form.is_valid():\n project = form.save(commit=False)\n project.user = current_user\n project.save()\n\n return redirect(index)\n\n else:\n form = ProjectForm()\n return render(request, 'project.html', {\"form\": form})\n\n\n\ndef votes(request,id):\n current_user = request.user\n post = Project.objects.get(id=id)\n votes = Votes.objects.filter(project=post)\n \n if request.method == 'POST':\n vote = VotesForm(request.POST)\n if vote.is_valid():\n design = vote.cleaned_data['design']\n usability = vote.cleaned_data['usability']\n content = vote.cleaned_data['content']\n rating = Votes(design=design,usability=usability,content=content,user=request.user,project=post)\n rating.save()\n return redirect(index) \n else:\n form = VotesForm()\n return render(request, 'vote.html', {\"form\":form,'post':post,'user':current_user,'votes':votes})\n\ndef search_results(request):\n\n if 'project' in request.GET and request.GET[\"project\"]:\n search_term = request.GET.get(\"project\")\n searched = Project.search_project(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html',{\"message\":message,\"searched\": searched})\n\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html',{\"message\":message}) \n\nclass ProfileList(APIView):\n def get(self, request, format=None):\n serializers = ProfileSerializer(data=request.data)\n if serializers.is_valid():\n serializers.save()\n return Response(serializers.data, status=status.HTTP_201_CREATED)\n return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)\n\n","sub_path":"awwrds/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"354469391","text":"#! -*- coding: utf-8 -*-\n\n#---------------------------------\n# モジュールのインポート\n#---------------------------------\nimport os\nimport argparse\n\nfrom data_loader.data_loader import DataLoaderMNIST\nfrom data_loader.data_loader import DataLoaderCIFAR10\n\nfrom trainer.trainer import TrainerMLP, TrainerCNN, TrainerResNet\n\n#---------------------------------\n# 定数定義\n#---------------------------------\n\n#---------------------------------\n# 関数\n#---------------------------------\ndef ArgParser():\n\tparser = argparse.ArgumentParser(description='TensorFlowの学習実装サンプル\\n'\n\t\t\t\t\t\t\t\t\t\t\t\t\t' * No.01: MNISTデータセットを用いた全結合NN学習サンプル\\n'\n\t\t\t\t\t\t\t\t\t\t\t\t\t' * No.02: CIFAR-10データセットを用いたCNN学習サンプル\\n'\n\t\t\t\t\t\t\t\t\t\t\t\t\t' * No.03: CIFAR-10データセットを用いたResNet学習サンプル',\n\t\t\t\tformatter_class=argparse.RawTextHelpFormatter)\n\n\t# --- 引数を追加 ---\n\tparser.add_argument('--data_type', dest='data_type', type=str, default='CIFAR-10', required=False, \\\n\t\t\thelp='データ種別(MNIST, CIFAR-10)')\n\tparser.add_argument('--dataset_dir', dest='dataset_dir', type=str, default=None, required=True, \\\n\t\t\thelp='データセットディレクトリ')\n\tparser.add_argument('--model_type', dest='model_type', type=str, default='ResNet', required=False, \\\n\t\t\thelp='モデル種別(MLP, SimpleCNN, SimpleResNet)')\n\tparser.add_argument('--result_dir', dest='result_dir', type=str, default='./result', required=False, \\\n\t\t\thelp='学習結果の出力先ディレクトリ')\n\n\targs = parser.parse_args()\n\n\treturn args\n\ndef main():\n\t# --- 引数処理 ---\n\targs = ArgParser()\n\tprint('[INFO] Arguments')\n\tprint(' * args.data_type = {}'.format(args.data_type))\n\tprint(' * args.dataset_dir = {}'.format(args.dataset_dir))\n\tprint(' * args.model_type = {}'.format(args.model_type))\n\tprint(' * args.result_dir = {}'.format(args.result_dir))\n\t\n\tif (args.data_type == \"MNIST\"):\n\t\tdataset = DataLoaderMNIST(args.dataset_dir)\n\t\tprint(dataset.train_images.shape)\n\t\tprint(dataset.train_labels.shape)\n\t\tprint(dataset.test_images.shape)\n\t\tprint(dataset.test_labels.shape)\n\t\t\n\t\tx_train = dataset.train_images / 255\n\t\ty_train = dataset.train_labels\n\t\tx_test = dataset.test_images / 255\n\t\ty_test = dataset.test_labels\n\t\toutput_dims = dataset.output_dims\n\telif (args.data_type == \"CIFAR-10\"):\n\t\tdataset = DataLoaderCIFAR10(args.dataset_dir)\n\t\tprint(dataset.train_images.shape)\n\t\tprint(dataset.train_labels.shape)\n\t\tprint(dataset.test_images.shape)\n\t\tprint(dataset.test_labels.shape)\n\t\t\n\t\tx_train = dataset.train_images / 255\n\t\ty_train = dataset.train_labels\n\t\tx_test = dataset.test_images / 255\n\t\ty_test = dataset.test_labels\n\t\toutput_dims = dataset.output_dims\n\telse:\n\t\tprint('[ERROR] Unknown data_type: {}'.format(args.data_type))\n\t\tquit()\n\t\n\tif (args.model_type == 'MLP'):\n\t\ttrainer = TrainerMLP(dataset.train_images.shape[1:], output_dir=args.result_dir)\n\t\ttrainer.fit(x_train, y_train, x_test=x_test, y_test=y_test)\n\t\ttrainer.save_model()\n\t\t\n\t\tpredictions = trainer.predict(x_test)\n\t\tprint('\\nPredictions(shape): {}'.format(predictions.shape))\n\telif (args.model_type == 'SimpleCNN'):\n\t\ttrainer = TrainerCNN(dataset.train_images.shape[1:], output_dir=args.result_dir)\n\t\ttrainer.fit(x_train, y_train, x_test=x_test, y_test=y_test)\n\t\ttrainer.save_model()\n\t\t\n\t\tpredictions = trainer.predict(x_test)\n\t\tprint('\\nPredictions(shape): {}'.format(predictions.shape))\n\telif (args.model_type == 'SimpleResNet'):\n\t\ttrainer = TrainerResNet(dataset.train_images.shape[1:], output_dims, output_dir=args.result_dir)\n\t\ttrainer.fit(x_train, y_train, x_test=x_test, y_test=y_test)\n\t\ttrainer.save_model()\n\t\t\n\t\tpredictions = trainer.predict(x_test)\n\t\tprint('\\nPredictions(shape): {}'.format(predictions.shape))\n\telse:\n\t\tprint('[ERROR] Unknown model_type: {}'.format(args.model_type))\n\t\tquit()\n\n\treturn\n\n#---------------------------------\n# メイン処理\n#---------------------------------\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"python/tensorflow_sample/Ver2.x/04_compare_models/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"359333568","text":"import time\r\nimport serial\r\nser = serial.Serial('COM7', 9600,timeout=None) # Establish the connection on a specific port\r\ntime.sleep(2)\r\n#sol=\"RLFFBBrlDDRLFFBBrlLLRLFFBBrlDRLFFBBrldfRLFFBBrlDDRLFFBBrlRLRLFFBBrlDRLFFBBrlFLBBRRDBBRLFFBBrlDRLFFBBrlFFRLFFBBrlDRLFFBBrlRRBBDD\"\r\n#sol=sol[::-1].swapcase()\r\n#for i in sol[::-1]:\r\n# ser.write(i.encode())\r\n##for i in range(60):\r\n## print(\"start\"+str(i))\r\n## ser.write('F'.encode())\r\n## print(ser.isOpen())\r\n## print(\"end\"+str(i))\r\n##time.sleep(30)\r\nser.write('R'.encode())\r\nser.write('L'.encode())\r\nfor i in range(60):\r\n print(\"start\"+str(i))\r\n ser.write('D'.encode())\r\n time.sleep(1)\r\n ser.write('D'.encode())\r\n time.sleep(1)\r\n ser.write('F'.encode())\r\n## print(ser.isOpen())\r\n## print(\"end\"+str(i))\r\n##print(\"done\")\r\n##time.sleep(1)\r\n##for i in range(10):\r\n## ser.write('F'.encode())\r\n##time.sleep(30)\r\n##for i in range(10):\r\n## ser.write('R'.encode())\r\n##print(\"done\")\r\n##time.sleep(1)\r\n##\r\n##\r\n##ser.write('R'.encode())\r\n##time.sleep(1)\r\n##\r\n##ser.write('F'.encode())\r\n##time.sleep(1)\r\n##ser.write('B'.encode())\r\n","sub_path":"tests/pyserialtest.py","file_name":"pyserialtest.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"525159873","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 16 16:56:32 2017\n\n@author: Caiyd\n\"\"\"\n\nimport sys\nfrom collections import defaultdict\nimport click\nimport numpy as np\n\n\ndef loadRefdb(refdb):\n win2pos = defaultdict(dict)\n pos2win = defaultdict(dict)\n with open(refdb) as f:\n for line in f:\n line = line.strip().split('\\t')\n chrom = line[0]\n win = int(line[1])\n pos = int(line[2])\n win2pos[chrom][win] = pos\n pos2win[chrom][pos] = win\n return win2pos, pos2win\n\n\ndef loadEffWinId(gain_win, loss_win, win2pos):\n effWinId = defaultdict(set)\n effPos = defaultdict(set)\n gain_eff_window_data = np.genfromtxt(gain_win, dtype='unicode_', delimiter='\\t')\n loss_eff_window_data = np.genfromtxt(loss_win, dtype='unicode_', delimiter='\\t')\n all_eff_window_data = np.vstack([gain_eff_window_data, loss_eff_window_data])\n del(gain_eff_window_data)\n del(loss_eff_window_data)\n for line in all_eff_window_data:\n chrom = line[0]\n win = int(line[1])\n pos = win2pos[chrom][win]\n effWinId[chrom].add(win)\n effPos[chrom].add(pos)\n return effWinId, effPos\n\n\ndef loadCnvr(cnvr, effPos, effWinId, pos2win, step_size):\n segWin = defaultdict(list)\n raw_cnv_data = np.genfromtxt(cnvr, dtype='unicode_', delimiter='\\t')\n n_empty_value = np.sum(raw_cnv_data == '')\n if n_empty_value != 0:\n print('There are %s empty value in the cnvr file!')\n sys.exit()\n chrom_ay = raw_cnv_data[1:, 0]\n start_ay = raw_cnv_data[1:, 1].astype('int64')\n end_ay = raw_cnv_data[1:, 2].astype('int64')\n chrom_list = list(chrom_ay)\n uniq_chrom_list = list(set(chrom_list))\n uniq_chrom_list.sort(key=chrom_list.index)\n del(chrom_list)\n for chrom in uniq_chrom_list:\n tmp_effWinId_set = effWinId[chrom]\n tmp_effPos_set = effPos[chrom]\n tmp_pos2win = pos2win[chrom]\n tmp_start_ay = start_ay[chrom_ay == chrom]\n tmp_end_ay = end_ay[chrom_ay == chrom]\n for start, end in zip(tmp_start_ay, tmp_end_ay):\n end -= step_size\n for pos in range(start, end, step_size):\n if pos in tmp_effPos_set:\n win = tmp_pos2win[pos]\n assert win in tmp_effWinId_set\n segWin[chrom].append(win)\n segWin[chrom].append('#')\n return segWin, uniq_chrom_list, raw_cnv_data\n\n\ndef loadNormfile(normfile, sample_name, segWin, uniq_chrom_list):\n cnv_mid_list = []\n cnv_mid_list.append(sample_name)\n with open(normfile) as f:\n for n_chrom, query_chrom in enumerate(uniq_chrom_list):\n print('query_chrom is %s' % query_chrom)\n win_list = segWin[query_chrom]\n win_iter = iter(win_list)\n query_win = next(win_iter)\n line = next(f).strip().split('\\t')\n print(line)\n chrom = line[0]\n win = int(line[1])\n depth = float(line[2])\n tmp_depth_list = []\n n_line = 0\n if win == query_win:\n tmp_depth_list.append(depth)\n query_win = next(win_iter)\n notFinished = True\n try:\n n_iter = 0\n while notFinished:\n line = next(f).strip().split('\\t')\n n_line += 1\n chrom = line[0]\n win = int(line[1])\n depth = float(line[2])\n if win == query_win and chrom == query_chrom:\n tmp_depth_list.append(depth)\n query_win = next(win_iter)\n if query_win == '#':\n cnv_mid_list.append(str(np.median(tmp_depth_list)))\n tmp_depth_list = []\n try:\n query_win = next(win_iter)\n except StopIteration:\n notFinished = False\n print(line)\n print(\"n_line is %s\" % n_line)\n print(\"n_iter is %s\" % n_iter)\n print(\"chrom is %s\" % chrom)\n print(\"query_chrom is %s\" % query_chrom)\n print(\"tmp_depth_list is %s \" % len(tmp_depth_list))\n print(\"cnv_mid_list is %s\" % len(cnv_mid_list))\n n_iter += 1\n except StopIteration:\n continue\n cnv_mid_list = [str(x) for x in cnv_mid_list]\n return cnv_mid_list\n\n\n@click.command()\n@click.option('-S', '--step_size', default=400)\n@click.argument('refdb')\n@click.argument('cnvr')\n@click.argument('gain_win')\n@click.argument('loss_win')\n@click.argument('sample_name_file')\n@click.argument('norm_list_file')\n@click.argument('out')\ndef main(step_size, refdb, cnvr, gain_win, loss_win, sample_name_file, norm_list_file, out):\n print(\"begain to load refdb\")\n win2pos, pos2win = loadRefdb(refdb)\n print(\"begain to load EffWinId\")\n effWinId, effPos = loadEffWinId(gain_win, loss_win, win2pos)\n print(\"begain to load Cnvr\")\n segWin, uniq_chrom_list, raw_cnv_data = loadCnvr(cnvr, effPos, effWinId, pos2win, step_size)\n name_list = []\n norm_list = []\n with open(sample_name_file) as f:\n for line in f:\n name = line.strip()\n name_list.append(name)\n with open(norm_list_file) as f:\n for line in f:\n line = line.strip()\n norm_list.append(line)\n add_cnv_list = []\n for sample_name, normfile in zip(name_list, norm_list):\n print(\"sample is %s\" % sample_name)\n print(\"file is %s\" % sample_name)\n cnv_mid_list = loadNormfile(normfile, sample_name, segWin, uniq_chrom_list)\n add_cnv_list.append(cnv_mid_list)\n add_cnv_ay = np.array(add_cnv_list).T\n print(\"begin to merge\")\n all_cnv_ay = np.concatenate((raw_cnv_data, add_cnv_ay), axis=1)\n with open(out, 'w') as f:\n for ay in all_cnv_ay:\n f.write('\\t'.join(ay) + '\\n')\n\nif __name__ == '__main__':\n main()\n","sub_path":"cnv_tools/addSampleToCnvr.py","file_name":"addSampleToCnvr.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"72284277","text":"import pygame\r\nimport math\r\nimport random\r\nfrom pygame import mixer # it is atlas that help us to handle all kinds of music inside the game\r\n\r\n# initialising the pygame (always)\r\npygame.init()\r\n\r\n\r\n\r\n\r\n# create the surface (i.e., screen) (width, height)\r\nsurface = pygame.display.set_mode((900, 600))\r\n\r\n# Changing title and game_icon\r\npygame.display.set_caption('Ghost Shooting')\r\ngame_icon = pygame.image.load('Aircraft 24 pxl.png')\r\npygame.display.set_icon(game_icon)\r\n\r\n# Loading the background image\r\nbackground_img = pygame.image.load('background image.jpg')\r\n\r\n# loading and playing the background sound\r\nmixer.music.load('background sound.mp3') # music - used to play the sound continuously (used for long sound)\r\nmixer.music.play(-1) # to play the music again and again (looping)\r\n\r\n\r\n\r\n\r\n# adding aircraft image and setting x and y co-ordinates\r\naircraft_img = pygame.image.load('aircraft.png')\r\naircraft_X = 420\r\naircraft_Y = 520\r\naircraft_X_change = 0\r\n\r\n# adding ghost image and setting x and y co-ordinates\r\nghost_img = []\r\nghost_X = []\r\nghost_Y = []\r\nghost_X_change = []\r\nghost_Y_change = []\r\nno_of_ghosts = 10\r\n\r\nfor i in range(no_of_ghosts ):\r\n ghost_img.append(pygame.image.load('red ghost.png'))\r\n ghost_X.append(random.randint(0, 836))\r\n ghost_Y.append(random.randint(0, 150))\r\n ghost_X_change.append(0.7) # change of ghost_X_change pxls per while loop\r\n ghost_Y_change.append(50) # change of ghost_Y_change pxls every time\r\n\r\n# adding missile image and setting x and y co-ordinates\r\n# load - missile can't be seen on surface\r\n# launch - missile is currently moving\r\nmissile_img = pygame.image.load('missile.png')\r\nmissile_X = 0\r\nmissile_Y = 520\r\nmissile_X_change = 0\r\nmissile_Y_change = 12\r\nmissile_state = 'load'\r\n\r\n\r\n\r\n\r\n\r\n# Selecting font and it's size to display 'score'\r\nscore_value = 0\r\nscore_font = pygame.font.Font('freesansbold.ttf', 25) # (font name, size)\r\ntext_X = 10 # pxl distance where score has to be shown\r\ntext_Y = 10\r\n\r\n# Selecting font and it's size to display 'Game Over' and 'Final Score'\r\ngame_over_font = pygame.font.Font('freesansbold.ttf', 65 )\r\nfinal_score_font = pygame.font.Font('freesansbold.ttf', 50 )\r\n\r\n# Selecting font and it's size to display Name of game, 'Pause' and functions of keys to play the game\r\ncommon_font = pygame.font.Font('freesansbold.ttf', 65)\r\nkey_functions_font = pygame.font.Font('freesansbold.ttf', 30)\r\n\r\n\r\n\r\n\r\n# blit = draw -> to draw image of aircraft on surface\r\ndef draw_aircraft(x, y):\r\n surface.blit(aircraft_img , (x, y))\r\n\r\n# blit = draw -> to draw image of ghost on surface\r\ndef draw_ghost(x, y, i):\r\n surface.blit(ghost_img[i], (x, y))\r\n\r\n# function to launch the missile from the aircraft\r\ndef launch_missile(x, y):\r\n global missile_state\r\n missile_state = 'launch'\r\n surface.blit(missile_img, (x + 20, y))\r\n\r\n# function to show the score\r\ndef show_score(x, y):\r\n score = score_font.render('SCORE: ' + str(score_value), True, (0, 0, 0))\r\n surface.blit(score, (x, y))\r\n\r\n\r\n\r\n# function to check the collision between missile and ghost\r\ndef check_collision(ghost_X, ghost_Y, missile_X, missile_Y):\r\n D = math.sqrt(pow(ghost_X - missile_X, 2) + pow(ghost_Y - missile_Y, 2))\r\n if D < 35:\r\n return True\r\n\r\n\r\n\r\n# function to pause/resume the game and to display functions of the keys\r\ndef pause_resume() :\r\n is_paused = True\r\n while is_paused :\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_p :\r\n is_paused = False\r\n if event.key == pygame.K_q :\r\n quit()\r\n if event.type == pygame.QUIT:\r\n quit()\r\n\r\n pygame.display.update()\r\n surface.fill((0, 200, 0))\r\n\r\n display_pause = common_font.render('PAUSED', True, (0, 0, 0))\r\n surface.blit(display_pause, (325, 50))\r\n\r\n display_key_functions1 = key_functions_font.render('Press left arrow key/a to move the aircraft left. ', True,(0, 0, 0))\r\n surface.blit(display_key_functions1, (10, 200))\r\n\r\n display_key_functions2 = key_functions_font.render('Press right arrow key/d to move the aircraft right. ', True,(0, 0, 0))\r\n surface.blit(display_key_functions2, (10, 250))\r\n\r\n display_key_functions3 = key_functions_font.render('Press space to launch missile.', True, (0, 0, 0))\r\n surface.blit(display_key_functions3, (10, 300))\r\n\r\n display_key_functions4 = key_functions_font.render('Press P to pause and resume.', True, (0, 0, 0))\r\n surface.blit(display_key_functions4, (10, 350))\r\n\r\n display_key_functions5 = key_functions_font.render('Press Q or cross to quit.', True, (0, 0, 0))\r\n surface.blit(display_key_functions5, (10, 400))\r\n\r\n# function to print 'Game Over' and 'Final Score'\r\ndef game_over_text():\r\n text_game_over = game_over_font.render('GAME OVER!', True, (0, 0, 0))\r\n surface.blit(text_game_over, (225, 200))\r\n text_final_score = final_score_font.render('FINAL SCORE: ' + str(score_value), True, (0, 0, 0))\r\n surface.blit(text_final_score, (230, 270))\r\n\r\n# function to display completion of level\r\ndef level_complete() :\r\n is_paused = True\r\n while is_paused :\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_p :\r\n is_paused = False\r\n if event.key == pygame.K_q :\r\n quit()\r\n if event.type == pygame.QUIT:\r\n quit()\r\n\r\n pygame.display.update()\r\n surface.fill((0, 200, 0))\r\n\r\n display_level_complete = common_font.render('Level Completed', True, (0, 0, 0))\r\n surface.blit(display_level_complete, (150, 200))\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Starting - displaying name of game and some functions of the keys\r\nnot_started = True\r\nwhile not_started :\r\n pygame.display.update()\r\n surface.fill((255, 128, 0))\r\n\r\n game_name = common_font.render('GHOST SHOOTING', True, (0, 0, 0))\r\n surface.blit(game_name, (150, 50))\r\n\r\n display_action1 = key_functions_font.render('Press S to start.', True,(0, 0, 0))\r\n surface.blit(display_action1, (10, 150))\r\n\r\n display_action2 = key_functions_font.render('Press P to pause/resume and for functions of the keys used.', True,(0, 0, 0))\r\n surface.blit(display_action2, (10, 200))\r\n\r\n display_action3 = key_functions_font.render('Press Q or cross to quit.', True,(0, 0, 0))\r\n surface.blit(display_action3, (10, 250))\r\n\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_s :\r\n not_started = False\r\n if event.type == pygame.QUIT or event.key == pygame.K_q:\r\n quit()\r\n if event.type == pygame.QUIT :\r\n quit()\r\n\r\n\r\n# Game loop so to keep game window open till the close button(cross button) is not pressed\r\ncarry_on = True\r\nwhile carry_on: # the operations which to be always on surface (display screen) should be under while loop\r\n pygame.display.update() # (always) - since objects will move on surface (screen) so it should always be updating\r\n\r\n surface.blit(background_img, (0, 0))\r\n draw_aircraft(aircraft_X,aircraft_Y) # calling the function inside while - to always show the aircraft, always after background image - so that aircraft should be above te surface\r\n show_score(text_X, text_Y)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n carry_on = False\r\n\r\n # to check if any key is pressed and which key - (left or right arrow key, space bar) - is pressed\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_a :\r\n aircraft_X_change = -2\r\n if event.key == pygame.K_RIGHT or event.key == pygame.K_d :\r\n aircraft_X_change = 2\r\n if event.key == pygame.K_SPACE :\r\n if missile_state == 'load': # missile will be launched only if missile_state is 'load'\r\n missile_sound = mixer.Sound('silent-gun.wav') # used sound to play the sound for short duration\r\n missile_sound.play()\r\n missile_X = aircraft_X\r\n launch_missile(missile_X, missile_Y)\r\n if event.key == pygame.K_p :\r\n pause_resume()\r\n if event.key == pygame.K_q:\r\n quit()\r\n\r\n if event.type == pygame.KEYUP: # to stop the motion of aircraft on lifting the 'left or right arrow key' up\r\n if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT or event.key == pygame.K_a or event.key == pygame.K_d :\r\n aircraft_X_change = 0\r\n\r\n\r\n\r\n aircraft_X += aircraft_X_change\r\n\r\n # creating the boundries\r\n if aircraft_X < 0:\r\n aircraft_X = 0\r\n elif aircraft_X > 836:\r\n aircraft_X = 836\r\n\r\n\r\n\r\n for i in range(no_of_ghosts):\r\n\r\n\r\n # motion of ghost\r\n ghost_X[i] += ghost_X_change[i] # ghost_X is changing continuously , not ghost_Y\r\n if ghost_X[i] < 0:\r\n ghost_X_change[i] = 0.7\r\n ghost_Y[i] += ghost_Y_change[i]\r\n\r\n elif ghost_X[i] > 836:\r\n ghost_X_change[i] = -0.7\r\n ghost_Y[i] += ghost_Y_change[i]\r\n\r\n # if collision between missile and ghost occurs then missile does not pass the ghost and score increases\r\n collision = check_collision(ghost_X[i], ghost_Y[i], missile_X, missile_Y)\r\n if collision:\r\n exposion_Sound = mixer.Sound('explosion sound.wav') # used sound to play the sound for short duration\r\n exposion_Sound.play()\r\n missile_state = 'load'\r\n missile_Y = 520\r\n score_value += 10\r\n ghost_X[i] = random.randint(0, 836)\r\n ghost_Y[i] = random.randint(0, 150)\r\n draw_ghost(ghost_X[i], ghost_Y[i], i)\r\n\r\n # If the any ghost crosses the line then 'Game over'\r\n if ghost_Y[i] > 450:\r\n for j in range(no_of_ghosts):\r\n ghost_Y[j] = 2000\r\n game_over_text()\r\n break\r\n\r\n\r\n # motion of missile\r\n if missile_state == 'launch':\r\n launch_missile(missile_X, missile_Y)\r\n missile_Y -= missile_Y_change\r\n\r\n if missile_Y < 0:\r\n missile_Y = 520\r\n missile_state = 'load'\r\n\r\n\r\n\r\n # Level 1 completes if score reaches 1000\r\n if score_value >= 1000:\r\n level_complete()\r\n carry_on = False","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"277712935","text":"import time\n\nfrom library.core.TestCase import TestCase\nfrom library.core.utils.applicationcache import current_mobile\nfrom library.core.utils.testcasefilter import tags\nfrom preconditions.BasePreconditions import WorkbenchPreconditions\nfrom pages import *\nimport warnings\nfrom pages.contacts.my_group import ALLMyGroup\n\n\n\nREQUIRED_MOBILES = {\n 'Android-移动': 'M960BDQN229CH',\n # 'Android-移动': 'single_mobile',\n 'IOS-移动': 'iphone',\n 'IOS-移动-移动': 'M960BDQN229CHiphone8',\n}\n\nclass Preconditions(WorkbenchPreconditions):\n \"\"\"前置条件\"\"\"\n\n @staticmethod\n def make_already_in_message_page(reset=False):\n \"\"\"确保应用在消息页面\"\"\"\n # 如果在消息页,不做任何操作\n mp = MessagePage()\n if mp.is_on_this_page():\n return\n else:\n try:\n current_mobile().launch_app()\n mp.wait_for_page_load()\n except:\n # 进入一键登录页\n Preconditions.make_already_in_one_key_login_page()\n # 从一键登录页面登录\n Preconditions.login_by_one_key_login()\n\n @staticmethod\n def enter_group_messenger_page():\n \"\"\"进入群发信使首页\"\"\"\n\n mp = MessagePage()\n mp.wait_for_page_load()\n mp.click_workbench()\n wbp = WorkbenchPage()\n wbp.wait_for_page_load()\n wbp.click_add_group_messenger()\n\n @staticmethod\n def enter_collection_page():\n \"\"\"进入收藏页面\"\"\"\n\n mp = MessagePage()\n mp.wait_for_page_load()\n mp.open_me_page()\n me_page = MePage()\n me_page.wait_for_page_load()\n me_page.click_collection()\n mcp = MeCollectionPage()\n mcp.wait_for_page_load()\n time.sleep(1)\n\n\nclass CommonGroupPress(TestCase):\n \"\"\"普通群页面--长按\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"删除消息列表的消息记录\"\"\"\n warnings.simplefilter('ignore', ResourceWarning)\n Preconditions.select_mobile('IOS-移动')\n # 删除消息列表\n Preconditions.make_already_in_message_page()\n MessagePage().delete_all_message_list()\n time.sleep(3)\n\n @classmethod\n def default_setUp(self):\n \"\"\"确保每个用例执行前在群聊聊天界面\"\"\"\n warnings.simplefilter('ignore', ResourceWarning)\n Preconditions.select_mobile('IOS-移动')\n Preconditions.make_already_in_message_page()\n time.sleep(2)\n msg=MessagePage()\n name = '群聊1'\n if msg.is_text_present(name):\n msg.click_text(name)\n else:\n msg.open_contacts_page()\n ContactsPage().open_group_chat_list()\n ALLMyGroup().select_group_by_name(name)\n time.sleep(2)\n\n def default_tearDown(self):\n Preconditions.disconnect_mobile('IOS-移动')\n\n @tags('ALL', 'msg', 'CMCC')\n def test_msg_xiaoqiu_0051(self):\n \"\"\"在聊天会话页面,长按文本消息——转发——选择一个群作为转发对象\"\"\"\n # 确保当前页面有文本消息记录\n chat = GroupChatPage()\n chat.make_sure_chatwindow_have_message()\n # 1、长按文本消息,选择转发功能,跳转到联系人选择器页面(群聊文本消息id无法获取,长按使用坐标长按)\n chat.press_last_text_message()\n time.sleep(2)\n chat.click_forward()\n select = SelectContactsPage()\n self.assertTrue(select.is_on_this_page())\n # 2、选择一个群,进入到群聊列表展示页面,任意选中一个群聊,确认转发,会在消息列表,重新产生一个新的会话窗口或者在已有窗口中增加一条记录\n select.click_select_one_group()\n group = SelectOneGroupPage()\n name = '群聊2'\n group.selecting_one_group_by_name(name)\n group.click_sure_send()\n time.sleep(2)\n # 在消息列表,重新产生一个新的会话窗口\n Preconditions.make_already_in_message_page()\n mess = MessagePage()\n mess.page_should_contain_text(name)\n # 3、进入到聊天会话窗口页面,转发的消息,已发送成功并正常展示\n mess.click_text(name)\n self.assertTrue(chat.is_element_present_message())\n\n\n @tags('ALL', 'msg', 'CMCC')\n def test_msg_xiaoqiu_0052(self):\n \"\"\"在聊天会话页面,长按文本消息——转发——选择团队联系人作为转发对象\"\"\"\n # 确保当前页面有文本消息记录\n chat = GroupChatPage()\n chat.make_sure_chatwindow_have_message()\n # 1、长按文本消息,选择转发功能,跳转到联系人选择器页面(群聊文本消息id无法获取,长按使用坐标长按)\n chat.press_last_text_message()\n time.sleep(2)\n chat.click_forward()\n select = SelectContactsPage()\n self.assertTrue(select.is_on_this_page())\n # 2、选择一个群,进入到群聊列表展示页面,任意选中一个团队联系人,确认转发,会在消息列表,重新产生一个新的会话窗口或者在已有窗口中增加一条记录\n name = '大佬2'\n select.click_group_contact()\n group_contact = SelectHeContactsPage()\n group_contact.select_one_team_by_name('ateam7272')\n group_detail = SelectHeContactsDetailPage()\n time.sleep(2)\n group_detail.select_one_he_contact_by_name(name)\n group_detail.click_sure()\n time.sleep(2)\n # 在消息列表,重新产生一个新的会话窗口\n Preconditions.make_already_in_message_page()\n mess = MessagePage()\n mess.page_should_contain_text(name)\n # 3、进入到聊天会话窗口页面,转发的消息,已发送成功并正常展示\n mess.click_text(name)\n self.assertTrue(chat.is_element_present_message())\n\n\n @tags('ALL', 'msg', 'CMCC')\n def test_msg_xiaoqiu_0053(self):\n \"\"\"在聊天会话页面,长按文本消息——转发——选择手机联系人作为转发对象\"\"\"\n # 确保当前页面有文本消息记录\n chat = GroupChatPage()\n chat.make_sure_chatwindow_have_message()\n # 1、长按文本消息,选择转发功能,跳转到联系人选择器页面(群聊文本消息id无法获取,长按使用坐标长按)\n chat.press_last_text_message()\n time.sleep(2)\n chat.click_forward()\n select = SelectContactsPage()\n self.assertTrue(select.is_on_this_page())\n # 2、选择一个群,进入到群聊列表展示页面,任意选中一个手机联系人,确认转发,会在消息列表,重新产生一个新的会话窗口或者在已有窗口中增加一条记录\n name = '大佬1'\n select.select_local_contacts()\n local_contact = SelectLocalContactsPage()\n self.assertEqual(local_contact.is_on_this_page(), True)\n local_contact.swipe_select_one_member_by_name(name)\n local_contact.click_sure()\n time.sleep(2)\n # 在消息列表,重新产生一个新的会话窗口\n Preconditions.make_already_in_message_page()\n mess = MessagePage()\n mess.page_should_contain_text(name)\n # 3、进入到聊天会话窗口页面,转发的消息,已发送成功并正常展示\n mess.click_text(name)\n self.assertTrue(chat.is_element_present_message())\n\n\n @tags('ALL', 'msg', 'CMCC')\n def test_msg_xiaoqiu_0054(self):\n \"\"\"在聊天会话页面,长按文本消息——转发——选择最近聊天作为转发对象\"\"\"\n # 确保当前页面有文本消息记录\n chat = GroupChatPage()\n chat.make_sure_chatwindow_have_message()\n # 1、长按文本消息,选择转发功能,跳转到联系人选择器页面(群聊文本消息id无法获取,长按使用坐标长按)\n chat.press_last_text_message()\n time.sleep(2)\n chat.click_forward()\n select = SelectContactsPage()\n self.assertTrue(select.is_on_this_page())\n # 2、选择一个群,进入到群聊列表展示页面,任意选中最近聊天,确认转发,会在消息列表,重新产生一个新的会话窗口或者在已有窗口中增加一条记录\n name = select.get_recent_chat_contact_name()\n select.click_recent_chat_contact()\n select.click_sure_forward()\n time.sleep(2)\n # 在消息列表,重新产生一个新的会话窗口\n Preconditions.make_already_in_message_page()\n mess = MessagePage()\n mess.page_should_contain_text(name)\n # 3、进入到聊天会话窗口页面,转发的消息,已发送成功并正常展示\n mess.click_text(name)\n self.assertTrue(chat.is_element_present_message())\n\n @tags('ALL', 'msg', 'CMCC')\n def test_msg_xiaoqiu_0070(self):\n \"\"\"仅发送文字模式下,输入框存在内容后,点击发送按钮\"\"\"\n # 设置语音模式为:仅发送文字模式\n chat = GroupChatPage()\n chat.click_voice()\n audio = ChatAudioPage()\n audio.setting_voice_icon_in_send_text_only()\n # 2、输入框中存在内容后,点击发送按钮,发送出去的消息是否展示为文本消息(暂时无法判断是否为文本消息)\n chat.click_input_box()\n chat.input_message_text('文本消息')\n chat.click_send_button()\n time.sleep(2)\n chat.click_voice()\n audio.setting_voice_icon_in_send_voice_only()\n time.sleep(2)\n","sub_path":"TestCase/m002_message/group_chat/GroupChatPress.py","file_name":"GroupChatPress.py","file_ext":"py","file_size_in_byte":9609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"493333877","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom pyvirtualdisplay import Display\nfrom torrent import torrent\nfrom Query import Query\nimport urllib.request\nimport os\nimport time\nimport subprocess\nimport signal\nimport util_functions\nimport re\nclass torrent_downloader:\n\tBASE = 'http://www.nyaa.se/?page=rss'\n\t__torrents_to_search_for = set() #list of titles you are looking for\n\t__torrent_providers=set() #provider of torrent\n\t__url = \"\" # url of rss torrent feed\n\t__query_type = Query.ALL\n\n\t#initialize member variables\n\tdef __init__(self,url,search_for,providers,query_type = Query.ALL):\n\t\tself.__query_type = query_type\n\t\tself.__torrent_providers = [p.lower() for p in providers]\n\t\tif self.__query_type is Query.ALL:\n\t\t\tself.__url = url\n\t\t\tself.__torrents_to_search_for = [ s.lower() for s in search_for]\n\t\telif self.__query_type is Query.SPECIFIC:\n\t\t\tself.__url = self.BASE + '&cats=1_11&term='+search_for[0]+'&sort=2'\n\t\t\tself.__torrents_to_search_for = search_for\n\n\n\t'''\n\tdef __init__(self, search):\n\t\turl = base+'&term='+search.replace(' ','+')+'sort=2'\n\t'''\n\n\t\t\n\tdef run(self,run_once):\n\t\tcanRun= True\n\t\tif not self.__torrents_to_search_for or not self.__torrent_providers:\n\t\t\tcanRun = False\n\t\t\tprint(\"please add titles and/or providers\")\n\t\twhile canRun:\n\t\t\tcode = self.get_code()\n\t\t\ttorrents = self.parse_code(code)\n\t\t\ttorr_to_download = self.search_torrent_list(torrents)\n\t\t\tfiles = self.retrieve_torrent_files(torr_to_download)\n\t\t\tself.download_torrents(files,run_once)\n\t\t\tif run_once==True:\n\t\t\t\tbreak\n\t\n\n\t#verify whether torrent\n\tdef verify(self, torrents):\n\t\ttorrent_list = []\n\t\tfor torr in torrents:\n\t\t\tif torrent.min_size < torr.size torrent.min_seeders and torr.leechers >torrent.min_leechers:\n\t\t\t\t\ttorrent_list.append(torr)\n\t\treturn torrent_list\n\t\t\t\t\n\n\t#create a browser session and retrieve the html\n\tdef get_code(self):\n\t\t#This allows Firefox to run headless\n\t\tdisplay = Display(visible=0,size = (800,600))\n\t\tdisplay.start()\n\t\tbrowser = webdriver.Firefox()\n\t\tbrowser.get(self.__url)\n\t\tcode = browser.page_source #returns pages source code\n\t\tbrowser.close() #cleanup\n\t\tdisplay.stop()\n\t\tprint (self.__url + ' ' + str(self.__query_type) )\n\t\treturn code\n\n\t#takes in html code and retrieves anchor tags and meta data\n\tdef parse_code(self,html):\n\t\tparser = BeautifulSoup(html,'html.parser')\n\t\ttorrent_data = parser.findAll('div',class_ = 'entry' )\n\t\ttorrents = []\n\t\tfor data in torrent_data:\n\t\t\tanchor_tag = data.find('a',href= True)\n\t\t\tmeta_string = data.find('div', class_ = 'feedEntryContent').text\n\t\t\tmeta_data = re.findall('\\d+\\.*\\d*', meta_string)\n\t\t\ttitle = anchor_tag.text\n\t\t\tlink = anchor_tag['href']\n\t\t\tseeders = int(meta_data[0])\n\t\t\tleechers = int(meta_data[1])\n\t\t\t#if GB, convert to MB: \n\t\t\tif torrent.GB in meta_string:\n\t\t\t\tsize = 1000* float(meta_data[3])\n\t\t\telse:\n\t\t\t\tsize = float(meta_data[3])\n\t\t\ttorr = torrent(title.lower(),link,seeders,leechers,size)\n\t\t\ttorrents.append(torr)\n\t\t\t\n\t\ttorrents = self.verify(torrents)\n\t\treturn torrents\n\n\t#searches dictionary of torrents to find what the user wants\n\tdef search_torrent_list(self,torrents):\n\t\ttorr_to_download = {}\n\t\tif self.__query_type is Query.ALL:\n\t\t\tfor torr in torrents:\n\t\t\t\tfor provider in self.__torrent_providers: #iterates through providers\n\t\t\t\t\tif provider in torr.title:\n\t\t\t\t\t\tfor title in self.__torrents_to_search_for: #iterates through titles\n\t\t\t\t\t\t\tif title in torr.title and not title in torr_to_download:\n\t\t\t\t\t\t\t\ttorr_to_download[title] = torr\n\t\t\t\t\t\t\t\tbreak\n\t\telse:\n\t\t\tspecific_title = self.__torrents_to_search_for[0] # first index is title, followed by episode range\n\t\t\tlower_bound = self.__torrents_to_search_for[1]\n\t\t\tupper_bound = self.__torrents_to_search_for[2]\n\t\t\tif lower_bound >=upper_bound:\n\t\t\t\tfor torr in torrents:\n\t\t\t\t\t\tif specific_title in torr.title and lower_bound in torr.title:\n\t\t\t\t\t\t\tfor provider in self.__torrent_providers:\n\t\t\t\t\t\t\t\tif provider in torr.title:\n\t\t\t\t\t\t\t\t\ttorr_to_download[specific_title]=torr\n\t\t\t\t\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tfor num in range(lower_bound,upper_bound):\n\t\t\t\t\tif specific_title in torr.title and num in torr.title:\n\t\t\t\t\t\tfor provider in torr.title:\n\t\t\t\t\t\t\ttorr_to_download[specific_title+ ' ' + num]=torr\n\n\t\tprint(torr_to_download)\n\t\treturn torr_to_download\n\n\t#uses urllib.request to retrieve the torrent file\n\tdef retrieve_torrent_files(self,torr_to_download):\n\t\tfiles = []\n\t\t#make sure the same file has not already been downloaded\n\t\ttorr_to_download = util_functions.check_duplicates(torr_to_download)\n\t\t\n\t\ttry:\n\t\t\tfor title,torr in torr_to_download.items():\t\n\t\t\t\tfile_name = torr.title + '.torrent' #save file as file_name\n\t\t\t\tfiles.append(file_name) #keeps track of all files\n\t\t\t\turllib.request.urlretrieve(torr.link,file_name)\n\t\t\tprint(files)\n\t\texcept TypeError:\n\t\t\tpass\n\t\treturn files\n\n\t#This downloads all torrents in the list with rtorrent\n\tdef download_torrents(self,files,run_once):\n\t\tif not files:\n\t\t\tprint(\"No files found. Taking a break\")\n\t\t\tif run_once==False:\n\t\t\t\ttime.sleep(1200)\n\t\telse:\n\t\t\tcommand = 'rtorrent'\n\t\t\tfor f in files:\n\t\t\t\tprint(f)\n\t\t\t\tname = '\"' + f +'\"'\n\t\t\t\tcommand = command + ' ' + name\n\t\t\tprint(command)\n\t\t\tpro = subprocess.Popen(command, shell=True, preexec_fn=os.setsid)\n\t\t\ttime.sleep(1500)\n\t\t\tos.killpg(pro.pid, signal.SIGTERM) #kills rtorrent process\n\t\t\tutil_functions.remove_files() #removes torrent files\n\n","sub_path":"torrent_downloader.py","file_name":"torrent_downloader.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"375233348","text":"import collections\nimport re\nfrom pathlib import Path\n\nimport numpy as np\n\n\"\"\"\nATTENTION: Use the following dictionaries to get the correct index for each\n amino acid when accessing any type of matrix (PSSM or substitution\n matrix) parameters. Failure to do so will most likely result in not\n passing the tests.\n\"\"\"\nALPHABET = \"ACDEFGHIKLMNPQRSTVWY\"\nAA_TO_INT = {aa: index for index, aa in enumerate(ALPHABET)}\nINT_TO_AA = {index: aa for index, aa in enumerate(ALPHABET)}\n\n\ndef all_words():\n all_3 = []\n for i in ALPHABET:\n for j in ALPHABET:\n for k in ALPHABET:\n all_3.append(f\"{i}{j}{k}\")\n return all_3\n\n\nclass BlastDb:\n def __init__(self):\n \"\"\"\n Initialize the BlastDb class.\n \"\"\"\n self.seqs = []\n\n def add_sequence(self, sequence):\n \"\"\"\n Add a sequence to the database.\n\n :param sequence: a protein sequence (string).\n \"\"\"\n self.seqs.append(sequence)\n\n def get_sequences(self, word):\n \"\"\"\n Return all sequences in the database containing a given word.\n\n :param word: a word (string).\n\n :return: List with sequences.\n \"\"\"\n return [s for s in self.seqs if word in s]\n\n def get_db_stats(self):\n \"\"\"\n Return some database statistics:\n - Number of sequences in database\n - Number of different words in database\n - Average number of words per sequence (rounded to nearest int)\n - Average number of sequences per word (rounded to nearest int)\n\n :return: Tuple with four integer numbers corrsponding to the mentioned\n statistics (in order of listing above).\n \"\"\"\n all_3 = all_words()\n\n c = collections.Counter(all_3)\n\n c1 = collections.Counter(all_3)\n sum_dif_words = 0\n for s in self.seqs:\n c2 = collections.Counter(all_3)\n update_list = []\n for i in range(len(s) - 2):\n update_list.append(s[i : i + 3])\n c1.update(update_list)\n c2.update(update_list)\n c2 = c2 - c\n sum_dif_words += len(c2)\n c1 = c1 - c\n avg_word_per_seq = sum_dif_words / len(self.seqs)\n\n sum_word_occuring = 0\n for s in self.seqs:\n for key in c1:\n if key in s:\n sum_word_occuring += 1\n avg_seq_per_word = sum_word_occuring / len(c1)\n return (\n len(self.seqs),\n len(c1),\n int(round(avg_word_per_seq)),\n int(round(avg_seq_per_word)),\n )\n\n\nclass Blast:\n def __init__(self, substitution_matrix):\n \"\"\"\n Initialize the Blast class with the given substitution_matrix.\n\n :param substitution_matrix: 20x20 amino acid substitution score matrix.\n \"\"\"\n self.sub = substitution_matrix\n\n def get_words(self, *, sequence=None, pssm=None, T=11):\n \"\"\"\n Return all words with score >= T for given protein sequence or PSSM.\n Only a sequence or PSSM will be provided, not both at the same time.\n A word may only appear once in the list.\n\n :param sequence: a protein sequence (string).\n :param pssm: a PSSM (Lx20 matrix, where L is length of sequence).\n :param T: score threshold T for the words.\n\n :return: List of unique words.\n \"\"\"\n all_3 = all_words()\n over_thr = []\n\n if sequence:\n for i in range(len(sequence) - 2):\n for word in all_3:\n if not word in over_thr:\n score = (\n self.sub[AA_TO_INT[sequence[i]]][AA_TO_INT[word[0]]]\n + self.sub[AA_TO_INT[sequence[i + 1]]][AA_TO_INT[word[1]]]\n + self.sub[AA_TO_INT[sequence[i + 2]]][AA_TO_INT[word[2]]]\n )\n if score >= T:\n over_thr.append(word)\n\n if pssm is not None:\n for i in range(pssm.shape[0] - 2):\n for word in all_3:\n if not word in over_thr:\n score = (\n pssm[i][AA_TO_INT[word[0]]]\n + pssm[i + 1][AA_TO_INT[word[1]]]\n + pssm[i + 2][AA_TO_INT[word[2]]]\n )\n if score >= T:\n over_thr.append(word)\n\n return over_thr\n\n def get_words_positions(self, *, sequence=None, pssm=None, T=11):\n all_3 = all_words()\n over_thr = []\n\n if sequence:\n range_len = len(sequence) - 2\n else:\n range_len = pssm.shape[0] - 2\n\n for i in range(range_len):\n for word in all_3:\n if not (word, i) in over_thr:\n if sequence:\n score = (\n self.sub[AA_TO_INT[sequence[i]]][AA_TO_INT[word[0]]]\n + self.sub[AA_TO_INT[sequence[i + 1]]][AA_TO_INT[word[1]]]\n + self.sub[AA_TO_INT[sequence[i + 2]]][AA_TO_INT[word[2]]]\n )\n else:\n score = (\n pssm[i][AA_TO_INT[word[0]]]\n + pssm[i + 1][AA_TO_INT[word[1]]]\n + pssm[i + 2][AA_TO_INT[word[2]]]\n )\n if score >= T:\n over_thr.append((word, i))\n\n return over_thr\n\n def search_one_hit(self, blast_db, *, query=None, pssm=None, T=13, X=5, S=30):\n \"\"\"\n Search a database for target sequences with a given query sequence or\n PSSM. Return a dictionary where the keys are the target sequences for\n which HSPs have been found and the corresponding values are lists of\n tuples. Each tuple is a HSP with the following elements (and order):\n - Start position of HSP in query sequence\n - Start position of HSP in target sequence\n - Length of the HSP\n - Total score of the HSP\n The same HSP may not appear twice in the list (remove duplictes).\n Only a sequence or PSSM will be provided, not both at the same time.\n\n :param blast_db: BlastDB class object with protein sequences.\n :param query: query protein sequence.\n :param pssm: query PSSM (Lx20 matrix, where L is length of sequence).\n :param T: score threshold T for the words.\n :param X: drop-off threshold X during extension.\n :param S: score threshold S for the HSP.\n\n :return: dictionary of target sequences and list of HSP tuples.\n \"\"\"\n result = collections.defaultdict(list)\n\n initials = self.get_words_positions(sequence=query, pssm=pssm, T=T)\n for word, occ_q in initials:\n targets = blast_db.get_sequences(word)\n for target in targets:\n all_occurances = [m.start() for m in re.finditer(f\"(?={word})\", target)]\n for occ_t in all_occurances:\n if query:\n ending_q = len(query)\n max_score = (\n self.sub[AA_TO_INT[query[occ_q]]][AA_TO_INT[target[occ_t]]]\n + self.sub[AA_TO_INT[query[occ_q + 1]]][\n AA_TO_INT[target[occ_t + 1]]\n ]\n + self.sub[AA_TO_INT[query[occ_q + 2]]][\n AA_TO_INT[target[occ_t + 2]]\n ]\n )\n else:\n ending_q = pssm.shape[0]\n max_score = (\n pssm[occ_q][AA_TO_INT[target[occ_t]]]\n + pssm[occ_q + 1][AA_TO_INT[target[occ_t + 1]]]\n + pssm[occ_q + 2][AA_TO_INT[target[occ_t + 2]]]\n )\n max_score_length = 3\n score = max_score\n i = occ_q + max_score_length\n j = occ_t + max_score_length\n # To the right\n while i < ending_q and j < len(target):\n if query:\n score += self.sub[AA_TO_INT[query[i]]][AA_TO_INT[target[j]]]\n else:\n score += pssm[i][AA_TO_INT[target[j]]]\n if score > max_score:\n max_score = score\n max_score_length = i - occ_q + 1\n elif score <= max_score - X:\n break\n i += 1\n j += 1\n\n max_start_q = occ_q\n max_start_t = occ_t\n max_score_length_left = 0\n score = max_score\n i = occ_q - 1\n j = occ_t - 1\n # To the left\n while i >= 0 and j >= 0:\n if query:\n score += self.sub[AA_TO_INT[query[i]]][AA_TO_INT[target[j]]]\n else:\n score += pssm[i][AA_TO_INT[target[j]]]\n if score > max_score:\n max_score = score\n max_score_length_left = occ_q - i\n max_start_q = i\n max_start_t = j\n elif score <= max_score - X:\n break\n i -= 1\n j -= 1\n\n max_score_length += max_score_length_left\n if max_score < S:\n continue\n\n if not target in result:\n result[target] = set()\n result[target].add(\n (max_start_q, max_start_t, max_score_length, max_score)\n )\n\n if pssm is not None:\n # TODO\n pass\n\n # print(dict(result))\n return dict(result)\n\n def search_two_hit(self, blast_db, *, query=None, pssm=None, T=11, X=5, S=30, A=40):\n \"\"\"\n Search a database for target sequences with a given query sequence or\n PSSM. Return a dictionary where the keys are the target sequences for\n which HSPs have been found and the corresponding values are lists of\n tuples. Each tuple is a HSP with the following elements (and order):\n - Start position of HSP in query sequence\n - Start position of HSP in target sequence\n - Length of the HSP\n - Total score of the HSP\n The same HSP may not appear twice in the list (remove duplictes).\n Only a sequence or PSSM will be provided, not both at the same time.\n\n :param blast_db: BlastDB class object with protein sequences.\n :param query: query protein sequence.\n :param pssm: query PSSM (Lx20 matrix, where L is length of sequence).\n :param T: score threshold T for the words.\n :param X: drop-off threshold X during extension.\n :param S: score threshold S for the HSP.\n :param A: max distance A between two hits for the two-hit method.\n\n :return: dictionary of target sequences and list of HSP tuples.\n \"\"\"\n d = dict()\n d[\"SEQWENCE\"] = [(1, 2, 4, 13)]\n","sub_path":"codechecker/repos/5/collected_files/blast/ge73zez.py","file_name":"ge73zez.py","file_ext":"py","file_size_in_byte":11599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"311076637","text":"\"\"\"This script aims to plot 3lp molecular clouds using external data\nas the contour.\n\n\"\"\"\n\n\nfrom common import *\nimport matplotlib.pyplot as plt\nimport lib\nimport plotstyle\nfrom matplotlib import colors, ticker\n\n# parser defined in common\nparser.add_argument(\"--back\", default=\"external/meerkat/MeerKAT_radio_bubbles.fits\")\nparser.add_argument(\"--title\", default=\"GCRA and Sgr A\")\nparser.add_argument(\"--figsize\", default=None)\nparser.add_argument(\"--smooth\", type=float, default=None)\nparser.add_argument(\"--freq\", default='f090')\nparser.add_argument(\"--mask\", action='store_true')\nparser.add_argument(\"--min2\", type=float, default=None)\nparser.add_argument(\"--max2\", type=float, default=None)\nparser.add_argument(\"--scale\", type=int, default=100)\nargs = parser.parse_args()\nif not op.exists(args.odir): os.makedirs(args.odir)\nbox = boxes[args.area]\n\n# load coadd map\nimap = load_map(filedb[args.freq]['coadd'], fcode=args.freq, box=box) / 1e9\nivar = load_ivar(filedb[args.freq]['coadd_ivar'], fcode=args.freq, box=box) * 1e18\n# smooth if necessary\nif args.smooth:\n imap = enmap.smooth_gauss(imap, args.smooth*u.fwhm*u.arcmin)\n ivar = enmap.smooth_gauss(ivar, args.smooth*u.fwhm*u.arcmin)\n s = sfactor(args.freq, args.smooth)\nelse:\n imap = imap\n ivar = ivar\n s = 1\n\n# load external data\nirmap = enmap.read_map(args.back)\nirmap = enmap.submap(irmap, box=box)\n\n# setup two panel plot\nif args.figsize: figsize=eval(args.figsize)\nelse: figsize=None\nY, X = imap.posmap()/np.pi*180\nfig = plt.figure(figsize=figsize)\n\n##############\n# left panel #\n##############\nax = plt.subplot(121, projection=imap.wcs)\n# ax = plt.subplot(121, projection=irmap.wcs)\nopts = {\n # 'cmap': 'magma',\n 'norm': colors.LogNorm(vmin=1e-3, vmax=1e-1),\n # 'cmap': 'planck_half',\n 'cmap': 'plasma',\n # 'norm': colors.LogNorm(vmin=1e-5, vmax=1e-2),\n\n}\nplotstyle.setup_axis(ax, nticks=[5,5], fmt=None)\nP = np.sum(imap[1:]**2,axis=0)**0.5\nim = ax.imshow(P/imap[0], **opts)\n# im = ax.imshow(irmap, **opts)\nax.set_xlabel('$l$')\nax.set_ylabel('$b$')\ncax = plotstyle.add_colorbar_hpad(ax, pad=\"1%\", hpad=\"50%\")\nfig.colorbar(im, cax=cax, orientation='horizontal',\n shrink='50%').set_label(texify(\"P/I \"), fontsize=12)\ncax.xaxis.set_label_position('top')\ncax.xaxis.set_ticks_position('top')\nax.text(0.15, 1.03, texify(\"f090\"), transform=ax.transAxes, fontsize=14)\nax.tick_params(axis='x', colors='white', which='both', labelcolor='black')\nax.tick_params(axis='y', colors='white', which='both', labelcolor='black')\nax.set_aspect('equal')\nfor side in ['left','right','top','bottom']:\n ax.spines[side].set_visible(True)\n ax.spines[side].set_color('white')\n\n# add contours\n# levels = np.logspace(np.log10(5),np.log10(25),5)\n# levels = [5,9,13,17,21,25]\nlevels = np.arange(1,31,2)\n# print(levels)\n# ax.contour(imap[0], levels=10, cmap='gray', norm=colors.LogNorm(vmin=5, vmax=50))\n# ax.contour(imap[0], levels=levels, cmap='Greys', norm=colors.Normalize(vmin=5, vmax=50), alpha=0.6)\nax.contour(imap[0], levels=levels, colors='w', alpha=0.5)\n# ax.contour(X, Y, imap[0], levels=levels, colors='k', alpha=0.3, transform=ax.get_transform('world'))\nsagax, sagay = [359.94423568, -0.04616002]\nax.scatter([sagax], [sagay], s=15, marker='x', color='w',\n transform=ax.get_transform('world'), alpha=0.7)\n\n# calculate polarization fraction\ndeg = 180/np.pi\nrmap = imap.modrmap(ref=[sagay/deg, (sagax-360)/deg])*deg\nmask = rmap < 1/60\nPfrac= P/imap[0]\nPerr = lib.P_error(imap, ivar)\nIerr = ivar[0]**-0.5\n# Ierr = 0.01*imap[0]\n# dfrac I + dI frac = d P ==> dfrac = (dP - dI frac)/I = I dP / I^2 - P dI / I^2\nPfrac_err = (Perr - Ierr * Pfrac)/imap[0]\nprint(f\"mean polfrac={np.mean(Pfrac[mask]):.4f} +- {np.mean(Pfrac_err[mask])/np.sqrt(np.sum(mask)):.4f}\")\n\n###############\n# right panel #\n###############\nax = plt.subplot(122, projection=irmap.wcs)\nopts = {\n 'cmap': 'planck_half',\n 'norm': colors.LogNorm(vmin=1e-5, vmax=1e-2),\n}\nplotstyle.setup_axis(ax, nticks=[5,5], yticks=False, fmt=None)\nirmap[irmap<0] = 1e-6\nim = ax.imshow(irmap, **opts)\n# polarization angle plot\n# reload imap to get the original resolution\ntheta = lib.Bangle(imap[1], imap[2], toIAU=True)\ntheta += (np.pi/2) # this gets the B-field angle corrected\n# x- and y-components of magnetic field\nBx = np.cos(theta)\nBy = np.sin(theta)\n# mask by polarization intensity\nif args.mask:\n P = np.sum(imap[1:]**2,axis=0)**0.5\n P_err = lib.P_error(imap, ivar*s**2)\n Psnr = P / P_err\n mask = Psnr < 3\n # Pangle_err = lib.Pangle_error(imap, ivar*s**2, deg=True)\n # mask = Pangle_err > 10\n cmap_ = plt.get_cmap('binary') # actual cmap doesn't matter\n color = cmap_(np.ones_like(X))\n # color[ mask,-1] = 0.2\n # color[~mask,-1] = 1\n val = np.min([Psnr, np.ones_like(Psnr)*3], axis=0)\n val /= 3\n color[...,-1] = val\n color=color.reshape(color.shape[0]*color.shape[1],4)\nelse:\n color='k'\nsagax, sagay = [359.94423568, -0.04616002]\nax.scatter([sagax], [sagay], s=15, marker='x', color='w',\n transform=ax.get_transform('world'), alpha=0.7)\nax.quiver(X,Y,Bx,By,pivot='middle', headlength=0, headaxislength=0, scale=args.scale,\n color=color, transform=ax.get_transform('world'))\nax.set_xlabel('$l$')\nax.set_ylabel('$b$')\nax.set_aspect('equal')\n\n# colorbar\n# fig.colorbar(im, cax=cax).set_label(texify(\"Total Intensity [MJy/sr]\"), fontsize=12)\n# new colorbar\ncax = plotstyle.add_colorbar_hpad(ax, pad=\"1%\", hpad=\"50%\")\ncb = fig.colorbar(im, cax=cax, orientation='horizontal',\n ticks=[1e-5,1e-4,1e-3,1e-2], ticklocation='top')\ncb.set_label(texify(\"I [MJy/sr]\"), fontsize=12)\nx_minor = ticker.LogLocator(base=10.0, subs=np.arange(1.0, 10.0)*0.1, numticks=10)\ncb.ax.xaxis.set_minor_locator(x_minor)\ncb.update_ticks()\n\nax.text(0.06, 1.07, texify(\"I\")+\": \"+ texify(\"1.28 GHz\"), transform=ax.transAxes, fontsize=12)\n# ax.text(0.04, 1.07, texify(\"1.28 GHz\"), transform=ax.transAxes, fontsize=10)\nax.text(0.06, 1.02, texify(\"B\")+\"-\"+texify(\"fields\")+\": \"+texify(\"f090\"),\n transform=ax.transAxes, fontsize=12)\n# ax.text(0.1, 1.03, texify(\"1.28 GHz\"), transform=ax.transAxes, fontsize=14)\nplt.subplots_adjust(hspace=0, wspace=0.1)\n\nif args.title: plt.suptitle(texify(args.title), fontsize=16)\nofile = op.join(args.odir, args.oname)\nprint(\"Writing:\", ofile)\nplt.savefig(ofile, bbox_inches='tight')\n","sub_path":"plot_saga4.py","file_name":"plot_saga4.py","file_ext":"py","file_size_in_byte":6349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"287823469","text":"\"\"\"\nFeedback functions of the Source module\n\"\"\"\n\nfrom pedal.core.commands import feedback\nfrom pedal.core.feedback import FeedbackResponse\nfrom pedal.core.location import Location\nfrom pedal.core.report import MAIN_REPORT\nfrom pedal.utilities.exceptions import ExpandedTraceback\nfrom pedal.source.constants import TOOL_NAME\n\n\nclass SourceFeedback(FeedbackResponse):\n \"\"\" Base class of all Feedback functions for Source Tool \"\"\"\n category = feedback.CATEGORIES.SYNTAX\n kind = feedback.KINDS.MISTAKE\n tool = TOOL_NAME\n\n\nclass blank_source(SourceFeedback):\n \"\"\" Source code file was blank. \"\"\"\n title = \"No Source Code\"\n message_template = \"Source code file is blank.\"\n justification = \"After stripping the code, there were no characters.\"\n\n\nclass not_enough_sections(SourceFeedback):\n \"\"\" Didn't have all the needed sections. \"\"\"\n title = \"Not Enough Sections\"\n message_template = (\"Tried to advance to next section but the \"\n \"section was not found. Tried to load section \"\n \"{count}, but there were only {found} sections.\")\n justification = (\"Section index exceeded the length of the separated \"\n \"sections list.\")\n\n def __init__(self, section_number, found, **kwargs):\n fields = {'count': section_number, 'found': found}\n super().__init__(fields=fields, **kwargs)\n\n\nclass source_file_not_found(SourceFeedback):\n \"\"\" No source file was given. \"\"\"\n title = 'Source File Not Found'\n message_template = (\"The given filename {name:filename} was either not \"\n \"found or could not be opened. Please make sure the \"\n \"file is available.\")\n version = '0.0.1'\n justification = \"IOError while opening file to set_source\"\n\n def __init__(self, name, sections, **kwargs):\n report = kwargs.get(\"report\", MAIN_REPORT)\n fields = {'name': name, 'sections': sections}\n group = 0 if sections else kwargs.get('group')\n super().__init__(fields=fields, group=group, **kwargs)\n\n\nclass syntax_error(SourceFeedback):\n \"\"\" Generic feedback for any kind of syntax error. \"\"\"\n muted = False\n title = \"Syntax Error\"\n message_template = (\"Bad syntax on line {lineno:line}\\n\\n\"\n \"The traceback was:\\n{traceback_message}\\n\\n\"\n \"Suggestion: Check line {lineno:line}, the line \"\n \"before it, and the line after it.\")\n version = '0.0.1'\n justification = \"Syntax error was triggered while calling ast.parse\"\n\n def __init__(self, line, filename, code, col_offset,\n exception, exc_info, **kwargs):\n report = kwargs.get('report', MAIN_REPORT)\n files = report.submission.get_files_lines()\n if filename not in files:\n files[filename] = code.split(\"\\n\")\n if report.submission is not None:\n lines = report.submission.get_lines()\n line_offsets = report.submission.line_offsets\n else:\n lines = code.split(\"\\n\")\n line_offsets = {}\n line_offset = line_offsets.get(filename, 0)\n traceback = ExpandedTraceback(exception, exc_info, False,\n [report.submission.instructor_file],\n line_offsets, [filename], lines, files)\n traceback_stack = traceback.build_traceback()\n traceback_message = traceback.format_traceback(traceback_stack,\n report.format)\n line_offset = line_offsets.get(filename, 0)\n fields = {'lineno': line+line_offset,\n 'filename': filename, 'offset': col_offset,\n 'exception': exception,\n 'traceback': traceback,\n 'traceback_stack': traceback_stack,\n 'traceback_message': traceback_message}\n location = Location(line=line+line_offset, col=col_offset, filename=filename)\n super().__init__(fields=fields, location=location, **kwargs)\n\n\nclass incorrect_number_of_sections(SourceFeedback):\n \"\"\" Incorrect number of sections \"\"\"\n title = \"Incorrect Number of Sections\"\n message_template = (\"Incorrect number of sections in your file. \"\n \"Expected {count}, but only found {found}\")\n justification = \"\"\n\n def __init__(self, count, found, **kwargs):\n fields = {'count': count, 'found': found}\n super().__init__(fields=fields, **kwargs)\n\n# TODO: IndentationError\n# TODO: TabError\n","sub_path":"pedal/source/feedbacks.py","file_name":"feedbacks.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"431698380","text":"\nimport sys\nimport numpy as np\nimport scripts.HillasData as HillasData\n\nimport matplotlib.pyplot as plt\n\nif len(sys.argv) == 6 :\n im_folder=\"data/im\"\n sig_folder=\"data/sig\"\n wavelet_name = sys.argv[1]\n nb_events=int(sys.argv[2])\n fact_sig_noi = (sys.argv[3])\n cam_name = sys.argv[4]\n wavelet_name += \"_nei\" if sys.argv[5] == \"--nei\" else \"\"\nelif len(sys.argv) == 8 :\n wavelet_name = sys.argv[1]\n nb_events = int(sys.argv[2])\n fact_sig_noi = (sys.argv[3])\n cam_name = sys.argv[4]\n im_folder = sys.argv[5]\n sig_folder = sys.argv[6]\n wavelet_name += \"_nei\" if sys.argv[7] == \"--nei\" else \"\"\nelse :\n print (\"argv:\\n\\twavelet_name nbEvent factSignalNoise cam_name --nei|notnei\")\n exit()\n\nhillasData = HillasData.HillasData(wavelet_name, nb_events, fact_sig_noi, cam_name, im_folder, sig_folder)\nhillasData.save_all ()\n","sub_path":"pysimulation/errorExtractor.py","file_name":"errorExtractor.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"367694474","text":"# Call Login python file\nimport driver as driver\nimport Login_Add_SENR\nfrom Login_Add_SENR import webdriver\nfrom Login_Add_SENR import Keys\nfrom Login_Add_SENR import WebDriverWait\nfrom Login_Add_SENR import By\nfrom Login_Add_SENR import Select\nfrom Login_Add_SENR import driver\nfrom Login_Add_SENR import webdriver\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC, wait\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.common.exceptions import *\n\nimport time\nimport xlrd # import package to read data from Excel\nimport openpyxl\nfrom openpyxl import load_workbook\n\nglobal file_path\nfile_path = (\n r\"C:\\Users\\AbhinavDixit\\PycharmProjects\\Skat-eIncomes\\Online-INDB\\1-Submit_Online-INDB\\Online_INDB_Excel.xlsx\")\nclass nullindbreversal():\n global recent_indbid, file_path\n # ************ Method to Handle Current Window **************#\n def handle_current_window_method(self):\n handles = driver.window_handles\n for handle in handles:\n driver.switch_to.window(handle)\n # print(driver.title)\n driver.maximize_window()\n\n def reversalScreenNavigation(self):\n # Click on Forespørg/Kopiér/Tilbagefør indberetninger\n time.sleep(5)\n driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td[1]/table/tbody/tr[1]/td/a[7]\").click()\n\n # Move to current new window\n nullindbreversal.handle_current_window_method(self)\n time.sleep(5)\n\n # select search option Indberetnings-ID from drop down\n driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[7]/td[2]/select\").is_displayed()\n driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[7]/td[2]/select\").send_keys(\n \"IndberetningsID\")\n time.sleep(3)\n nullindbreversal.readINDBfromexcel(self)\n\n def readINDBfromexcel(self):\n # Pass entire file path as parameter\n # set file path\n #file_path = (r\"C:\\Users\\AbhinavDixit\\PycharmProjects\\Skat-eIncomes\\Online-INDB\\1-Submit_Online-INDB\\Online_INDB_Excel.xlsx\")\n book = xlrd.open_workbook(file_path)\n aa = book.sheet_by_index(1)\n list_ad = []\n total_rows = aa.nrows\n print(\"Total number of Rows are:\", total_rows)\n for i in range(1, total_rows):\n list_ad.append(aa.cell(rowx=i, colx=0).value)\n print(\"Length of List\", len(list_ad))\n print(\"LIST\", list_ad)\n print(\"THE FINAL LIST IS \", list_ad)\n time.sleep(3)\n recent_indbid = list_ad[-1]\n # Enter INDB ID to be searched\n driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[7]/td[2]/input\").send_keys(\n recent_indbid)\n driver.find_element_by_xpath(\"//*[@id='defaultButton']\").click() # Press Sog Button\n nullindbreversal.nullindbreversalmethod(self,recent_indbid)\n\n def nullindbreversalmethod(self,recent_indbid):\n\n try:\n WebDriverWait(driver, 3).until(EC.alert_is_present(),\n 'Timed out waiting for PA creation ' +\n 'confirmation popup to appear.')\n\n alert = driver.switch_to.alert\n print(alert.text)\n time.sleep(5)\n alert.accept()\n print(\"Popup Alert Message Appeared and Accepted while searching INDB\")\n except TimeoutException:\n print(\"No Popup Alert Message Appeared while searching INDB\")\n time.sleep(5)\n\n try:\n NULL_INDB_ID = driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[18]/td/table/tbody/tr[2]/td[3]\").text\n ART_VALUE = driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[18]/td/table/tbody/tr[2]/td[7]\").text\n TILBAGEFORT_VALUE = driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[18]/td/table/tbody/tr[2]/td[8]\").text\n print(\"INDB ID is :\", NULL_INDB_ID)\n print(\"ART Value is:\", ART_VALUE)\n print(\"TILBAGEFORT VALUE is:\", TILBAGEFORT_VALUE)\n print(recent_indbid)\n if driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[18]/td/table/tbody/tr[2]/td[3]\").is_displayed():\n if NULL_INDB_ID == recent_indbid and ART_VALUE == 'I' and TILBAGEFORT_VALUE == 'Nej':\n driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[18]/td/table/tbody/tr[2]/td[11]/input\").click() # select Radio Button\n driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[16]/td[2]/input\").click() # click Tilbagefør button\n time.sleep(3)\n\n New_NULL_INDBREV_ID = driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[7]/td[2]/input\").is_displayed()\n print(New_NULL_INDBREV_ID) # Check whether New INDB REV ID field is dispalyed\n\n New_NULL_INDB_REV_ID = driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[7]/td[2]/input\").get_attribute(\n \"value\")\n print(\"New_INDB_REV_ID is:-\", New_NULL_INDB_REV_ID) # print New INDB REV ID\n\n Hovedindberetningsident = driver.find_element_by_xpath(\n \"/html/body/table[2]/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[4]/td[2]/input\").get_attribute(\n \"value\")\n print(\"Hovedindberetningsident is:\", Hovedindberetningsident)\n\n # Copy INDB ID to Excel File\n time.sleep(5)\n workbook = openpyxl.load_workbook(file_path) # Load Workbook\n sheet = workbook['REV_INDBID']\n print(New_NULL_INDB_REV_ID)\n # Copy INDB_ID in to Excel\n i = 1\n while sheet.cell(row=i, column=1).value != None:\n i = i + 1\n sheet.cell(i, 6).value = NULL_INDB_ID\n sheet.cell(i, 7).value = New_NULL_INDB_REV_ID\n sheet.cell(i, 8).value = Hovedindberetningsident\n workbook.save(file_path)\n driver.find_element_by_xpath(\"//*[@id='defaultButton']\").click()\n else:\n print('Since TILBAGEFORT VALUE is: Ja File cannot be reversed ')\n except NoSuchElementException:\n print(' ')\n\n # Click bekraft button to commit Tilbage (Reversal)\n driver.find_element_by_xpath(\"//*[@id='defaultButton']\").click()\n try:\n WebDriverWait(driver, 3).until(EC.alert_is_present(),\n 'Timed out waiting for PA creation ' +\n 'confirmation popup to appear.')\n\n alert = driver.switch_to.alert\n print(alert.text)\n time.sleep(5)\n alert.accept()\n print(\"alert accepted\")\n except TimeoutException:\n print(\"no popup alert\")\n time.sleep(5)\n\nA1 = nullindbreversal()\nA1.reversalScreenNavigation()\n\n","sub_path":"Online-INDB/File_Copy_Reversal/File_Reversal_NullINDB.py","file_name":"File_Reversal_NullINDB.py","file_ext":"py","file_size_in_byte":8149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"234058289","text":"import math\n\nimport numpy as np\nfrom deap import base, creator\n\nfrom data.repository import read_problem\n\ncreator.create(\"FitnessMinMax\", base.Fitness, weights=(-1.0, 1.0))\ncreator.create(\"Individual\", dict, fitness=creator.FitnessMinMax)\n\nimport random\nfrom deap import tools\n\nproblem = read_problem(\"test-example-n4\")\n\nprint(\"### Problem instance ###\")\nprint(problem.items)\nprint(problem.cities)\nprint(\"###\")\n\n\ndef initIndividual(container, city_func, item_func):\n return container(zip(['cities', 'items'], [city_func(), item_func()]))\n\n\ndef initPermutation():\n return random.sample(range(problem.no_cities - 1), problem.no_cities - 1)\n\n\ndef initZeroOne():\n return 1 if random.random() > 0.9 else 0\n\n\ndef euclidean_distance(a, b):\n return math.sqrt(\n math.pow(problem.cities[a][0] - problem.cities[b][0], 2) + math.pow(problem.cities[a][1] - problem.cities[b][1],\n 2))\n\n\ndef evaluate(individual):\n pi = individual['cities']\n z = individual['items']\n\n # print(full_pi, z)\n\n profit = 0\n time = 0\n weight = 0\n\n full_pi = [x + 1 for x in pi]\n\n for index, city in enumerate([0] + full_pi):\n possible_items_for_current_city = problem.items.get(city, [])\n items_collected_for_current_city = filter(lambda x: z[x[0] - 1] == 1, possible_items_for_current_city)\n\n for item in items_collected_for_current_city:\n profit += item[1]\n weight += item[2]\n\n speed = problem.max_speed - (weight / problem.knapsack_capacity) * (problem.max_speed - problem.min_speed)\n next = full_pi[(index + 1) % (problem.no_cities - 1)]\n\n # print(\"Cities: \", city, next)\n\n distance = math.ceil(euclidean_distance(city, next))\n\n # print(distance)\n\n # print(distance, speed)\n\n time += distance / speed\n\n if weight > problem.knapsack_capacity:\n time = np.inf\n profit = - np.inf\n break\n\n return time, profit\n\n\ndef crossover(ind1, ind2, city_crossover, item_crossover, indpb1, indpb2):\n pi1 = ind1['cities']\n z1 = ind1['items']\n\n pi2 = ind2['cities']\n z2 = ind2['items']\n\n city_crossover_result1, city_crossover_result2 = city_crossover(pi1, pi2)\n item_crossover_result1, item_crossover_result2 = item_crossover(z1, z2)\n\n return initIndividual(creator.Individual, lambda: city_crossover_result1, lambda: item_crossover_result1), \\\n initIndividual(creator.Individual, lambda: city_crossover_result2, lambda: item_crossover_result2)\n\n\ndef mutation(ind, city_mutation, item_mutation, indpb1, indpb2):\n pi = ind['cities']\n z = ind['items']\n\n return initIndividual(creator.Individual, lambda: city_mutation(pi, indpb1), lambda: item_mutation(z, indpb2))\n\n\ntoolbox = base.Toolbox()\n\ntoolbox.register(\"city_attribute\", initPermutation)\ntoolbox.register(\"items_attribute\", tools.initRepeat, list, initZeroOne, problem.no_items)\ntoolbox.register(\"individual\", initIndividual, creator.Individual, toolbox.city_attribute, toolbox.items_attribute)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\ntoolbox.register(\"evaluate\", evaluate)\ntoolbox.register(\"mate\", crossover, city_crossover=tools.cxPartialyMatched, item_crossover=tools.cxOnePoint, indpb1=None, indpb2=None)\ntoolbox.register(\"mutate\", mutation, city_mutation=tools.mutShuffleIndexes, item_mutation=tools.mutFlipBit, indpb1=0.05, indpb2=0.05)\ntoolbox.register(\"select\", tools.selNSGA2)\n\nstats = tools.Statistics(key=lambda ind: ind.fitness.values)\nstats.register(\"avg\", np.mean, axis=0)\nstats.register(\"std\", np.std, axis=0)\nstats.register(\"min\", np.min, axis=0)\nstats.register(\"max\", np.max, axis=0)\n\n# stats.register(\"profit-avg\", np.mean, axis=1)\n# stats.register(\"profit-std\", np.std, axis=1)\n# stats.register(\"profit-min\", np.min, axis=1)\n# stats.register(\"profit-max\", np.max, axis=1)\n\n\npop = toolbox.population(n=10)\nCXPB, MUTPB, NGEN = 0.3, 0.1, 50\n\n# Evaluate the entire population\nfitnesses = map(toolbox.evaluate, pop)\nfor ind, fit in zip(pop, fitnesses):\n ind.fitness.values = fit\n\nfor g in range(NGEN):\n # Logging current population fitnesses\n record = stats.compile(pop)\n print(record)\n\n # Select the next generation individuals\n offspring = toolbox.select(pop, 10)\n # Clone the selected individuals\n offspring = list(map(toolbox.clone, offspring))\n\n # Apply crossover and mutation on the offspring\n for child1, child2 in zip(offspring[::2], offspring[1::2]):\n if random.random() < CXPB:\n toolbox.mate(child1, child2)\n del child1.fitness.values\n del child2.fitness.values\n\n for mutant in offspring:\n if random.random() < MUTPB:\n toolbox.mutate(mutant)\n del mutant.fitness.values\n\n # Evaluate the individuals with an invalid fitness\n invalid_ind = [ind for ind in offspring if not ind.fitness.valid]\n fitnesses = map(toolbox.evaluate, invalid_ind)\n for ind, fit in zip(invalid_ind, fitnesses):\n ind.fitness.values = fit\n\n # The population is entirely replaced by the offspring\n pop[:] = offspring\n\nfor ind in pop:\n print([1] + [x + 2 for x in ind['cities']], ind['items'], evaluate(ind))\n\n\n","sub_path":"alternative/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"571926283","text":"import numpy as np\nfrom gym_urbandriving.planning import Trajectory\n\n\"\"\"\nTest our trajectory class for various modes. \n\"\"\"\n\nfor t in range(500):\n global_mode='xyvacst'\n\n # choose dimension of our trajectory randomly\n dimension = np.random.randint(1,7)\n\n # build our mode randomly\n indices = np.random.choice(7,dimension,replace=False)\n mode = ''\n for i in indices:\n mode += global_mode[i]\n\n traj_test = Trajectory(mode = mode)\n\n # test is not empty\n traj_test.add_point(np.ones(dimension))\n assert(not traj_test.is_empty())\n\n # insert a bunch of elements\n for j in range(np.random.randint(5,100)):\n traj_test.add_point(np.random.uniform(0,1,dimension))\n\n # insert last element with distinct elements\n traj_test.add_point(np.arange(dimension))\n assert(not traj_test.is_empty())\n\n # pop elements off making sure they are correctly shaped and populated\n while(not traj_test.is_empty()):\n p = traj_test.pop()\n assert p.shape[0] == dimension\n assert not np.nan in p\n\n # check last element popped is the same as the last element added\n assert (p == np.arange(dimension)).all()\n\n # assert everything popped off\n assert(traj_test.is_empty())","sub_path":"tests/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"171862266","text":"\n\nimport pandas as pd\nimport numpy as np\n\nfrom rewards import RewardStrategy\nfrom trades import TradeType, Trade\n\n\nclass SimpleProfitStrategy(RewardStrategy):\n \"\"\"A reward strategy that rewards the agent for profitable trades and prioritizes trading over not trading.\n\n This strategy supports simple action strategies that trade a single position in a single instrument at a time.\n \"\"\"\n\n def reset(self):\n \"\"\"Necessary to reset the last purchase price and state of open positions.\"\"\"\n self._purchase_price = -1\n self._is_holding_instrument = False\n\n def get_reward(self, current_step: int, trade: Trade) -> float:\n \"\"\"Reward -1 for not holding a position, 1 for holding a position, 2 for opening a position, and 1 + 5^(log_10(profit)) for closing a position.\n\n The 5^(log_10(profit)) function simply slows the growth of the reward as trades get large.\n \"\"\"\n if trade.is_hold and self._is_holding_instrument:\n return 1\n elif trade.is_buy and trade.amount > 0:\n self._purchase_price = trade.price\n self._is_holding_instrument = True\n\n return 2\n elif trade.is_sell and trade.amount > 0:\n self._is_holding_instrument = False\n profit_per_instrument = trade.price - self._purchase_price\n profit = trade.amount * profit_per_instrument\n profit_sign = np.sign(profit)\n\n return profit_sign * (1 + (5 ** np.log10(abs(profit))))\n\n return -1\n","sub_path":"rewards/simple_profit_strategy.py","file_name":"simple_profit_strategy.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"634588505","text":"# All rights to this package are hereby disclaimed and its contents\n# released into the public domain by the authors.\n\n# Sample code authorization support.\nimport auth\n# Functions to help run a load job.\nimport run_load\n\ndef main():\n service = auth.build_bq_client()\n\n # Load configuration with the destination specified.\n load_config = {\n 'destinationTable': {\n 'projectId': 'publicdata',\n 'datasetId': 'samples',\n 'tableId': 'mypersonaltable'\n }\n }\n # Setup the job here.\n # load[property] = value\n load_config['sourceUris'] = [\n 'gs://bigquery-e2e/chapters/06/sample.csv',\n ]\n # End of job configuration.\n\n run_load.start_and_wait(service.jobs(),\n auth.PROJECT_ID,\n load_config)\n\nif __name__ == '__main__':\n main()\n","sub_path":"samples/ch06/load_error_access_denied.py","file_name":"load_error_access_denied.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"157295362","text":"\"\"\"\nCopyright 2018 Rackspace\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport json\n\nfrom cafe.engine.models.base import AutoMarshallingModel\n\n\nclass VirtualInterface(AutoMarshallingModel):\n\n def __init__(self, id=None, mac_address=None, ip_addresses=None):\n\n \"\"\"\n An object that represents the data of a Virtual Interface.\n \"\"\"\n super(VirtualInterface, self).__init__()\n self.id = id\n self.mac_address = mac_address\n self.ip_addresses = ip_addresses or []\n\n def get_ipv4_address(self, network_id):\n ret = None\n for ip_address in self.ip_addresses:\n if (ip_address.network_id == network_id and\n ip_address.address.find('.') > 0):\n ret = ip_address\n break\n return ret\n\n def get_ipv6_address(self, network_id):\n ret = None\n for ip_address in self.ip_addresses:\n if (ip_address.network_id == network_id and\n ip_address.address.find(':') > 0):\n ret = ip_address\n break\n return ret\n\n @property\n def network_label(self):\n for ip_address in self.ip_addresses:\n if ip_address.network_label is not None:\n return ip_address.network_label\n\n @property\n def network_id(self):\n for ip_address in self.ip_addresses:\n if ip_address.network_id is not None:\n return ip_address.network_id\n\n @classmethod\n def _json_to_obj(cls, serialized_str):\n ret = None\n json_dict = json.loads(serialized_str)\n vif = 'virtual_interface'\n vifs = 'virtual_interfaces'\n if vif in json_dict:\n interface_dict = json_dict.get(vif)\n ip_addrs = IPAddress._dict_to_obj(interface_dict)\n interface_dict['ip_addresses'] = ip_addrs\n ret = VirtualInterface(**interface_dict)\n if vifs in json_dict:\n ret = []\n for interface_dict in json_dict.get(vifs):\n ip_addrs = IPAddress._dict_to_obj(interface_dict)\n interface_dict['ip_addresses'] = ip_addrs\n ret.append(VirtualInterface(**interface_dict))\n return ret\n\n\nclass IPAddress(AutoMarshallingModel):\n\n def __init__(self, network_id=None, network_label=None, address=None):\n super(IPAddress, self).__init__()\n self.network_id = network_id\n self.network_label = network_label\n self.address = address\n\n @classmethod\n def _json_to_obj(cls, serialized_str):\n json_dict = json.loads(serialized_str)\n return cls._dict_to_obj(json_dict)\n\n @classmethod\n def _dict_to_obj(cls, json_dict):\n ret = []\n if 'ip_addresses' in json_dict:\n ret = [IPAddress(**addr) for addr in json_dict.get('ip_addresses')]\n return ret\n","sub_path":"cloudcafe/networking/networks/common/models/response/virtual_interface.py","file_name":"virtual_interface.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"420599398","text":"#!/usr/bin/env python\n# coding: utf-8\nimport _env # noqa\nfrom solo.web.mongo import Doc\nfrom app.pspm.model import GidKey\nfrom app.web.model.gid import gid as _gid\nfrom app.pspm.controller.tools import DateTime\n__author__ = 'ZivLi'\n\n\nclass LogOperation(Doc):\n\n structure = dict(\n _id=int,\n user_id=str,\n user_name=str,\n role=str,\n route=str,\n operation=str,\n operate_time=str,\n deleted=bool\n )\n\n _t = DateTime()\n default_values = {\n \"deleted\": False\n }\n\n @classmethod\n def _create(cls, **kw):\n logop = LogOperation(dict(\n _id=_gid(GidKey.log_operation_key),\n user_id=kw.get(\"user_id\"),\n user_name=kw.get(\"user_name\"),\n role=kw.get(\"role\"),\n route=kw.get(\"route\"),\n operation=kw.get(\"operation\"),\n operate_time=kw.get(\"operation_time\")\n ), True)\n logop.save()\n return logop\n\n @classmethod\n def get_list(cls, keyword=None, limit=0, offset=0, fields_display=None):\n spec = dict(deleted=False)\n lop = cls.find(spec, fields_display, limit=limit, skip=offset,\n sort=[('_id', -1)])\n lopcount = LogOperation.count(spec)\n return lop, lopcount\n","sub_path":"pspm/model/log_operation.py","file_name":"log_operation.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"544277164","text":"from django.db import models\n\nclass UserFeedback(models.Model):\n\tIMAGE_DIR_PATH = 'images/'\n\tIMG_TAG = (\n\t\t('exterior', 'exterior'),\n\t\t('interior', 'interior'),\n\t\t('others', 'others'),\n\t)\n\n\tname = models.CharField(max_length = 30, default = \"Ekko User\")\n\trating = models.IntegerField(default = 4)\n\treview = models.TextField(default='Quality Service and Friendly Staff, Must try!')\n\tpicture = models.ImageField(upload_to = IMAGE_DIR_PATH)\n\tpicture_tag = models.CharField(max_length = 9, choices = IMG_TAG, default = 'exterior')","sub_path":"EkkoWash/Django/ekkowash/feedback/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"152500912","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)\n\nfrom _builtins import _str_from_str, _str_guard, _str_len\n\n\n_empty_iterator = iter(())\n\n\nclass _SubscriptParser:\n def __init__(self, field_name, idx):\n self.field_name = field_name\n self.idx = idx\n\n def __iter__(self):\n return self\n\n def __next__(self):\n field_name = self.field_name\n if not field_name:\n raise StopIteration\n if field_name[0] != \"[\" and field_name[0] != \".\":\n raise ValueError(\"Only '.' or '[' may follow ']' in format field specifier\")\n if field_name[0] == \".\":\n right_idx = find_arg_end(field_name[1:])\n subscript = (\n field_name[self.idx + 1 :]\n if right_idx == -1\n else field_name[self.idx + 1 : right_idx + 1]\n )\n if subscript == \"\":\n raise ValueError(\"Empty attribute in format string\")\n self.field_name = \"\" if right_idx == -1 else field_name[right_idx + 1 :]\n self.idx = 0\n return (True, subscript)\n right_idx = field_name.find(\"]\")\n if right_idx == -1:\n raise ValueError(\"Missing ']' in format string\")\n subscript = field_name[self.idx + 1 : right_idx]\n if subscript == \"\":\n raise ValueError(\"Empty attribute in format string\")\n self.field_name = field_name[right_idx + 1 :]\n self.idx = 0\n return (False, int(subscript) if subscript.isdigit() else subscript)\n\n\ndef find_arg_end(field_name):\n \"\"\"\n Returns the index of the end of an attribute name or element index.\n field_name: the field being looked up, e.g. \"0.name\"\n or \"lookup[3]\"\n \"\"\"\n dot_idx = field_name.find(\".\")\n lbrack_idx = field_name.find(\"[\")\n if dot_idx == -1:\n return lbrack_idx\n if lbrack_idx == -1:\n return dot_idx\n return min(dot_idx, lbrack_idx)\n\n\ndef formatter_field_name_split(field_name):\n _str_guard(field_name)\n\n idx = find_arg_end(field_name)\n if idx != -1:\n field = field_name[:idx]\n if field.isdigit():\n field = int(field)\n elif not field:\n # In order to accept \"[0]\" as an implicit \"0[0]\", return 0 instead\n # of the empty string here. See https://bugs.python.org/issue39985\n # for more detail.\n field = 0\n return (field, _SubscriptParser(field_name[idx:], 0))\n\n if field_name.isdigit():\n field_name = int(field_name)\n else:\n field_name = _str_from_str(str, field_name)\n return (field_name, _empty_iterator)\n\n\ndef formatter_parser(string): # noqa: C901\n _str_guard(string)\n idx = -1\n fragment_begin = 0\n it = str.__iter__(string)\n end_error = None\n try:\n while True:\n idx += 1\n ch = it.__next__()\n if ch == \"}\":\n end_error = \"Single '}' encountered in format string\"\n idx += 1\n next_ch = it.__next__()\n\n if next_ch != \"}\":\n raise ValueError(end_error)\n yield (string[fragment_begin:idx], None, None, None)\n end_error = None\n fragment_begin = idx + 1\n continue\n if ch != \"{\":\n continue\n\n end_error = \"Single '{' encountered in format string\"\n idx += 1\n next_ch = it.__next__()\n\n if next_ch == \"{\":\n yield (string[fragment_begin:idx], None, None, None)\n end_error = None\n fragment_begin = idx + 1\n continue\n\n fragment = string[fragment_begin : idx - 1]\n\n ch = next_ch\n id_begin = idx\n end_error = \"expected '}' before end of string\"\n while ch != \"}\" and ch != \"!\" and ch != \":\":\n if ch == \"{\":\n raise ValueError(\"unexpected '{' in field name\")\n if ch == \"[\":\n while True:\n idx += 1\n ch = it.__next__()\n if ch == \"]\":\n break\n idx += 1\n ch = it.__next__()\n ident = string[id_begin:idx]\n\n if ch == \"!\":\n end_error = \"end of string while looking for conversion specifier\"\n idx += 1\n ch = it.__next__()\n end_error = \"unmatched '{' in format spec\"\n conversion = ch\n\n idx += 1\n ch = it.__next__()\n if ch != \":\" and ch != \"}\":\n raise ValueError(\"expected ':' after conversion specifier\")\n else:\n conversion = None\n\n spec = \"\"\n if ch == \":\":\n spec_begin = idx + 1\n end_error = \"unmatched '{' in format spec\"\n curly_count = 1\n while True:\n idx += 1\n ch = it.__next__()\n if ch == \"{\":\n curly_count += 1\n continue\n if ch == \"}\":\n curly_count -= 1\n if curly_count == 0:\n spec = string[spec_begin:idx]\n break\n\n yield (fragment, ident, spec, conversion)\n fragment_begin = idx + 1\n end_error = None\n except StopIteration:\n if end_error is not None:\n raise ValueError(end_error)\n # Make sure everyone called `idx += 1` before `it.__next__()`.\n assert idx == _str_len(string)\n\n if idx - fragment_begin > 0:\n yield (string[fragment_begin:idx], None, None, None)\n","sub_path":"library/_string.py","file_name":"_string.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"510398943","text":"#\n# This file is part of PCAP BGP Parser (pbgpp)\n#\n# Copyright 2016-2017 DE-CIX Management GmbH\n# Author: Tobias Hannaske \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport socket\nimport struct\nimport math\n\nfrom pbgpp.BGP.Statics import BGPStatics\nfrom pbgpp.BGP.Exceptions import BGPRouteInitializeError, BGPRouteConvertionError\n\n\nclass BGPRoute:\n def __init__(self, prefix, prefix_length, proto=BGPStatics.IP4_CODE): #If ipv6, proto needs to be set. otherwise, this operation\n # A route is universally used\n # Prefix = e.g. 123.123.123.123\n # Length = 32\n # To String: 123.123.123.123/32 (CIDR notation)\n #\n # Or IPv6\n # Prefix = e.g. 1337:1337:1337:1337::\n # Length = 64\n # To String: 1337:1337:1337:1337::/64 (CIDR notation)\n\n # Assign values\n self.proto = proto\n self.prefix = prefix\n self.prefix_length = prefix_length\n\n # Values that need to be assigned due to parsing\n self.prefix_string = None\n self.prefix_length_string = None\n self.prefix_length_decimal = None\n\n self._parse()\n\n @classmethod\n def from_binary(cls, prefix, prefix_length, proto=BGPStatics.IP4_CODE):\n # Create a class instance from bytes\n if isinstance(prefix, bytes) and isinstance(prefix_length, bytes):\n return cls(prefix, prefix_length, proto)\n else:\n raise BGPRouteInitializeError(\"prefix and prefix_length must be instance of bytes.\")\n\n def __str__(self):\n # Return the prefix string that was created during parsing\n return self.prefix_string\n\n def __eq__(self, other):\n # Compare two routes by comparing the prefix and its length\n if isinstance(other, BGPRoute):\n return self.prefix == other.prefix and self.prefix_length == other.prefix_length\n else:\n # This wont work for any other classes. Just for BGPRoute objects.\n return NotImplemented\n\n def _parse(self):\n if self.proto == BGPStatics.IP4_CODE:\n # Check the prefix length at first as that length is needed to determine\n # how many bytes we need to parse afterwards\n self.prefix_length_decimal = struct.unpack(\"!B\", self.prefix_length)[0]\n self.prefix_length_string = str(self.prefix_length_decimal)\n\n if 0 <= self.prefix_length_decimal <= 8:\n # Length of prefix field: 1 Byte\n fields = struct.unpack(\"!B\", self.prefix)\n self.prefix_string = str(fields[0]) + \".0.0.0/\" + self.prefix_length_string\n\n elif 9 <= self.prefix_length_decimal <= 16:\n # Length of prefix field: 2 Bytes\n fields = struct.unpack(\"!BB\", self.prefix)\n self.prefix_string = str(fields[0]) + \".\" + str(fields[1]) + \".0.0/\" + self.prefix_length_string\n\n elif 17 <= self.prefix_length_decimal <= 24:\n # Length of prefix field: 3 Bytes\n fields = struct.unpack(\"!BBB\", self.prefix)\n self.prefix_string = str(fields[0]) + \".\" + str(fields[1]) + \".\" + str(fields[2]) + \".0/\" + self.prefix_length_string\n\n elif 25 <= self.prefix_length_decimal:\n # Length of prefix field: 4 Bytes\n fields = struct.unpack(\"!BBBB\", self.prefix)\n self.prefix_string = str(fields[0]) + \".\" + str(fields[1]) + \".\" + str(fields[2]) + \".\" + str(fields[3]) + \"/\" + self.prefix_length_string\n\n else:\n raise BGPRouteConvertionError(\"was not able to parse bytes.\")\n \n else:\n # Check the prefix length at first as that length is needed to determine\n # how many bytes we need to parse afterwards\n self.prefix_string = \"\"\n\n self.prefix_length_decimal = struct.unpack(\"!B\", self.prefix_length)[0]\n self.prefix_length_string = str(self.prefix_length_decimal)\n\n byte_len = int(math.ceil(self.prefix_length_decimal / 8))\n\n if self.prefix_length_decimal >= 0 and self.prefix_length_decimal <= 128:\n if byte_len == 0:\n self.prefix_string += \"::\"\n else:\n\n i=0\n while i < byte_len:\n\n if i+1 < byte_len: # interpet two bytes\n field = struct.unpack(\"!H\", self.prefix[i:i+2])[0]\n self.prefix_string += str( hex(field)[2:] ) + \":\"\n i+=1\n\n else: # interpret one byte\n field = struct.unpack(\"!B\", self.prefix[i])[0]\n if field == 0: # if zero, use the approriate formatting\n self.prefix_string += \"0:\"\n else:\n self.prefix_string += str( hex(field)[2:] ) + \"00:\"\n\n i+=1\n\n if byte_len == 16:\n self.prefix_string = self.prefix_length_string[:-1]\n else:\n self.prefix_string += \":\"\n\n self.prefix_string += \"/\" + str(self.prefix_length_string)\n\n else:\n raise BGPRouteConvertionError(\"was not able to parse bytes.\")\n\n\n @staticmethod\n def decimal_ip_to_string(decimal): # implement 16byte int to convert to ipv6 addresses\n return socket.inet_ntoa(struct.pack('!L', decimal))\n","sub_path":"pbgpp/BGP/Update/Route.py","file_name":"Route.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"170548493","text":"class FileInfo:\n def __init__(self, name, size, filetype, filepath, revision_list):\n self.name = name\n self.size = size\n self.filetype = filetype\n self.filepath = filepath\n self.revision_list = revision_list\n \nclass CommitHistory:\n def __init__(self, revision, author, summary, date):\n self.revision = revision\n self.author = author\n self.summary = summary\n self.date = date","sub_path":"SVNProjectPortfolio/project_portfolio/static/files/szhou42/Assignment3.0/project_portfolio/FileInfo.py","file_name":"FileInfo.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"232126765","text":"#!/usr/bin/env python\n\nimport getopt\nimport os\nimport shutil\nimport sys\nimport tempfile\nfrom shutil import copyfile\n\n\ndef usage():\n sys.stderr.write(\"%s -p|--program -o|--ofile \\n\" % sys.argv[0])\n sys.stderr.write(\"Sample: %s -p \\\"{[(1),(2,3)]*1,[(4,5),(6)]*3,[(7)]*1}\\\" -o prog.pdf\\n\" % sys.argv[0])\n\n\nclass RawLexer:\n spaces = {\" \": 0, \"\\t\": 1, \"\\n\": 2}\n numbers = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4,\n \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9}\n\n def __init__(self, it):\n self.iterator = it\n self.peeked = None\n\n def next(self):\n if self.peeked != None:\n item = self.peeked\n self.peeked = None\n else:\n try:\n item = self.iterator.next()\n except StopIteration:\n return None\n while item in RawLexer.spaces:\n try:\n item = self.iterator.next()\n except StopIteration:\n return None\n if item not in RawLexer.numbers and not item.isalpha():\n return item\n\n result = item\n while True:\n try:\n self.peeked = self.iterator.next()\n except StopIteration:\n self.peeked = None\n if self.peeked not in RawLexer.numbers and not self.peeked.isalpha():\n break\n result = result + self.peeked\n return result\n\n\nclass Lexer:\n def __init__(self, it):\n self.rlexer = RawLexer(it)\n self.peeked = None\n\n def next(self):\n if self.peeked == None:\n return self.rlexer.next()\n else:\n c = self.peeked\n self.peeked = None\n return c\n\n def peek(self):\n if self.peeked == None:\n self.peeked = self.rlexer.next()\n return self.peeked\n\n\nclass Parse:\n @staticmethod\n def eat(seen, expected):\n if (seen != expected):\n raise Exception('Parsing error, unexpected text. Found: ' + seen + 'was expecting: ' + expected)\n\n\nclass Program:\n def __init__(self):\n self.regions = []\n\n def addRegion(self, region):\n self.regions.append(region)\n\n def getRegions(self):\n return self.regions\n\n @staticmethod\n def parse(lexer):\n program = Program()\n c = lexer.next()\n Parse.eat(c, \"{\")\n done = False\n first = True\n while not done:\n c = lexer.peek()\n if c == \"}\":\n c = lexer.next()\n Parse.eat(c, \"}\")\n done = True\n else:\n if not first:\n c = lexer.next()\n Parse.eat(c, \",\")\n region = Region.parse(lexer)\n program.addRegion(region)\n first = False\n return program\n\n def getText(self):\n result = \"{\"\n regions = self.getRegions()\n if (len(regions) > 0):\n region = regions[0]\n result = result + region.getText()\n for region in regions[1:]:\n result = result + \",\" + region.getText()\n result = result + \"}\"\n return result\n\n\nclass Region:\n def __init__(self):\n self.pipelines = []\n self.numReplicas = 0\n\n def setNumReplicas(self, numReplicas):\n self.numReplicas = numReplicas\n\n def getNumReplicas(self):\n return self.numReplicas\n\n def addPipeline(self, pipeline):\n self.pipelines.append(pipeline)\n\n def getPipelines(self):\n return self.pipelines\n\n @staticmethod\n def parse(lexer):\n region = Region()\n c = lexer.next()\n Parse.eat(c, \"[\")\n done = False\n first = True\n while not done:\n c = lexer.peek()\n if c == \"]\":\n c = lexer.next()\n Parse.eat(c, \"]\")\n done = True\n else:\n if not first:\n c = lexer.next()\n Parse.eat(c, \",\")\n pipeline = Pipeline.parse(lexer)\n region.addPipeline(pipeline)\n first = False\n c = lexer.next()\n Parse.eat(c, \"*\")\n replicas = lexer.next()\n region.setNumReplicas(int(replicas))\n return region\n\n def getText(self):\n result = \"[\"\n pipelines = self.getPipelines()\n if (len(pipelines) > 0):\n pipeline = pipelines[0]\n result = result + pipeline.getText()\n for pipeline in pipelines[1:]:\n result = result + \",\" + pipeline.getText()\n result = result + \"]\"\n result = result + \"x\" + str(self.getNumReplicas())\n return result\n\n\nclass Pipeline:\n def __init__(self):\n self.operators = []\n\n def addOperator(self, operator):\n self.operators.append(operator)\n\n def getOperators(self):\n return self.operators\n\n @staticmethod\n def parse(lexer):\n pipeline = Pipeline()\n c = lexer.next()\n Parse.eat(c, \"(\")\n done = False\n first = True\n while not done:\n c = lexer.peek()\n\n if c == \")\":\n c = lexer.next()\n Parse.eat(c, \")\")\n done = True\n else:\n if not first:\n c = lexer.next()\n Parse.eat(c, \",\")\n operator = lexer.next()\n pipeline.addOperator(operator)\n first = False\n return pipeline\n\n def getText(self):\n result = \"(\"\n operators = self.getOperators()\n if (len(operators) > 0):\n operator = operators[0]\n result = result + operator\n for operator in operators[1:]:\n result = result + \",\" + operator\n result = result + \")\"\n return result\n\n\ndef printProgramLatex(program, file):\n print >> file, \"\\\\documentclass{article}\"\n print >> file, \"\\\\usepackage{tikz}\"\n print >> file, \"\\\\usetikzlibrary{external}\"\n print >> file, \"\\\\usetikzlibrary{fit}\"\n print >> file, \"\\\\usetikzlibrary{arrows}\"\n print >> file, \"\\\\begin{document}\"\n print >> file, \"\\\\begin{center}\"\n print >> file, \"\\\\resizebox{\\\\linewidth}{!}{\"\n print >> file, \"\\\\tikzstyle{region} = [rectangle,draw]\"\n print >> file, \"\\\\tikzstyle{pipeline} = [rectangle,rounded corners,draw]\"\n print >> file, \"\\\\tikzstyle{oper} = [circle,fill=white,node distance=0.2\\\\linewidth,draw]\"\n print >> file, \"\\\\tikzstyle{joint} = [circle,fill=black,draw]\"\n print >> file, \"\\\\tikzstyle{stream} = [-latex',draw]\"\n print >> file, \"\\\\tikzstyle{line} = [draw]\"\n print >> file, \"\\\\begin{tikzpicture}[auto]\"\n for (regionIndex, region) in enumerate(program.getRegions()):\n if (regionIndex == 0):\n print >> file, \"\\\\node[joint](j%s){};\" % regionIndex\n else:\n print >> file, \"\\\\node[joint,right of=%s](j%s){};\" % (lastBox, regionIndex)\n lastBox = \"j%s\" % regionIndex\n for replica in xrange(0, region.getNumReplicas()):\n for (pipelineIndex, pipeline) in enumerate(region.getPipelines()):\n operList = \"\"\n for (operatorIndex, operator) in enumerate(pipeline.getOperators()):\n if replica == 0:\n print >> file, \"\\\\node[oper,right of=%s](o%s_%s){$o_{%s,%s}$};\" % (lastBox, operator, replica, operator, replica)\n lastBox = \"o%s_%s\" % (operator, replica)\n else:\n print >> file, \"\\\\node[oper,above of=o%s_%s](o%s_%s){$o_{%s,%s}$};\" % (\n operator, replica - 1, operator, replica, operator, replica)\n operList = operList + (\"(o%s_%s)\" % (operator, replica))\n print >> file, \"\\\\node[pipeline,fit=%s] (t%s_%s) {};\" % (operList, pipelineIndex, replica)\n print >> file, \"\\\\node[joint,right of=%s](j%s){};\" % (lastBox, len(program.getRegions()))\n for (regionIndex, region) in enumerate(program.getRegions()):\n for replica in xrange(0, region.getNumReplicas()):\n for (pipelineIndex, pipeline) in enumerate(region.getPipelines()):\n lastOperator = \"\"\n for (operatorIndex, operator) in enumerate(pipeline.getOperators()):\n if operatorIndex > 0:\n print >> file, \"\\\\path[stream] (o%s_%s) -- (o%s_%s);\" % (lastOperator, replica, operator, replica)\n if pipelineIndex == 0 and operatorIndex == 0:\n print >> file, \"\\\\path[stream] (j%s) -- (o%s_%s);\" % (regionIndex, operator, replica)\n if pipelineIndex == len(region.getPipelines()) - 1 and operatorIndex == len(pipeline.getOperators()) - 1:\n print >> file, \"\\\\path[line] (o%s_%s) -- (j%s);\" % (operator, replica, regionIndex + 1)\n lastOperator = operator\n if pipelineIndex > 0:\n lastOp = region.getPipelines()[pipelineIndex - 1].getOperators()[-1]\n firstOp = pipeline.getOperators()[0]\n print >> file, \"\\\\path[stream] (o%s_%s) -- (o%s_%s);\" % (lastOp, replica, firstOp, replica)\n print >> file, \"\\\\end{tikzpicture}\"\n print >> file, \"}\"\n print >> file, \"\\\\end{center}\"\n print >> file, \"\\\\end{document}\"\n file.flush()\n\n\nif __name__ == '__main__':\n try:\n optlist, remaining = getopt.getopt(sys.argv[1:], \"hp:o:\", [\"help\", \"program=\", \"ofile=\"])\n except getopt.GetoptError:\n usage()\n sys.exit(2)\n programText = \"\"\n outputFile = \"\"\n for opt, arg in optlist:\n if opt in (\"-h\"):\n usage()\n sys.exit(0)\n elif opt in (\"-p\", \"--program\"):\n programText = arg\n elif opt in (\"-o\", \"--ofile\"):\n outputFile = arg\n lexer = Lexer(iter(programText))\n program = Program.parse(lexer)\n try:\n mydir = os.getcwd()\n tmpdir = tempfile.mkdtemp()\n (tmpfd, tmpfile) = tempfile.mkstemp(dir=tmpdir)\n printProgramLatex(program, os.fdopen(tmpfd, \"w\"))\n os.chdir(tmpdir)\n os.system(\"latex '%s' > /dev/null\" % tmpfile)\n os.system(\"dvips '%s'.dvi > /dev/null 2>&1\" % tmpfile)\n os.system(\"ps2pdf '%s'.ps > /dev/null\" % tmpfile)\n os.chdir(mydir)\n copyfile(\"%s.pdf\" % tmpfile, outputFile)\n finally:\n shutil.rmtree(tmpdir)\n","sub_path":"joker-experiments/scripts/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":10437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"57433196","text":"from __future__ import division\n\nfrom pyspark.sql import SparkSession\nimport argparse\nfrom datetime import date\nimport pyspark.sql.functions as func\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport json\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pyspark.sql.types import *\nimport importlib\n\nclass ExampleUseCase():\n float_formatter = lambda self, x: \"%.2f\" % x\n\n def __init__(self, spark_session, environment, source, destination):\n ms = int(round(time.time() * 1000))\n master = \"yarn\"\n if environment == \"test\":\n master = \"local[*]\"\n self.spark = (SparkSession.builder\n .master(master)\n .appName('example_use_case_'+str(ms) )\n .enableHiveSupport()\n .getOrCreate())\n self.helpers = {}\n self.data = {}\n self.load_helpers()\n self.source = source\n self.destination = destination\n\n def load_helpers(self):\n with open('use_case/helpers/list.json') as json_file:\n data = json.load(json_file)\n for obj in data:\n self.data[obj['name']] = obj\n mod = importlib.import_module(\"use_case.helpers.\" + obj['path'])\n met = getattr(mod, obj['prefix'])\n self.helpers[obj['name']] = met\n\n def run(self):\n # for helper in self.helpers:\n # self.helpers[helper]().ingest(self.spark)\n ########## return\n for helper in self.helpers:\n self.helpers[helper]().process(self.spark, self.source)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-source', required=True)\n parser.add_argument('-destination', required=True)\n parser.add_argument('-format', choices=['csv', 'parquet'], default='csv', type=str.lower)\n parser.add_argument('-environment', default='prod')\n args = parser.parse_args()\n\n source = args.source\n destination = args.destination\n format = args.format\n\n # define master\n master = 'yarn'\n if args.environment != 'prod':\n master = 'local'\n\n spark_session = spark_session.builder.master(master).appName('example_use_case').getOrCreate()\n use_case = ExampleUseCase(spark_session=spark_session, environment=\"prod\", source=source, destination=destination)\n use_case.run()\n spark_session.stop()\n","sub_path":"use_case/src/example_use_case.py","file_name":"example_use_case.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"495467062","text":"from collections import OrderedDict\n\nfrom systems.commands import args\nfrom utility import text, data\nfrom .meta import MetaBaseMixin\n\nimport re\nimport copy\nimport json\n\n\nclass BaseMixin(object, metaclass = MetaBaseMixin):\n\n @classmethod\n def generate(cls, command, generator):\n # Override in subclass if needed\n pass\n\n\n def parse_flag(self, name, flag, help_text):\n if name not in self.option_map:\n self.add_schema_field(name,\n args.parse_bool(self.parser, name, flag, help_text),\n True\n )\n self.option_map[name] = True\n\n def parse_variable(self, name, optional, type, help_text, value_label = None, default = None, choices = None):\n if name not in self.option_map:\n if optional and isinstance(optional, (str, list, tuple)):\n if not value_label:\n value_label = name\n\n self.add_schema_field(name,\n args.parse_option(self.parser, name, optional, type, help_text,\n value_label = value_label.upper(),\n default = default,\n choices = choices\n ),\n True\n )\n else:\n self.add_schema_field(name,\n args.parse_var(self.parser, name, type, help_text,\n optional = optional,\n default = default,\n choices = choices\n ),\n optional\n )\n self.option_map[name] = True\n\n def parse_variables(self, name, optional, type, help_text, value_label = None, default = None):\n if name not in self.option_map:\n if optional and isinstance(optional, (str, list, tuple)):\n help_text = \"{} (comma separated)\".format(help_text)\n\n if not value_label:\n value_label = name\n\n self.add_schema_field(name,\n args.parse_csv_option(self.parser, name, optional, help_text,\n value_label = value_label.upper(),\n default = default\n ),\n True\n )\n else:\n self.add_schema_field(name,\n args.parse_vars(self.parser, name, type, help_text,\n optional = optional\n ),\n optional\n )\n self.option_map[name] = True\n\n def parse_fields(self, facade, name, optional = False, help_callback = None, callback_args = None, callback_options = None, exclude_fields = None):\n if not callback_args:\n callback_args = []\n if not callback_options:\n callback_options = {}\n\n if exclude_fields:\n exclude_fields = data.ensure_list(exclude_fields)\n callback_options['exclude_fields'] = exclude_fields\n\n if name not in self.option_map:\n if facade:\n help_text = \"\\n\".join(self.field_help(facade, exclude_fields))\n else:\n help_text = \"\\nfields as key value pairs\\n\"\n\n if help_callback and callable(help_callback):\n help_text += \"\\n\".join(help_callback(*callback_args, **callback_options))\n\n self.add_schema_field(name,\n args.parse_key_values(self.parser, name, help_text,\n value_label = 'field=VALUE',\n optional = optional\n ),\n optional\n )\n self.option_map[name] = True\n\n\n def parse_test(self):\n self.parse_flag('test', '--test', 'test execution without permanent changes')\n\n @property\n def test(self):\n return self.options.get('test', False)\n\n\n def parse_plan(self):\n self.parse_flag('plan', '--plan', 'generate plan of potential changes')\n\n @property\n def plan(self):\n return self.options.get('plan', False)\n\n\n def parse_force(self):\n self.parse_flag('force', '--force', 'force execution even with provider errors')\n\n @property\n def force(self):\n return self.options.get('force', False)\n\n\n def parse_count(self):\n self.parse_variable('count',\n '--count', int,\n 'instance count (default 1)',\n value_label = 'COUNT',\n default = 1\n )\n\n @property\n def count(self):\n return self.options.get('count', 1)\n\n\n def parse_clear(self):\n self.parse_flag('clear', '--clear', 'clear all items')\n\n @property\n def clear(self):\n return self.options.get('clear', False)\n\n\n def parse_search(self, optional = True, help_text = 'one or more search queries'):\n self.parse_variables('instance_search_query', optional, str, help_text,\n value_label = 'REFERENCE'\n )\n self.parse_flag('instance_search_or', '--or', 'perform an OR query on input filters')\n\n @property\n def search_queries(self):\n return self.options.get('instance_search_query', [])\n\n @property\n def search_join(self):\n join_or = self.options.get('instance_search_or', False)\n return 'OR' if join_or else 'AND'\n\n\n def parse_scope(self, facade):\n for name in facade.scope_parents:\n getattr(self, \"parse_{}_name\".format(name))(\"--{}\".format(name.replace('_', '-')))\n\n def parse_dependency(self, facade):\n for name in facade.relation_fields:\n getattr(self, \"parse_{}_name\".format(name))(\"--{}\".format(name.replace('_', '-')))\n\n def set_scope(self, facade, optional = False):\n relations = facade.relation_fields\n filters = {}\n for name in OrderedDict.fromkeys(facade.scope_parents + relations).keys():\n instance_name = getattr(self, \"{}_name\".format(name), None)\n if (optional or name in relations) and not instance_name:\n name = None\n\n if name and name in facade.fields:\n sub_facade = getattr(self, \"_{}\".format(\n facade.get_subfacade(name).name\n ))\n if facade.name != sub_facade.name:\n self.set_scope(sub_facade, optional)\n else:\n sub_facade.set_scope(filters)\n\n if instance_name:\n instance = self.get_instance(sub_facade, instance_name, required = not optional)\n if instance:\n filters[\"{}_id\".format(name)] = instance.id\n elif not optional:\n self.error(\"{} {} does not exist\".format(facade.name.title(), instance_name))\n\n facade.set_scope(filters)\n return filters\n\n def get_scope_filters(self, instance):\n facade = instance.facade\n filters = {}\n for name, value in facade.get_scope_filters(instance).items():\n filters[\"{}_name\".format(name)] = value\n return filters\n\n\n def parse_relations(self, facade):\n for field_name, info in facade.get_relations().items():\n name = info['name']\n if name != 'environment':\n option_name = \"--{}\".format(field_name.replace('_', '-'))\n\n if info['multiple']:\n method_name = \"parse_{}_names\".format(name)\n else:\n method_name = \"parse_{}_name\".format(name)\n\n getattr(self, method_name)(option_name)\n\n def get_relations(self, facade):\n relations = {}\n for field_name, info in facade.get_relations().items():\n name = info['name']\n sub_facade = getattr(self, \"_{}\".format(name), None)\n if sub_facade:\n self.set_scope(sub_facade, True)\n\n if info['multiple']:\n method_name = \"{}_names\".format(name)\n else:\n method_name = \"{}_name\".format(name)\n\n relations[field_name] = getattr(self, method_name, None)\n\n return relations\n\n\n def check_available(self, facade, name, warn = False):\n instance = self.get_instance(facade, name, required = False)\n if instance:\n if warn:\n self.warning(\"{} {} already exists\".format(\n facade.name.title(),\n name\n ))\n return False\n return True\n\n def check_exists(self, facade, name, warn = False):\n instance = self.get_instance(facade, name, required = False)\n if not instance:\n if warn:\n self.warning(\"{} {} does not exist\".format(\n facade.name.title(),\n name\n ))\n return False\n return True\n\n\n def get_instance_by_id(self, facade, id, required = True):\n instance = facade.retrieve_by_id(id)\n\n if not instance and required:\n self.error(\"{} {} does not exist\".format(facade.name.title(), id))\n elif instance and instance.initialize(self):\n return instance\n return None\n\n def get_instance(self, facade, name, required = True):\n instance = self._get_cache_instance(facade, name)\n\n if not instance:\n instance = facade.retrieve(name)\n\n if not instance and required:\n self.error(\"{} {} does not exist\".format(facade.name.title(), name))\n else:\n if instance and instance.initialize(self):\n self._set_cache_instance(facade, name, instance)\n else:\n return None\n\n return instance\n\n\n def get_instances(self, facade,\n names = [],\n objects = [],\n groups = [],\n fields = {}\n ):\n search_items = []\n results = {}\n\n if not names and not groups and not objects and not fields:\n search_items = facade.all()\n else:\n search_items.extend(data.ensure_list(names))\n search_items.extend(data.ensure_list(objects))\n\n for group in data.ensure_list(groups):\n search_items.extend(facade.keys(groups__name = group))\n\n def init_instance(object):\n if isinstance(object, str):\n cached = self._get_cache_instance(facade, object)\n if not cached:\n instance = facade.retrieve(object)\n else:\n instance = cached\n else:\n instance = object\n cached = self._get_cache_instance(facade, getattr(instance, facade.pk))\n\n if instance:\n id = getattr(instance, facade.pk)\n if not cached:\n if instance.initialize(self):\n self._set_cache_instance(facade, id, instance)\n else:\n instance = None\n else:\n instance = cached\n\n if instance:\n if fields:\n for field, values in fields.items():\n values = data.normalize_value(values)\n value = getattr(instance, field, None)\n if isinstance(values, str) and not value and re.match(r'^(none|null)$', values, re.IGNORECASE):\n results[id] = instance\n elif value and value in data.ensure_list(values):\n results[id] = instance\n else:\n results[id] = instance\n else:\n self.error(\"{} instance {} does not exist\".format(facade.name.title(), object))\n\n self.run_list(search_items, init_instance)\n return results.values()\n\n\n def search_instances(self, facade, queries = None, joiner = 'AND', error_on_empty = True):\n if not queries:\n queries = []\n\n valid_fields = facade.query_fields\n queries = data.ensure_list(queries)\n joiner = joiner.upper()\n results = {}\n\n def perform_query(filters, excludes, fields):\n instances = facade.query(**filters).exclude(**excludes)\n if len(instances) > 0:\n for instance in self.get_instances(facade,\n objects = list(instances),\n fields = fields\n ):\n results[getattr(instance, facade.pk)] = instance\n\n if queries:\n filters = {}\n excludes = {}\n extra = {}\n\n for query in queries:\n matches = re.search(r'^(\\~)?([^\\s\\=]+)\\s*(?:(\\=|[^\\s]*))\\s*(.*)', query)\n\n if matches:\n negate = True if matches.group(1) else False\n field = matches.group(2).strip()\n field_list = field.split('.')\n\n lookup = matches.group(3)\n if not lookup:\n lookup = field_list.pop()\n\n value = re.sub(r'^[\\'\\\"]|[\\'\\\"]$', '', matches.group(4).strip())\n\n base_field = field_list[0]\n field_path = \"__\".join(field_list)\n if lookup != '=':\n field_path = \"{}__{}\".format(field_path, lookup)\n\n if ',' in value:\n value = [ x.strip() for x in value.split(',') ]\n\n if value in ('null', 'NULL', 'none', 'None'):\n value = None\n elif value in ('true', 'True', 'TRUE') or lookup == 'isnull' and value == '':\n value = True\n elif value in ('false', 'False', 'FALSE'):\n value = False\n\n if joiner.upper() == 'OR':\n filters = {}\n excludes = {}\n extra = {}\n\n if base_field in valid_fields:\n if negate:\n excludes[field_path] = value\n else:\n filters[field_path] = value\n else:\n extra[field_path] = value\n\n if joiner == 'OR':\n perform_query(filters, excludes, extra)\n else:\n self.error(\"Search filter must be of the format: field[.subfield][.lookup] [=] value\".format(query))\n\n if joiner == 'AND':\n perform_query(filters, excludes, extra)\n else:\n for instance in self.get_instances(facade):\n results[getattr(instance, facade.pk)] = instance\n\n if error_on_empty and not results:\n if queries:\n self.warning(\"No {} instances were found: {}\".format(facade.name, \", \".join(queries)))\n else:\n self.warning(\"No {} instances were found\".format(facade.name))\n\n return results.values()\n\n\n def facade(self, facade, use_cache = True):\n result = None\n\n if use_cache and getattr(self, '_facade_cache', None) is None:\n self._facade_cache = {}\n\n if not isinstance(facade, str):\n name = facade.name\n else:\n name = facade\n facade = self.manager.index.get_facade_index()[name]\n\n if not self._facade_cache.get(name, None):\n if use_cache:\n self._facade_cache[name] = copy.deepcopy(facade)\n else:\n result = copy.deepcopy(facade)\n\n return self._facade_cache[name] if use_cache else result\n\n\n def get_data_set(self, data_type, *fields, filters = None, limit = 0, order = None):\n facade = self.facade(data_type)\n facade.set_limit(limit)\n facade.set_order(order)\n\n if filters is None:\n filters = {}\n\n return facade.values(*fields, **filters)\n\n def get_data_item(self, data_type, *fields, filters = None, order = None):\n return self.get_data_set(data_type, *fields,\n filters = filters,\n order = order,\n limit = 1\n )\n\n\n def field_help(self, facade, exclude_fields = None):\n field_index = facade.field_index\n system_fields = [ x.name for x in facade.system_field_instances ]\n\n if facade.name == 'user':\n system_fields.extend(['last_login', 'password']) # User abstract model exceptions\n\n lines = [ \"fields as key value pairs\", '' ]\n\n lines.append('requirements:')\n for name in facade.required:\n if exclude_fields and name in exclude_fields:\n continue\n\n if name not in system_fields:\n field = field_index[name]\n field_label = type(field).__name__.replace('Field', '').lower()\n if field_label == 'char':\n field_label = 'string'\n\n choices = []\n if field.choices:\n choices = [ self.value_color(x[0]) for x in field.choices ]\n\n lines.append(\" {} {}{}\".format(\n self.warning_color(field.name),\n field_label,\n ':> ' + \", \".join(choices) if choices else ''\n ))\n if field.help_text:\n lines.extend(('',\n \" - {}\".format(\n \"\\n\".join(text.wrap(field.help_text, 40,\n indent = \" \"\n ))\n ),\n ))\n lines.append('')\n\n lines.append('options:')\n for name in facade.optional:\n if exclude_fields and name in exclude_fields:\n continue\n\n if name not in system_fields:\n field = field_index[name]\n field_label = type(field).__name__.replace('Field', '').lower()\n if field_label == 'char':\n field_label = 'string'\n\n choices = []\n if field.choices:\n choices = [ self.value_color(x[0]) for x in field.choices ]\n\n lines.append(\" {} {} ({}){}\".format(\n self.key_color(field.name),\n field_label,\n self.value_color(str(facade.get_field_default(field))),\n ':> ' + \", \".join(choices) if choices else ''\n ))\n if field.help_text:\n lines.extend(('',\n \" - {}\".format(\n \"\\n\".join(text.wrap(field.help_text, 40,\n indent = \" \"\n ))\n ),\n ))\n lines.append('')\n return lines\n\n\n def _init_instance_cache(self, facade):\n cache_variable = \"_data_{}_cache\".format(facade.name)\n\n if not getattr(self, cache_variable, None):\n setattr(self, cache_variable, {})\n\n return cache_variable\n\n def _get_cache_instance(self, facade, name):\n cache_variable = self._init_instance_cache(facade)\n return getattr(self, cache_variable).get(name, None)\n\n def _set_cache_instance(self, facade, name, instance):\n cache_variable = self._init_instance_cache(facade)\n getattr(self, cache_variable)[name] = instance\n","sub_path":"app/systems/commands/mixins/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":19479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"596245886","text":"import logging\nimport time\n\nfrom rq.timeouts import JobTimeoutException\nfrom redash import models, redis_connection, settings, statsd_client\nfrom redash.models.parameterized_query import (\n InvalidParameterError,\n QueryDetachedFromDataSourceError,\n)\nfrom redash.tasks.failure_report import track_failure\nfrom redash.tasks.queries.samples import refresh_samples\nfrom redash.utils import json_dumps, sentry\nfrom redash.worker import get_job_logger, job\nfrom redash.monitor import rq_job_ids\n\nfrom .execution import enqueue_query\nfrom .samples import truncate_long_string\n\nlogger = get_job_logger(__name__)\n\n\ndef empty_schedules():\n logger.info(\"Deleting schedules of past scheduled queries...\")\n\n queries = models.Query.past_scheduled_queries()\n for query in queries:\n query.schedule = None\n models.db.session.commit()\n\n logger.info(\"Deleted %d schedules.\", len(queries))\n\n\ndef _should_refresh_query(query):\n if settings.FEATURE_DISABLE_REFRESH_QUERIES:\n logger.info(\"Disabled refresh queries.\")\n return False\n elif query.org.is_disabled:\n logger.debug(\"Skipping refresh of %s because org is disabled.\", query.id)\n return False\n elif query.data_source is None:\n logger.debug(\"Skipping refresh of %s because the datasource is none.\", query.id)\n return False\n elif query.data_source.paused:\n logger.debug(\n \"Skipping refresh of %s because datasource - %s is paused (%s).\",\n query.id,\n query.data_source.name,\n query.data_source.pause_reason,\n )\n return False\n else:\n return True\n\n\ndef _apply_default_parameters(query):\n parameters = {p[\"name\"]: p.get(\"value\") for p in query.parameters}\n if any(parameters):\n try:\n return query.parameterized.apply(parameters).query\n except InvalidParameterError as e:\n error = u\"Skipping refresh of {} because of invalid parameters: {}\".format(\n query.id, str(e)\n )\n track_failure(query, error)\n raise\n except QueryDetachedFromDataSourceError as e:\n error = (\n \"Skipping refresh of {} because a related dropdown \"\n \"query ({}) is unattached to any datasource.\"\n ).format(query.id, e.query_id)\n track_failure(query, error)\n raise\n else:\n return query.query_text\n\n\nclass RefreshQueriesError(Exception):\n pass\n\n\ndef refresh_queries():\n logger.info(\"Refreshing queries...\")\n enqueued = []\n for query in models.Query.outdated_queries():\n if not _should_refresh_query(query):\n continue\n\n try:\n enqueue_query(\n _apply_default_parameters(query),\n query.data_source,\n query.user_id,\n scheduled_query=query,\n metadata={\"Query ID\": query.id, \"Username\": \"Scheduled\"},\n )\n enqueued.append(query)\n except Exception as e:\n message = \"Could not enqueue query %d due to %s\" % (query.id, repr(e))\n logging.info(message)\n error = RefreshQueriesError(message).with_traceback(e.__traceback__)\n sentry.capture_exception(error)\n\n status = {\n \"outdated_queries_count\": len(enqueued),\n \"last_refresh_at\": time.time(),\n \"query_ids\": json_dumps([q.id for q in enqueued]),\n }\n\n redis_connection.hmset(\"redash:status\", status)\n logger.info(\"Done refreshing queries: %s\" % status)\n\n\ndef cleanup_query_results():\n \"\"\"\n Job to cleanup unused query results -- such that no query links to them anymore, and older than\n settings.QUERY_RESULTS_MAX_AGE (a week by default, so it's less likely to be open in someone's browser and be used).\n\n Each time the job deletes only settings.QUERY_RESULTS_CLEANUP_COUNT (100 by default) query results so it won't choke\n the database in case of many such results.\n \"\"\"\n\n logger.info(\n \"Running query results clean up (removing maximum of %d unused results, that are %d days old or more)\",\n settings.QUERY_RESULTS_CLEANUP_COUNT,\n settings.QUERY_RESULTS_CLEANUP_MAX_AGE,\n )\n\n unused_query_results = models.QueryResult.unused(\n settings.QUERY_RESULTS_CLEANUP_MAX_AGE\n )\n deleted_count = models.QueryResult.query.filter(\n models.QueryResult.id.in_(\n unused_query_results.limit(settings.QUERY_RESULTS_CLEANUP_COUNT).subquery()\n )\n ).delete(synchronize_session=False)\n models.db.session.commit()\n logger.info(\"Deleted %d unused query results.\", deleted_count)\n\n\ndef remove_ghost_locks():\n \"\"\"\n Removes query locks that reference a non existing RQ job.\n \"\"\"\n keys = redis_connection.keys(\"query_hash_job:*\")\n locks = {k: redis_connection.get(k) for k in keys}\n jobs = list(rq_job_ids())\n\n count = 0\n\n for lock, job_id in locks.items():\n if job_id not in jobs:\n redis_connection.delete(lock)\n count += 1\n\n logger.info(\"Locks found: {}, Locks removed: {}\".format(len(locks), count))\n\n\n@job(settings.SCHEMAS_REFRESH_QUEUE, timeout=settings.SCHEMA_REFRESH_TIME_LIMIT)\ndef refresh_schema(data_source_id, max_type_string_length=250):\n ds = models.DataSource.get_by_id(data_source_id)\n logger.info(\"task=refresh_schema state=start ds_id=%s\", ds.id)\n lock_key = \"data_source:schema:refresh:{}:lock\".format(data_source_id)\n lock = redis_connection.lock(lock_key, timeout=settings.SCHEMA_REFRESH_TIME_LIMIT)\n acquired = lock.acquire(blocking=False)\n start_time = time.time()\n\n if acquired:\n logger.info(\"task=refresh_schema state=locked ds_id=%s\", ds.id)\n try:\n # Stores data from the updated schema that tells us which\n # columns and which tables currently exist\n existing_tables_set = set()\n existing_columns_set = set()\n\n # Stores data that will be inserted into postgres\n table_data = {}\n column_data = {}\n\n new_column_names = {}\n new_column_metadata = {}\n\n for table in ds.query_runner.get_schema(get_stats=True):\n table_name = table[\"name\"]\n existing_tables_set.add(table_name)\n\n table_data[table_name] = {\n \"org_id\": ds.org_id,\n \"name\": table_name,\n \"data_source_id\": ds.id,\n \"column_metadata\": \"metadata\" in table,\n \"exists\": True,\n }\n new_column_names[table_name] = table[\"columns\"]\n new_column_metadata[table_name] = table.get(\"metadata\", None)\n\n models.TableMetadata.store(ds, existing_tables_set, table_data)\n\n all_existing_persisted_tables = models.TableMetadata.query.filter(\n models.TableMetadata.exists.is_(True),\n models.TableMetadata.data_source_id == ds.id,\n ).all()\n\n for table in all_existing_persisted_tables:\n for i, column in enumerate(new_column_names.get(table.name, [])):\n existing_columns_set.add(column)\n column_data[column] = {\n \"org_id\": ds.org_id,\n \"table_id\": table.id,\n \"name\": column,\n \"type\": None,\n \"exists\": True,\n }\n\n if table.column_metadata:\n column_type = new_column_metadata[table.name][i][\"type\"]\n column_type = truncate_long_string(\n column_type, max_type_string_length\n )\n column_data[column][\"type\"] = column_type\n\n models.ColumnMetadata.store(table, existing_columns_set, column_data)\n\n existing_columns_list = list(existing_columns_set)\n\n # If a column did not exist, set the 'column_exists' flag to false.\n models.ColumnMetadata.query.filter(\n models.ColumnMetadata.exists.is_(True),\n models.ColumnMetadata.table_id == table.id,\n ~models.ColumnMetadata.name.in_(existing_columns_list),\n ).update(\n {\"exists\": False, \"updated_at\": models.db.func.now()},\n synchronize_session=\"fetch\",\n )\n\n # Clear the set for the next round\n existing_columns_set.clear()\n\n # If a table did not exist in the get_schema() response above,\n # set the 'exists' flag to false.\n existing_tables_list = list(existing_tables_set)\n models.TableMetadata.query.filter(\n models.TableMetadata.exists.is_(True),\n models.TableMetadata.data_source_id == ds.id,\n ~models.TableMetadata.name.in_(existing_tables_list),\n ).update(\n {\"exists\": False, \"updated_at\": models.db.func.now()},\n synchronize_session=\"fetch\",\n )\n\n models.db.session.commit()\n\n logger.info(\"task=refresh_schema state=caching ds_id=%s\", ds.id)\n ds.schema_cache.populate(forced=True)\n logger.info(\"task=refresh_schema state=cached ds_id=%s\", ds.id)\n\n logger.info(\n \"task=refresh_schema state=finished ds_id=%s runtime=%.2f\",\n ds.id,\n time.time() - start_time,\n )\n statsd_client.incr(\"refresh_schema.success\")\n except JobTimeoutException:\n logger.info(\n \"task=refresh_schema state=timeout ds_id=%s runtime=%.2f\",\n ds.id,\n time.time() - start_time,\n )\n statsd_client.incr(\"refresh_schema.timeout\")\n except Exception:\n logger.warning(\n \"Failed refreshing schema for the data source: %s\", ds.name, exc_info=1\n )\n statsd_client.incr(\"refresh_schema.error\")\n logger.info(\n \"task=refresh_schema state=failed ds_id=%s runtime=%.2f\",\n ds.id,\n time.time() - start_time,\n )\n finally:\n lock.release()\n logger.info(\"task=refresh_schema state=unlocked ds_id=%s\", ds.id)\n else:\n logger.info(\"task=refresh_schema state=alreadylocked ds_id=%s\", ds.id)\n\n\ndef refresh_schemas():\n \"\"\"\n Refreshes the data sources schemas.\n \"\"\"\n blacklist = [\n int(ds_id)\n for ds_id in redis_connection.smembers(\"data_sources:schema:blacklist\")\n if ds_id\n ]\n global_start_time = time.time()\n\n logger.info(u\"task=refresh_schemas state=start\")\n\n for ds in models.DataSource.query:\n if ds.paused:\n logger.info(\n u\"task=refresh_schema state=skip ds_id=%s reason=paused(%s)\",\n ds.id,\n ds.pause_reason,\n )\n elif ds.id in blacklist:\n logger.info(\n u\"task=refresh_schema state=skip ds_id=%s reason=blacklist\", ds.id\n )\n elif ds.org.is_disabled:\n logger.info(\n u\"task=refresh_schema state=skip ds_id=%s reason=org_disabled\", ds.id\n )\n else:\n refresh_schema.delay(ds.id)\n refresh_samples.delay(ds.id, table_sample_limit=50)\n\n logger.info(\n u\"task=refresh_schemas state=finish total_runtime=%.2f\",\n time.time() - global_start_time,\n )\n","sub_path":"redash/tasks/queries/maintenance.py","file_name":"maintenance.py","file_ext":"py","file_size_in_byte":11610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"627232803","text":"'''\nCreated on Dec 1, 2012\n\n@author: mark\n'''\nimport webapp2\nfrom envdef import Handler\nfrom dbfunc import getGenreList\n\nHTML_TEMPLATE = \"mainpage.html\"\n\nclass MainPage(Handler):\n def get(self, arg):\n user = self.testCookie('user')\n if not user:\n self.redirect(\"/login\")\n return\n rating = str(self.testCookie('rating'))[len(user):len(user)+7]\n genreList = getGenreList()\n \n self.render(HTML_TEMPLATE, username=user, rating=rating, genreList=genreList)\n \n def post(self, arg):\n self.redirect(\"/\")\n \napp = webapp2.WSGIApplication([('/(.*)', MainPage)], debug=True)\n","sub_path":"mainpage.py","file_name":"mainpage.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"579008849","text":"from .util import Xmleable, default_document\r\n\r\n\r\nclass RegistrationAddress(Xmleable):\r\n def __init__(self, address_type_code=\"0000\", address=None, urbanization=None,\r\n province_name=None, ubigeo=None, departament=None,\r\n district=None, country_code=\"PE\"):\r\n self.address_type_code = address_type_code\r\n self.address = address\r\n self.urbanization = urbanization\r\n self.province_name = province_name\r\n self.ubigeo = ubigeo\r\n self.departament = departament\r\n self.district = district\r\n self.country_code = country_code\r\n\r\n def generate_address(self):\r\n ans = default_document.createElement(\"cac:AddressLine\")\r\n line = default_document.createElement(\"cbc:Line\")\r\n text = default_document.createCDATASection(self.address)\r\n line.appendChild(text)\r\n ans.appendChild(line)\r\n return ans\r\n\r\n def generate_urbanization(self):\r\n ans = default_document.createElement(\"cbc:CitySubdivisionName\")\r\n text = default_document.createTextNode(self.urbanization)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n def generate_province(self):\r\n ans = default_document.createElement(\"cbc:CityName\")\r\n text = default_document.createTextNode(self.province_name)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n def generate_ubigeo(self):\r\n ans = default_document.createElement(\"cbc:ID\")\r\n ans.setAttribute(\"schemeAgencyName\", \"PE:INEI\")\r\n ans.setAttribute(\"schemeName\", \"Ubigeos\")\r\n text = default_document.createTextNode(self.ubigeo)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n def generate_departament(self):\r\n ans = default_document.createElement(\"cbc:CountrySubentity\")\r\n text = default_document.createTextNode(self.departament)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n def generate_district(self):\r\n ans = default_document.createElement(\"cbc:District\")\r\n text = default_document.createTextNode(self.district)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n def generate_country(self):\r\n ans = default_document.createElement(\"cac:Country\")\r\n elem = default_document.createElement(\"cbc:IdentificationCode\")\r\n elem.setAttribute(\"listID\", \"ISO 3166-1\")\r\n elem.setAttribute(\"listAgencyName\", \"United Nations Economic Commission for Europe\")\r\n elem.setAttribute(\"listName\", \"Country\")\r\n text = default_document.createTextNode(self.country_code)\r\n elem.appendChild(text)\r\n ans.appendChild(elem)\r\n return ans\r\n\r\n def generate_adress_type(self):\r\n ans = default_document.createElement(\"cbc:AddressTypeCode\")\r\n # ans.setAttribute(\"schemeAgencyName\", \"PE:SUNAT\")\r\n # ans.setAttribute(\"schemeName\", \"Establecimientos anexos\")\r\n text = default_document.createTextNode(self.address_type_code)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n def generate_doc(self):\r\n self.doc = default_document.createElement(\"cac:RegistrationAddress\")\r\n if self.address:\r\n self.doc.appendChild(self.generate_address())\r\n if self.urbanization:\r\n self.doc.appendChild(self.generate_urbanization())\r\n if self.province_name:\r\n self.doc.appendChild(self.generate_province())\r\n if self.ubigeo:\r\n self.doc.appendChild(self.ubigeo)\r\n if self.departament:\r\n self.doc.appendChild(self.generate_departament())\r\n if self.district:\r\n self.doc.appendChild(self.generate_district())\r\n self.doc.appendChild(self.generate_adress_type())\r\n","sub_path":"addons/gestionit_pe_fe/models/account/api_facturacion/efact21/RegistrationAddress.py","file_name":"RegistrationAddress.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"646796206","text":"from datetime import datetime\n\nfrom scp import user, bot\nfrom scp.utils.selfInfo import info\n\nimport humanize\n\n\nAFK = False\nAFK_REASON = ''\nAFK_TIME = ''\nUSERS = {}\nGROUPS = {}\n\n\ndef subtract_time(start, end):\n return str(humanize.naturaltime(start - end))\n\n\n@user.on_message(\n (\n (user.filters.group & user.filters.mentioned)\n | user.filters.private\n )\n & ~user.filters.me\n & ~user.filters.bot\n & ~user.filters.service,\n)\nasync def _(_, message: user.types.Message):\n if not AFK:\n return\n last_seen = subtract_time(datetime.now(), AFK_TIME)\n is_group = message.chat.type in [\n 'supergroup', 'group',\n ]\n CHAT_TYPE = GROUPS if is_group else USERS\n\n if message.chat.id not in CHAT_TYPE:\n text = user.md.KanTeXDocument(\n user.md.Section(\n 'Away from Keyboard',\n user.md.KeyValueItem(\n user.md.Bold(\n 'last_seen',\n ), user.md.Code(last_seen),\n ),\n user.md.KeyValueItem(\n user.md.Bold(\n 'reason',\n ), user.md.Code(AFK_REASON),\n ),\n ),\n )\n CHAT_TYPE[message.chat.id] = 1\n return await user.send_message(\n chat_id=message.chat.id,\n text=text,\n reply_to_message_id=message.message_id,\n )\n else:\n if CHAT_TYPE[message.chat.id] == 50:\n text = user.md.KanTeXDocument(\n user.md.Section(\n 'Away from Keyboard',\n user.md.KeyValueItem(\n user.md.Bold('last_seen'), user.md.Code(\n last_seen,\n ),\n ),\n ),\n )\n await user.send_message(\n chat_id=message.chat.id,\n text=text,\n reply_to_message_id=message.message_id,\n )\n elif CHAT_TYPE[message.chat.id] > 50:\n return\n elif CHAT_TYPE[message.chat.id] % 5 == 0:\n text = user.md.KanTeXDocument(\n user.md.Section(\n 'Away from Keyboard',\n user.md.KeyValueItem(\n user.md.Bold(\n 'last_seen',\n ), user.md.Code(last_seen),\n ),\n user.md.KeyValueItem(\n user.md.Bold(\n 'reason',\n ), user.md.Code(AFK_REASON),\n ),\n ),\n )\n await user.send_message(\n chat_id=message.chat.id,\n text=text,\n reply_to_message_id=message.message_id,\n )\n\n CHAT_TYPE[message.chat.id] += 1\n\n\n@user.on_message(user.command('afk') & user.filters.me, group=3)\nasync def _(_, message: user.types.Message):\n global AFK_REASON, AFK, AFK_TIME\n cmd = message.command\n afk_text = ''\n if len(cmd) > 1:\n afk_text = ' '.join(cmd[1:])\n if isinstance(afk_text, str):\n AFK_REASON = afk_text\n AFK = True\n AFK_TIME = datetime.now()\n await message.delete()\n\n\n@user.on_message(user.filters.me, group=3)\nasync def _(_, __):\n global AFK, AFK_TIME, AFK_REASON, USERS, GROUPS\n if AFK:\n t = sum(USERS.values()) + sum(GROUPS.values())\n last_seen = subtract_time(\n datetime.now(), AFK_TIME,\n ).replace('ago', '').strip()\n await bot.send_message(\n info['_user_id'],\n f'While you were away (for {last_seen}), you received {t} '\n f'messages from {len(USERS) + len(GROUPS)} chats`',\n )\n AFK = False\n AFK_TIME = ''\n AFK_REASON = ''\n USERS = {}\n GROUPS = {}\n","sub_path":"scp/plugins/user/afk.py","file_name":"afk.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"100224353","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.text import Tokenizer\n\nsentences = [\n 'I love my dog',\n 'I love my cat',\n 'You love my Dog!',\n 'Do you think my dog is amazing?'\n]\n\ntokenizer = Tokenizer(num_words = 100, oov_token=\"\")\ntokenizer.fit_on_texts(sentences)\nword_index = tokenizer.word_index\nprint(word_index)\n\nsequences = tokenizer.texts_to_sequences(sentences)\nprint(sequences)\n\ntest_data = [\n 'i really love my dog',\n 'my dog loves my manatee'\n]\n\ntext_sequence = tokenizer.texts_to_sequences(test_data)\nprint(text_sequence)\n\n","sub_path":"testing/SequencesExample.py","file_name":"SequencesExample.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"385322304","text":"import pygame\r\npygame.init()\r\ntela = pygame.display.set_mode((1024, 768))\r\n\r\ncor = (80, 60, 70)\r\n\r\nwhile True: #Game Loop\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n exit()\r\n tela.fill(cor) \r\n pygame.display.update()\r\n","sub_path":"exemplo2.py","file_name":"exemplo2.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"610688181","text":"import numpy as np\nimport math\nimport time\n\nclass KNNClassifier:\n\n def __init__(self, k_value=5):\n self.k_parameter = k_value\n self.data_arr = None\n self.train_res = None\n\n def train(self, train_dataframe_path):\n self.data_arr = np.genfromtxt(train_dataframe_path, delimiter = ',')\n self.train_res = self.data_arr[:,0]\n self.data_arr = self.data_arr[:, 1:]\n\n def predict(self, test_dataframe_path):\n test_egs = np.genfromtxt(test_dataframe_path, delimiter = ',')\n prediction_list = []\n for test_ind in range(test_egs.shape[0]):\n # print(\"validation sample number \"+str(test_ind+1))\n lis = []\n test_row = test_egs[test_ind,:]\n hashmap = [0 for i in range(10)]\n for train_ind in range(self.data_arr.shape[0]):\n train_row = self.data_arr[train_ind,:]\n diff = test_row - train_row\n diff = diff*diff\n dist = (diff.sum())\n lis.append([dist, self.train_res[train_ind]])\n lis = sorted(lis, key=lambda pair:pair[0])\n lis = lis[0:self.k_parameter]\n for pair in lis:\n hashmap[int(pair[1])] += 1\n maxval = hashmap[0]\n ind = 0\n for iter in range(1,10):\n val = hashmap[iter]\n if val > maxval:\n maxval = val\n ind = iter\n prediction_list.append(ind)\n return prediction_list","sub_path":"q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"290020119","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 26 21:22:45 2021\r\n\r\n@author: sreekanesh\r\n\"\"\"\r\nlst=[]\r\n\r\nn=int(input('enter the number of elements :'))\r\n\r\n\r\nfor i in range(0,n):\r\n elements=(int(input()))\r\n lst.append(elements)\r\n \r\n \r\n\r\ndef positive_num():\r\n for item in lst:\r\n if item < 0:\r\n lst.remove(item)\r\n print(lst)\r\n \r\n \r\npositive_num() ","sub_path":"positive_int.py","file_name":"positive_int.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"643900012","text":"from keras.applications.vgg16 import VGG16\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.optimizers import SGD\n\n\ndef build_transfer_model(vgg16):\n model = Sequential(vgg16.layers)\n for layer in model.layers[:15]:\n layer.trainable = False\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1, activation='sigmoid'))\n return model\n\n\ndef get_model():\n vgg16 = VGG16(include_top=False, input_shape=(224, 224, 3))\n model = build_transfer_model(vgg16)\n model.compile(\n loss='binary_crossentropy',\n optimizer=SGD(lr=1e-4, momentum=0.9),\n metrics=['accuracy'])\n return model\n\n\ndef main():\n model = get_model()\n model.summary()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"deeplearning/keras/book/vgg16Series/transferLearning/transfer_learning.py","file_name":"transfer_learning.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"121446180","text":"# -*-coding:utf-8-*-\n# !/usr/bin/python3\n\"\"\"\nRead data from unix format file\n\nSept 23, 2018\n@author: shoujiangma@163.com\n\"\"\"\nimport sys\nfrom binascii import b2a_hex\n\nfrom Cryptodome import Random\nfrom Cryptodome.Cipher import AES\n\nimport huffman_tree as huffman_tree\n\n\ndef encrypt(in_file, out_file, key):\n with open(in_file, 'rb') as inputf, open(out_file, 'wb') as outputf:\n data = inputf.read()\n iv = Random.new().read(AES.block_size)\n\n mycipher = AES.new(key, AES.MODE_CFB, iv)\n ciphertext = iv + mycipher.encrypt(data)\n\n print(\"key:\", key)\n print(\"iv:\", b2a_hex(ciphertext)[:16])\n # print(\"encrypt data:\", b2a_hex(ciphertext)[16:])\n\n outputf.write(ciphertext)\n\n\ndef decrypt(in_file, out_file, key):\n with open(in_file, 'rb') as inputf, open(out_file, 'wb') as outputf:\n ciphertext = inputf.read()\n mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16])\n decrypttext = mydecrypt.decrypt(ciphertext[16:])\n\n print(\"key:\", key)\n print(\"iv:\", ciphertext[:16])\n # print(\"decrypt data:\", decrypttext)\n outputf.write(decrypttext)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Too few parameters. Usage example: ./run.py file_name KEY\")\n exit(0)\n\n INPUT_FILE = sys.argv[1]\n ENCODE_FILE = INPUT_FILE + \".encode\"\n DECODE_FILE = INPUT_FILE + \".decode\"\n ENCRYPT_FILE = INPUT_FILE + \".encrypt\"\n DECRYPT_FILE = INPUT_FILE + \".decrypt\"\n KEY = sys.argv[2].encode()\n\n # compress org file by huffman coding\n huffman_tree.compress(INPUT_FILE, ENCODE_FILE)\n print(\"compress done.\\n\")\n\n # encrypt compressed file\n encrypt(ENCODE_FILE, ENCRYPT_FILE, KEY)\n\n # decrypt bin file\n decrypt(ENCRYPT_FILE, DECRYPT_FILE, KEY)\n\n # decompress file\n huffman_tree.decompress(DECRYPT_FILE, DECODE_FILE)\n print(\"decompress done.\\n\")\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"418938425","text":"'''\nCopyright (C) 2017-2021 Bryant Moscon - bmoscon@gmail.com\n\nPlease see the LICENSE file for the terms and conditions\nassociated with this software.\n'''\nimport os\nimport glob\nimport json\n\nimport pytest\n\nfrom cryptofeed.util.async_file import playback\nfrom cryptofeed.defines import BINANCE, BINANCE_DELIVERY, BITCOINCOM, BITFINEX, EXX, BINANCE_FUTURES, BINANCE_US, BITFLYER, BITMAX, BITMEX, BITSTAMP, BITTREX, BLOCKCHAIN, COINBASE, COINGECKO, DERIBIT, FTX_US, FTX, GATEIO, GEMINI, HITBTC, HUOBI, HUOBI_DM, HUOBI_SWAP, KRAKEN, KRAKEN_FUTURES, OKCOIN, OKEX, OPEN_INTEREST, POLONIEX, PROBIT, TICKER, TRADES, L2_BOOK, BYBIT, UPBIT, WHALE_ALERT\nfrom cryptofeed.feedhandler import _EXCHANGES\n\n\n# Some exchanges discard messages so we cant use a normal in == out comparison for testing purposes\n\n\nlookup_table = {\n BITSTAMP: {TRADES: 32, L2_BOOK: 3109},\n POLONIEX: {TICKER: 56, TRADES: 2, L2_BOOK: 356}, # With Poloniex you sub to a channel, not a symbol, so in != out\n OKCOIN: [{TICKER: 53, TRADES: 44, L2_BOOK: 3516}, {L2_BOOK: 3500, TICKER: 53, TRADES: 44}],\n OKEX: [{L2_BOOK: 11992, OPEN_INTEREST: 30, TICKER: 156, TRADES: 163}, {L2_BOOK: 12034, OPEN_INTEREST: 30, TICKER: 156, TRADES: 163}],\n KRAKEN_FUTURES: {TICKER: 3041, TRADES: 93, L2_BOOK: 62073},\n BITTREX: {TICKER: 170, TRADES: 8, L2_BOOK: 1083},\n BINANCE_US: {TICKER: 2624, TRADES: 188, L2_BOOK: 3185},\n BYBIT: {TRADES: 149, L2_BOOK: 9031},\n HITBTC: {TICKER: 927, TRADES: 1016, L2_BOOK: 3248},\n BINANCE_FUTURES: {TICKER: 3424, TRADES: 574, L2_BOOK: 4395},\n BINANCE_DELIVERY: {L2_BOOK: 9323, TICKER: 24861, TRADES: 473},\n HUOBI_DM: {L2_BOOK: 19965, TRADES: 467},\n HUOBI_SWAP: {L2_BOOK: 16689, TRADES: 197},\n HUOBI: {L2_BOOK: 956, TRADES: 30},\n BITMEX: {L2_BOOK: 6393, TICKER: 1836, TRADES: 122},\n BINANCE: {L2_BOOK: 4642, TICKER: 5408, TRADES: 1240},\n FTX_US: {L2_BOOK: 1933, TICKER: 1960, TRADES: 4},\n FTX: {L2_BOOK: 3377, TICKER: 3420, TRADES: 81},\n BLOCKCHAIN: {L2_BOOK: 3725},\n GEMINI: {L2_BOOK: 1758, TRADES: 22},\n DERIBIT: {L2_BOOK: 187, OPEN_INTEREST: 10, TICKER: 273},\n PROBIT: {L2_BOOK: 24, TRADES: 1003},\n UPBIT: {L2_BOOK: 1061, TRADES: 672},\n COINBASE: {L2_BOOK: 42586, TICKER: 301, TRADES: 301},\n GATEIO: {L2_BOOK: 317, TRADES: 1027},\n BITFLYER: {L2_BOOK: 2857, TICKER: 933, TRADES: 115},\n KRAKEN: [{L2_BOOK: 14506}, {TRADES: 28}, {TICKER: 22}],\n BITMAX: {L2_BOOK: 1525, TRADES: 11},\n BITCOINCOM: {L2_BOOK: 4255, TICKER: 971, TRADES: 69},\n BITFINEX: {L2_BOOK: 22474, TICKER: 58, TRADES: 248},\n\n}\n\n\ndef get_message_count(filename):\n with open(filename, 'r') as fp:\n counter = 0\n next(fp)\n for line in fp.readlines():\n if line == \"\\n\":\n continue\n start = line[:3]\n if start == 'wss':\n continue\n counter += 1\n return counter\n\n\n@pytest.mark.parametrize(\"exchange\", [e for e in _EXCHANGES.keys() if e not in [COINGECKO, EXX, WHALE_ALERT]])\ndef test_exchange_playback(exchange):\n dir = os.path.dirname(os.path.realpath(__file__))\n for pcap in glob.glob(f\"{dir}/../../sample_data/{exchange}-*.0\"):\n \n feed = _EXCHANGES[exchange]\n with open(pcap, 'r') as fp:\n header = fp.readline()\n sub = json.loads(header.split(\": \", 1)[1])\n\n results = playback(feed(subscription=sub), pcap)\n message_count = get_message_count(pcap)\n\n assert results['messages_processed'] == message_count\n if isinstance(lookup_table[exchange], list):\n assert results['callbacks'] in lookup_table[exchange]\n else:\n assert lookup_table[exchange] == results['callbacks']\n","sub_path":"tests/unit/test_exchange.py","file_name":"test_exchange.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"97141188","text":"import hashlib as hasher\nimport datetime as date\nValorSensorph1 = 0\n# Define what a Snakecoin block is\nclass Block:\n def __init__(self, index, timestamp, data, previous_hash):\n self.index = index\n self.timestamp = timestamp\n self.data = data\n self.previous_hash = previous_hash\n self.hash = self.ValorSensorph1()\n \n def hashMe(ValorSensorph1):\n \n if type(ValorSensorph1)!=str:\n ValorSensorph1 = json.dumps(ValorSensorph1,sort_keys=True)\n \n \n if sys.version_info.major == 2:\n return unicode(hashlib.sha256(ValorSensorph1).hexdigest(),'utf-8')\n else:\n return hashlib.sha256(str(ValorSensorph1).encode('utf-8')).hexdigest()\n# Generate genesis block\ndef create_genesis_block():\n # Manually construct a block with\n # index zero and arbitrary previous hash\n return Block(0, date.datetime.now(), \"Genesis Block\", \"0\")\n\n# Generate all later blocks in the blockchain\ndef next_block(last_block):\n this_index = last_block.index + 1\n this_timestamp = date.datetime.now()\n this_data = \"Hey! I'm block \" + str(this_index)\n this_hash = last_block.hash\n return Block(this_index, this_timestamp, this_data, this_hash)\n\n# Create the blockchain and add the genesis block\nblockchain = [create_genesis_block()]\nprevious_block = blockchain[0]\n\n# How many blocks should we add to the chain\n# after the genesis block\nnum_of_blocks_to_add = 20\n\n# Add blocks to the chain\nfor i in range(0, num_of_blocks_to_add):\n block_to_add = next_block(previous_block)\n blockchain.append(block_to_add)\n previous_block = block_to_add\n # Tell everyone about it!\n print (\"Block {} has been added to the blockchain!\", format(block_to_add.index))\n print (\"Hash: {}\\n\", format(block_to_add.hash) )","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"55767825","text":"import requests\nimport os\nimport json\n\ndef identify():\n url = 'https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/'\n path = '/home/pi/Documents/smartbin3-master/images'\n name_list = os.listdir(path)\n full_list = [os.path.join(path,i) for i in name_list]\n time_sorted_list = sorted(full_list, key=os.path.getmtime)\n sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]\n lastfile = sorted_filename_list[-1]\n data = {'file': open('/home/pi/Documents/smartbin3-master/images/'+lastfile, 'rb'), 'modelId': ('', 'febf1ef2-559e-4877-9803-ddf4247155e5')}\n #data = {'file': open('./images/image2.jpg', 'rb'), 'modelId': ('', 'febf1ef2-559e-4877-9803-ddf4247155e5')}\n response = requests.post(url, auth= requests.auth.HTTPBasicAuth('GvqHLwBkqU4tpSyXDU471CG6K1y5XYw8', ''), files=data)\n #print(response.text)\n data = json.loads(response.text)\n a = data[\"result\"][0][\"prediction\"][0][\"label\"]\n print(a)\n return(a)\n","sub_path":"identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"301328221","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 16 11:32:08 2014\n\n@author: nhpnp3\n\"\"\"\n\nimport functions_polycrystal as rr\nimport numpy as np\nimport time\n\ndef read_euler(el, ns, set_id, vtk_filename, wrt_file):\n\n start = time.time() \n \n euler = np.zeros([el**3,ns,3])\n \n for sn in xrange(ns):\n l_sn = str(sn+1).zfill(5) \n euler[:,sn,:] = rr.read_vtk_vector(filename = vtk_filename %l_sn, el = el)\n \n np.save('euler_%s%s' %(ns,set_id), euler)\n \n end = time.time()\n timeE = np.round((end - start),3)\n \n msg = 'euler angles read from .vtk file for %s: %s seconds' %(set_id, timeE)\n rr.WP(msg,wrt_file)\n\n \ndef read_meas(el, ns, set_id, step, comp, vtk_filename, tensor_id, wrt_file):\n\n start = time.time() \n \n r_real = np.zeros([el,el,el,ns])\n \n \n for sn in xrange(ns):\n l_sn = str(sn+1).zfill(5) \n r_temp = rr.read_vtk_tensor(filename = vtk_filename %l_sn, el = el, tensor_id = tensor_id, comp = comp)\n r_real[:,:,:,sn] = np.swapaxes(np.reshape(np.flipud(r_temp), [el,el,el]),1,2)\n\n \n np.save('r%s_%s%s_s%s' %(comp,ns,set_id,step), r_real)\n\n ## fftn of response fields \n r_fft = np.fft.fftn(r_real, axes = [0,1,2]) \n del r_real\n np.save('r%s_fft_%s%s_s%s' %(comp,ns,set_id,step),r_fft) \n \n\n end = time.time()\n timeE = np.round((end - start),3)\n \n msg = 'The measure of interest has been read from .vtk file for %s, set %s: %s seconds' %(set_id,comp,timeE)\n rr.WP(msg,wrt_file)","sub_path":"fip_collab/2014_09_29_stress_colony_large/vtk_read.py","file_name":"vtk_read.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"292319656","text":"# # K-means design and implementations\n# \n# - Load the synthetic 2-D dataset containing Gaussian clusters.\n# - Plot the data points as a scatter chart using the Matplotlib library. At first sight, you should see 15 different globular clusters.\n# - Once you get to a fully functional version of your class, load also the Chameleon data and run the K-means algorithm on both the datasets.\n# - Improve your K-means class with an additional visualization tool.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport math\n\n\ndef euclidean_distance(x1, x2, y1, y2):\n\n # Compute euclidean distance\n return ((x2 - x1)**2 + (y2 - y1)**2)**.5\n\nclass KMeans:\n \n def __init__(self, n_clusters, max_iter=100):\n \n # Initialize parameters\n self.n_clusters = n_clusters \n self.max_iter = max_iter \n \n # Initialize clusters dictionary\n self.clusters = None\n self.centroids = None\n self.labels = None\n \n def _nearest_centroid(self, x, y):\n \n # Compute euclidean distances from centroids\n centroid_distances = [euclidean_distance(centroid[0], x, centroid[1], y) for centroid in self.centroids.values()]\n # Extract cluster index for minimum distance\n centroid_index = centroid_distances.index(min(centroid_distances))\n \n return centroid_index\n \n def _update_centroids(self):\n \n # Sotre old centroids\n old_centroids = self.centroids.copy()\n differences = [None] * self.n_clusters\n \n # Iterate over all points\n for index, cluster in enumerate(self.clusters.values()):\n \n # Compute means\n centroid_x_mean = sum([point[0] for point in cluster])/len(cluster)\n centroid_y_mean = sum([point[1] for point in cluster])/len(cluster)\n \n # Update centroid position\n self.centroids[index] = (centroid_x_mean, centroid_y_mean)\n differences[index] = euclidean_distance(old_centroids[index][0], centroid_x_mean, old_centroids[index][1], centroid_y_mean)\n \n return all([difference == 0 for difference in differences])\n \n def _plot_clusters(self):\n \n # Iterate over clusters\n for i in range(self.n_clusters):\n \n # Store x and y values\n x = [point[0] for point in self.clusters[i]]\n y = [point[1] for point in self.clusters[i]]\n # Generate scatter plot\n plt.scatter(x, y)\n \n # Print centroids \n x_centroids = [point[0] for point in self.centroids.values()]\n y_centroids = [point[1] for point in self.centroids.values()]\n # Generate centroids scatter plot\n plt.scatter(x_centroids, y_centroids, marker='*', color='red')\n \n # Show the plot\n plt.show()\n\n def fit_predict(self, X, plot_clusters=False, plot_step=None):\n \n \"\"\"Run the K-means clustering on X.\n \n :param X: input data points, array, shape = (N,C).\n :return: labels, array: shape = N.\n \"\"\"\n \n # Extract centroids\n indices = random.sample(range(len(X)), self.n_clusters)\n self.centroids = dict(zip(range(self.n_clusters), [(X[index][0], X[index][1]) for index in indices]))\n \n # Iterate over all points\n for i in range(self.max_iter):\n \n # Condition to update centroids\n if self.clusters and all([len(value) > 0 for value in self.clusters.values()]):\n \n # Update centroids\n updated_centroids = self._update_centroids()\n # Check if centroids were updated\n if updated_centroids:\n break\n \n # Reset cluster points\n self.clusters = dict(zip(range(self.n_clusters), [[] for i in range(self.n_clusters)]))\n self.labels = [None] * len(X)\n \n # Assign each point to one cluster\n for index, point in enumerate(X):\n\n # Unpack point\n x, y = point\n # Compute nearest centroid\n centroid_index = self._nearest_centroid(x, y)\n \n # Log point cluster\n self.labels[index] = centroid_index\n # Store point in cluster\n self.clusters[centroid_index].append(tuple(X[index]))\n \n if plot_clusters and i > 0 and ((i+1) % plot_step) == 0:\n self._plot_clusters()\n \n return self.labels\n \n def dump_to_file(self, filename):\n \n \"\"\"Dump the evaluated labels to a CSV file.\"\"\"\n \n # Open file to write\n with open(f'output/{filename}.csv', 'w') as file:\n \n # File heading\n file.write('Id,ClusterId\\n')\n # Print points clusters\n for index, cluster in enumerate(self.labels):\n file.write(f'{str(index)},{str(cluster)}\\n')\n \ndef silhouette_samples(X, labels):\n \n \"\"\"Evaluate the silhouette for each point and return them as a list.\n \n :param X: input data points, array, shape = (N,C). \n :param labels: the list of cluster labels, shape = N. \n :return: silhouette : array, shape = N\n \"\"\"\n \n # Initialize a and b collections\n a = [0] * len(X)\n b = [0] * len(X)\n s = []\n \n # Store points in different clusters \n distinct_clusters = sorted(set(labels))\n clusters = dict(zip(distinct_clusters, [[] for i in range(len(distinct_clusters))]))\n\n # Populate clusters dictionary\n for index, label in enumerate(labels):\n clusters[label].append({'value': tuple(X[index]), 'index': index})\n \n # A parameter\n for cluster, points in clusters.items():\n for point in points:\n\n a[point['index']] = sum([euclidean_distance(ext_point['value'][0], point['value'][0], ext_point['value'][1], point['value'][1]) for ext_point in points if ext_point['index'] != point['index']])\n a[point['index']] = a[point['index']]/(len(points) - 1)\n \n # B parameter\n for cluster, points in clusters.items():\n for point in points:\n \n # Collect all distance means\n distance_means = []\n \n # Iterate over all k clusters\n for ext_cluster, ext_points in clusters.items():\n if ext_cluster != cluster:\n\n # Append distance from cluster\n distance_sum = sum([euclidean_distance(ext_point['value'][0], point['value'][0], ext_point['value'][1], point['value'][1]) for ext_point in ext_points])\n distance_mean = distance_sum/len(ext_points)\n distance_means.append(distance_mean)\n \n # Store B for a given point\n b[point['index']] = min(distance_means)\n \n # Compute silhouette \n for a_i, b_i in zip(a, b): \n s.append((b_i - a_i)/max([a_i, b_i]))\n \n return s\n \ndef silhouette_score(X, labels):\n\n \"\"\"Evaluate the silhouette for each point and return the mean.\n :param X: input data points, array, shape = (N,C). \n :param labels: the list of cluster labels, shape = N. \n :return: silhouette : float\n \"\"\"\n\n # Get silhouette from silhouette_samples\n s = silhouette_samples(X, labels)\n\n return sum(s)/len(s)\n\nif __name__ == '__main__':\n\n # Open points file\n with open('src/2D_gauss_clusters.txt', 'r') as file:\n # Load points with numpy\n points = np.loadtxt(file, delimiter=',', dtype=int, skiprows=1, unpack=False)\n\n # Store x and y coordinates\n x = [point[0] for point in points]\n y = [point[1] for point in points]\n\n # Plot points dataset as a scatterplot\n plt.scatter(x, y)\n plt.title('2D Gaussian Dataset')\n plt.show()\n\n # Extract clusters\n kmeans_points = KMeans(13, 5)\n points_labels = kmeans_points.fit_predict(points, True, 5)\n kmeans_points.dump_to_file('results')\n\n # Open chameleon file\n with open('src/chameleon_clusters.txt', 'r') as file:\n # Load points with numpy\n chameleons = np.loadtxt(file, delimiter=',', skiprows=1, unpack=False)\n\n # Extract clusters\n kmeans_chameleon = KMeans(6, 5)\n chameleon_labels = kmeans_chameleon.fit_predict(chameleons, True, 5)\n\n # Computing silhouette for 2D Gaussian Dataset\n points_silhouette = silhouette_samples(points, points_labels)\n # Computing silhouette for Chameleon Dataset\n chameleon_silhouette = silhouette_samples(chameleons, chameleon_labels)\n\n # Sort silhouettes\n sorted_points_silhouette = sorted(points_silhouette)\n sorted_chameleon_silhouette = sorted(chameleon_silhouette)\n\n # Plot sorted silhouette\n fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n fig.suptitle('Silhouettes comparison')\n\n ax1.plot(sorted_points_silhouette)\n ax1.set_title('Points silhouette')\n ax2.plot(sorted_chameleon_silhouette)\n ax2.set_title('Chameleons silhouette')\n\n plt.show()\n\n # Initialize mean silhouette collection\n points_means = []\n\n # Try clustering for different k values\n for k in range(10, 16):\n \n # Compute K-means for value k\n kmeans_iter = KMeans(k, 5)\n points_labels_iter = kmeans_iter.fit_predict(points, False)\n \n # Append silhouette mean\n points_means.append(silhouette_score(points, points_labels_iter))\n \n # Plot sorted silhouette\n plt.plot(range(10, 16), points_means)\n plt.title('Silhouette mean variation')\n plt.show()\n","sub_path":"L04/scripts/E01-02.py","file_name":"E01-02.py","file_ext":"py","file_size_in_byte":9693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"311500554","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.view_all, name='all_urls'),\n url(r'^add/url/$', views.URLCreate.as_view(), name='add_url'),\n url(r'^edit/(?P\\w{6})$', views.URLUpdate.as_view(), name='update_url'),\n url(r'^delete/(?P\\w{6})$', views.URLDelete.as_view(), name='delete_url'),\n url(r'^(?P\\w{6})/$', views.redirection, name='redirection_url'),\n]","sub_path":"url_shortcut/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"445087488","text":"from django import forms \nfrom django_summernote.widgets import SummernoteWidget\nfrom django.contrib.auth import get_user_model\n\nfrom .models import Question, TypeQuestion, Comment\n\nclass QuestionForm(forms.ModelForm):\n\tcategory = forms.ModelChoiceField(label=\"Category\", widget=forms.Select,queryset=TypeQuestion.objects.all())\n\n\tclass Meta:\n\t\tmodel = Question\n\t\tfields = ('title','category','content',)\n\t\twidgets = {\n\t\t\t'content': SummernoteWidget()\n\t\t}\n\t\t\n# class TypeQuestionForm(forms.ModelForm):\n\t\n# \tclass Meta:\n# \t\tmodel = TypeQuestion\n# \t\tfields = ('name',)\n\nclass CommentForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Comment\n\t\tfields = ('content',)\n\t\twidgets={\n\t\t\t'content': SummernoteWidget()\n\t\t}","sub_path":"answerly/qanda/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"155182217","text":"from django.shortcuts import render\nfrom catalog.models import Furniture\nfrom order.order import *\nfrom order.order_payments import *\nfrom django.contrib.auth.models import User\nfrom accounts.models import Customer, TempCarpenter\n\n\n# Create your views here.\n\ndef make_order_page(request):\n furniture = Furniture.objects.all()\n customers = Customer.objects.all()\n return render(request, 'order/order_make.html', locals())\n\n\ndef make_order(request):\n # data for order\n order_name = request.POST['order_name']\n quantity = float(request.POST['quantity'])\n order_completion_date = request.POST['order_completion_date']\n customer = int(request.POST['customer'])\n\n # data for order payment\n deposit = float(request.POST['deposit'])\n\n # getting the material price of the order and hence the order price\n furniture = Furniture.objects.get(furniture_name=order_name)\n order_price = (float(furniture.material_price) * 1.7) * quantity\n\n # create and save order\n save_order(customer, order_name, quantity, order_price, deposit)\n msg = 'Order was created successfully.'\n furniture = Furniture.objects.all()\n customers = Customer.objects.all()\n return render(request, 'order/order_make.html', locals())\n\n\ndef change_complete_status(request):\n order_number = request.POST['order_id']\n status = request.POST['order_status']\n change_order_status(order_number, status)\n orders = get_started_orders()\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n msg = 'Complete status for order with order id ' + order_number + ' successfully changed.'\n return render(request, 'order/order_view.html', locals())\n\n\ndef view_all_orders(request):\n orders = get_started_orders()\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n return render(request, 'order/order_view.html', locals())\n\n\ndef search_order(request):\n search_query = request.POST['query']\n search_field = request.POST['search_field']\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n orders = search_for_orders(search_query, search_field)\n return render(request, 'order/order_view.html', locals())\n\n\ndef view_orders_for_customer(request):\n customer_id = request.POST['customer_id']\n orders = get_orders_for(customer_id)\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n return render(request, 'order/order_view.html', locals())\n\n\ndef view_complete_status_orders(request):\n status = request.POST['status']\n if status == \"complete\":\n orders = get_complete_orders()\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n return render(request, 'order/order_view.html', locals())\n elif status == \"incomplete\":\n orders = get_incomplete_orders()\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n return render(request, 'order/order_view.html', locals())\n else:\n orders = get_started_orders()\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n return render(request, 'order/order_view.html', locals())\n\n\ndef carpenter_orders(request):\n carpenter_id = request.POST['carpenter_id']\n orders = get_carpenter_orders(carpenter_id)\n customers = Customer.objects.all()\n carpenters = User.objects.all().exclude(username=\"wolf\")\n return render(request, 'order/order_view.html', locals())\n\n\ndef assign_order_page(request):\n orders = get_unassigned_orders()\n user = request.user\n temporary_carpenters = TempCarpenter.objects.all()\n active_orders = Order.objects.filter(carpenter=user,\n complete_status=False,\n temp_carpenter=None)\n return render(request, 'order/order_assign.html', locals())\n\n\ndef take_order(request):\n # get user\n carpenter = request.user\n\n # check if carpenter has more than 4 already assigned to him/her\n if carpenter_active_orders(carpenter) < 4:\n order_id = request.POST['order_id']\n assign_order_self(carpenter, order_id)\n msg = \"You have taken the order with id \" + order_id\n orders = get_unassigned_orders()\n temporary_carpenters = TempCarpenter.objects.all()\n styling = \"card-panel green accent-4\"\n return render(request, 'order/order_assign.html', locals())\n else:\n msg = \"Currently, you have the maximum allowed active orders.\"\n orders = get_unassigned_orders()\n temporary_carpenters = TempCarpenter.objects.all()\n styling = \"card-panel red lighten-1\"\n return render(request, 'order/order_assign.html', locals())\n\n\ndef assign_order(request):\n order_id = request.POST['order_id']\n temp_carpenter_id = request.POST['temp_carpenter']\n carpenter = request.user\n assign_order_to(temp_carpenter_id, carpenter, order_id)\n msg = \"You have successfully assigned the order.\"\n orders = get_unassigned_orders()\n temporary_carpenters = TempCarpenter.objects.all()\n styling = \"card-panel green accent-4\"\n return render(request, 'order/order_assign.html', locals())\n\n\ndef edit_order(request):\n order_id = request.POST['order_id']\n order = Order.object.get(id=order_id)\n customers = Customer.objects.all()\n return render(request, 'order/order_edit.html', locals())\n\n\ndef delete_order(request):\n pass\n\n\ndef show_payment_list(request):\n order_payments = get_undelivered_order_payments()\n return render(request, 'order/order_payments_list.html', locals())\n\n\ndef show_order_payment(request):\n order = request.POST['order']\n order_payment = get_order_payment(order)\n return render(request, 'order/order_payment.html', locals())\n\n\ndef update_order(request):\n order_id = request.POST['order']\n paid_amount = float(request.POST['paid_amount'])\n delivery = request.POST['delivery']\n update_order_payment(order_id, paid_amount, delivery)\n\n msg = \"Update was made successfully.\"\n order_payments = get_undelivered_order_payments()\n return render(request, 'order/order_payments_list.html', locals())\n","sub_path":"furniture_palace/order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"255641223","text":"from mock import call\nfrom mock import Mock\nfrom mock import patch\n\nfrom paasta_tools.mesos import framework\nfrom paasta_tools.mesos import master\nfrom paasta_tools.mesos import task\n\n\n@patch.object(master.MesosMaster, '_framework_list', autospec=True)\ndef test_frameworks(mock_framework_list):\n fake_frameworks = [\n {\n 'name': 'test_framework1',\n },\n {\n 'name': 'test_framework2',\n },\n ]\n mock_framework_list.return_value = fake_frameworks\n expected_frameworks = [framework.Framework(config) for config in fake_frameworks]\n mesos_master = master.MesosMaster({})\n assert expected_frameworks == mesos_master.frameworks()\n\n\n@patch.object(master.MesosMaster, '_framework_list', autospec=True)\ndef test_framework_list_includes_completed_frameworks(mock_framework_list):\n fake_frameworks = [\n {\n 'name': 'test_framework1',\n },\n {\n 'name': 'test_framework2',\n },\n ]\n mock_framework_list.return_value = fake_frameworks\n expected_frameworks = [framework.Framework(config) for config in fake_frameworks]\n mesos_master = master.MesosMaster({})\n assert expected_frameworks == mesos_master.frameworks()\n\n\n@patch.object(master.MesosMaster, 'fetch', autospec=True)\ndef test__frameworks(mock_fetch):\n mesos_master = master.MesosMaster({})\n mock_frameworks = Mock()\n mock_fetch.return_value = Mock(json=Mock(return_value=mock_frameworks))\n ret = mesos_master._frameworks\n mock_fetch.assert_called_with(mesos_master, \"/master/frameworks\")\n assert ret == mock_frameworks\n\n\n@patch.object(master.MesosMaster, '_frameworks', autospec=True)\ndef test__framework_list(mock__frameworks):\n mock_frameworks = Mock()\n mock_completed = Mock()\n mock__frameworks.__get__ = Mock(return_value={\n 'frameworks': [mock_frameworks],\n 'completed_frameworks': [mock_completed],\n })\n mesos_master = master.MesosMaster({})\n ret = mesos_master._framework_list()\n expected = [mock_frameworks, mock_completed]\n assert list(ret) == expected\n\n ret = mesos_master._framework_list(active_only=True)\n expected = [mock_frameworks]\n assert list(ret) == expected\n\n\n@patch.object(master.MesosMaster, '_framework_list', autospec=True)\ndef test__task_list(mock__frameworks_list):\n mock_task_1 = Mock()\n mock_task_2 = Mock()\n mock_framework = {\n 'tasks': [mock_task_1],\n 'completed_tasks': [mock_task_2],\n }\n mock__frameworks_list.return_value = [mock_framework]\n mesos_master = master.MesosMaster({})\n ret = mesos_master._task_list()\n mock__frameworks_list.assert_called_with(mesos_master, False)\n expected = [mock_task_1, mock_task_2]\n assert list(ret) == expected\n\n ret = mesos_master._task_list(active_only=True)\n expected = [mock_task_1]\n assert list(ret) == expected\n\n ret = mesos_master._task_list(active_only=False)\n expected = [mock_task_1, mock_task_2]\n assert list(ret) == expected\n\n\n@patch.object(task, 'Task', autospec=True)\n@patch.object(master.MesosMaster, '_task_list', autospec=True)\ndef test_tasks(mock__task_list, mock_task):\n mock_task_1 = {'id': 'aaa'}\n mock_task_2 = {'id': 'bbb'}\n mock__task_list.return_value = [mock_task_1, mock_task_2]\n mock_task.return_value = Mock()\n mesos_master = master.MesosMaster({})\n ret = mesos_master.tasks()\n mock_task.assert_has_calls([\n call(mesos_master, mock_task_1),\n call(mesos_master, mock_task_2),\n ])\n mock__task_list.assert_called_with(mesos_master, False)\n expected = [mock_task.return_value, mock_task.return_value]\n assert list(ret) == expected\n\n\ndef test_orphan_tasks():\n mesos_master = master.MesosMaster({})\n mock_task_1 = Mock()\n mesos_master.state = {'orphan_tasks': [mock_task_1]}\n assert mesos_master.orphan_tasks() == [mock_task_1]\n","sub_path":"tests/mesos/test_master.py","file_name":"test_master.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"245581034","text":"'''Exercício Python 077: Crie um programa que tenha uma tupla com várias\r\npalavras (não usar acentos). Depois disso, você deve mostrar, para cada\r\npalavra, quais são as suas vogais.'''\r\n\r\npalavras = ('Igor', 'Rosi', 'Tavares',\r\n 'Leilane', 'Maria', 'Eduarda')\r\n\r\nfor p in palavras:\r\n print(f'\\nNa plalavra {p.upper()} temos as vogais: ', end='')\r\n for letra in p:\r\n if letra.upper() in 'AEIOU':\r\n print(letra.upper(), end=' ')\r\n","sub_path":"Aula16 - Tuplas/ex077 – Contando vogais em Tupla.py","file_name":"ex077 – Contando vogais em Tupla.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"331304814","text":"import tensorflow as tf\n\nclass Model(object):\n def __init__(self, params, src_net):\n self.X = tf.placeholder(\"float\", [None, 210, 160, 3]) #input image\n self.actions = tf.placeholder(\"float\", [None, params['num_actions']])\n self.rewards = tf.placeholder(\"float\", [None, 1])\n self.terminals = tf.placeholder(\"float\", [None, 1])\n \n if src_net is not None: #copy network\n self.w = tf.Variable(src_net.w); self.w2 = tf.Variable(src_net.w2);\n self.w3 = tf.Variable(src_net.w3); self.w4 = tf.Variable(src_net.w4)\n self.w_o = tf.Variable(src_net.w_o)\n else: #initialize network from scratch\n self.w = self.init_weights([8, 8, 3, 32] )\n self.w2 = self.init_weights([4, 4, 32, 64])\n self.w3 = self.init_weights([3, 3, 64, 64])\n self.w4 = self.init_weights([64 * 4 * 3, 512])\n self.w_o = self.init_weights([512, params['num_actions']])\n\n self.param_list = [self.w, self.w2, self.w3, self.w4, self.w_o]\n \n self.l1a = tf.nn.relu(tf.nn.conv2d(self.X, self.w, [1, 4, 4, 1], 'SAME'))\n self.l1 = tf.nn.max_pool(self.l1a, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n self.l2a = tf.nn.relu(tf.nn.conv2d(self.l1, self.w2, [1, 2, 2, 1], 'SAME'))\n self.l2 = tf.nn.max_pool(self.l2a, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n self.l3a = tf.nn.relu(tf.nn.conv2d(self.l2, self.w3, [1, 1, 1, 1], 'SAME'))\n self.l3 = tf.nn.max_pool(self.l3a, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n self.l3 = tf.reshape(self.l3, [-1, self.w4.get_shape().as_list()[0]])\n\n self.l4 = tf.nn.relu(tf.matmul(self.l3, self.w4))\n\n self.pyx = tf.matmul(self.l4, self.w_o)\n\n def init_weights(self, shape):\n return tf.Variable(tf.random_normal(shape, stddev=0.01))\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"4802523","text":"from __future__ import print_function\n\nimport gc\nimport inspect\nimport math\nimport os\nimport sys\nimport threading\nimport multiprocessing\nimport concurrent.futures\nimport time\nimport warnings\n\nimport h5py\nimport numpy as np\nimport png\nfrom scipy import io\n\n\n# set this to True after importing this module to prevent multithreading\nUSE_ONE_THREAD = False\n\nDEBUG = True\n\n# Determine where PyGreentea is\npygtpath = os.path.normpath(os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0])))\n\n# Determine where PyGreentea gets called from\ncmdpath = os.getcwd()\n\nsys.path.append(pygtpath)\nsys.path.append(cmdpath)\n\n\nfrom numpy import float32, int32, uint8\n\n# Load the configuration file\nimport config\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n# Direct call to PyGreentea, set up everything\nif __name__ == \"__main__\":\n # Load the setup module\n import setup\n\n if (pygtpath != cmdpath):\n os.chdir(pygtpath)\n \n if (os.geteuid() != 0):\n print(bcolors.WARNING + \"PyGreentea setup should probably be executed with root privileges!\" + bcolors.ENDC)\n \n if config.install_packages:\n print(bcolors.HEADER + (\"==== PYGT: Installing OS packages ====\").ljust(80,\"=\") + bcolors.ENDC)\n setup.install_dependencies()\n \n print(bcolors.HEADER + (\"==== PYGT: Updating Caffe/Greentea repository ====\").ljust(80,\"=\") + bcolors.ENDC)\n setup.clone_caffe(config.caffe_path, config.clone_caffe, config.update_caffe)\n \n print(bcolors.HEADER + (\"==== PYGT: Updating Malis repository ====\").ljust(80,\"=\") + bcolors.ENDC)\n setup.clone_malis(config.malis_path, config.clone_malis, config.update_malis)\n \n if config.compile_caffe:\n print(bcolors.HEADER + (\"==== PYGT: Compiling Caffe/Greentea ====\").ljust(80,\"=\") + bcolors.ENDC)\n setup.compile_caffe(config.caffe_path)\n \n if config.compile_malis:\n print(bcolors.HEADER + (\"==== PYGT: Compiling Malis ====\").ljust(80,\"=\") + bcolors.ENDC)\n setup.compile_malis(config.malis_path)\n \n if (pygtpath != cmdpath):\n os.chdir(cmdpath)\n \n print(bcolors.OKGREEN + (\"==== PYGT: Setup finished ====\").ljust(80,\"=\") + bcolors.ENDC)\n sys.exit(0)\nelse: \n import data_io\n\n\n# Import Caffe\ncaffe_parent_path = os.path.dirname(os.path.dirname(__file__))\ncaffe_path = os.path.join(caffe_parent_path, 'caffe_gt', 'python')\nsys.path.append(caffe_path)\nimport caffe as caffe\n\n# Import the network generator\nimport network_generator as netgen\n\n# Import Malis\nimport malis as malis\n\n\n# Wrapper around a networks set_input_arrays to prevent memory leaks of locked up arrays\nclass NetInputWrapper:\n \n def __init__(self, net, shapes):\n self.net = net\n self.shapes = shapes\n self.dummy_slice = np.ascontiguousarray([0]).astype(float32)\n self.inputs = []\n self.input_keys = ['data', 'label', 'scale', 'components', 'nhood']\n self.input_layers = []\n \n for i in range(0, len(self.input_keys)):\n if (self.input_keys[i] in self.net.layers_dict):\n self.input_layers += [self.net.layers_dict[self.input_keys[i]]]\n \n if DEBUG:\n print(\"Input layers: \", len(self.input_layers))\n \n for i in range(0,len(shapes)):\n # Pre-allocate arrays that will persist with the network\n self.inputs += [np.zeros(tuple(self.shapes[i]), dtype=float32)]\n \n if DEBUG:\n print(\"Shapes: \", len(shapes))\n \n def setInputs(self, data): \n for i in range(0,len(self.shapes)):\n np.copyto(self.inputs[i], np.ascontiguousarray(data[i]).astype(float32))\n self.net.set_layer_input_arrays(self.input_layers[i], self.inputs[i], self.dummy_slice)\n \n\n# Transfer network weights from one network to another\ndef net_weight_transfer(dst_net, src_net):\n # Go through all source layers/weights\n for layer_key in src_net.params:\n # Test existence of the weights in destination network\n if (layer_key in dst_net.params):\n # Copy weights + bias\n for i in range(0, min(len(dst_net.params[layer_key]), len(src_net.params[layer_key]))):\n np.copyto(dst_net.params[layer_key][i].data, src_net.params[layer_key][i].data)\n \n\ndef normalize(dataset, newmin=-1, newmax=1):\n maxval = dataset\n while len(maxval.shape) > 0:\n maxval = maxval.max(0)\n minval = dataset\n while len(minval.shape) > 0:\n minval = minval.min(0)\n return ((dataset - minval) / (maxval - minval)) * (newmax - newmin) + newmin\n\n\ndef getSolverStates(prefix):\n files = [f for f in os.listdir('.') if os.path.isfile(f)]\n print(files)\n solverstates = []\n for file in files:\n if(prefix+'_iter_' in file and '.solverstate' in file):\n solverstates += [(int(file[len(prefix+'_iter_'):-len('.solverstate')]),file)]\n return sorted(solverstates)\n \ndef getCaffeModels(prefix):\n files = [f for f in os.listdir('.') if os.path.isfile(f)]\n print(files)\n caffemodels = []\n for file in files:\n if(prefix+'_iter_' in file and '.caffemodel' in file):\n caffemodels += [(int(file[len(prefix+'_iter_'):-len('.caffemodel')]),file)]\n return sorted(caffemodels)\n\n\ndef scale_errors(data, factor_low, factor_high):\n scaled_data = np.add((data >= 0.5) * factor_high, (data < 0.5) * factor_low)\n return scaled_data\n\n\ndef count_affinity(dataset):\n aff_high = np.sum(dataset >= 0.5)\n aff_low = np.sum(dataset < 0.5)\n return aff_high, aff_low\n\n\ndef border_reflect(dataset, border):\n return np.pad(dataset,((border, border)),'reflect')\n\n\ndef augment_data_simple(dataset):\n nset = len(dataset)\n for iset in range(nset):\n for reflectz in range(2):\n for reflecty in range(2):\n for reflectx in range(2):\n for swapxy in range(2):\n\n if reflectz==0 and reflecty==0 and reflectx==0 and swapxy==0:\n continue\n\n dataset.append({})\n dataset[-1]['name'] = dataset[iset]['name']+'_x'+str(reflectx)+'_y'+str(reflecty)+'_z'+str(reflectz)+'_xy'+str(swapxy)\n\n\n\n dataset[-1]['nhood'] = dataset[iset]['nhood']\n dataset[-1]['data'] = dataset[iset]['data'][:]\n dataset[-1]['components'] = dataset[iset]['components'][:]\n\n if reflectz:\n dataset[-1]['data'] = dataset[-1]['data'][::-1,:,:]\n dataset[-1]['components'] = dataset[-1]['components'][::-1,:,:]\n\n if reflecty:\n dataset[-1]['data'] = dataset[-1]['data'][:,::-1,:]\n dataset[-1]['components'] = dataset[-1]['components'][:,::-1,:]\n\n if reflectx:\n dataset[-1]['data'] = dataset[-1]['data'][:,:,::-1]\n dataset[-1]['components'] = dataset[-1]['components'][:,:,::-1]\n\n if swapxy:\n dataset[-1]['data'] = dataset[-1]['data'].transpose((0,2,1))\n dataset[-1]['components'] = dataset[-1]['components'].transpose((0,2,1))\n\n dataset[-1]['label'] = malis.seg_to_affgraph(dataset[-1]['components'],dataset[-1]['nhood'])\n\n dataset[-1]['reflectz']=reflectz\n dataset[-1]['reflecty']=reflecty\n dataset[-1]['reflectx']=reflectx\n dataset[-1]['swapxy']=swapxy\n return dataset\n\n \ndef augment_data_elastic(dataset,ncopy_per_dset):\n dsetout = []\n nset = len(dataset)\n for iset in range(nset):\n for icopy in range(ncopy_per_dset):\n reflectz = np.random.rand()>.5\n reflecty = np.random.rand()>.5\n reflectx = np.random.rand()>.5\n swapxy = np.random.rand()>.5\n\n dataset.append({})\n dataset[-1]['reflectz']=reflectz\n dataset[-1]['reflecty']=reflecty\n dataset[-1]['reflectx']=reflectx\n dataset[-1]['swapxy']=swapxy\n\n dataset[-1]['name'] = dataset[iset]['name']\n dataset[-1]['nhood'] = dataset[iset]['nhood']\n dataset[-1]['data'] = dataset[iset]['data'][:]\n dataset[-1]['components'] = dataset[iset]['components'][:]\n\n if reflectz:\n dataset[-1]['data'] = dataset[-1]['data'][::-1,:,:]\n dataset[-1]['components'] = dataset[-1]['components'][::-1,:,:]\n\n if reflecty:\n dataset[-1]['data'] = dataset[-1]['data'][:,::-1,:]\n dataset[-1]['components'] = dataset[-1]['components'][:,::-1,:]\n\n if reflectx:\n dataset[-1]['data'] = dataset[-1]['data'][:,:,::-1]\n dataset[-1]['components'] = dataset[-1]['components'][:,:,::-1]\n\n if swapxy:\n dataset[-1]['data'] = dataset[-1]['data'].transpose((0,2,1))\n dataset[-1]['components'] = dataset[-1]['components'].transpose((0,2,1))\n\n # elastic deformations\n\n dataset[-1]['label'] = malis.seg_to_affgraph(dataset[-1]['components'],dataset[-1]['nhood'])\n\n return dataset\n\n \ndef slice_data(data, offsets, sizes):\n if (len(offsets) == 1):\n return data[offsets[0]:offsets[0] + sizes[0]]\n if (len(offsets) == 2):\n return data[offsets[0]:offsets[0] + sizes[0], offsets[1]:offsets[1] + sizes[1]]\n if (len(offsets) == 3):\n return data[offsets[0]:offsets[0] + sizes[0], offsets[1]:offsets[1] + sizes[1], offsets[2]:offsets[2] + sizes[2]]\n if (len(offsets) == 4):\n return data[offsets[0]:offsets[0] + sizes[0], offsets[1]:offsets[1] + sizes[1], offsets[2]:offsets[2] + sizes[2], offsets[3]:offsets[3] + sizes[3]]\n\n\ndef set_slice_data(data, insert_data, offsets, sizes):\n if (len(offsets) == 1):\n data[offsets[0]:offsets[0] + sizes[0]] = insert_data\n if (len(offsets) == 2):\n data[offsets[0]:offsets[0] + sizes[0], offsets[1]:offsets[1] + sizes[1]] = insert_data\n if (len(offsets) == 3):\n data[offsets[0]:offsets[0] + sizes[0], offsets[1]:offsets[1] + sizes[1], offsets[2]:offsets[2] + sizes[2]] = insert_data\n if (len(offsets) == 4):\n data[offsets[0]:offsets[0] + sizes[0], offsets[1]:offsets[1] + sizes[1], offsets[2]:offsets[2] + sizes[2], offsets[3]:offsets[3] + sizes[3]] = insert_data\n\n\ndef sanity_check_net_blobs(net):\n for key in net.blobs.keys():\n dst = net.blobs[key]\n data = np.ndarray.flatten(dst.data[0].copy())\n print('Blob: %s; %s' % (key, data.shape))\n failure = False\n first = -1\n for i in range(0,data.shape[0]):\n if abs(data[i]) > 1000:\n failure = True\n if first == -1:\n first = i\n print('Failure, location %d; objective %d' % (i, data[i]))\n print('Failure: %s, first at %d, mean %3.5f' % (failure,first,np.mean(data)))\n if failure:\n break\n \ndef dump_feature_maps(net, folder):\n for key in net.blobs.keys():\n dst = net.blobs[key]\n norm = normalize(dst.data[0], 0, 255)\n # print(norm.shape)\n for f in range(0,norm.shape[0]):\n outfile = open(folder+'/'+key+'_'+str(f)+'.png', 'wb')\n writer = png.Writer(norm.shape[2], norm.shape[1], greyscale=True)\n # print(np.uint8(norm[f,:]).shape)\n writer.write(outfile, np.uint8(norm[f,:]))\n outfile.close()\n \n \ndef dump_tikzgraph_maps(net, folder):\n xmaps = 2\n ymaps = 2\n padding = 12\n \n for key in net.blobs.keys():\n dst = net.blobs[key]\n norm = normalize(dst.data[0], 0, 255)\n \n width = xmaps*norm.shape[2]+(xmaps-1)*padding\n height = ymaps*norm.shape[2]+(ymaps-1)*padding\n \n mapout = np.ones((width,height))*255\n \n # print(norm.shape)\n for f in range(0,xmaps * ymaps):\n xoff = (norm.shape[2] + padding) * (f % xmaps)\n yoff = (norm.shape[1] + padding) * (f / xmaps)\n \n mapout[xoff:xoff+norm.shape[2],yoff:yoff+norm.shape[1]] = norm[min(f,norm.shape[0]-1),:]\n \n outfile = open(folder+'/'+key+'.png', 'wb')\n writer = png.Writer(width, height, greyscale=True)\n # print(np.uint8(norm[f,:]).shape)\n writer.write(outfile, np.uint8(mapout))\n outfile.close()\n \n \ndef get_net_input_specs(net, test_blobs = ['data', 'label', 'scale', 'label_affinity', 'affinty_edges']):\n \n shapes = []\n \n # The order of the inputs is strict in our network types\n for blob in test_blobs:\n if (blob in net.blobs):\n shapes += [[blob, np.shape(net.blobs[blob].data)]]\n \n return shapes\n\ndef get_spatial_io_dims(net):\n out_primary = 'label'\n \n if ('prob' in net.blobs):\n out_primary = 'prob'\n \n shapes = get_net_input_specs(net, test_blobs=['data', out_primary])\n \n dims = len(shapes[0][1]) - 2\n print(dims)\n \n input_dims = list(shapes[0][1])[2:2+dims]\n output_dims = list(shapes[1][1])[2:2+dims]\n padding = [input_dims[i]-output_dims[i] for i in range(0,dims)]\n \n return input_dims, output_dims, padding\n\ndef get_fmap_io_dims(net):\n out_primary = 'label'\n \n if ('prob' in net.blobs):\n out_primary = 'prob'\n \n shapes = get_net_input_specs(net, test_blobs=['data', out_primary])\n \n input_fmaps = list(shapes[0][1])[1]\n output_fmaps = list(shapes[1][1])[1]\n \n return input_fmaps, output_fmaps\n\n\ndef get_net_output_specs(net):\n return np.shape(net.blobs['prob'].data)\n\n\ndef process_input_data(net_io, input_data):\n net_io.setInputs([input_data])\n net_io.net.forward()\n net_outputs = net_io.net.blobs['prob']\n output = net_outputs.data[0].copy()\n return output\n\n\ndef generate_dataset_offsets_for_processing(net, data_arrays, process_borders):\n input_dims, output_dims, input_padding = get_spatial_io_dims(net)\n dims = len(output_dims)\n dataset_offsets_to_process = dict()\n for i in range(len(data_arrays)):\n data_array = data_arrays[i]['data']\n data_dims = len(data_array.shape)\n if process_borders:\n border_widths = [int(math.ceil(pad / float(2))) for pad in input_padding]\n origin = [-border_width for border_width in border_widths]\n else:\n origin = [0 for _ in input_padding]\n offsets = list(origin)\n in_dims = []\n out_dims = []\n for d in range(dims):\n in_dims += [data_array.shape[data_dims-dims+d]]\n out_dims += [data_array.shape[data_dims-dims+d] - input_padding[d]]\n list_of_offsets_to_process = []\n while True:\n offsets_to_append = list(offsets) # make a copy. important!\n list_of_offsets_to_process.append(offsets_to_append)\n incremented = False\n for d in range(dims):\n if process_borders:\n maximum_offset = in_dims[dims - 1 - d] - output_dims[dims - 1 - d] - border_widths[dims - 1 - d]\n else:\n maximum_offset = out_dims[dims - 1 - d] - output_dims[dims - 1 - d]\n if offsets[dims - 1 - d] == maximum_offset:\n # Reset direction\n offsets[dims - 1 - d] = origin[dims - 1 - d]\n else:\n # Increment direction\n next_potential_offset = offsets[dims - 1 - d] + output_dims[dims - 1 - d]\n offsets[dims - 1 - d] = min(next_potential_offset, maximum_offset)\n incremented = True\n break\n if not incremented:\n break\n dataset_offsets_to_process[i] = list_of_offsets_to_process\n return dataset_offsets_to_process\n\n\ndef process_core_multithreaded(device_locks, net_io, data_slice, offsets, pred_array, input_padding, fmaps_out,\n output_dims, using_data_loader, offsets_to_enqueue, processing_data_loader,\n index_of_shared_dataset, source_dataset_index):\n # Each thread sets its GPU\n current_device_id = -1\n while (current_device_id == -1):\n for device_list_id in range(0,len(device_locks)):\n if (device_locks[device_list_id].acquire(False)):\n current_device_id = device_list_id\n break\n if current_device_id == -1:\n time.sleep(0.0005)\n if DEBUG:\n print(\"Using device (list ID): \", current_device_id)\n # Note that this is the list ID, not the absolute device ID\n caffe.select_device(current_device_id, True)\n process_core(net_io[current_device_id], data_slice, offsets, pred_array, input_padding, fmaps_out,\n output_dims, using_data_loader, offsets_to_enqueue, processing_data_loader,\n index_of_shared_dataset, source_dataset_index)\n device_locks[device_list_id].release()\n \ndef process_core(net_io, data_slice, offsets, pred_array, input_padding, fmaps_out,\n output_dims, using_data_loader, offsets_to_enqueue, processing_data_loader,\n index_of_shared_dataset, source_dataset_index):\n process_local_net_io = None\n if isinstance(net_io, list):\n process_local_net_io = net_io[multiprocessing.Process.name]\n else:\n process_local_net_io = net_io\n \n output = process_input_data(process_local_net_io, data_slice)\n print(offsets)\n print(output.mean())\n pads = [int(math.ceil(pad / float(2))) for pad in input_padding]\n offsets_for_pred_array = [0] + [offset + pad for offset, pad in zip(offsets, pads)]\n set_slice_data(pred_array, output, offsets_for_pred_array, [fmaps_out] + output_dims)\n if using_data_loader and len(offsets_to_enqueue) > 0:\n # start adding the next slice to the loader with index_of_shared_dataset\n new_offsets = offsets_to_enqueue.pop(0)\n processing_data_loader.start_refreshing_shared_dataset(\n index_of_shared_dataset,\n new_offsets,\n source_dataset_index,\n transform=False\n )\n\ndef process(nets, data_arrays, shapes=None, net_io=None, zero_pad_source_data=True, target_arrays=None):\n net = None\n thread_pool = None\n device_locks = None\n if isinstance(nets, list):\n # Grab one network to figure out parameters\n net = nets[0]\n else:\n net = nets\n input_dims, output_dims, input_padding = get_spatial_io_dims(net)\n fmaps_in, fmaps_out = get_fmap_io_dims(net)\n dims = len(output_dims)\n if target_arrays is not None:\n assert len(data_arrays) == len(target_arrays)\n for data_array, target in zip(data_arrays, target_arrays):\n prediction_shape = (fmaps_out,) + data_array['data'].shape[-dims:]\n assert prediction_shape == target.shape, \\\n \"Target array for dname {} is the wrong shape. {} should be {}\"\\\n .format(data_array['name'], target.shape, prediction_shape)\n pred_arrays = []\n if shapes is None:\n # Raw data slice input (n = 1, f = 1, spatial dims)\n shapes = [[1, fmaps_in] + input_dims]\n if net_io is None:\n if isinstance(nets, list):\n net_io = []\n for net_inst in nets:\n net_io += [NetInputWrapper(net_inst, shapes)]\n else: \n net_io = NetInputWrapper(net, shapes)\n \n using_data_loader = data_io.data_loader_should_be_used_with(data_arrays)\n processing_data_loader = None\n if using_data_loader:\n processing_data_loader = data_io.DataLoader(\n size=5,\n datasets=data_arrays,\n input_shape=tuple(input_dims),\n output_shape=None, # ignore labels\n n_workers=3\n )\n dataset_offsets_to_process = generate_dataset_offsets_for_processing(\n net, data_arrays, process_borders=zero_pad_source_data)\n for source_dataset_index in dataset_offsets_to_process:\n \n # Launch \n if isinstance(nets, list):\n thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=len(nets))\n device_locks = []\n for device_list_id in range(0,len(nets)):\n device_locks += [threading.Lock()]\n \n list_of_offsets_to_process = dataset_offsets_to_process[source_dataset_index]\n if DEBUG:\n print(\"source_dataset_index = \", source_dataset_index)\n print(\"Processing source volume #{i} with offsets list {o}\"\n .format(i=source_dataset_index, o=list_of_offsets_to_process))\n # make a copy of that list for enqueueing purposes\n offsets_to_enqueue = list(list_of_offsets_to_process)\n data_array = data_arrays[source_dataset_index]['data']\n if target_arrays is not None:\n pred_array = target_arrays[source_dataset_index]\n else:\n prediction_shape = (fmaps_out,) + data_array.shape[-dims:]\n pred_array = np.zeros(shape=prediction_shape, dtype=np.float32)\n if using_data_loader:\n # start pre-populating queue\n for shared_dataset_index in range(min(processing_data_loader.size, len(list_of_offsets_to_process))):\n # fill shared-memory datasets with an offset\n offsets = offsets_to_enqueue.pop(0)\n offsets = tuple([int(o) for o in offsets])\n # print(\"Pre-populating processing data loader with data at offset {}\".format(offsets))\n print(\"Pre-populating data loader's dataset #{i}/{size} with dataset #{d} and offset {o}\"\n .format(i=shared_dataset_index, size=processing_data_loader.size,\n d=source_dataset_index, o=offsets))\n shared_dataset_index, async_result = processing_data_loader.start_refreshing_shared_dataset(\n shared_dataset_index,\n offsets,\n source_dataset_index,\n transform=False,\n wait=True\n )\n # process each offset\n for i_offsets in range(len(list_of_offsets_to_process)):\n index_of_shared_dataset = None\n if using_data_loader:\n dataset, index_of_shared_dataset = processing_data_loader.get_dataset()\n offsets = list(dataset['offset']) # convert tuple to list\n data_slice = dataset['data']\n if DEBUG:\n print(\"Processing next dataset in processing data loader, which has offset {o}\"\n .format(o=dataset['offset']))\n else:\n offsets = list_of_offsets_to_process[i_offsets]\n if zero_pad_source_data:\n data_slice = data_io.util.get_zero_padded_slice_from_array_by_offset(\n array=data_array,\n origin=[0] + offsets,\n shape=[fmaps_in] + [output_dims[di] + input_padding[di] for di in range(dims)]\n )\n else:\n data_slice = slice_data(\n data_array,\n [0] + offsets,\n [fmaps_in] + [output_dims[di] + input_padding[di] for di in range(dims)]\n )\n # process the chunk\n if isinstance(net_io, list):\n thread_pool.submit(process_core_multithreaded, device_locks, net_io, data_slice, offsets, pred_array, input_padding, fmaps_out,\n output_dims, using_data_loader, offsets_to_enqueue, processing_data_loader,\n index_of_shared_dataset, source_dataset_index)\n else:\n process_core(net_io, data_slice, offsets, pred_array, input_padding, fmaps_out,\n output_dims, using_data_loader, offsets_to_enqueue, processing_data_loader,\n index_of_shared_dataset, source_dataset_index)\n\n if not (thread_pool is None):\n thread_pool.shutdown(True)\n \n pred_arrays.append(pred_array)\n if using_data_loader:\n processing_data_loader.destroy()\n return pred_arrays\n\n\nclass TestNetEvaluator(object):\n def __init__(self, test_net, train_net, data_arrays, options):\n self.options = options\n self.test_net = test_net\n self.train_net = train_net\n self.datasets = data_arrays\n self.thread = None\n input_dims, output_dims, input_padding = get_spatial_io_dims(self.test_net)\n fmaps_in, fmaps_out = get_fmap_io_dims(self.test_net)\n self.shapes = [[1, fmaps_in] + input_dims]\n self.fmaps_out = fmaps_out\n self.n_data_dims = len(output_dims)\n self.net_io = NetInputWrapper(self.test_net, self.shapes)\n\n def run_test(self, iteration):\n caffe.select_device(self.options.test_device, False)\n for dataset_i in range(len(self.datasets)):\n dataset_to_process = self.datasets[dataset_i]\n if 'name' in dataset_to_process:\n h5_file_name = dataset_to_process['name'] + '.h5'\n else:\n h5_file_name = 'test_out_' + repr(dataset_i) + '.h5'\n temp_file_name = h5_file_name + '.inprogress'\n with h5py.File(temp_file_name, 'w') as h5_file:\n prediction_shape = (self.fmaps_out,) + dataset_to_process['data'].shape[-self.n_data_dims:]\n target_array = h5_file.create_dataset(name='main', shape=prediction_shape, dtype=np.float32)\n output_arrays = process(self.test_net,\n data_arrays=[dataset_to_process],\n shapes=self.shapes,\n net_io=self.net_io,\n target_arrays=[target_array])\n os.rename(temp_file_name, h5_file_name)\n print(\"Just saved {}\".format(h5_file_name))\n\n def evaluate(self, iteration):\n # Test/wait if last test is done\n if self.thread is not None:\n try:\n self.thread.join()\n except:\n self.thread = None\n net_weight_transfer(self.test_net, self.train_net)\n if USE_ONE_THREAD:\n self.run_test(iteration)\n else:\n self.thread = threading.Thread(target=self.run_test, args=[iteration])\n self.thread.start()\n\n\ndef init_solver(solver_config, options):\n caffe.set_mode_gpu()\n caffe.select_device(options.train_device, False)\n solver_inst = caffe.get_solver(solver_config)\n if options.test_net is None:\n return solver_inst, None\n else:\n return solver_inst, init_testnet(options.test_net, test_device=options.test_device)\n\n\ndef init_testnet(test_net, trained_model=None, test_device=0):\n caffe.set_mode_gpu()\n if isinstance(test_device, list):\n # Initialize test network for each device\n networks = []\n for device in test_device:\n caffe.select_device(device, False)\n if trained_model is None:\n networks += [caffe.Net(test_net, caffe.TEST)]\n else:\n networks += [caffe.Net(test_net, trained_model, caffe.TEST)]\n return networks\n else:\n # Initialize test network for a single device\n caffe.select_device(test_device, False)\n if trained_model is None:\n return caffe.Net(test_net, caffe.TEST)\n else:\n return caffe.Net(test_net, trained_model, caffe.TEST)\n\n\nclass MakeDatasetOffset(object):\n def __init__(self, input_dims, output_dims):\n self.input_dims = input_dims\n input_padding = [in_ - out_ for in_, out_ in zip(input_dims, output_dims)]\n self.border = [int(math.ceil(pad / float(2))) for pad in input_padding]\n self.dims = len(input_dims)\n self.random_state = np.random.RandomState()\n \n def calculate_offset_bounds(self, dataset):\n shape_of_source_data = dataset['data'].shape[-self.dims:]\n offset_bounds = [(0, n - i) for n, i in zip(shape_of_source_data, self.input_dims)]\n client_requested_zero_padding = dataset.get('zero_pad_inputs', False)\n net_requires_zero_padding = any([max_ < min_ for min_, max_ in offset_bounds])\n if net_requires_zero_padding or client_requested_zero_padding:\n # then expand bounds to include borders\n offset_bounds = [(min_ - border, max_ + border) for (min_, max_), border in zip(offset_bounds, self.border)]\n if DEBUG and net_requires_zero_padding and not client_requested_zero_padding:\n print(\"Zero padding even though the client didn't ask, \"\n \"because net input size exceeds source data shape\")\n return offset_bounds\n\n def __call__(self, data_array_list):\n which_dataset = self.random_state.randint(0, len(data_array_list))\n dataset = data_array_list[which_dataset]\n offset_bounds = self.calculate_offset_bounds(dataset)\n offsets = [self.random_state.randint(min_, max_ + 1) for min_, max_ in offset_bounds]\n if DEBUG:\n print(\"Training offset generator: dataset #\", which_dataset,\n \"at\", offsets, \"from bounds\", offset_bounds,\n \"from source shape\", dataset['data'].shape, \"with input_dims\", self.input_dims)\n return which_dataset, offsets\n\n\ndef train(solver, test_net, data_arrays, train_data_arrays, options):\n caffe.select_device(options.train_device, False)\n\n net = solver.net\n\n test_eval = None\n if (options.test_net != None):\n test_eval = TestNetEvaluator(test_net, net, train_data_arrays, options)\n \n input_dims, output_dims, input_padding = get_spatial_io_dims(net)\n fmaps_in, fmaps_out = get_fmap_io_dims(net)\n\n dims = len(output_dims)\n losses = []\n \n shapes = []\n # Raw data slice input (n = 1, f = 1, spatial dims)\n shapes += [[1,fmaps_in] + input_dims]\n # Label data slice input (n = 1, f = #edges, spatial dims)\n shapes += [[1,fmaps_out] + output_dims]\n \n if (options.loss_function == 'malis'):\n # Connected components input (n = 1, f = 1, spatial dims)\n shapes += [[1,1] + output_dims]\n if (options.loss_function == 'euclid'):\n # Error scale input (n = 1, f = #edges, spatial dims)\n shapes += [[1,fmaps_out] + output_dims]\n # Nhood specifications (n = #edges, f = 3)\n if (('nhood' in data_arrays[0]) and (options.loss_function == 'malis')):\n shapes += [[1,1] + list(np.shape(data_arrays[0]['nhood']))]\n net_io = NetInputWrapper(net, shapes)\n make_dataset_offset = MakeDatasetOffset(input_dims, output_dims)\n if data_io.data_loader_should_be_used_with(data_arrays):\n using_data_loader = True\n # and initialize queue!\n loader_size = 20\n n_workers = 10\n make_dataset_offset = MakeDatasetOffset(dims, output_dims, input_padding)\n loader_kwargs = dict(\n size=loader_size,\n datasets=data_arrays,\n input_shape=tuple(input_dims),\n output_shape=tuple(output_dims),\n n_workers=n_workers,\n dataset_offset_func=make_dataset_offset\n )\n print(\"creating queue with kwargs {}\".format(loader_kwargs))\n training_data_loader = data_io.DataLoader(**loader_kwargs)\n # start populating the queue\n for i in range(loader_size):\n if DEBUG:\n print(\"Pre-populating data loader's dataset #{i}/{size}\"\n .format(i=i, size=training_data_loader.size))\n shared_dataset_index, async_result = \\\n training_data_loader.start_refreshing_shared_dataset(i)\n else:\n using_data_loader = False\n\n # Loop from current iteration to last iteration\n for i in range(solver.iter, solver.max_iter):\n start = time.time()\n if (options.test_net != None and i % options.test_interval == 1):\n test_eval.evaluate(i)\n if USE_ONE_THREAD:\n # after testing finishes, switch back to the training device\n caffe.select_device(options.train_device, False)\n if not using_data_loader:\n dataset_index, offsets = make_dataset_offset(data_arrays)\n dataset = data_arrays[dataset_index]\n # These are the raw data elements\n data_slice = data_io.util.get_zero_padded_slice_from_array_by_offset(\n array=dataset['data'],\n origin=[0] + offsets,\n shape=[fmaps_in] + input_dims)\n label_slice = slice_data(dataset['label'], [0] + [offsets[di] + int(math.ceil(input_padding[di] / float(2))) for di in range(0, dims)], [fmaps_out] + output_dims)\n if 'transform' in dataset:\n # transform the input\n # assumes that the original input pixel values are scaled between (0,1)\n if DEBUG:\n print(\"data_slice stats, pre-transform: min\", data_slice.min(), \"mean\", data_slice.mean(),\n \"max\", data_slice.max())\n lo, hi = dataset['transform']['scale']\n data_slice = 0.5 + (data_slice - 0.5) * np.random.uniform(low=lo, high=hi)\n lo, hi = dataset['transform']['shift']\n data_slice = data_slice + np.random.uniform(low=lo, high=hi)\n else:\n dataset, index_of_shared_dataset = training_data_loader.get_dataset()\n data_slice = dataset['data']\n assert data_slice.shape == (fmaps_in,) + tuple(input_dims)\n label_slice = dataset['label']\n assert label_slice.shape == (fmaps_out,) + tuple(output_dims)\n if DEBUG:\n print(\"Training with next dataset in data loader, which has offset\", dataset['offset'])\n mask_slice = None\n if 'mask' in dataset:\n mask_slice = dataset['mask']\n if DEBUG:\n print(\"data_slice stats: min\", data_slice.min(), \"mean\", data_slice.mean(), \"max\", data_slice.max())\n if options.loss_function == 'malis':\n components_slice, ccSizes = malis.connected_components_affgraph(label_slice.astype(int32), dataset['nhood'])\n # Also recomputing the corresponding labels (connected components)\n net_io.setInputs([data_slice, label_slice, components_slice, data_arrays[0]['nhood']])\n elif options.loss_function == 'euclid':\n label_slice_mean = label_slice.mean()\n if 'mask' in dataset:\n label_slice = label_slice * mask_slice\n label_slice_mean = label_slice.mean() / mask_slice.mean()\n w_pos = 1.0\n w_neg = 1.0\n if options.scale_error:\n frac_pos = np.clip(label_slice_mean, 0.05, 0.95)\n w_pos = w_pos / (2.0 * frac_pos)\n w_neg = w_neg / (2.0 * (1.0 - frac_pos))\n error_scale_slice = scale_errors(label_slice, w_neg, w_pos)\n net_io.setInputs([data_slice, label_slice, error_scale_slice])\n elif options.loss_function == 'softmax':\n # These are the affinity edge values\n net_io.setInputs([data_slice, label_slice])\n loss = solver.step(1) # Single step\n if using_data_loader:\n training_data_loader.start_refreshing_shared_dataset(index_of_shared_dataset)\n while gc.collect():\n pass\n time_of_iteration = time.time() - start\n if options.loss_function == 'euclid' or options.loss_function == 'euclid_aniso':\n print(\"[Iter %i] Time: %05.2fs Loss: %f, frac_pos=%f, w_pos=%f\" % (i, time_of_iteration, loss, frac_pos, w_pos))\n else:\n print(\"[Iter %i] Time: %05.2fs Loss: %f\" % (i, time_of_iteration, loss))\n losses += [loss]\n if hasattr(options, 'loss_snapshot') and ((i % options.loss_snapshot) == 0):\n io.savemat('loss.mat',{'loss':losses})\n\n if using_data_loader:\n training_data_loader.destroy()\n","sub_path":"PyGreentea.py","file_name":"PyGreentea.py","file_ext":"py","file_size_in_byte":36625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"583563250","text":"from django.conf.urls import url\nfrom basicapp import views\n\n#template tagging\napp_name = 'basicapp'\n\nurlpatterns = [\n url(r'^about/$', views.about, name = 'about'),\n url(r'^other/$',views.other, name = 'other'),\n]","sub_path":"learning_templates/basicapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"55959078","text":"import chainer\nfrom rnn_classify import MultiLayerLSTM, Classifier\nfrom sklearn.model_selection import train_test_split\nimport time\nimport numpy as np\nfrom chainer import Variable, optimizers\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\nfrom TrainingSet import TrainRNN\nimport os\nimport pickle\nimport random\nimport winsound\n\n\"\"\" Used for the conference paper for MLSP2017 \"\"\"\n\n\"\"\" Trains a Recurrent Neural Network\n Args:\n Requires time series, each time sample labelled.\n Requires input and training parameters to be adjusted.\n Return:\n An RNN model. \"\"\"\n\n\"\"\" Data should be three dimensional ar ray\n data: [num_samples x length of time signal x number of channels]\n label: [num_samples x 1 x length of time signal] \"\"\"\n\nfolder_dat = \\\n '.\\dat\\modified_CSL_RSVPKeyboard_di830609_IRB130107_ERPCalibration_2016-07-22-T-16-48'\n# If \\a kinda happens in print name add M for model in front\nprint_name = '\\di830609_IRB130107_2016-07-22-T-16-48_v1'\n\n# As we are using reshape form Matrix dimensions should be as this\nsamples_o = sio.loadmat(folder_dat + '\\data.mat')\nlabels_o = sio.loadmat(folder_dat + '\\label.mat')\nstart_idx = sio.loadmat(folder_dat + '\\stime.mat')\ntrial_label_o = sio.loadmat(folder_dat + '\\T_lab.mat')\nraw_samples = samples_o['data_m']\nraw_labels = np.concatenate(labels_o['label_m']).astype(np.int32)\ntrial_time_idx = start_idx['start_m']\ntrial_label = trial_label_o['trial_lab_m']\nfs = 256\n\ntrial_time = np.floor(np.mean(trial_time_idx, axis=0))[0]\nprob_letter = np.ones(np.max(trial_label)) * np.power(10, 6)\n\n# Parameters\ncross_val_num = 10\nnum_layer = 4 # Number of LSTM layers (depth)\nsize_layer = 35\nsize_out = 2\nmax_num_iter = 120\ntest_size = .97\n\nRNN = TrainRNN(raw_samples, raw_labels, ratio_batch=0.3, test_size=test_size,\n valid_size=0.1, size_out=size_out, size_state=size_layer,\n num_layer=num_layer, bptt=20, max_num_iter=max_num_iter,\n valid_epoch=2, print_name=print_name)\n\nif os.path.exists('models' + print_name + '.p'):\n model = pickle.load(open(\"models\" + print_name + \".p\", \"rb\"))\nelse:\n\n RNN.train(k=cross_val_num)\n\n plt.figure()\n plt.plot(np.arange(1, RNN.max_num_iter + 1),\n RNN.train_loss,\n label='train loss')\n for idx_val_plot in range(5):\n plt.plot(\n np.arange(RNN.valid_epoch, RNN.max_num_iter + 1,\n step=RNN.valid_epoch, ), RNN.valid_loss[idx_val_plot],\n label='valid loss_' + str(idx_val_plot))\n plt.xlabel('iteration[number]')\n plt.ylabel('loss[softmax cross entropy]')\n plt.title('layers: {}x{}'.format(num_layer, size_layer))\n plt.legend(loc='upper right', shadow=True)\n plt.grid(True)\n plt.savefig('.\\FigDummy' + print_name + '_Train.pdf', format='pdf')\n model = RNN.min_val_e_model\n\nx_test = RNN.test_samples\ny_test = RNN.test_labels\n\nx_test = np.asarray(x_test)\nx_test = x_test.reshape(x_test.shape[0], x_test.shape[1],\n RNN.size_inp)\nx_test = x_test.astype(np.float32)\ny_test = np.asarray(y_test)\ny_test = y_test.astype(np.int32)\n\nx = [Variable(x_test[:, n]) for n in range(RNN.num_samples)]\ny = [Variable(y_test[:, n]) for n in range(RNN.num_samples)]\n\nwith chainer.no_backprop_mode():\n prob_hat = np.array([pn.data for pn in model.classify(x)])\n\ncount = 1\nP = []\nplt.style.use('grayscale')\nfor j, (x, y, p) in enumerate(\n zip(RNN.test_samples, RNN.test_labels, prob_hat.swapaxes(0, 1))):\n x = RNN.test_samples[j]\n y = RNN.test_labels[j]\n\n # fig = plt.figure()\n # ax1 = fig.add_subplot(211)\n #\n # ax2 = ax1.twinx()\n # ax1.plot(x, linewidth=2)\n # ax2.plot(p[:, -1], '.-', label='estimate', linewidth=2)\n # ax2.plot(y, '--', label='true', linewidth=2)\n #\n # ax1.set_xlim(0, RNN.num_samples - 1)\n # ax1.set_ylim(-30, 30)\n # ax1.set_xlabel('samples', fontsize=18)\n # ax1.set_ylabel('data [uV]', fontsize=18)\n #\n # ax2.set_ylim(0, 1)\n # ax2.set_ylabel('probability', fontsize=18)\n # ax2.legend(loc='upper right', shadow=True, fontsize=15)\n #\n # ax1.grid(True)\n #\n # ax2.spines['top'].set_visible(False)\n # ax2.spines['left'].set_visible(False)\n # ax2.get_xaxis().tick_bottom()\n # ax2.get_yaxis().tick_right()\n #\n # ax1.spines['top'].set_visible(False)\n # ax1.spines['right'].set_visible(False)\n # ax1.get_xaxis().tick_bottom()\n # ax1.get_yaxis().tick_left()\n #\n # plt.savefig('.\\FigRNN' + print_name + '\\S' + str(count) + 'DSFig.eps',\n # format='eps', bbox_inches='tight', pad_inches=0.0, dpi=1200)\n # plt.savefig('.\\FigRNN' + print_name + '\\S' + str(count) + 'DSFig.jpg',\n # format='jpg', bbox_inches='tight', pad_inches=0.0, dpi=1200)\n\n p = np.power(p, 1 / p.shape[0])\n p.astype(np.float64)\n\n tmp = [np.prod(p[:, 0])]\n for idx in range(len(trial_time)):\n tmp.append(\n np.prod(p[int(trial_time[idx]):int(trial_time[idx] + fs / 2), -1])\n / (np.prod(p[int(trial_time[idx]):int(trial_time[idx] + fs / 2),\n 0]) + np.power(.1, 6)) * np.prod(p[:, 0]))\n\n P.append(np.array(tmp))\n # p_this = np.array(tmp)\n #\n # letter_labels = trial_label[RNN.test_idx[count - 1]]\n # for l in range(np.max(trial_label)):\n # if l in set(letter_labels[0]):\n # prob_letter[l] *= p_this[\n # int(1 + np.where(letter_labels[0] == l)[0][0])]\n # else:\n # prob_letter[l] *= (p_this[0] / (np.max(trial_label)\n # - letter_labels.shape[1]))\n #\n # prob_letter *= np.pow(10, 6) / np.max(prob_letter)\n #\n # a = plt.figure()\n # plt.stem(np.array(prob_letter) / np.sum(prob_letter))\n # plt.pause(.5)\n\n count += 1\n\n# For AUC Calc in Matlab\nsio.savemat(folder_dat + '\\P.mat', {'P': np.asarray(P)})\nsio.savemat(folder_dat + '\\pr.mat', {'pr': RNN.test_idx})\n# Do other stuff while running and let it warn you\nFreq = 2500 # Set Frequency To 2500 Hertz\nDur = 500 # Set Duration To 1000 ms == 1 second\nwinsound.Beep(Freq, Dur)\n","sub_path":"RNNFitModel_Test.py","file_name":"RNNFitModel_Test.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"222861895","text":"'当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights'\nfilters = set()\n\ndef fileterWords():\n try:\n with open(r'E:\\Programs\\Python\\python_daily\\test_0013\\test_0013.txt', 'r', -1, encoding='utf8') as f:\n for line in f.readlines():\n filters.add(line.rstrip('\\n'))\n while True:\n s = input('���输入字符:')\n if s == 'exit':\n break\n else:\n for it in filters:\n if it in s:\n # 将敏感字符用同样数量的*替代\n s = s.replace(it, '*' * len(it))\n print(s)\n\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n fileterWords()\n","sub_path":"python_daily/test_0013/python_0013.py","file_name":"python_0013.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"617398537","text":"import numpy as np\nimport collections\n\ndef majority(val_spk):\n \"\"\"\n :return: counts, majority\n \"\"\"\n unique, counts = np.unique(val_spk, return_counts=True)\n counts = np.transpose(np.asarray((unique, counts)))\n\n frequencies = counts[:,1]\n\n count_single_instances = 0\n for frequency in frequencies:\n if frequency == '1':\n count_single_instances += 1\n\n # 11 speakers that have only a single entry, stratification needs at least two instances of each speaker\n #print(count_single_instances)\n\n # Problem was here. Labels were shifted!\n # counts = np.sort(counts, axis=0)\n counts = counts[counts[:,0].argsort()]\n\n # Summing of frequencies of all speakers should be equal to the size of the speaker dataset\n total_occurrences = counts[:, 1].sum()\n assert total_occurrences == val_spk.shape[0]\n\n majority_speaker = counts[counts.shape[0] - 1]\n\n # Majority baseline is 360/5000 = 0.072\n return counts, (majority_speaker[1] / total_occurrences)\n\ndef majority_places(val_spk):\n \"\"\"\n :param val_spk:\n :return:\n \"\"\"\n\n counts = collections.Counter(val_spk)\n\n count_single_instances = 0\n for key, value in counts.items():\n if value == 1:\n count_single_instances += 1\n # 40 speakers with only a single instance, stratification needs at least two instances of each speaker\n #print(count_single_instances)\n\n # Majority baseline is 0.362\n print(\"Majority baseline is {}\".format(max(counts.values()) / val_spk.shape[0]))\n\n return counts\n\n#majority(val_spk)\n#majority_places(val_spk_int)\n","sub_path":"majority.py","file_name":"majority.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"225265851","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 27 18:48:27 2018\n\n@author: Saud\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\nimport numpy\n\nnumpy.random.seed(7)\n\ndataset= numpy.loadtxt('pima-indians-diabetes.csv',delimiter=\",\")\n\nx = dataset[:,0:8]\ny = dataset[:,8]\n\nprint(x)\n#Dense used for fully connected network\n#input_dim = no. of nodes in the input layer\nmodel = Sequential()\nmodel.add(Dense(12,input_dim = 8,activation = 'relu'))\nmodel.add(Dense(8,activation = 'relu'))\nmodel.add(Dense(1,activation = 'sigmoid'))\n#compile model\n#binary_crossentropy is logarithmic loss function\n#adam opitmizaer being used\n#since classification problem so accuracy is metric\nmodel.compile(loss= 'binary_crossentropy',optimizer = 'adam',metrics = ['accuracy'])\n#nepochs is used to set the number of epochs/iterations\n#batch_size indicates number of instances that are evaluated before updating weights\nmodel.fit(x,y,epochs=150,batch_size=10)\n#testing the model on trained data\nscores = model.evaluate(x,y)\nprint(\"\\n%s: %0.2f%%\" % (model.metrics_names[1], scores[1]*100))\n#making predictions\nprediction = model.predict(x)\n#rounding off prediction due to sigmoid function producing value between 0 to 1\nrounded = [round(x[0]) for x in prediction]\nprint(rounded)\n\n\n\n\n\n\n","sub_path":"first_nn_keras.py","file_name":"first_nn_keras.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"288872952","text":"#!/usr/local/bin/python3.7\n\nfrom numba import jit\n\ndef py_total(n):\n\ty = 0\n\tfor i in range(n + 1):\n\t\ty += i\n\treturn y\n\n@jit\ndef numba_total(n):\n\ty = 0\n\tfor i in range(n + 1):\n\t\ty += i\n\treturn y\n\n# print(py_total(10000000))\n# print(numba_total(10000000))\n","sub_path":"Python/Interfacing-C/Numba/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"585934163","text":"\n# Instrukcja warunkowa if jest bardzo czytelna\n# if 7 > 3:\n# print(\"To oczywiste!\")\n\n# if 10 < 4:\n# print(\"To się nigdy nie zdarzy\")\n# print(\"Inne\")\n\n# If w połączeniu z dynamicznymi (np. wprowadzanymi przez użytkownika) danymi\n# name = input(\"Jak się nazywasz? \")\n# print(f\"Miło Cię poznać {name}\")\n#\n# if len(name) >= 7:\n# print(f\"{name} to całkiem długie imię!\")\n# if len(name) < 7:\n# print(f\"{name} to raczej krótkie imię\")\n\n\nage = int(input(\"Ile masz lat? \"))\n# if age < 18:\n# print(\"Jeszcze nie możesz głosować\")\n# if age >= 18:\n# print(\"Możesz już głosować!\")\n# if age >= 21:\n# print(\"Możesz kandydować na posła\")\n# if age >= 30:\n# print(\"Możesz kandydować na senatora\")\n# if age >= 35:\n# print(\"Możesz kandydować na prezydenta\")\n\n# Drobna pomyłka - program nie działa poprawnie!\nif age < 18:\n print(\"Jeszcze nie możesz głosować\")\nif age >= 8:\n print(\"Możesz już głosować!\")\n","sub_path":"week_4/if_condidtion/if_examples.py","file_name":"if_examples.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"301916257","text":"import json\nimport os\nimport re\nfrom urllib.parse import parse_qs\n\nfrom common.redis import rds\nfrom django.views import View\nfrom django.http import HttpResponse, JsonResponse\nfrom ihomeapp.verify_code import get_image_code\nfrom .models import User, Area, House, Facility, HouseImage, Order\nimport random\nfrom libs.yuntongxun.SendTemplateSMS import CCP\nfrom common.commons import login_required\n# from tasks.task_sms import send_sms\nfrom tasks.sms.tasks import send_sms\nfrom datetime import datetime\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom alipay import AliPay\n\nclass image_codes(View):\n def get(self, request):\n \"\"\"\n 获取图片验证码\n :param request: a:验证码编号\n :return: 验证码图片\n \"\"\"\n b = request.GET.get('a')\n name, text, image_data = get_image_code(b)\n return HttpResponse(image_data, content_type='image/jpg')\n\n def post(self, request):\n a = json.loads(request.body.decode())\n bianma = a['bianma']\n code = a['code']\n if rds.get(\"image_code_%s\" % bianma):\n if code == rds.get(\"image_code_%s\" % bianma).decode():\n rds.delete(\"image_code_%s\" % bianma)\n return JsonResponse({\"msg\": \"ok\"})\n else:\n return JsonResponse({\"msg\": \"no\"})\n else:\n return JsonResponse({\"msg\": \"cuowu\"})\n\n\n# def verify_code(request):\n# a = json.loads(request.body.decode())\n# b = a['a']\n#\n# name, text, image_data = get_image_code(b)\n# return HttpResponse(image_data, content_type='image/jpg')\n\n# 非异步处理发送短信\n# def get_sms_code(request):\n# \"\"\"\n# 获取短信验证码\n# :param request: mobile,image_code,image_code_id\n# :return: code:0 成功 -1失败\n# \"\"\"\n# image_code = request.GET.get('image_code')\n# image_code_id = request.GET.get('image_code_id')\n# mobile = request.GET.get('mobile')\n#\n# if not all([image_code, image_code_id, mobile]):\n# # 参数不完整\n# return JsonResponse({\"err\": \"参数不完整\"})\n#\n# # 业务逻辑处理\n# # 从redis中取出真实的图片验证码\n# try:\n# real_image_code = rds.get('image_code_%s' % image_code_id)\n# except Exception as e:\n# return JsonResponse({\"err\": \"redis数据库异常\"})\n#\n# # 判断图片验证码是否过期\n# if real_image_code is None:\n# return JsonResponse({\"err\": \"图片验证码失效\"})\n#\n# # 删除图片验证码\n# try:\n# rds.delete(\"image_code_%s\" % image_code_id)\n# except Exception as e:\n# print(e)\n#\n# # 与用户填写的值进行对比\n# if real_image_code.decode().lower() != image_code.lower():\n# return JsonResponse({\"err\": \"图片验证码错误\"})\n#\n# # 判断60s内是否有发送短信\n# try:\n# send_flag = rds.get(\"send_sms_code_%s\" % mobile)\n# except Exception as e:\n# print(e)\n# else:\n# if send_flag is not None:\n# return JsonResponse({\"err\": \"请求过于频繁\"})\n#\n# # 判断手机号是否存在\n# try:\n# user = User.objects.filter(mobile=mobile).first()\n# except Exception as e:\n# print(e)\n# else:\n# if user is not None:\n# # 表示手机号已存在\n# return JsonResponse({\"err\": \"手机号已存在\"})\n#\n# sms_code = \"%06d\" % random.randint(0, 999999)\n#\n# # 保存真实的短信验证码\n# try:\n# # rds.setex(\"sms_code_%s\" % mobile, 300, sms_code)\n# rds.set(\"sms_code_%s\" % mobile, sms_code)\n# # 保存发送给这个手机号码的记录,防止用户再60s内再次发送短信的操作\n# rds.setex(\"send_sms_code_%s\" % mobile, 60, 1)\n# except Exception as e:\n# print(e)\n# return JsonResponse({\"err\": \"保存短信验证码异常\"})\n# try:\n# ccp = CCP()\n# result = ccp.send_template_sms(mobile, [sms_code, 5], 1)\n# except Exception as e:\n# print(e)\n#\n# if result == 0:\n# return JsonResponse({\"msg\": \"发送成功\", \"code\": 0})\n# else:\n# return JsonResponse({\"msg\": \"发送失败\", \"code\": -1})\n\n# 异步处理发送短信\ndef get_sms_code(request):\n \"\"\"\n 获取短信验证码\n :param request: mobile,image_code,image_code_id\n :return: code:0 成功 -1失败\n \"\"\"\n image_code = request.GET.get('image_code')\n image_code_id = request.GET.get('image_code_id')\n mobile = request.GET.get('mobile')\n\n if not all([image_code, image_code_id, mobile]):\n # 参数不完整\n return JsonResponse({\"err\": \"参数不完整\"})\n\n # 业务逻辑处理\n # 从redis中取出真实的图片验证码\n try:\n real_image_code = rds.get('image_code_%s' % image_code_id)\n except Exception as e:\n return JsonResponse({\"err\": \"redis数据库异常\"})\n\n # 判断图片验证码是否过期\n if real_image_code is None:\n return JsonResponse({\"err\": \"图片验证码失效\"})\n\n # 删除图片验证码\n try:\n rds.delete(\"image_code_%s\" % image_code_id)\n except Exception as e:\n print(e)\n\n # 与用户填写的值进行对比\n if real_image_code.decode().lower() != image_code.lower():\n return JsonResponse({\"err\": \"图片验证码错误\"})\n\n # 判断60s内是否有发送短信\n try:\n send_flag = rds.get(\"send_sms_code_%s\" % mobile)\n except Exception as e:\n print(e)\n else:\n if send_flag is not None:\n return JsonResponse({\"err\": \"请求过于频繁\"})\n\n # 判断手机号是否存在\n # try:\n # user = User.objects.filter(mobile=mobile).first()\n # except Exception as e:\n # print(e)\n # else:\n # if user is not None:\n # # 表示手机号已存在\n # return JsonResponse({\"err\": \"手机号已存在\"})\n\n sms_code = \"%06d\" % random.randint(0, 999999)\n\n # 保存真实的短信验证码\n try:\n # rds.setex(\"sms_code_%s\" % mobile, 300, sms_code)\n rds.set(\"sms_code_%s\" % mobile, sms_code)\n # 保存发送给这个手机号码的记录,防止用户再60s内再次发送短信的操作\n rds.setex(\"send_sms_code_%s\" % mobile, 60, 1)\n except Exception as e:\n print(e)\n return JsonResponse({\"err\": \"保存短信验证码异常\"})\n # 发送短信\n send_sms.delay(mobile, [sms_code, 5], 1)\n return JsonResponse({\"msg\": \"发送成功\", \"code\": 0})\n\n\ndef login(request):\n \"\"\"\n 登录\n :param request: 手机号,密码\n :return: 成功,失败\n \"\"\"\n req = json.loads(request.body.decode())\n mobile = req['mobile']\n password = req['password']\n if not all([mobile, password]):\n # 参数不完整\n return JsonResponse({\"err\": \"参数不完整\"})\n\n # 手机号的格式\n if not re.match(r'1[34567]\\d{9}', mobile):\n return JsonResponse({\"err\": \"手机号格式错误\"})\n\n # 判断错误次数是否超过限制,如果超过限制,则返回\n # redis记录: \"access_nums_请求ip\":\"次数\"\n user_ip = request.META['REMOTE_ADDR']\n try:\n access_nums = rds.get(\"access_num_%s\" % user_ip).decode()\n print(type(access_nums), access_nums)\n except Exception as e:\n print(e)\n else:\n if access_nums is not None and int(access_nums) >= 5:\n return JsonResponse({\"err\": \"错误次数过多,请稍后重试\"})\n\n try:\n user = User.objects.filter(mobile=mobile).first()\n except Exception as e:\n print(e)\n return JsonResponse({\"err\": \"获取用户信息失败\"})\n\n # 用数据库的密码与用户填写的密码进行对比验证\n if user is None or not user.check_password(password):\n # 如果验证失败,记录错误次数,返回信息\n try:\n rds.incr(\"access_num_%s\" % user_ip)\n rds.expire(\"access_num_%s\" % user_ip, 300)\n except Exception as e:\n print(e)\n return JsonResponse({\"err\": \"用户名或密码错误\"})\n\n # 如果验证相同成功,保存登录状态,再session中\n request.session[\"islogin\"] = True\n return JsonResponse({\"msg\": \"登录成功\"})\n\n\ndef check_login(request):\n # 尝试从session中获取用户的名字\n name = request.session.get(\"name\")\n # 如果session中数据name名字存在, 则表示用户已登录,否则未登录\n if name is not None:\n return JsonResponse({\"err\": \"tree\"})\n else:\n return JsonResponse({\"err\": \"false\"})\n\n\ndef logout(request):\n # 清除session\n request.session.clear()\n return JsonResponse({\"err\": \"ok\"})\n\n\ndef area(request):\n # 尝试从redis中读取数据\n try:\n resp_json = rds.get(\"area_info\")\n except Exception as e:\n print(e)\n else:\n if resp_json is not None:\n return JsonResponse({\"data\": json.loads(resp_json.decode()), \"is\": \"yes\"})\n\n try:\n area_li = Area.objects.all()\n except Exception as e:\n return JsonResponse({\"err\": \"数据库异常\"})\n\n area_dict_li = []\n for area in area_li:\n area_dict_li.append(area.to_dict())\n\n # 将数据保存到redis中\n\n areas = json.dumps(area_dict_li)\n try:\n rds.setex(\"area_info\", 300, areas)\n except Exception as e:\n print(e)\n return JsonResponse({\"data\": area_dict_li, \"is\": \"no\"})\n\n\n@login_required\ndef change_user_name(request):\n \"\"\"修改用户名\"\"\"\n data = json.loads(request.body.decode())\n userid = data['userid']\n change_name = data['changename']\n if not all([userid, change_name]):\n return JsonResponse({\"err\": \"参数不完整\"})\n try:\n user = User.objects.get(mobile=userid)\n except Exception as e:\n return JsonResponse({\"err\": \"不存在该用户\"})\n\n user.name = change_name\n user.save()\n return HttpResponse(\"ok\")\n\n\n@login_required\ndef get_user_info(request):\n mobile = request.GET.get('mobile')\n user = User.objects.filter(mobile=mobile).first()\n data = user.to_dict()\n return JsonResponse({\"data\": data})\n\n\n@login_required\ndef save_house_info(request):\n data = json.loads(request.body.decode())\n house = House()\n facility = Facility.objects.filter(id=data['facilities']).first()\n user = User.objects.filter(id=data['userid']).first()\n house.title = data['title']\n house.price = data['price']\n house.address = data['address']\n house.room_count = data['room_count']\n house.acreage = data['acreage']\n house.unit = data['unit']\n house.capacity = data['capacity']\n house.beds = data['beds']\n house.deposit = data['deposit']\n house.min_days = data['min_days']\n house.max_days = data['max_days']\n house.order_count = data['order_count']\n house.facilities = facility\n house.user_id = user\n house.save()\n return JsonResponse({'msg': 'ok'})\n\n\n@login_required\ndef save_house_image(request):\n data = json.loads(request.body.decode())\n house = House.objects.filter(id=data['house_id']).first()\n house_image = HouseImage()\n house_image.house_id = house\n house_image.url = data[\"url\"]\n house_image.save()\n return JsonResponse({'msg': 'ok'})\n\n\ndef get_house_list(request):\n \"\"\"获取房屋的列表信息(搜索页面)\"\"\"\n # start_date = request.GET.get('sd')\n # end_date = request.GET.get('ed')\n # area_id = request.GET.get('aid')\n # sort_key = request.GET.get('sk')\n # # page = request.GET.get('p')\n #\n # # 处理时间\n # try:\n # if start_date:\n # start_date = datetime.strftime(start_date, \"%Y-%m-%d\")\n #\n # if end_date:\n # end_date = datetime.strftime(end_date, \"%Y-%m-%d\")\n #\n # if start_date and end_date:\n # assert start_date <= end_date\n # except Exception as e:\n # return JsonResponse({\"err\": \"日期参数有误\"})\n #\n # # 判断区域id\n # try:\n # area = Area.objects.filter(id=area_id)\n # except Exception as e:\n # return JsonResponse({\"err\": \"区域参数有误\"})\n #\n # try:\n # page = int(page)\n # except Exception as e:\n # page = 1\n\n # 查询数据库\n house_list = House.objects.filter().all()\n\n # 生成paginator对象,定义每页显示10条记录\n paginator = Paginator(house_list, 1)\n\n #从前端获取当前的页码数,默认为1\n page = request.GET.get('p', 1)\n\n try:\n print(page)\n list = paginator.page(page)#获取当前页码的记录\n except PageNotAnInteger:\n list = paginator.page(1)#如果用户输入的页码不是整数时,显示第1页的内容\n except EmptyPage:\n list = paginator.page(paginator.num_pages)#如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容\n return JsonResponse({\"data\": list})\n\n\n@login_required\ndef order_pay(request):\n \"\"\"发起支付宝支付\"\"\"\n data = json.loads(request.body.decode())\n order_id = data['order_id']\n # 判断订单状态\n try:\n order = Order.objects.filter(id=order_id).first()\n except Exception as e:\n return JsonResponse({\"err\": \"数据库异常\"})\n\n if order is None:\n return JsonResponse({\"err\": \"订单数据有误\"})\n\n # 创建支付宝sdk的工具对象\n app_private_key_string = open(os.path.join(os.path.dirname(__file__), \"key\\\\app_private_key.pem\")).read()\n alipay_public_key_string = open(os.path.join(os.path.dirname(__file__), \"key\\\\alipay_public_key.pem\")).read()\n alipay_client = AliPay(\n appid=\"2016092500594174\",\n app_notify_url=None, # 默认回调url\n app_private_key_string=app_private_key_string,\n # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,\n alipay_public_key_string=alipay_public_key_string,\n sign_type=\"RSA2\", # RSA 或者 RSA2\n debug=True # 默认False\n )\n\n # 手机网站支付,需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string\n order_string = alipay_client.api_alipay_trade_wap_pay(\n out_trade_no=order.id, # 订单编号\n total_amount=str(order.amount/100.0), # 总金额\n subject=u\"爱家租房 %s\" % order.id, # 订单标题\n return_url=\"https://www.baidu.com\", # 返回的链接地址\n notify_url=None # 可选, 不填则使用默认notify url\n )\n\n # 构建让用户跳转的支付连接地址\n pay_url = \"https://openapi.alipaydev.com/gateway.do?\" + order_string\n return JsonResponse({\"data\": {\"pay_url\": pay_url}})\n\n\ndef save_order_payment_result(request):\n \"\"\"保存订单支付结果\"\"\"\n data = request.body.decode()\n post_data = parse_qs(data)\n post_dict = {}\n # 支付宝的数据进行分离,提取出支付宝的签名参数sign和剩下的其他数据\n for k, v in post_data.items():\n post_dict[k] = v[0]\n alipay_sign = post_dict.pop(\"sign\")\n\n app_private_key_string = open(os.path.join(os.path.dirname(__file__), \"key\\\\app_private_key.pem\")).read()\n alipay_public_key_string = open(os.path.join(os.path.dirname(__file__), \"key\\\\alipay_public_key.pem\")).read()\n alipay_client = AliPay(\n appid=\"2016092500594174\",\n app_notify_url=None, # 默认回调url\n app_private_key_string=app_private_key_string,\n # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,\n alipay_public_key_string=alipay_public_key_string,\n sign_type=\"RSA2\", # RSA 或者 RSA2\n debug=True # 默认False\n )\n result = alipay_client.verify(post_dict, alipay_sign)\n if result:\n # 修改数据库的订单状态信息\n order_id = post_dict.get(\"out_trade_no\")\n order = Order.objects.filter(id=order_id).first()\n order.status = 4\n order.save()\n return JsonResponse({\"msg\": \"ok\"})\n else:\n return JsonResponse({'err': 'error'})\n","sub_path":"ihomeapp/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":15935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"485399794","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\n# First, we're going to import some modules, add a few utility functions, and specify some symbols and variables we need.\n\n# \n\n# Import all sorts of things\nfrom sympy.interactive.printing import init_printing\ninit_printing(use_unicode=False, wrap_line=False, no_global=True)\nfrom sympy.matrices import *\nfrom sympy import var, sin, cos, symbol, MatrixSymbol, Matrix, eye, Symbol, simplify, cse, solve, jscode, Function, acos, asin, sqrt, Wild\nfrom functools import reduce\nfrom jinja2 import Template\nimport re\nimport sys\n\n# \n\n# Replace references to matrix elements with JS references\ndef subs_matrix_elements(expr_str, matrix_name):\n for row in range(4):\n for col in range(4):\n expr_str = expr_str.replace(\"%s_%d,%d\" % (matrix_name, row, col),\n \"%s.elements[%d]\" % (matrix_name,\n 4*col + row,))\n return expr_str\n\n# Given an expression, find the parameters that will be needed\ndef extract_parameters(expr):\n atoms = expr.atoms(Symbol)\n matrices = set([])\n scalars = set([])\n for atom in atoms:\n matrix_name = re.findall(\"([a-zA-Z]+)_\\d,\\d\", atom.name)\n if len(matrix_name) > 0:\n matrices.add(matrix_name[0])\n else:\n scalars.add(atom.name)\n\n # Put in a nice order\n matrices = list(matrices)\n matrices.sort()\n scalars = list(scalars)\n scalars.sort()\n return matrices+scalars\n\n# Dummy matrix for solving\ndef make_dummy_matrix(name):\n elements = []\n for i in range(4):\n for j in range(4):\n elements.append(Symbol(\"%s_%d,%d\" % (name, i, j)))\n\n return Matrix(4,4, elements)\n\n# Formats a 4x4 Sympy matrix as a Javascript matrix\ndef format_js_mat(mat):\n js_exprs = [jsify_expr(x) for x in mat]\n return \"new THREE.Matrix4().set(%s)\" % (\", \".join(js_exprs),)\n\n# Makes massive redundant expression easier to read for debugging\ndef format_big_expr(expr):\n terms, vec = cse(expr)\n return (Matrix(terms), vec)\n\ndef jsify_expr(expr):\n clamp = Function(\"clamp\")\n bottom_clamp = Function(\"bottom\")\n x = Wild(\"x\")\n # Prevent NaNs on inverse trig functions\n expr = expr.replace(asin, lambda x: asin(clamp(x, -1, 1)))\n expr = expr.replace(acos, lambda x: acos(clamp(x, -1, 1)))\n # Prevent NaNs on sqrts\n expr = expr.replace(sqrt(x + 1),\n sqrt(bottom_clamp(x + 1, 0)))\n js_expr = jscode(expr, user_functions = {\n \"clamp\": \"THREE.Math.clamp\",\n \"bottom\": \"THREE.Math.clampBottom\"\n })\n # Convert all matrix references for compatibility with\n # three.js\n atoms = expr.atoms(Symbol)\n matrices = set([])\n for atom in atoms:\n matrix_name = re.findall(\"([a-zA-Z]+)_\\d,\\d\", atom.name)\n if len(matrix_name) > 0:\n matrices.add(matrix_name[0])\n for matrix in matrices:\n js_expr = subs_matrix_elements(js_expr, matrix)\n return js_expr\n\n# Utilities to format JS\ndef jsify_terms(terms):\n lines = []\n for var_name, term in terms:\n term_js = jsify_expr(term)\n lines.append(\"var %s = %s;\" % (jscode(var_name), term_js))\n return \"\\n\".join(lines)\n\ndef jsify_list(list_expr):\n return \"[%s]\" % \", \".join([jsify_expr(x) for x in list_expr])\n\n# \n\n# Variable setup\nfor i in range(1,8):\n var(\"theta_\" + str(i))\n\nfor i in range(1,8):\n var(\"s_%d\" % i)\n var(\"c_%d\" % i)\n\n# Shoulder location\nvar(\"shoulder_x\")\nvar(\"shoulder_y\")\nvar(\"shoulder_z\")\n# Arm bone length\nvar(\"l_4\")\nvar(\"l_5\")\n\n# \n\n# We're making assumptions about the model geometry here. We assume that the x-axis is used to\n# displace the elbow from the shoulder and the wrist from the elbow. We also assume that, in\n# the elbow's coordinate system the arm is bending in the XZ-plane and the wrist twists in\n# the YZ-plane.\n\n# \n\nR = [Matrix([[1, 0, 0, shoulder_x],\n [0, 1, 0, shoulder_y],\n [0, 0, 1, shoulder_z],\n [0, 0, 0, 1]])]\nR.append(Matrix([[ 1, 0, 0, 0],\n [ 0, c_1, -s_1, 0],\n [ 0, s_1, c_1, 0],\n [ 0, 0, 0, 1]]))\nR.append(Matrix([[ c_2, -s_2, 0, 0],\n [ s_2, c_2, 0, 0],\n [ 0, 0, 1, 0],\n [ 0, 0, 0, 1]]))\nR.append(Matrix([[ c_3, 0, -s_3, 0],\n [ 0, 1, 0, 0],\n [ s_3, 0, c_3, 0],\n [ 0, 0, 0, 1]]))\nR.append(Matrix([[ c_4, 0, -s_4, l_4],\n [ 0, 1, 0, 0],\n [ s_4, 0, c_4, 0],\n [ 0, 0, 0, 1]]))\nR.append(Matrix([[ 1, 0, 0, 0],\n [ 0, c_5, -s_5, 0],\n [ 0, s_5, c_5, 0],\n [ 0, 0, 0, 1]]))\nR.append(Matrix([[ c_6, -s_6, 0, l_5],\n [ s_6, c_6, 0, 0],\n [ 0, 0, 1, 0],\n [ 0, 0, 0, 1]]))\nR.append(Matrix([[ c_7, 0, -s_7, 0],\n [ 0, 1, 0, 0],\n [ s_7, 0, c_7, 0],\n [ 0, 0, 0, 1]]))\n\nz_0 = Matrix([0,0,1,0])\no_0 = Matrix([0,0,0,1])\n\n# These are to represent a black box matrix for the joints\n# to use in a solver\ndummy_shoulder_mat = make_dummy_matrix(\"shoulder\")\ndummy_elbow_mat = make_dummy_matrix(\"elbow\")\ndummy_wrist_mat = make_dummy_matrix(\"wrist\")\ngeneric_mat4 = make_dummy_matrix(\"M\")\n\n# These are to specify a new matrix for the joints\nshoulder_mat = R[0] * R[1] * R[2] * R[3]\nelbow_mat = R[4] * R[5]\nwrist_mat = R[6] * R[7]\n\ndef rotation_matrix(i):\n R_0_i = eye(4)\n for i in range(0, i+1):\n R_0_i = R_0_i * R[i]\n return R_0_i\n\nR_0 = [rotation_matrix(i) for i in range(8)]\no_7 = R_0[7] * o_0\n\n# External variables\n# The current hand world matrix\nhand = make_dummy_matrix(\"hand\")\n# The current torso world matrix\ntorso = make_dummy_matrix(\"torso\")\n# The hand displacement for this step\ndelta_s = Symbol(\"delta_s\")\n# rotational displacement\ndelta_r = Symbol(\"delta_r\")\n\n# \n\n# We're going to work on the configuration, but, before we can work with the configuration, we need to calculate a sane initial configuration from the model matrices.\n\n# \n\nfrom sympy.solvers import solve\nfrom sympy import Symbol\n\n# Replace the placeholder trig function variables with actual trig functions\ndef subs_trig_exprs(expr):\n result = expr\n for i in range(1,8):\n result = result.subs(\"s_%d\" % (i,), \"sin(theta_%d)\" % (i,))\n result = result.subs(\"c_%d\" % (i,), \"cos(theta_%d)\" % (i,))\n return result\n\ntrig_shoulder = subs_trig_exprs(shoulder_mat)\ntrig_elbow = subs_trig_exprs(elbow_mat)\ntrig_wrist = subs_trig_exprs(wrist_mat)\n\nshoulder_solns = solve(dummy_shoulder_mat - trig_shoulder, theta_1, theta_2, theta_3)\nelbow_solns = solve(dummy_elbow_mat - trig_elbow, theta_4, theta_5)\nwrist_solns = solve(dummy_wrist_mat - trig_wrist, theta_6, theta_7)\n\ndef find_shortest_soln(solns):\n shortest_sol_len = float(\"inf\")\n shortest_sol = None\n for sol in solns:\n if len(str(sol)) < shortest_sol_len:\n shortest_sol_len = len(str(sol))\n shortest_sol = sol\n return shortest_sol\n\ninverse_config = reduce(lambda x, y: x+y, [list(find_shortest_soln(solns)) for solns in [shoulder_solns, elbow_solns, wrist_solns]])\n\nconfig_terms, config_list = cse(inverse_config)\nconfig_terms_js = jsify_terms(config_terms)\nconfig_list_js = \", \".join([jsify_expr(x) for x in config_list])\nconfig_list_js = \"[%s]\" %config_list_js\n\n# \n\n# Maybe I'm calculating the Jacobian wrong? Sympy has a Jacobian function. I also just realized that those angles have nothing to do with the actual Euler angle of the hand. Since the most important component of the hand orientation is the direction the palm of the hand faces, we will take a local palm vector, which corresponds to a point on the palm, and rotate it into world space. This is nice because all the units will match, allowing us to use Euclidean distance.\n\n# \n\nlocal_palm_vector = Matrix([Symbol(\"palm_x\"), Symbol(\"palm_y\"), Symbol(\"palm_z\"), 1])\nglobal_palm_vector = R_0[7] * local_palm_vector\n\ntarget2 = Matrix([Symbol(\"target_%s\" % s) for s in [\"x\", \"y\", \"z\", \"palm_x\", \"palm_y\", \"palm_z\"]])\n\nhand_pose2 = Matrix([R_0[7][0,3],\n R_0[7][1,3],\n R_0[7][2,3]]).col_join(global_palm_vector[:3,0])\n\nhand_pose2 = hand_pose2.subs([(\"shoulder_%s\" % axis, dummy_shoulder_mat[row, 3])\n for row, axis in enumerate([\"x\",\"y\",\"z\"])])\nhand_pose2 = subs_trig_exprs(hand_pose2)\nJ2 = hand_pose2.jacobian(\n [Symbol(\"theta_%d\" % i) for i in range(1,8)])\nhand_dist = (Matrix(hand_pose2)-target2).norm()\ndelta_pose2 = delta_s * (Matrix(hand_pose2)-target2)\ndelta_config2 = J2.T * delta_pose2\nnew_config = Matrix([Symbol(\"theta_%d\" % i) for i in range(1,8)]) + delta_config2\n\n# \n\nstep_config_terms, step_config_list = cse(new_config, optimizations='basic')\nstep_config_terms_js = jsify_terms(step_config_terms)\nstep_config_list_js = jsify_list(step_config_list[0])\nextract_parameters(new_config)\n\n# \n\n# Joining all the matrices is a hack to get around a problem in cse\nconfig_mats = trig_shoulder.col_join(trig_elbow).col_join(trig_wrist)\nconfig_mats = config_mats.subs([(\"shoulder_%s\" % axis, dummy_shoulder_mat[row, 3]) for row, axis in enumerate([\"x\",\"y\",\"z\"])])\nconfig_mat_terms, config_mat_clean = cse(config_mats, optimizations='basic')\nconfig_mat_terms_js = jsify_terms(config_mat_terms)\nconfig_shoulder_mat_js = format_js_mat(config_mat_clean[0][0:4,:])\nconfig_elbow_mat_js = format_js_mat(config_mat_clean[0][4:8,:])\nconfig_wrist_mat_js = format_js_mat(config_mat_clean[0][8:12,:])\n\n# \n\nhand_dist_terms, hand_dist_clean = cse(hand_dist, optimizations='basic')\nhand_dist_terms_js = jsify_terms(hand_dist_terms)\nhand_dist_js = jsify_expr(hand_dist_clean[0])\n\n# \n\nfunc_template2 = Template(\"\"\"\n\n// This file is automatically generated. Do not commit or edit. Instead, edit\n// build_motion.py\n\n'use strict';\n\nvar THREE = require('./three');\n\n/** @exports vbot/motion */\n\n/**\n * Calculates the distance of the hand from it's target in the workspace.\n *\n * @memberof module:vbot/motion\n * @param {THREE.Matrix4} shoulder the local shoulder matrix\n * @param {Number} upperArmLength\n * @param {Number} lowerArmLength\n * @param {THREE.Vector3} localPalmPos the location of the center of\n * the palm in wrist space\n * @param {THREE.Vector3} targetWristPos the target position of the\n * wrist in torso space\n * @param {THREE.Vector3} targetPalmPos the target position of the\n * center of the palm in torso\n * space\n * @param {Number[]} config the configuration of the joints\n * @returns {Number} the distance of config from the target\n */\nfunction handDist(shoulder,\n upperArmLength,\n lowerArmLength,\n localPalmPos,\n targetWristPos,\n targetPalmPos,\n config) {\n var theta_1 = config[0];\n var theta_2 = config[1];\n var theta_3 = config[2];\n var theta_4 = config[3];\n var theta_5 = config[4];\n var theta_6 = config[5];\n var theta_7 = config[6];\n var target_x = targetWristPos.x;\n var target_y = targetWristPos.y;\n var target_z = targetWristPos.z;\n var target_palm_x = targetPalmPos.x;\n var target_palm_y = targetPalmPos.y;\n var target_palm_z = targetPalmPos.z;\n var palm_x = localPalmPos.x;\n var palm_y = localPalmPos.y;\n var palm_z = localPalmPos.z;\n var l_4 = upperArmLength;\n var l_5 = lowerArmLength;\n {{hand_dist_terms|indent|indent}}\n return {{hand_dist}};\n}\n\n/**\n * Calculates the configuration parameters from matrices.\n *\n * @param {THREE.Matrix4} shoulder the local shoulder matrix\n * @param {THREE.Matrix4} elbow the local elbow matrix\n * @param {THREE.Matrix4} wrist the local wrist matrix\n * @returns {Number[]} the configuration those matrices indicate\n */\nfunction calcConfig(shoulder, elbow, wrist) {\n {{config_terms|indent|indent}}\n return {{config_list}};\n}\n\n/**\n * Calculates the next step of motion in configuration space.\n *\n * @memberof module:vbot/motion\n * @param {THREE.Matrix4} shoulder the local shoulder matrix\n * @param {Number[]} config the configuration of the joints\n * @param {Number} delta_s the distance to step the hand\n * @param {Number} upperArmLength\n * @param {Number} lowerArmLength\n * @param {THREE.Vector3} localPalmPos the location of the center of\n * the palm in wrist space\n * @param {THREE.Vector3} targetWristPos the target position of the\n * wrist in torso space\n * @param {THREE.Vector3} targetPalmPos the target position of the\n * center of the palm in torso\n * space\n * @returns {Number[]} the new configuration\n */\nfunction stepConfig(shoulder,\n config,\n delta_s,\n upperArmLength,\n lowerArmLength,\n localPalmPos,\n targetWristPos,\n targetPalmPos) {\n var l_4 = upperArmLength;\n var l_5 = lowerArmLength;\n var theta_1 = config[0];\n var theta_2 = config[1];\n var theta_3 = config[2];\n var theta_4 = config[3];\n var theta_5 = config[4];\n var theta_6 = config[5];\n var theta_7 = config[6];\n var target_x = targetWristPos.x;\n var target_y = targetWristPos.y;\n var target_z = targetWristPos.z;\n var target_palm_x = targetPalmPos.x;\n var target_palm_y = targetPalmPos.y;\n var target_palm_z = targetPalmPos.z;\n var palm_x = localPalmPos.x;\n var palm_y = localPalmPos.y;\n var palm_z = localPalmPos.z;\n {{step_config_terms|indent|indent}}\n return {{step_config_list}};\n}\n\n\n\n/**\n * Calculates the matrices of each joint\n *\n * @memberof module:vbot/motion\n * @param {THREE.Matrix4} shoulder the local shoulder matrix\n * @param {Number} upperArmLength\n * @param {Number} lowerArmLength\n * @param {Number[]} config the configuration of the joints\n * @returns {Object} the matrices\n */\nfunction configToMatrices(shoulder,\n upperArmLength,\n lowerArmLength,\n config) {\n var theta_1 = config[0];\n var theta_2 = config[1];\n var theta_3 = config[2];\n var theta_4 = config[3];\n var theta_5 = config[4];\n var theta_6 = config[5];\n var theta_7 = config[6];\n var l_4 = upperArmLength;\n var l_5 = lowerArmLength;\n {{config_mat_terms|indent|indent}}\n return {\n shoulder: {{config_shoulder_mat}},\n elbow: {{config_elbow_mat}},\n wrist: {{config_wrist_mat}}\n };\n}\n\nmodule.exports = {\n configToMatrices: configToMatrices,\n stepConfig: stepConfig,\n calcConfig: calcConfig,\n handDist: handDist\n};\n\"\"\")\n\ncode = func_template2.render(config_terms=config_terms_js,\n config_list=config_list_js,\n step_config_terms=step_config_terms_js,\n step_config_list=step_config_list_js,\n config_mat_terms=config_mat_terms_js,\n config_shoulder_mat=config_shoulder_mat_js,\n config_elbow_mat=config_elbow_mat_js,\n config_wrist_mat=config_wrist_mat_js,\n hand_dist_terms=hand_dist_terms_js,\n hand_dist=hand_dist_js)\n\n# If the code is running as a script, check for an argument for\n# the target location.\ndef is_interactive():\n import __main__ as main\n return not hasattr(main, '__file__')\n\nif not is_interactive():\n # If there is no argument, print to stdout\n if len(sys.argv) == 1:\n print(code)\n elif len(sys.argv) == 2:\n open(sys.argv[1], \"w\").write(code)\n else:\n print(\"Syntax: %s []\" % sys.argv[0])\n sys.exit(1)\nelse:\n print(code)\n\n\n# \n\n\n","sub_path":"js/vbot/build_motion.py","file_name":"build_motion.py","file_ext":"py","file_size_in_byte":16403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"584046231","text":"#!/usr/bin/python\n\n#----------------------------------------------------------------\n# Author: Jason Gors \n# Creation Date: 11-01-2015\n# Purpose: use to set-up & install a temp repo for unit-testing\n# License: BSD\n#----------------------------------------------------------------\n\n\nsetup_args = dict(\n name='testrepo2',\n version='1.0',\n description='test repo for unit-testing',\n author=\"jason gors\",\n packages=['Testrepo2']\n)\n\n\n### use setuptools if it's installed, if not, then use distutils\ntry:\n ### for using setuptools (maybe needed for windows instead of distutils?)\n import setuptools\n setuptools._dont_write_bytecode = True\n from setuptools import setup\nexcept ImportError:\n ### for using distutils\n from distutils.core import setup\n\n\ndef main():\n setup(**setup_args)\n\nif __name__ == '__main__':\n main()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"204985207","text":"import unittest\n\nfrom reactivex import operators as ops\nfrom reactivex.testing import ReactiveTest, TestScheduler\n\non_next = ReactiveTest.on_next\non_completed = ReactiveTest.on_completed\non_error = ReactiveTest.on_error\nsubscribe = ReactiveTest.subscribe\nsubscribed = ReactiveTest.subscribed\ndisposed = ReactiveTest.disposed\ncreated = ReactiveTest.created\n\n\nclass TestTakeWithTime(unittest.TestCase):\n def test_take_zero(self):\n scheduler = TestScheduler()\n xs = scheduler.create_hot_observable(\n on_next(210, 1), on_next(220, 2), on_completed(230)\n )\n\n def create():\n return xs.pipe(ops.take_with_time(0))\n\n res = scheduler.start(create)\n\n assert res.messages == [on_completed(200)]\n assert xs.subscriptions == [subscribe(200, 200)]\n\n def test_take_some(self):\n scheduler = TestScheduler()\n xs = scheduler.create_hot_observable(\n on_next(210, 1), on_next(220, 2), on_next(230, 3), on_completed(240)\n )\n\n def create():\n return xs.pipe(ops.take_with_time(25))\n\n res = scheduler.start(create)\n\n assert res.messages == [on_next(210, 1), on_next(220, 2), on_completed(225)]\n assert xs.subscriptions == [subscribe(200, 225)]\n\n def test_take_late(self):\n scheduler = TestScheduler()\n xs = scheduler.create_hot_observable(\n on_next(210, 1), on_next(220, 2), on_completed(230)\n )\n\n def create():\n return xs.pipe(ops.take_with_time(50))\n\n res = scheduler.start(create)\n\n assert res.messages == [on_next(210, 1), on_next(220, 2), on_completed(230)]\n assert xs.subscriptions == [subscribe(200, 230)]\n\n def test_take_Error(self):\n scheduler = TestScheduler()\n ex = \"ex\"\n xs = scheduler.create_hot_observable(on_error(210, ex))\n\n def create():\n return xs.pipe(ops.take_with_time(50))\n\n res = scheduler.start(create)\n\n assert res.messages == [on_error(210, ex)]\n assert xs.subscriptions == [subscribe(200, 210)]\n\n def test_take_never(self):\n scheduler = TestScheduler()\n xs = scheduler.create_hot_observable()\n\n def create():\n return xs.pipe(ops.take_with_time(50))\n\n res = scheduler.start(create)\n\n assert res.messages == [on_completed(250)]\n assert xs.subscriptions == [subscribe(200, 250)]\n\n def test_take_twice1(self):\n scheduler = TestScheduler()\n xs = scheduler.create_hot_observable(\n on_next(210, 1),\n on_next(220, 2),\n on_next(230, 3),\n on_next(240, 4),\n on_next(250, 5),\n on_next(260, 6),\n on_completed(270),\n )\n\n def create():\n return xs.pipe(\n ops.take_with_time(55),\n ops.take_with_time(35),\n )\n\n res = scheduler.start(create)\n\n assert res.messages == [\n on_next(210, 1),\n on_next(220, 2),\n on_next(230, 3),\n on_completed(235),\n ]\n assert xs.subscriptions == [subscribe(200, 235)]\n\n def test_take_twice2(self):\n scheduler = TestScheduler()\n xs = scheduler.create_hot_observable(\n on_next(210, 1),\n on_next(220, 2),\n on_next(230, 3),\n on_next(240, 4),\n on_next(250, 5),\n on_next(260, 6),\n on_completed(270),\n )\n\n def create():\n return xs.pipe(\n ops.take_with_time(35),\n ops.take_with_time(55),\n )\n\n res = scheduler.start(create)\n\n assert res.messages == [\n on_next(210, 1),\n on_next(220, 2),\n on_next(230, 3),\n on_completed(235),\n ]\n assert xs.subscriptions == [subscribe(200, 235)]\n","sub_path":"tests/test_observable/test_takewithtime.py","file_name":"test_takewithtime.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"143434841","text":"# This is required otherwise it asks for email server\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nACCOUNT_USER_MODEL_USERNAME_FIELD = 'email'\nACCOUNT_USERNAME_REQUIRED = False\n\nACCOUNT_USER_MODEL_EMAIL_FIELD = 'email'\nACCOUNT_AUTHENTICATION_METHOD = 'email'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_LOGOUT_ON_GET = True\n\n# Following is added to enable registration with email instead of username\nAUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n \"django.contrib.auth.backends.ModelBackend\",\n\n # `allauth` specific authentication methods, such as login by e-mail\n \"allauth.account.auth_backends.AuthenticationBackend\",\n)\n\nREST_AUTH_SERIALIZERS = {\n 'USER_DETAILS_SERIALIZER': 'v1.accounts.serializers.RestAuthSerializer',\n}\n\nREST_AUTH_REGISTER_SERIALIZERS = {\n 'REGISTER_SERIALIZER': 'v1.accounts.serializers.RegisterSerializer', # noqa : E501\n}\n\nREST_USE_JWT = True\n","sub_path":"v1/settings/component_settings/rest_auth.py","file_name":"rest_auth.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"229384712","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\n\nimport proto # type: ignore\n\nfrom google.ads.googleads.v14.common.types import bidding\nfrom google.ads.googleads.v14.enums.types import bidding_strategy_status\nfrom google.ads.googleads.v14.enums.types import bidding_strategy_type\n\n\n__protobuf__ = proto.module(\n package=\"google.ads.googleads.v14.resources\",\n marshal=\"google.ads.googleads.v14\",\n manifest={\n \"BiddingStrategy\",\n },\n)\n\n\nclass BiddingStrategy(proto.Message):\n r\"\"\"A bidding strategy.\n This message has `oneof`_ fields (mutually exclusive fields).\n For each oneof, at most one member field can be set at the same time.\n Setting any member of the oneof automatically clears all other\n members.\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n resource_name (str):\n Immutable. The resource name of the bidding strategy.\n Bidding strategy resource names have the form:\n\n ``customers/{customer_id}/biddingStrategies/{bidding_strategy_id}``\n id (int):\n Output only. The ID of the bidding strategy.\n\n This field is a member of `oneof`_ ``_id``.\n name (str):\n The name of the bidding strategy.\n All bidding strategies within an account must be\n named distinctly.\n The length of this string should be between 1\n and 255, inclusive, in UTF-8 bytes, (trimmed).\n\n This field is a member of `oneof`_ ``_name``.\n status (google.ads.googleads.v14.enums.types.BiddingStrategyStatusEnum.BiddingStrategyStatus):\n Output only. The status of the bidding\n strategy.\n This field is read-only.\n type_ (google.ads.googleads.v14.enums.types.BiddingStrategyTypeEnum.BiddingStrategyType):\n Output only. The type of the bidding\n strategy. Create a bidding strategy by setting\n the bidding scheme.\n This field is read-only.\n currency_code (str):\n Immutable. The currency used by the bidding strategy (ISO\n 4217 three-letter code).\n\n For bidding strategies in manager customers, this currency\n can be set on creation and defaults to the manager\n customer's currency. For serving customers, this field\n cannot be set; all strategies in a serving customer\n implicitly use the serving customer's currency. In all cases\n the effective_currency_code field returns the currency used\n by the strategy.\n effective_currency_code (str):\n Output only. The currency used by the bidding strategy (ISO\n 4217 three-letter code).\n\n For bidding strategies in manager customers, this is the\n currency set by the advertiser when creating the strategy.\n For serving customers, this is the customer's currency_code.\n\n Bidding strategy metrics are reported in this currency.\n\n This field is read-only.\n\n This field is a member of `oneof`_ ``_effective_currency_code``.\n aligned_campaign_budget_id (int):\n ID of the campaign budget that this portfolio\n bidding strategy is aligned with. When a\n portfolio and a campaign budget are aligned,\n that means that they are attached to the same\n set of campaigns. After a bidding strategy is\n aligned with a campaign budget, campaigns that\n are added to the bidding strategy must also use\n the aligned campaign budget.\n campaign_count (int):\n Output only. The number of campaigns attached\n to this bidding strategy.\n This field is read-only.\n\n This field is a member of `oneof`_ ``_campaign_count``.\n non_removed_campaign_count (int):\n Output only. The number of non-removed\n campaigns attached to this bidding strategy.\n\n This field is read-only.\n\n This field is a member of `oneof`_ ``_non_removed_campaign_count``.\n enhanced_cpc (google.ads.googleads.v14.common.types.EnhancedCpc):\n A bidding strategy that raises bids for\n clicks that seem more likely to lead to a\n conversion and lowers them for clicks where they\n seem less likely.\n\n This field is a member of `oneof`_ ``scheme``.\n maximize_conversion_value (google.ads.googleads.v14.common.types.MaximizeConversionValue):\n An automated bidding strategy to help get the\n most conversion value for your campaigns while\n spending your budget.\n\n This field is a member of `oneof`_ ``scheme``.\n maximize_conversions (google.ads.googleads.v14.common.types.MaximizeConversions):\n An automated bidding strategy to help get the\n most conversions for your campaigns while\n spending your budget.\n\n This field is a member of `oneof`_ ``scheme``.\n target_cpa (google.ads.googleads.v14.common.types.TargetCpa):\n A bidding strategy that sets bids to help get\n as many conversions as possible at the target\n cost-per-acquisition (CPA) you set.\n\n This field is a member of `oneof`_ ``scheme``.\n target_impression_share (google.ads.googleads.v14.common.types.TargetImpressionShare):\n A bidding strategy that automatically\n optimizes towards a chosen percentage of\n impressions.\n\n This field is a member of `oneof`_ ``scheme``.\n target_roas (google.ads.googleads.v14.common.types.TargetRoas):\n A bidding strategy that helps you maximize\n revenue while averaging a specific target Return\n On Ad Spend (ROAS).\n\n This field is a member of `oneof`_ ``scheme``.\n target_spend (google.ads.googleads.v14.common.types.TargetSpend):\n A bid strategy that sets your bids to help\n get as many clicks as possible within your\n budget.\n\n This field is a member of `oneof`_ ``scheme``.\n \"\"\"\n\n resource_name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n id: int = proto.Field(\n proto.INT64,\n number=16,\n optional=True,\n )\n name: str = proto.Field(\n proto.STRING,\n number=17,\n optional=True,\n )\n status: bidding_strategy_status.BiddingStrategyStatusEnum.BiddingStrategyStatus = proto.Field(\n proto.ENUM,\n number=15,\n enum=bidding_strategy_status.BiddingStrategyStatusEnum.BiddingStrategyStatus,\n )\n type_: bidding_strategy_type.BiddingStrategyTypeEnum.BiddingStrategyType = proto.Field(\n proto.ENUM,\n number=5,\n enum=bidding_strategy_type.BiddingStrategyTypeEnum.BiddingStrategyType,\n )\n currency_code: str = proto.Field(\n proto.STRING,\n number=23,\n )\n effective_currency_code: str = proto.Field(\n proto.STRING,\n number=20,\n optional=True,\n )\n aligned_campaign_budget_id: int = proto.Field(\n proto.INT64,\n number=25,\n )\n campaign_count: int = proto.Field(\n proto.INT64,\n number=18,\n optional=True,\n )\n non_removed_campaign_count: int = proto.Field(\n proto.INT64,\n number=19,\n optional=True,\n )\n enhanced_cpc: bidding.EnhancedCpc = proto.Field(\n proto.MESSAGE,\n number=7,\n oneof=\"scheme\",\n message=bidding.EnhancedCpc,\n )\n maximize_conversion_value: bidding.MaximizeConversionValue = proto.Field(\n proto.MESSAGE,\n number=21,\n oneof=\"scheme\",\n message=bidding.MaximizeConversionValue,\n )\n maximize_conversions: bidding.MaximizeConversions = proto.Field(\n proto.MESSAGE,\n number=22,\n oneof=\"scheme\",\n message=bidding.MaximizeConversions,\n )\n target_cpa: bidding.TargetCpa = proto.Field(\n proto.MESSAGE,\n number=9,\n oneof=\"scheme\",\n message=bidding.TargetCpa,\n )\n target_impression_share: bidding.TargetImpressionShare = proto.Field(\n proto.MESSAGE,\n number=48,\n oneof=\"scheme\",\n message=bidding.TargetImpressionShare,\n )\n target_roas: bidding.TargetRoas = proto.Field(\n proto.MESSAGE,\n number=11,\n oneof=\"scheme\",\n message=bidding.TargetRoas,\n )\n target_spend: bidding.TargetSpend = proto.Field(\n proto.MESSAGE,\n number=12,\n oneof=\"scheme\",\n message=bidding.TargetSpend,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/ads/googleads/v14/resources/types/bidding_strategy.py","file_name":"bidding_strategy.py","file_ext":"py","file_size_in_byte":9340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"210813287","text":"from resources import *\r\nimport random\r\n\r\n@register_block(\"TNT\")\r\nclass tntblock(Block):\r\n blast_resistance = 0\r\n def block_update(self,faces):\r\n for face in faces:\r\n nachbarblockposition = self.position + face\r\n nachbarblock = self.world[nachbarblockposition]\r\n if nachbarblock[\"p_level\"] > 0:\r\n self.activated(None,None)\r\n break\r\n\r\n def activated(self,character,face):\r\n tntrange = random.randint(3,7)\r\n self.world[self.position] = \"AIR\"\r\n for dx in range(-tntrange,tntrange+1):\r\n for dy in range(-tntrange,tntrange+1):\r\n for dz in range(-tntrange,tntrange+1):\r\n tp = self.position+(dx,dy,dz)\r\n dp = type(self.position)((dx,dy,dz))\r\n self.world[tp].exploded(dp.length()/tntrange)\r\n \r\n def exploded(self,entf):\r\n if entf < 1:\r\n self.activated(None,None)\r\n","sub_path":"resources/blocks/TNT.py","file_name":"TNT.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"54004796","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom gi.repository import Gio\n\n\nclass BackgroundChanger():\n SCHEMA = 'org.gnome.desktop.background'\n KEY = 'picture-uri'\n\n def change_background(self, filename):\n gsettings = Gio.Settings.new(self.SCHEMA)\n print(gsettings.get_string(self.KEY))\n print(gsettings.set_string(self.KEY, \"file://\" + filename))\n gsettings.apply()\n print(gsettings.get_string(self.KEY))\n","sub_path":"setWallpaper.py","file_name":"setWallpaper.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"148565267","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'edurpg.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'', include('academico.urls')),\n)\n\nurlpatterns += patterns(\n 'django.contrib.auth.views',\n url(r'^entrar/$', 'login', {'template_name': 'index.html'}, name='entrar'),\n url(r'^sair/$', 'logout', {'next_page': '/'}, name='sair'),\n)\n","sub_path":"edurpg/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"125744357","text":"from google.appengine.api import urlfetch\nfrom urlparse import urljoin\nimport BeautifulSoup\nimport string\n\nclass Crawler():\n def __init__(self,logger):\n self.logger = logger\n self.results = []\n\n def start(self, uri):\n count_uri = '' if uri is None else uri\n if len(count_uri) > 0:\n self.logger.debug(\"Starting crawler...\")\n page = CrawlerPage(self.logger,count_uri)\n page.download_content()\n page.parse_content()\n return page\n else:\n self.logger.debug(\"Invalid URI supplied\")\n return None\n\n\nclass CrawlerPage():\n def __init__(self,logger,uri):\n self.logger = logger\n self.uri = uri\n self.error = \"\"\n self.content = \"\"\n self.words = {}\n\n def download_content(self):\n try:\n self.logger.debug(\"Fetching page with HEAD\")\n page = urlfetch.fetch(self.uri)\n self.content = page.content\n except:\n self.logger.debug(\"Page download exception encountered\")\n self.error = \"An exception occurred while retrieving page content.\"\n\n def parse_content(self):\n self.logger.debug(\"Parsing tag soup\")\n min_length = 3\n allowed_chars = string.letters + string.digits + \"'\"\n suppressed_words = ['a', 'an', 'the', 'on', 'in','for', 'and', 'to']\n\n content_soup = BeautifulSoup.BeautifulSoup(self.content)\n if content_soup != None:\n soup_text = content_soup.getText() if content_soup.body is None else content_soup.body.getText()\n chars_f1 = [c if c in allowed_chars else ' ' for c in soup_text]\n words_f1 = ''.join(chars_f1).split()\n words_f2 = [w.lower() for w in words_f1 if len(w) >= min_length and w.lower() not in suppressed_words]\n\n def word_ct(word_dict,word):\n word_freq = word_dict.get(word,0)\n word_dict[word] = word_freq+1\n return word_dict\n\n words_dict = reduce(word_ct,words_f2,{})\n self.words = [(key,words_dict[key]) for key in words_dict.keys()]\n else:\n self.words = {} \n self.error = \"Unable to parse tag soup\"\n\n","sub_path":"Week03/wordcrawler.py","file_name":"wordcrawler.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"21722402","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('fbuser', '0004_remove_fbuser_email'),\n ('task', '0004_task_owner'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='task',\n name='title',\n field=models.CharField(default=b'', max_length=100),\n ),\n migrations.AlterField(\n model_name='task',\n name='text',\n field=models.CharField(default=b'', max_length=100),\n ),\n ]\n","sub_path":"apps/task/migrations/0005_auto_20150809_1859.py","file_name":"0005_auto_20150809_1859.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"394576856","text":"from bintree_class import TreeNode\n\n\ndef get_lca(root, n1, n2):\n if root is None:\n return None\n if n1 < root.val and n2 < root.val:\n return get_lca(root.left, n1, n2)\n if n1 > root.val and n2 > root.val:\n return get_lca(root.right, n1, n2)\n return root.val\n\n\nroot = TreeNode(20)\nroot.left = TreeNode(8)\nroot.right = TreeNode(22)\nroot.left.left = TreeNode(4)\nroot.left.right = TreeNode(12)\nroot.left.right.left = TreeNode(10)\nroot.left.right.right = TreeNode(14)\nn1 = 10\nn2 = 14\nexpected = 12\nactual = get_lca(root, n1, n2)\nprint(expected == actual)\n\nn1 = 14\nn2 = 8\nexpected = 8\nactual = get_lca(root, n1, n2)\nprint(expected == actual)\n\nn1 = 10\nn2 = 22\nexpected = 20\nactual = get_lca(root, n1, n2)\nprint(expected == actual)\n","sub_path":"tree/lowest_common_ancestor_bst.py","file_name":"lowest_common_ancestor_bst.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"90082394","text":"\"\"\" test elstruct writer/run/reader pipelines\n\"\"\"\nimport warnings\nimport tempfile\nimport numpy\nimport automol\nimport elstruct\n\n\nSCRIPT_DCT = {\n 'cfour2': None,\n 'gaussian09': None,\n 'gaussian16': None,\n 'molpro2015': None,\n 'mrcc2018': None,\n 'nwchem6': None,\n 'orca4': None,\n 'psi4': \"#!/usr/bin/env bash\\n\"\n \"psi4 -i run.inp -o run.out >> stdout.log &> stderr.log\",\n}\n\n\ndef test__energy():\n \"\"\" test the energy pipeline\n \"\"\"\n basis = '6-31g'\n geom = (('O', (0.0, 0.0, -0.110)),\n ('H', (0.0, -1.635, 0.876)),\n ('H', (-0.0, 1.635, 0.876)))\n mult_vals = [1, 2]\n charge_vals = [0, 1]\n\n for prog in elstruct.writer.programs():\n for method in elstruct.program_methods(prog):\n for mult, charge in zip(mult_vals, charge_vals):\n for orb_restricted in (\n elstruct.program_method_orbital_restrictions(\n prog, method, singlet=(mult == 1))):\n\n vals = _test_pipeline(\n script_str=SCRIPT_DCT[prog],\n writer=elstruct.writer.energy,\n readers=(\n elstruct.reader.energy_(prog, method),\n ),\n args=(geom, charge, mult, method, basis, prog),\n kwargs={'orb_restricted': orb_restricted},\n error=elstruct.Error.SCF_NOCONV,\n error_kwargs={'scf_options': [\n elstruct.option.specify(\n elstruct.Option.Scf.MAXITER_, 2)\n ]},\n )\n print(vals)\n\n\ndef test__gradient():\n \"\"\" test the gradient pipeline\n \"\"\"\n basis = 'sto-3g'\n geom = (('O', (0.0, 0.0, -0.110)),\n ('H', (0.0, -1.635, 0.876)),\n ('H', (-0.0, 1.635, 0.876)))\n mult_vals = [1, 2]\n charge_vals = [0, 1]\n\n for prog in elstruct.writer.gradient_programs():\n methods = list(elstruct.program_nondft_methods(prog))\n dft_methods = list(elstruct.program_dft_methods(prog))\n if dft_methods:\n methods.append(numpy.random.choice(dft_methods))\n\n for method in methods:\n for mult, charge in zip(mult_vals, charge_vals):\n for orb_restricted in (\n elstruct.program_method_orbital_restrictions(\n prog, method, singlet=(mult == 1))):\n\n vals = _test_pipeline(\n script_str=SCRIPT_DCT[prog],\n writer=elstruct.writer.gradient,\n readers=(\n elstruct.reader.energy_(prog, method),\n elstruct.reader.gradient_(prog),\n ),\n args=(geom, charge, mult, method, basis, prog),\n kwargs={'orb_restricted': orb_restricted},\n )\n print(vals)\n\n\ndef test__hessian():\n \"\"\" test the hessian pipeline\n \"\"\"\n basis = 'sto-3g'\n geom = (('O', (0.0, 0.0, -0.110)),\n ('H', (0.0, -1.635, 0.876)),\n ('H', (-0.0, 1.635, 0.876)))\n mult_vals = [1, 2]\n charge_vals = [0, 1]\n\n for prog in elstruct.writer.hessian_programs():\n methods = list(elstruct.program_nondft_methods(prog))\n dft_methods = list(elstruct.program_dft_methods(prog))\n if dft_methods:\n methods.append(numpy.random.choice(dft_methods))\n\n for method in methods:\n for mult, charge in zip(mult_vals, charge_vals):\n for orb_restricted in (\n elstruct.program_method_orbital_restrictions(\n prog, method, singlet=(mult == 1))):\n\n vals = _test_pipeline(\n script_str=SCRIPT_DCT[prog],\n writer=elstruct.writer.hessian,\n readers=(\n elstruct.reader.energy_(prog, method),\n elstruct.reader.hessian_(prog),\n ),\n args=(geom, charge, mult, method, basis, prog),\n kwargs={'orb_restricted': orb_restricted},\n )\n print(vals)\n\n\ndef test__optimization():\n \"\"\" test elstruct optimization writes and reads\n \"\"\"\n method = 'hf'\n basis = 'sto-3g'\n geom = ((('C', (None, None, None), (None, None, None)),\n ('O', (0, None, None), ('R1', None, None)),\n ('H', (0, 1, None), ('R2', 'A2', None)),\n ('H', (0, 1, 2), ('R3', 'A3', 'D3')),\n ('H', (0, 1, 2), ('R4', 'A4', 'D4')),\n ('H', (1, 0, 2), ('R5', 'A5', 'D5'))),\n {'R1': 2.6, 'R2': 2.0, 'A2': 1.9,\n 'R3': 2.0, 'A3': 1.9, 'D3': 2.1,\n 'R4': 2.0, 'A4': 1.9, 'D4': 4.1,\n 'R5': 1.8, 'A5': 1.8, 'D5': 5.2})\n mult = 1\n charge = 0\n orb_restricted = True\n frozen_coordinates = ('R5', 'A5', 'D3')\n ref_frozen_values = (1.8, 1.8, 2.1)\n for prog in elstruct.writer.optimization_programs():\n script_str = SCRIPT_DCT[prog]\n\n # MRCC2018 does not support constrained optimizations\n if prog != 'mrcc2018':\n opt_kwargs = {'orb_restricted': orb_restricted,\n 'frozen_coordinates': frozen_coordinates}\n else:\n opt_kwargs = {'orb_restricted': orb_restricted}\n\n vals = _test_pipeline(\n script_str=script_str,\n writer=elstruct.writer.optimization,\n readers=(\n elstruct.reader.energy_(prog, method),\n elstruct.reader.opt_geometry_(prog),\n elstruct.reader.opt_zmatrix_(prog),\n ),\n args=(geom, charge, mult, method, basis, prog),\n kwargs=opt_kwargs,\n error=elstruct.Error.OPT_NOCONV,\n error_kwargs={'job_options': [\n elstruct.option.specify(\n elstruct.Option.Opt.MAXITER_, 2)\n ]},\n )\n print(vals)\n\n if script_str is not None:\n # check that the frozen coordinates didn't change\n zma = vals[-1]\n val_dct = automol.zmatrix.values(zma)\n frozen_values = tuple(\n map(val_dct.__getitem__, frozen_coordinates))\n assert numpy.allclose(\n frozen_values, ref_frozen_values, rtol=1e-4)\n\n\ndef _test_pipeline(script_str, writer, readers,\n args, kwargs, error=None, error_kwargs=None):\n read_vals = []\n prog = args[-1]\n\n # for programs with no run test, ensure input file generated\n _ = writer(*args, **kwargs)\n if script_str is not None:\n script_str = SCRIPT_DCT[prog]\n run_dir = tempfile.mkdtemp()\n _, out_str = elstruct.run.direct(\n writer, script_str, run_dir, *args, **kwargs)\n\n assert elstruct.reader.has_normal_exit_message(prog, out_str)\n\n for reader in readers:\n val = reader(out_str)\n read_vals.append(val)\n\n if error is not None:\n run_dir = tempfile.mkdtemp()\n assert not elstruct.reader.has_error_message(prog, error,\n out_str)\n\n err_kwargs = kwargs.copy()\n err_kwargs.update(error_kwargs)\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n _, err_out_str = elstruct.run.direct(\n writer, script_str, run_dir, *args, **err_kwargs)\n\n assert elstruct.reader.has_error_message(prog, error,\n err_out_str)\n return read_vals\n\n\nif __name__ == '__main__':\n test__energy()\n test__gradient()\n test__hessian()\n test__optimization()\n","sub_path":"tests/test__pipeline.py","file_name":"test__pipeline.py","file_ext":"py","file_size_in_byte":7941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"629616567","text":"import os\n\nimport pandas as pd\nfrom collections import Counter\nimport random\nimport logging\nfrom logging import handlers\n\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom transformers import BertTokenizer, BertForSequenceClassification,BertConfig\nfrom tqdm import tqdm, trange\nfrom similarity_model.utils import *\n# from bert_chinese_encode import get_bert_encode_for_single\nimport torch\nimport torch.nn as nn\nimport math\nimport datetime\nimport matplotlib.pyplot as plt\nimport argparse\nimport time\n\nif hasattr(torch.cuda, 'empty_cache'):\n torch.cuda.empty_cache()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--bert_model\", default=None, type=str, required=False,\n help=\"Bert pre-trained model selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.\")\n parser.add_argument(\"--do_train\",\n required=False,\n default=True,\n action='store_true',\n help=\"do predict\")\n parser.add_argument(\"--do_eval\",\n required=False,\n default=True,\n action='store_true',\n help=\"do eval\")\n parser.add_argument(\"--do_predict\",\n required=False,\n default=False,\n action='store_true',\n help=\"do predict\")\n parser.add_argument(\"-lr\",\n \"--learning_rate\",\n required=False,\n default=0.0001,\n type=float,\n help=\"learning_rate\")\n parser.add_argument(\"--epoch\",\n required=False,\n default=500,\n type=int,\n help=\"epoch\")\n parser.add_argument(\"-bs\",\n \"--batch_size\",\n required=False,\n default=500,\n type=int,\n help=\"batch size\")\n parser.add_argument(\"--num_atten_head\",\n required=False,\n default=12,\n type=int,\n help=\"num attention heads\")\n parser.add_argument(\"--num_layers\",\n required=False,\n default=12,\n type=int,\n help=\"num hidden layers\")\n parser.add_argument(\"--seed\",\n required=False,\n default=1,\n type=int,\n help=\"seed\")\n parser.add_argument(\"--patience\",\n required=False,\n default=100,\n type=int,\n help=\"seed\")\n parser.add_argument(\"--output_dir\",\n default=\"./output\",\n type=str,\n required=False,\n help=\"The output directory where the model checkpoints will be written.\")\n parser.add_argument(\"--no_cuda\",\n default=False,\n action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n required=False,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--hidden_size\",\n required=False,\n default=768,\n type=int,\n help=\"num hidden layers\")\n args = parser.parse_args()\n\n # 读取数据\n train_data_path = 'data/train.txt'\n eval_data_path = 'data/dev.txt'\n\n hidden_size = 768\n # 预训练模型bert输出的维度\n input_size = 768\n n_categories = 3\n BATCH_SIZE = 500\n # 把学习率设定为0.005\n learning_rate = 0.005\n EPOCH = 500\n MAX_SEQ_LENGTH = 128\n PATIENTS=100\n\n num_attention_heads=12\n num_hidden_layers=12\n if args.learning_rate is not None:\n learning_rate = args.learning_rate\n if args.batch_size is not None:\n BATCH_SIZE = args.batch_size\n if args.epoch is not None:\n EPOCH = args.epoch\n if args.max_seq_length is not None:\n MAX_SEQ_LENGTH = args.max_seq_length\n if args.patience is not None:\n PATIENTS = args.patience\n if args.hidden_size is not None:\n hidden_size = args.hidden_size\n if args.num_atten_head is not None:\n num_attention_heads=args.num_atten_head\n if args.num_layers is not None:\n num_hidden_layers = args.num_layers\n\n logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\n logger = logging.getLogger(__name__)\n handler = handlers.RotatingFileHandler(\n filename='log.similarity_model.' + datetime.datetime.now().strftime('%Y-%m-%d') + '.' + str(\n time.time()) + '_epoch_' + str(EPOCH) + '_bs_' + str(BATCH_SIZE) + '_lr_' + str(learning_rate)\n + '_max_seq_length_' + str(MAX_SEQ_LENGTH),\n mode='w', backupCount=3, encoding='utf-8')\n format_str = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')\n handler.setLevel(logging.INFO)\n handler.setFormatter(format_str)\n logger.addHandler(handler)\n\n tokenizer = BertTokenizer.from_pretrained(args.bert_model)\n\n config=BertConfig.from_pretrained(args.bert_model)\n config.hidden_size=hidden_size\n config.num_hidden_layers=num_hidden_layers\n config.num_attention_heads=num_attention_heads\n\n model = BertForSequenceClassification(config)\n model = trans_to_cuda(model)\n\n no_decay = ['bias', 'gamma', 'beta']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.01},\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.0}\n ]\n optimizer = Adam(optimizer_grouped_parameters,\n lr=learning_rate)\n\n if args.do_train:\n train_examples = get_examples(train_data_path)\n train_features = convert_examples_to_features(\n train_examples, tokenizer, MAX_SEQ_LENGTH)\n logger.info(\"***** Loading train data*****\")\n logger.info(\" Num train examples = %d\", len(train_features))\n train_input_ids = torch.tensor(select_field(train_features, 'input_ids'), dtype=torch.long)\n train_input_mask = torch.tensor(select_field(train_features, 'input_mask'), dtype=torch.long)\n train_segment_ids = torch.tensor(select_field(train_features, 'segment_ids'), dtype=torch.long)\n train_label = torch.tensor([f.label for f in train_features], dtype=torch.long)\n train_dataset = TensorDataset(train_input_ids, train_input_mask, train_segment_ids, train_label)\n train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)\n # 打印正负标签比例\n # print(dict(Counter(train_data[0].values)))\n if args.do_eval:\n eval_examples = get_examples(eval_data_path)\n eval_features = convert_examples_to_features(\n eval_examples, tokenizer, MAX_SEQ_LENGTH)\n logger.info(\"***** Loading eval data*****\")\n logger.info(\" Num eval examples = %d\", len(eval_features))\n eval_input_ids = torch.tensor(select_field(eval_features, 'input_ids'), dtype=torch.long)\n eval_input_mask = torch.tensor(select_field(eval_features, 'input_mask'), dtype=torch.long)\n eval_segment_ids = torch.tensor(select_field(eval_features, 'segment_ids'), dtype=torch.long)\n eval_label = torch.tensor([f.label for f in eval_features], dtype=torch.long)\n eval_dataset = TensorDataset(eval_input_ids, eval_input_mask, eval_segment_ids, eval_label)\n eval_dataloader = DataLoader(eval_dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n best_eval_acc = 0.0\n global_step = 0 # 表示总共训练了多少个batch\n # 获取整个训练的开始时间\n start = time.time()\n # 为后续的画图做准备,存储每次打印间隔之间的平均损失和平均准确率\n all_train_loss = []\n all_train_acc = []\n all_eval_loss = []\n all_eval_acc = []\n\n patience=0\n for epoch in trange(int(EPOCH), desc=\"Epoch\"):\n model.train()\n # for step, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\")):\n logger.info(\"Epoch = \" + str(epoch) + \"| TimeSince: \" + timeSince(start))\n train_loss = 0\n train_accuracy = 0\n train_examples, train_steps = 0, 0\n for step, batch in enumerate(train_dataloader):\n model.train()\n batch = tuple(t.cuda() if not args.no_cuda else t for t in batch) # 如果指定了no_cuda参数,就用cpu类型\n input_ids, input_mask, segment_ids, label_ids = batch # batch={tuple:4}\n # flatten,[batch_size , 1 , max_seq_len] --> [batch_size , max_seq_len]\n input_ids_flat = input_ids.view(-1, input_ids.size(-1))\n input_mask_flat = input_mask.view(-1, input_mask.size(-1))\n segment_ids_flat = segment_ids.view(-1, segment_ids.size(-1))\n # 2020-12-02 basilwang Migrating from pytorch-pretrained-bert to transformers\n if args.no_cuda:\n loss, train_logits = model(input_ids_flat, token_type_ids=segment_ids_flat,\n attention_mask=input_mask_flat,\n labels=label_ids)\n else:\n loss, train_logits = model(input_ids_flat.cuda(), token_type_ids=segment_ids_flat.cuda(),\n attention_mask=input_mask_flat.cuda(),\n labels=label_ids.cuda())\n # 第一个输出是loss损失值,第二个输出是全连接层的输出值,即logits,shape=[batch_size,num_labels]\n\n train_logits = train_logits.view(-1, 2)\n train_logits = train_logits.detach().cpu().numpy()\n label_ids = label_ids.to('cpu').numpy()\n acc_tmp = accuracy(train_logits, label_ids)\n train_accuracy += acc_tmp\n train_loss += loss.item()\n train_examples += input_ids.size(0)\n train_steps += 1\n if step % 10 == 0: # 每训练10个batch输出一次loss\n logger.info('Batch %d , train_loss = %.4f, train_accuracy = %.4f' % (global_step + 1 , loss , acc_tmp))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n global_step += 1\n\n if args.do_eval and step % 10 == 0: # 每训练100个batch进行一次eval,计算一次accuracy\n eval_loss, eval_accuracy = do_evaluation(model, eval_dataloader, args.no_cuda)\n # 将损失,准确率的结果保存起来,为后续的画图使用\n train_accuracy = train_accuracy / train_examples\n train_loss = train_loss / train_steps\n\n all_train_loss.append(train_loss)\n all_train_acc.append(train_accuracy)\n all_eval_loss.append(eval_loss)\n all_eval_acc.append(eval_accuracy)\n\n train_accuracy = 0\n train_loss = 0\n train_examples = 0\n train_steps = 0\n # logger.info('Batch %d , train_loss = %.4f, train_accuracy = %.4f' % (global_step, eval_loss, eval_accuracy))\n logger.info('Batch %d , eval_loss = %.4f, eval_accuracy = %.4f' % (global_step + 1, eval_loss, eval_accuracy))\n\n if best_eval_acc < eval_accuracy:\n best_eval_acc = eval_accuracy\n logger.info('best_eval_acc= %.4f at training batch = %.4f' % (best_eval_acc, global_step))\n save_name = f\"pytorch_model_best_acc_%.4f.bin\" % best_eval_acc\n # torch.save(model.state_dict(), os.path.join(args.output_dir, f\"pytorch_model_best_acc.bin\"))\n torch.save(model.state_dict(), os.path.join(args.output_dir, save_name))\n patience=0\n else:\n patience += 1\n if patience > PATIENTS:\n break\n if patience > PATIENTS:\n break\n model_save_dir = os.path.join(args.output_dir, f'model{global_step}')\n os.makedirs(model_save_dir, exist_ok=True)\n torch.save(model.state_dict(), os.path.join(model_save_dir, f\"pytorch_model.bin\"))\n logger.info(\"after \" + str(global_step) + \" batches , model has been saved to \" + model_save_dir + \" bingo!!\")\n\n text_save(\"./output/all_train_acc.txt\", all_train_acc)\n text_save(\"./output/all_train_loss.txt\", all_train_loss)\n text_save(\"./output/all_eval_acc.txt\", all_eval_acc)\n text_save(\"./output/all_eval_loss.txt\", all_eval_loss)\n\n # plt.figure(0)\n # # plt.plot(all_train_loss, label=\"Train Loss\")\n # plt.plot(all_eval_loss, color=\"red\", label=\"Eval Loss\")\n # plt.legend(loc=\"upper left\")\n # plt.grid(True)\n # plt.savefig(\"./loss.png\")\n #\n # plt.figure(1)\n # # plt.plot(all_train_acc, label=\"Train Acc\")\n # plt.plot(all_eval_acc, color=\"red\", label=\"Eval Acc\")\n # plt.legend(loc=\"upper left\")\n # plt.grid(True)\n # plt.savefig(\"./acc.png\")\n\n # 模型的保存,首先给定保存的路径\n # MODEL_PATH = './BERT_RNN.pth'\n\n # torch.save(rnn.state_dict(), MODEL_PATH)\n\n\ndef text_save(filename, data):\n file = open(filename, 'a')\n for i in range(len(data)):\n s = str(data[i]).replace('[', '').replace(']', '') # 去除[],这两行按数据不同,可以选择\n s = s.replace(\"'\", '').replace(',', '') + '\\n' # 去除单引号,逗号,每行末尾追加换行符\n file.write(s)\n file.close()\n print(filename + \" saved!\")\n\n\ndef trans_to_cuda(variable):\n if torch.cuda.is_available():\n return variable.cuda()\n else:\n return variable\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ner_model/train_bert.py","file_name":"train_bert.py","file_ext":"py","file_size_in_byte":14618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"613437398","text":"import packages.ipm_cloud_postgresql.model as model\nimport bth.interacao_cloud as interacao_cloud\nimport json\nimport logging\nimport requests\nfrom datetime import datetime\n\ntipo_registro = 'fornecedores'\nsistema = 305\nlimite_lote = 1000\nurl = \"https://contratos.betha.cloud/contratacao-services/api/formas-pagamento/\"\n\n\ndef iniciar_processo_envio(params_exec, *args, **kwargs):\n print('- Iniciando busca dos dados de dados.')\n lista_conteudo_retorno = []\n hoje = datetime.now().strftime(\"%Y-%m-%d\")\n contador = 0\n req_res = interacao_cloud.busca_dados_cloud(params_exec,\n url=url,\n tipo_registro=tipo_registro,\n tamanho_lote=limite_lote)\n\n # print(req_res)\n\n token = params_exec.get('token')\n headers = {'authorization': f'bearer {token}', 'content-type': 'application/json'}\n\n for item in req_res:\n idExcluir = item['id']\n lista_conteudo_retorno.append(idExcluir)\n contador += 1\n for item in lista_conteudo_retorno:\n urlDelete = str(url) + str(item)\n print(urlDelete)\n retorno_req = requests.delete(urlDelete, headers=headers)\n print(str(item), retorno_req.status_code)\n # print(lista_controle_migracao)\n # model.insere_tabela_controle_migracao_auxiliar(params_exec, lista_req=lista_conteudo_retorno)\n print(contador)\n print('- Busca de dados finalizado.')\n","sub_path":"packages/ipm_cloud_postgresql/contratos/rotinas_envio/buscaFormasPagamento.py","file_name":"buscaFormasPagamento.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"627694300","text":"import os\r\nos.chdir('C:\\\\Users\\\\Кирилл\\\\Downloads\\\\PythonProject\\\\SaveDocuments')\r\nimport pandas as pd\r\n\r\n# Получаем файл на вход и редактируем информацию(обьединяем столбцы, убираем ненужные строки, переводим в нужный формат данных)\r\nxls_file = pd.read_excel('FILE76_01.01.2018_1191_1191.xls', 'Руководители', index_col=None)\r\nos.chdir('C:\\\\Users\\\\Кирилл\\\\Downloads\\\\PythonProject\\\\год2018')\r\nxls_file[4:].to_csv('Первая часть5.csv', encoding='utf-8',sep=';',index=False)\r\ndf=pd.read_csv('Первая часть5.csv',sep=';', comment='#',index_col=None)\r\ndf = df.fillna('')\r\ndf = df.rename(columns={'Руководители. РУКОВОДИТЕЛИ ФЕДЕРАЛЬНОГО ОКРУГА, АДМИНИСТРАЦИИ СУБЪЕКТА РОССИЙСКОЙ ФЕДЕРАЦИИ ': 'ПОКАЗАТЕЛЬ', 'Unnamed: 2': '','Unnamed: 3':'почтовый','Unnamed: 4':'электронной почты','Unnamed: 5':'телефона','Unnamed: 6':'факса'})\r\ndel df['Unnamed: 1']\r\ndf = df.loc[df['ПОКАЗАТЕЛЬ'] != '1']\r\narrays = [['', 'Фамилия, имя, отчество', 'Адрес', 'Адрес','Код и номер','Код и номер'], df.columns]\r\ndf.columns = pd.MultiIndex.from_arrays(arrays)\r\npd.set_option('max_colwidth', 1000)\r\n\r\n# Сохраняем полученный результат в папке \"html tablis\"\r\nos.chdir(\"C:\\\\Users\\\\Кирилл\\\\Downloads\\\\PythonProject\\\\год2018\\\\html tablis\")\r\ndf.to_html('Руководители(2018).html',index=False)\r\n","sub_path":"год2018/Визуализация таблиц(1-11)2018/Руководители 2018.py","file_name":"Руководители 2018.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"406934970","text":"# *** Переменные, функция input(), типы данных ***\n\n# in_1 = input(\"Введите число А: \")\n# in_2 = input(\"Введите число Б: \")\n\n# # result = int(in_1) + int(in_2) # конкатенация \n# result = int(in_1) + int(in_2) \n\n# print(\"Результат: \", result)\n\n\n# Типы данных\n\n# целочисленный тип данных\nint_num = 777\n\n# тип данных число с плавающей точкой (пишутся через ТОЧКУ)\nfloat_num = 3.14\n\n# строка (строковой тип данных)\nstring = \"Hello, World!\"\n\n# булевы типы данных (Джордж Буль)\nboolean_t = True # \"истина\" (логическая 1)\nboolean_f = False # \"ложь\" (логический 0)\n\n# print(boolean_t, boolean_f)\n\n\n# способ форматирования строк f-строка (f-string)\n\nname = \"Ayta\"\nage = 29\n\ns = f\"Имя: {name} Возраст: {age}\"\n\n# print(s)\n\n\n# Арифметические операции\n\nx = 5\ny = 7\n\n# сложение \nres = x + y\n\n# вычитание\nres = x - y\n\n# умножение\nres = x * y\n\n# обычное деление (результатом всегда является число с плавающей точкой)\nx = 10\ny = 5\nres = x / y\n\n# целочисленное деление\nres = x // y\n\n# деление по остатку\nx = 3\ny = 2\nres = x % y\n\n# возведение в степень\nres = x ** y\n\n\n# Логические операции\n\nx = 5\ny = 3\n\n# операция \"не равно\"\n# res = x != y\n\n# операция \"равно\"\nres = x == y\n\n# операция \"меньше\"\nres = x < y\n\n# операция \"больше\"\nres = x > y\n\n# операция \"меньше либо равно\"\nres = x <= y\n\n# операция \"больше либо равно\"\nres = x >= y\n\n\nz = False\nk = False\n\n# оператор НЕ (NOT, инверсия)\nres = not z\n\n# оператор И (AND, конъюнкция)\nres = z and k\n\n# оператор ИЛИ (OR, дизъюнкция)\nres = z or k\n\n\n# более слолжный пример\na = 5\nb = 3\nc = 1\n\nres = (a > b) and (b == c)\n\nprint(res)","sub_path":"2.var.py","file_name":"2.var.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"276310243","text":"import argparse\nfrom path import Path\n\nimport glob\nimport imageio\nimport joblib\nimport numpy as np\nfrom natsort import natsorted\nimport os\nimport tensorflow as tf\n\nfrom rllab.misc.console import query_yes_no\nfrom rllab.sampler.utils import rollout_two_policy\nimport pickle\n\nfrom rllab.envs.mujoco.pusher2d_vision_env import PusherEnvVision2D\nfrom rllab.envs.normalized_env import normalize\nfrom sandbox.rocky.tf.envs.base import TfEnv\n\ndef eval_success(path):\n obs = path['observations']\n # init = obs[0, -12:-10]\n # final = obs[-10:, -12:-10]\n target = obs[:-20, -3:-1]\n obj = obs[:-20, -6:-4]\n distractor = obs[:-20, -9:-7]\n dists1 = np.sum((target-obj)**2, 1) # distances at each timestep\n dists2 = np.sum((target-distractor)**2, 1) # distances at each timestep\n return np.sum(dists1 < 0.025) >= 5 and np.sum(dists2 < 0.025) >= 5\n\n\n#files = glob.glob('data/s3/rllab-fixed-push-experts/*/*itr_300*')\n#files = glob.glob('data/s3/init5-push-experts/*/*itr_300*')\n# files = '/home/kevin/rllab/data/local/trpo-push2d/trpo_push2d_2018_03_17_02_02_30_0001/itr_950.pkl'\n# file1 = '/home/kevin/rllab/data/local/trpo-push2d/trpo_push2d_2018_03_19_21_58_18_0001/itr_950.pkl'\nfile1 = '/home/kevin/rllab/data/local/trpo-push2d/trpo_push2d_2018_04_06_20_04_47_0001/itr_650.pkl'\nfile2 = '/home/kevin/rllab/data/local/trpo-push2d-distractor/trpo_push2d_distractor_2018_04_13_01_23_51_0001/itr_950.pkl'\nxmls = natsorted(glob.glob('/home/kevin/rllab/vendor/mujoco_models/pusher2d_multigoal_xmls/*'))\ndemos_per_expert = 8 #8\n#output_dir = 'data/expert_demos/'\n\n#use_filter = True\n#filter_thresh = -34\n#joint_thresh = 1.0\n#max_num_tries=16\n#output_dir = 'data/expert_demos_filter_joint0/'\n\nuse_filter = True\nfilter_thresh = -55\njoint_thresh=0.7\nmax_num_tries=24 #30 #12\n\noutput_dir = 'data/test_push2d_multigoal_demos/'\noutput_dir = Path(output_dir)\noutput_dir.mkdir_p()\n\noffset = 0\ntask_inds = range(0,100)\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)\ntf_config = tf.ConfigProto(gpu_options=gpu_options)\nwith tf.Session(config=tf_config) as sess:\n data1 = joblib.load(file1)\n data2 = joblib.load(file2)\n policy1 = data1['policy']\n policy2 = data2['policy']\n for task_i in task_inds:\n if task_i % 25 == 0:\n print('collecting #' + str(task_i))\n # if '2017_06_23_21_04_45_0091' in expert:\n # continue\n returns = []\n demoX = []\n demoU = []\n videos = []\n num_tries = 0\n obj_left = True\n while (len(returns) < demos_per_expert and num_tries < max_num_tries):\n xml_file = xmls[task_i*24 + num_tries]\n print(xml_file)\n pusher_env = PusherEnvVision2D(**{'xml_file':xml_file, 'distractors': True})\n env = TfEnv(normalize(pusher_env))\n num_tries += 1\n # path = rollout(env, policy, max_path_length=110, speedup=1,\n path = rollout_two_policy(env, policy1, policy2, path_length1=135, max_path_length=255, speedup=1,\n animated=True, always_return_paths=True, save_video=False, vision=True)\n # close the window after rollout\n env.render(close=True)\n # if path['observations'][-1,0] > joint_thresh:\n # num_tries = max_num_tries\n #if path['rewards'].sum() > filter_thresh and path['observations'][-1,0] < joint_thresh:\n if eval_success(path):# and path['observations'][-1,0] < joint_thresh:\n returns.append(path['rewards'].sum())\n demoX.append(path['nonimage_obs'])\n demoU.append(path['actions'])\n videos.append(path['image_obs'])\n print(len(returns))\n if len(returns) >= demos_per_expert:\n demoX = np.array(demoX)\n demoU = np.array(demoU)\n with open(output_dir + str(task_i) + '.pkl', 'wb') as f:\n #pickle.dump({'demoX': demoX, 'demoU': demoU, 'xml':prefix+suffix}, f, protocol=2)\n pickle.dump({'demoX': demoX, 'demoU': demoU, 'xml':xml_file}, f, protocol=2)\n video_dir = output_dir + 'object_' + str(task_i) + '/'\n video_path = Path(video_dir)\n video_path.mkdir_p()\n for demo_index in range(demos_per_expert):\n save_path = video_dir + 'cond' + str(demo_index) + '.samp0.gif'\n print('Saving video to %s' % save_path)\n imageio.mimwrite(save_path, list(videos[demo_index]), format='gif')\ntf.reset_default_graph()","sub_path":"scripts/collect_one_shot_push2d_multigoal_demos.py","file_name":"collect_one_shot_push2d_multigoal_demos.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"550734123","text":"from odoo import fields, models, api, _\nfrom datetime import datetime, date, timedelta\nimport base64\nimport requests\nimport json\n\n\nclass DispatchDocument(models.Model):\n _name = 'dispatch.document'\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _description = 'Dispatch Document'\n _rec_name = 'name'\n\n name = fields.Float('Number')\n cooespondence_ids = fields.Many2many('muk_dms.file', string='Correspondence', track_visibility='always')\n current_user_id = fields.Many2one('res.users', track_visibility='always')\n branch_id = fields.Many2one('res.branch', 'Branch', track_visibility='always')\n department_id = fields.Many2one('hr.department', 'Department', track_visibility='always')\n job_id = fields.Many2one('hr.job', 'Job Position', track_visibility='always')\n created_on = fields.Date(string='Date', default = fields.Date.today(), track_visibility='always')\n select_template = fields.Many2one('select.template.html', track_visibility='always')\n template_html = fields.Html('Template', track_visibility='always')\n basic_version = fields.Float('Basic Version')\n print_heading = fields.Char('Heading')\n dispatch_mode_ids = fields.One2many('dispatch.document.mode','dispatch_id',string='Dispatch Mode')\n\n version = fields.Many2one('dispatch.document', string='Version', track_visibility='always')\n previousversion = fields.Many2one('dispatch.document', string='Previous Version', track_visibility='always')\n\n folder_id = fields.Many2one('folder.master', string=\"File\", track_visibility='always')\n dispatch_mode = fields.Selection(\n [('hand_to_hand', 'Hand to Hand'),('email', 'Email'), ('fax', 'Fax'), ('splmess', 'Spl. Messenger'), ('post', 'Post')\n ], string='Dispatch Mode', track_visibility='always')\n enter_mode = fields.Char('Enter Mode of Dispatch')\n state = fields.Selection(\n [('draft', 'Draft'),('obsolete', 'Obsolete'), ('reject', 'Reject'), ('ready_for_dispatched', 'Ready for Dispatch'), ('dispatched', 'Dispatched')\n ], required=True, default='draft', string='Status', track_visibility='always')\n\n\n\n @api.multi\n def button_edit(self):\n for rec in self:\n cout = 0\n current_employee = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)\n dis_name = self.env['dispatch.document'].sudo().search([('folder_id', '=', self.folder_id.id),('basic_version', '=', self.basic_version)])\n m_name = self.env['dispatch.document'].sudo().search([('folder_id', '=', self.folder_id.id)])\n for ct in m_name:\n cout+=1\n if cout <1:\n name = 1\n else:\n name = rec.name\n # dd = self.env['dispatch.document'].create({\n # 'name': name + 0.001,\n # 'basic_version': int(rec.name),\n # 'print_heading': rec.print_heading,\n # 'previousversion': rec.id,\n # 'dispatch_mode': rec.dispatch_mode,\n # 'template_html': rec.template_html,\n # 'select_template': rec.select_template.id,\n # 'current_user_id': current_employee.user_id.id,\n # 'department_id': current_employee.department_id.id,\n # 'job_id': current_employee.job_id.id,\n # 'branch_id': current_employee.branch_id.id,\n # 'created_on': datetime.now().date(),\n # 'folder_id': rec.folder_id.id,\n # 'state': 'draft',\n # 'cooespondence_ids': rec.cooespondence_ids.ids,\n # })\n # dd.version = dd.id\n form_view = self.env.ref('smart_office.document_dispatch_form_view')\n tree_view = self.env.ref('smart_office.dispatch_document_tree_view1')\n value = {\n # 'domain': str([('id', '=', dd.id)]),\n 'view_type': 'form',\n 'view_mode': 'tree, form',\n 'res_model': 'dispatch.document',\n 'view_id': False,\n 'views': [(form_view and form_view.id or False, 'form'),\n (tree_view and tree_view.id or False, 'tree')],\n 'type': 'ir.actions.act_window',\n # 'res_id': dd.id,\n 'target': 'new',\n 'nodestroy': True,\n 'context': {\n 'default_name': name + 0.001,\n 'default_basic_version': int(rec.name),\n 'default_print_heading': rec.print_heading,\n 'default_previousversion': rec.id,\n 'default_dispatch_mode': rec.dispatch_mode,\n 'default_template_html': rec.template_html,\n 'default_select_template': rec.select_template.id,\n 'default_current_user_id': current_employee.user_id.id,\n 'default_department_id': current_employee.department_id.id,\n 'default_job_id': current_employee.job_id.id,\n 'default_branch_id': current_employee.branch_id.id,\n 'default_created_on': datetime.now().date(),\n 'default_folder_id': rec.folder_id.id,\n 'default_state': 'draft',\n 'default_cooespondence_ids': rec.cooespondence_ids.ids,\n },\n }\n return value\n #\n # @api.model\n # def create(self, vals):\n # res = super(DispatchDocument, self).create(vals)\n # res.version = res.id\n\n\n @api.multi\n def create_dispath_file(self):\n for rec in self:\n # cout = 0\n # current_employee = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)\n # dis_name = self.env['dispatch.document'].sudo().search(\n # [('folder_id', '=', self.folder_id.id), ('basic_version', '=', self.basic_version)])\n # m_name = self.env['dispatch.document'].sudo().search([('folder_id', '=', self.folder_id.id)])\n # for ct in m_name:\n # cout += 1\n # if cout < 1:\n # name = 1\n # else:\n # name = rec.name\n # dd = self.env['dispatch.document'].create({\n # 'name': name + 0.001,\n # 'basic_version': int(rec.name),\n # 'print_heading': rec.print_heading,\n # 'previousversion': rec.id,\n # 'dispatch_mode': rec.dispatch_mode,\n # 'template_html': rec.template_html,\n # 'select_template': rec.select_template.id,\n # 'current_user_id': current_employee.user_id.id,\n # 'department_id': current_employee.department_id.id,\n # 'job_id': current_employee.job_id.id,\n # 'branch_id': current_employee.branch_id.id,\n # 'created_on': datetime.now().date(),\n # 'folder_id': rec.folder_id.id,\n # 'state': 'draft',\n # 'cooespondence_ids': rec.cooespondence_ids.ids,\n # })\n rec.version = rec.id\n form_view = self.env.ref('smart_office.foldermaster_form_view')\n tree_view = self.env.ref('smart_office.foldermaster_tree_view1')\n value = {\n 'domain': str([('id', '=', rec.folder_id.id)]),\n 'view_type': 'form',\n 'view_mode': 'tree, form',\n 'res_model': 'folder.master',\n 'view_id': False,\n 'views': [(form_view and form_view.id or False, 'form'),\n (tree_view and tree_view.id or False, 'tree')],\n 'type': 'ir.actions.act_window',\n 'res_id': rec.folder_id.id,\n 'target': 'current',\n 'nodestroy': True,\n }\n return value\n\n @api.multi\n def button_obsellete(self):\n for rec in self:\n rec.write({'state': 'obsolete'})\n\n @api.multi\n def button_ready_for_dispatch(self):\n for rec in self:\n dis_name = self.env['dispatch.document'].sudo().search([('id', '!=', rec.id),('folder_id', '=', rec.folder_id.id),('basic_version', '=', rec.basic_version)])\n for dd in dis_name:\n dd.sudo().button_obsellete()\n rec.write({'state': 'ready_for_dispatched'})\n\n\n\n @api.multi\n def print_dispatch_document(self):\n return self.env.ref('smart_office.dispatch_document_status_print').report_action(self)\n\n\n def action_create_correspondence(self):\n pdf = self.env.ref('smart_office.dispatch_document_status_print').render_qweb_pdf(self.ids)\n b64_pdf = base64.b64encode(pdf[0])\n directory = self.env['muk_dms.directory'].sudo().search([('name', '=', 'Incoming Files')], limit=1)\n print('============my usr id======================',self.current_user_id.id)\n file = self.env['muk_dms.file'].create({\n 'dispatch_id': self.id,\n 'name': str(self.print_heading) + '-' + str(self.folder_id.folder_name) + '-' + str(self.name) + '.pdf',\n 'content': b64_pdf,\n 'directory': directory.id,\n 'write_uid': self.current_user_id.id,\n 'create_uid': self.current_user_id.id,\n 'responsible_user_id': self.current_user_id.id,\n 'current_owner_id': self.current_user_id.id,\n 'last_owner_id': self.current_user_id.id,\n 'sender_enclosures': \"Enclosure Details\" + ' *****' + str(self.print_heading) + '-' + str(self.folder_id.folder_name) + '-' + str(self.name) + '.pdf'\n })\n print('===============================mp===============================', file.id)\n self.folder_id.file_ids = [(4, file.id)]\n current_employee = self.env['hr.employee'].search([('user_id', '=', self.current_user_id.id)], limit=1)\n folder = self.env['file.tracker.report'].create({\n 'name': str(file.name),\n 'type': 'Correspondence',\n 'assigned_by': str(current_employee.user_id.name),\n 'assigned_by_dept': str(current_employee.department_id.name),\n 'assigned_by_jobpos': str(current_employee.job_id.name),\n 'assigned_by_branch': str(current_employee.branch_id.name),\n 'assigned_date': datetime.now().date(),\n 'action_taken': 'assigned_to_file',\n 'remarks': self.template_html,\n 'details': \"Correspondence attached to file {}\".format(self.folder_id.folder_name)\n })\n self.folder_id.document_ids = str(self.folder_id.document_ids) + ',' + str(file.php_letter_id)\n data = {\n 'assign_name': self.folder_id.folder_name,\n 'assign_no': self.folder_id.sequence,\n 'assign_date': self.folder_id.date,\n 'assign_subject': (self.folder_id.subject.subject),\n 'remarks': self.folder_id.description,\n 'created_by': self.folder_id.current_owner_id.id,\n 'doc_flow_id': 0,\n 'wing_id': self.folder_id.department_id.id,\n 'section_id': 0,\n 'designation_id': self.folder_id.job_id.id,\n 'document_ids': self.folder_id.document_ids,\n }\n req = requests.post('http://103.92.47.152/STPI/www/web-service/add-assignment/', data=data,\n json=None)\n try:\n pastebin_url = req.text\n print('============Patebin url=================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)\n\n\n\n @api.multi\n def button_dispatch(self):\n for rec in self:\n rec.sudo().action_create_correspondence()\n rec.write({'state': 'dispatched'})\n\n @api.multi\n def button_reset_to_draft(self):\n for rec in self:\n rec.write({'state': 'draft'})\n\n @api.multi\n def button_reject(self):\n for rec in self:\n rec.write({'state': 'reject'})\n\n\nclass DispatchDocumentMode(models.Model):\n _name = 'dispatch.document.mode'\n _description = 'Dispatch Document'\n\n dispatch_id = fields.Many2one('dispatch.document', string='Dispatch Document')\n dispatch_mode = fields.Selection(\n [('hand_to_hand', 'Hand to Hand'),('email', 'Email'), ('fax', 'Fax'), ('splmess', 'Spl. Messenger'), ('post', 'Post')\n ], string='Dispatch Mode', track_visibility='always')\n enter_mode = fields.Char('Dispatch Details')\n dispatch_number = fields.Char('Dispatch Number')","sub_path":"smart_office/models/document_dispatch.py","file_name":"document_dispatch.py","file_ext":"py","file_size_in_byte":12582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"54243243","text":"\"\"\"\nfile contains the Rational class, the anchor class of the keras package\n\"\"\"\nfrom tensorflow.keras.layers import Layer\nimport tensorflow as tf\n\nfrom rational.keras.versions import _version_a, _version_b, _version_c, _version_d\nfrom rational.utils.get_weights import get_parameters\n\n\nclass Rational(Layer):\n \"\"\"\n a class representing rational activation functions for tensorflow, inheriting from\n tensorflow.keras.layers.Layer\n \"\"\"\n\n def __init__(self, approx_func=\"leaky_relu\", degrees=(5, 4), cuda=False, version=\"A\",\n trainable=True, train_numerator=True, train_denominator=True):\n \"\"\"\n Inherited from tensorflow.keras.layers.Layer\n\n Defines custom layer attributes, and creates layer state variables that do not depend on\n input shapes, using ``add_weight()``\n\n :param approx_func: The name of the approximated function for initialisation.\n The different functions are available in `rational.rationals_config.json`.\n Default ``leaky_relu``.\n :param degrees: The degrees of the numerator (P) and denominator (Q).\n Default ``(5, 4)``\n :param cuda: whether to execute on cuda device. NOTE: CURRENTLY NOT USED, i.e.\n function always executes on cuda device if available.\n :param version: Version of Rational to use. Rational(x) = P(x)/Q(x)\n `A`: Q(x) = 1 + |b_1.x| + |b_2.x| + ... + |b_n.x|\n `B`: Q(x) = 1 + |b_1.x + b_2.x + ... + b_n.x|\n `C`: Q(x) = 0.1 + |b_1.x + b_2.x + ... + b_n.x|\n `D`: like `B` with noise\n Default ``A``\n :param trainable: If the weights are trainable, i.e, if they are updated during\n backward pass.\n Default ``True``\n :param train_numerator: whether numerator coefficients are trainable\n :param train_denominator: whether denominator coefficients are trainable\n \"\"\"\n super(Rational, self).__init__()\n\n w_numerator, w_denominator = get_parameters(version, degrees, approx_func)\n\n # add trainable weight vectors for numerator (a_0, ... a_n) and denominator (b_0, ... b_m)\n self.numerator = self.add_weight(shape=(len(w_numerator),), name='w_numerator',\n trainable=trainable and train_numerator,\n initializer=tf.keras.initializers.Constant(w_numerator))\n\n self.denominator = self.add_weight(shape=(len(w_denominator),), name='w_denominator',\n trainable=trainable and train_denominator,\n initializer=tf.keras.initializers\n .Constant(w_denominator))\n\n # record whether weights are trainable. Used later by call() method\n self.training = trainable\n\n # set rational activation function version\n self.rational_func = {'A': _version_a, 'B': _version_b, 'C': _version_c, 'D': _version_d}\\\n .get(version)\n if self.rational_func is None:\n raise ValueError(\"rational activation function version %s not implemented\" % version)\n\n def build(self, input_shape):\n \"\"\"\n Inherited from tensorflow.keras.layers.Layer\n\n This method can be used to create weights that depend on the shape(s) of the input(s),\n using ``add_weight()``. ``__call__()`` will automatically build the layer (if it has not\n been built yet) by calling ``build()``.\n\n :param input_shape: Instance of `TensorShape`, or list of instances of `TensorShape` if\n the layer expects a list of inputs (one instance per input).\n \"\"\"\n super(Rational, self).build(input_shape)\n\n def call(self, inputs, **kwargs):\n \"\"\"\n Inherited from tensorflow.keras.layers.Layer\n\n Called in ``__call__`` after making sure ``build()`` has been called. ``call()`` performs\n the logic of applying the layer to the input tensors (which should be passed in as\n argument). Two reserved keyword arguments you can optionally use in ``call()`` are:\n\n - training (boolean, whether the call is in inference mode or training mode)\n - mask (boolean tensor encoding masked timesteps in the input, used in RNN layers)\n\n :param inputs: input tensor\n :return: output tensor, with the respective rational activation function applied to it\n \"\"\"\n return self.rational_func(inputs, self.numerator, self.denominator, self.training)\n","sub_path":"rational/keras/rationals.py","file_name":"rationals.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"11519244","text":"Name = 'TableToUniformGrid'\nLabel = 'Table To Uniform Grid'\nFilterCategory = 'CSM Geophysics Filters'\nHelp = 'TThis filter takes a vtkTable object with columns that represent data to be translated (reshaped) into a 3D grid (2D also works, just set the third dimensions extent to 1). The grid will be a n1 by n2 by n3 vtkImageData structure and an origin (south-west bottom corner) can be set at any xyz point. Each column of the vtkTable will represent a data attribute of the vtkImageData formed (essentially a uniform mesh). The SEPlib option allows you to unfold data that was packed in the SEPlib format where the most important dimension is z and thus the z data is d1 (d1=z, d2=x, d3=y). When using SEPlib, specify n1 as the number of elements in the Z-direction, n2 as the number of elements in the X-direction, and n3 as the number of elements in the Y-direction (and so on for other parameters).'\n\nNumberOfInputs = 1\nInputDataType = 'vtkTable'\nOutputDataType = 'vtkImageData'\nExtraXml = ''\n\nProperties = dict(\n extent=[1, 1, 1],\n spacing=[1.0, 1.0, 1.0],\n origin=[0.0, 0.0, 0.0],\n SEPlib=False\n)\n\nPropertiesHelp = dict(\n SEPlib='Use the Stanford Exploration Project\\'s axial conventions (d1=z, d2=x, d3=y). Parameters would be entered [z,x,y].'\n)\n\ndef RequestData():\n from vtk.util import numpy_support as nps\n import numpy as np\n pdi = self.GetInput()\n image = self.GetOutput() #vtkImageData\n\n cols = pdi.GetNumberOfColumns()\n rows = pdi.GetColumn(0).GetNumberOfTuples()\n\n # Setup the ImageData\n if SEPlib:\n # SEPlib: d1=z, d2=x, d3=y\n nz,nx,ny = extent[0],extent[1],extent[2]\n sz,sx,sy = spacing[0],spacing[1],spacing[2]\n oz,ox,oy = origin[0],origin[1],origin[2]\n else:\n # Cartesian: d1=x, d2=y, d3=z\n nx,ny,nz = extent[0],extent[1],extent[2]\n sx,sy,sz = spacing[0],spacing[1],spacing[2]\n ox,oy,oz = origin[0],origin[1],origin[2]\n\n # make sure dimensions work\n if (nx*ny*nz != rows):\n raise Exception('Total number of elements must remain %d. Check reshape dimensions (n1 by n2 by n3).' % (rows))\n\n image.SetDimensions(nx, ny, nz)\n image.SetOrigin(ox, oy, oz)\n image.SetSpacing(sx, sy, sz)\n image.SetExtent(0,nx-1, 0,ny-1, 0,nz-1)\n\n def RearangeSEPlib(arr):\n # SWAP D1 AND D3 THEN SWAP D2 AND D1\n import numpy as np\n n1,n2,n3 = extent[0],extent[1],extent[2]\n arr = np.reshape(arr, (n2,n3,n1))\n arr = np.swapaxes(arr,0,1)\n arr = np.swapaxes(arr,0,2)\n arr = np.reshape(arr, (n1*n2*n3))\n return arr\n\n\n # Add all columns of the table as arrays to the PointData\n for i in range(cols):\n c = pdi.GetColumn(i)\n if SEPlib:\n name = c.GetName()\n arr = nps.vtk_to_numpy(c)\n arr = RearangeSEPlib(arr)\n c = nps.numpy_to_vtk(num_array=arr,deep=True)\n c.SetName(name)\n #image.GetCellData().AddArray(c) # Should we add here? flipper won't flip these...\n image.GetPointData().AddArray(c)\n\n\ndef RequestInformation():\n from paraview import util\n # Setup the ImageData\n # Cartesian: d1=x, d2=y, d3=z\n nx,ny,nz = extent[0],extent[1],extent[2]\n if SEPlib:\n # SEPlib: d1=z, d2=x, d3=y\n nz,nx,ny = extent[0],extent[1],extent[2]\n # ABSOLUTELY NECESSARY FOR THE FILTER TO WORK:\n util.SetOutputWholeExtent(self, [0,nx-1, 0,ny-1, 0,nz-1])\n","sub_path":"src/filters/filter_table_to_uniform_grid.py","file_name":"filter_table_to_uniform_grid.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"445220451","text":"#written by hao chen \n#z5102446\n\n\nimport sys\nimport copy\nimport os\nimport re\nimport itertools\nimport collections\n\n# begin with read the document\nfile_name = input('Which text file do you want to use for the puzzle? ')\n\ntry:\n with open(file_name,'r',encoding='utf_8') as file_object:\n content = file_object.read()\n # if content have no information, raise error\n if content == '':\n raise ValueError\n #replace '\\n' to space\n content = content.replace('\\n',' ') \nexcept IOError:\n print('Incorrect file.')\n sys.exit()\nexcept ValueError:\n print('Incorrect input.')\n sys.exit()\n\n\n# part 1: find all names\n# we remove all punctuation mark, and find names behind Sir and Sirs\n# then set so we get the correct one\n\n\ntext = copy.deepcopy(content)\n# split the content with ?/!/. so we can see all sentences\ncontent = re.split(r'[?!.]', content)\nL_name = []\nfor line in content:\n # replace all punctuation marks, so we can see just words\n line = line.replace(',','')\n line = line.replace(':','')\n line = line.replace('\"','')\n line = line.split()\n for i in range(len(line)):\n # the name is always behind Sir or Sirs, so we find them all\n # when it comes to Sirs, we keep looking until 'and'+1 word\n if line[i] == 'Sir':\n L_name.append(line[i+1])\n if line[i] == 'Sirs':\n x = i\n while True:\n x = x + 1\n if line[x] != 'and':\n L_name.append(line[x])\n if line[x] == 'and':\n L_name.append(line[x+1])\n break\n\n# we remove repeated names and sorted it by the string lower sequence\nL_name = list(set(L_name))\nL_name = sorted(L_name, key=str.lower)\n\n#print names\nprint('The Sirs are: ',end='')\nfor i in L_name:\n print(i, end = ' ')\nprint()\n# the part one of A3 ends\n\n\n# part 2: 1. find how many people speak, list who they are and what they said \n# 2. list all possibile situation\n# 3. create the object for all people, True for knight and False for Knave\n# 4. go through the first situation to the last situation and record the mathed situation\n# 5. about macth: the speaker has a status (T/F) and his/her claim has a status(T/F)\n# if his/her status is same with his claim (T-T or F-F) then it mathed\n\n\n# create the dictionary to store the speaker and his/her claim\ninfo = collections.defaultdict(list)\n\n# make sure no sentence ends with \"\ntext = text.replace('.\"','\".')\ntext = text.replace('!\"','\"!')\ntext = text.replace('?\"','\"?')\ntext = re.split(r'[?!.]', text)\n\nfor line in text:\n # remove all marks and replace \" with d_q\n line = line.replace(',','')\n line = line.replace(':','')\n line = line.replace('\"',' d_q ')\n line = line.split()\n # when find the first 'd_q' record its position and keep finding\n # until meet the next 'd_q' then record all information between two 'd_q' --the claims\n # outside the 'd_q' find the Sir and record it in the dictionary --the speaker\n # remove all 'd_q' finally so i will not go beyound the index\n text_n = ''\n statement = []\n for i in range(len(line)-2):\n if line[i] == 'd_q':\n n_1 = i\n x = i\n while True:\n x = x + 1\n if line[x] != 'd_q':\n text_n = text_n + ' '+ line[x]\n if line[x] == 'd_q' or x == len(line)-1 :\n n_2 = x\n statement.append(text_n)\n for line_s in statement:\n line_s = line_s.split()\n for y in range(len(line)):\n if y < n_1 or y > n_2:\n if line[y] == 'Sir':\n info[line[y+1]].append(line_s)\n del line[n_1]\n del line[n_2-1]\n break\n \n\n\n# list all possible situation (from 0 knight to all knight)\nassumption = {}\n\nfor i in range(0,len(L_name)+1):\n assumption[i] = []\n do_L = []\n # use the itertools to make the combinations\n iter = itertools.combinations(L_name,i)\n do_L.append(list(iter))\n for x in do_L:\n for y in x:\n assumption[i].append(y)\n\n\n# create the True/False class\n# value = 1 means state is True -- Knight\n# value = 0 means state is False -- Knave\n# set the default value = Flase\n\nL_init = copy.deepcopy(L_name)\n\nclass status:\n def __init__(self,name,value = 0):\n self.name = name\n self.value = value\n self.state = False\n if value == 1:\n self.state = True\n if value == 0:\n self.state = False\n\n# create the object\nfor i in range(len(L_init)):\n L_init[i] = status(L_name[i])\n\n# build a dictionary to store all possible situations\n# from 0 0 0 0 -> 1 1 1 1\n# key is how many Knight in all people from 0 to all is Knight\n\nL_all_situation = {}\n#list all possible situation\nsiutuation = copy.deepcopy(assumption)\nfor key in siutuation:\n L_all_situation[key] = []\n for i in siutuation[key]:\n L_record = []\n for x in i:\n L_record.append(x)\n L_s = copy.deepcopy(L_init)\n for k in L_s:\n if k.name in L_record:\n k.state = True\n L_all_situation[key].append(L_s)\n\n\n# count person number as nb_of_person\nnb_of_person = len(L_name)\n\n\n\n# create the list to see all combinations\n# for example: [(A,False),(B,False),(C,False),(D,False)]\n# all the way to [(A,True),(B,True),(C,True),(D,True)] -- assume 4 people together\n\nL_object = []\n\nfor i in L_name:\n l_object = status(i)\n L_object.append(l_object)\n\nL_state = []\nfor key in L_all_situation:\n for i in L_all_situation[key]:\n temp = []\n for j in range(nb_of_person):\n temp.append((i[j].name,i[j].state))\n L_state.append(temp)\n\n\n\n# based on the claimes, we can find all people who are mentioned\n# if 'us' appear then L_n shoud be same as L_name\n# else we replace the 'I' into names by the dictionary\ndef find_all_names(key,arr,L_name):\n L_n = []\n if 'us' in arr:\n return L_name\n if 'I' in arr:\n L_n.append(key)\n for i in range(len(arr)):\n if arr[i] == 'Sir':\n L_n.append(arr[i+1])\n return L_n\n\n# then we judge whether the claim is Ture\n# split into 8 type of sentences, and the each refers to Knight or Knave\n# L_n is the list store the people who are mentioned by one speaker\n\ndef judge_claim(key, L_s, words, L_n):\n\n # Type 1, at least.\n # if one of the L_n is True/False then this claim is True\n if 'least' in words and 'Knight' in words:\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n return True \n if 'least' in words and 'Knave' in words:\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n return True\n\n # Type 2, at most.\n # if only one of the L_n is True/False then this claim is True\n # if no people in L_n is True/False then this claim is alse True\n if 'most' in words and 'Knight' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n temp.append(j)\n if len(temp) <= 1:\n return True\n if 'most' in words and 'Knave' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n temp.append(j)\n if len(temp) <= 1:\n return True\n \n # Type 3, exactly/Exactly.\n # if just one of the L_n is True/False then this claim is True \n if 'exactly' in words or 'Exactly' in words:\n if 'Knight' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n temp.append(j)\n if len(temp) == 1:\n return True\n if 'exactly' in words or 'Exactly' in words:\n if 'Knave' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n temp.append(j)\n if len(temp) == 1:\n return True\n\n # Type 4, all/All.\n # if all people of the L_n is True/False then this claim is True \n if 'All' in words or 'all' in words:\n if 'Knights' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n temp.append(j)\n if len(temp) == nb_of_person:\n return True\n if 'All' in words or 'all' in words:\n if 'Knaves' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n temp.append(j)\n if len(temp) == nb_of_person:\n return True\n\n # Type 5, I am.\n # in this situation L_n will only contion one name\n # if this name is True/False the this claim is True\n if words[0] == 'I' and words[1] == 'am':\n if 'Knight' in words:\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n return True\n if words[0] == 'I' and words[1] == 'am':\n if 'Knave' in words:\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n return True\n\n # Type 6, Sir XXX is a.\n # in this situation L_n will only contion one name\n # if this name is True/False the this claim is True\n if words[0] == 'Sir' and words[2] == 'is':\n if 'Knight' in words:\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n return True\n if words[0] == 'Sir' and words[2] == 'is':\n if 'Knave' in words:\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n return True\n\n # Type 7, Sir XXX or Sir XXX is a .\n # if just one person in L_n is True/False then this claim is True\n if 'or' in words and 'Knight' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n temp.append(j)\n if len(temp) >= 1:\n return True\n if 'or' in words and 'Knave' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n temp.append(j)\n if len(temp) >= 1:\n return True\n\n # Type 8, Sir XXX and Sir XXX are \n # if all people in L_n is True/False then this claim is True\n if 'All' not in words and 'all' not in words and words[-2] == 'are':\n if 'Knights' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == True:\n temp.append(j)\n if len(temp) == len(L_n):\n return True\n if 'All' not in words and 'all' not in words and words[-2] == 'are':\n if 'Knaves' in words:\n temp = []\n for i in L_s:\n for j in L_n:\n if i[0] == j and i[1] == False:\n temp.append(j)\n if len(temp) == len(L_n):\n return True\n \n # else this claim is False\n return False\n\n# caculate the number of all claims, which is all a situation need to pass if this situation is satisfied\nlength_of_claims = 0\nfor key in info.keys():\n length_of_claims = length_of_claims + len(info[key])\n \n\n \nL_result = []\nL_n = []\n# go through the first situation to the last situaion (from no kinghts to all knights)\nfor i in L_state:\n L_s = i\n temp_Result = []\n for key in info:\n for value in info[key]:\n words = value\n # find all mentioned name in one claim\n L_n = find_all_names(key,words,L_name)\n for j in L_s:\n # if one person is True and his/her claim is True, add this situion to the temp lsit\n if j[0] == key and judge_claim(key, L_s, words, L_n) == True and j[1] == True:\n temp_Result.append(L_s)\n # if one person is True and his/her claim is False, add this situion to the temp lsit\n if j[0] == key and judge_claim(key, L_s, words, L_n) == False and j[1] == False:\n temp_Result.append(L_s)\n # if one situation could be pass by every statement by every speaker \n # then this situation could be one possible result\n # -- judge by how many times this situation passed\n if len(temp_Result)==length_of_claims:\n L_result.append(L_s)\n\n\n\n\n#print the final result\nif len(L_result) == 0:\n print('There is no solution.')\nelif len(L_result)==1:\n print('There is a unique solution:')\n for i in L_result:\n for j in i:\n if j[1] == True:\n print('Sir {} is a Knight.'.format(j[0]))\n if j[1] == False:\n print('Sir {} is a Knave.'.format(j[0]))\nelse:\n print('There are {} solutions.'.format(len(L_result))) \n\n","sub_path":"Assignment_3/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":13469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"133647906","text":"import json\nfrom REST.Interfaces.GoogleInterface import create_service\nfrom REST.JSONBuilders import DigiJsonBuilder\n\n_API_NAME = 'classroom'\n_API_VERSION = 'v1'\n_GOOGLE_URI = 'https://www.googleapis.com/'\n_SCOPES = ['https://www.googleapis.com/auth/classroom.courses',\n 'https://www.googleapis.com/auth/classroom.coursework.me',\n 'https://www.googleapis.com/auth/classroom.announcements',\n 'https://www.googleapis.com/auth/classroom.guardianlinks.me.readonly'\n ]\n\ndef get_course_list(user_auth, user_email):\n courselist = []\n service = create_service(user_auth, _API_NAME, _API_VERSION, _SCOPES, user_email=user_email)\n res = service.courses().list().execute()\n #print(res.toString())\n if 'courses' in res:\n for course in res['courses']:\n cw = get_coursework_list(user_auth, user_email, course['id'], ser=service)\n annou = get_announcements(user_auth, user_email, course['id'], ser=service)\n coursejson = DigiJsonBuilder.create_course(course['name'], course['id'], [user_email], announcements=annou,\n coursework=cw)\n courselist.append(coursejson)\n return courselist\n\n\ndef get_announcements(user_auth, user_email, course_id, ser=None):\n service = create_service(user_auth, _API_NAME, _API_VERSION, _SCOPES, user_email=user_email) if ser == None else ser\n gannoulist = service.courses().announcements().list(courseId=course_id, announcementStates='PUBLISHED').execute()\n anlist = []\n mode = None\n if 'announcements' in gannoulist:\n for gan in gannoulist[\"announcements\"]:\n anid = gan['id']\n antext = gan['text'] if 'text' in gan else None\n anmats = _get_materials_from_json(gan) if 'materials' in gan else None\n anctime = gan['creationTime'] if 'creationTime' in gan else None\n anstu = [user_email]\n anou = DigiJsonBuilder.create_announcement(anid, antext, anmats, anctime, mode, anstu)\n anlist.append(anou)\n return anlist\n\n\ndef get_course(user_auth, user_email, course_id, ser=None):\n service = create_service(user_auth, _API_NAME, _API_VERSION, _SCOPES, user_email=user_email) if ser == None else ser\n course = service.courses().get(id=course_id).execute()\n coursejson = DigiJsonBuilder.create_course(course['name'], course_id, [user_email], announcements=[], coursework=[])\n otherfromgoogle = {\n 'section': course['section'] if 'section' in course else None,\n 'room': course['room'] if 'room' in course else None,\n 'courseState': course['courseState'] if 'courseState' else None,\n 'teacherGroupEmail': course['teacherGroupEmail'] if 'teacherGroupEmail' in course else None,\n 'courseDescription': course['descriptionHeading'] if 'descriptionHeading' in course else None\n }\n coursejson.update(otherfromgoogle)\n mats = _get_materials_from_json(course['courseMaterialSets'] if 'courseMaterialSets' in course else None)\n coursejson.update({'materialSets': mats})\n return coursejson\n\n\ndef get_coursework_list(user_auth, user_email, course_id, ser=None):\n service = create_service(user_auth, _API_NAME, _API_VERSION, _SCOPES, user_email=user_email) if ser == None else ser\n gcwlist = service.courses().courseWork().list(courseId=course_id).execute()\n cwlist = []\n if 'courseWork' in gcwlist:\n for coursework in gcwlist['courseWork']:\n cwid = coursework['id']\n cwjson = get_coursework(user_auth, user_email, course_id, cwid, service)\n cwlist.append(cwjson)\n return cwlist\n\n\ndef get_coursework(user_auth, user_email, course_id, coursework_id, ser=None):\n service = create_service(user_auth, _API_NAME, _API_VERSION, _SCOPES, user_email=user_email) if ser == None else ser\n cw = service.courses().courseWork().get(courseId=course_id, id=coursework_id).execute()\n cwid = cw['id']\n title = cw['title']\n desc = cw['description'] if 'description' in cw else None\n mats = get_materials(user_auth, user_email, course_id, cwid, service)\n ctime = cw['creationTime']\n ddate = cw['dueDate'] if 'dueDate' in cw else None\n dtime = cw['dueTime'] if 'dueTime' in cw else None\n wtype = cw['workType'] if 'workType' in cw else None\n dets = cw['multipleChoiceQuestion'] if 'multipleChoiceQuestion' in cw else None\n pts = cw['maxPoints'] if 'maxPoints' in cw else None\n cwjson = DigiJsonBuilder.create_coursework(cwid, title, desc, mats, ctime, ddate, dtime, wtype, None, [user_email], dets)\n if pts != None:\n cwjson.update({\"maxPoints\": pts})\n return cwjson\n\n\ndef get_materials(user_auth, user_email, course_id, coursework_id, ser=None):\n service = create_service(user_auth, _API_NAME, _API_VERSION, _SCOPES, user_email=user_email) if ser == None else ser\n cw = service.courses().courseWork().get(courseId=course_id, id=coursework_id).execute()\n matlist = _get_materials_from_json(cw)\n return matlist\n\n\ndef _get_materials_from_json(mat):\n if mat is not None:\n cm = []\n if 'materials' in mat:\n df = mat['driveFile'] if \"driveFile\" in mat else None\n yt = mat['youtubeVideo'] if \"youtubeVideo\" in mat else None\n lnk = mat['link'] if \"link\" in mat else None\n form = mat['form'] if \"form\" in mat else None\n # at this point we arent storing these files\n material = DigiJsonBuilder.create_material(df, yt, lnk, form, None)\n cm.append(material)\n return cm\n # this will be similar to get materials loop\n return None\n\n","sub_path":"com/DigiLearn/DigitalBackpack/Server/REST/Interpreters/GClassInterpreter.py","file_name":"GClassInterpreter.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"317699105","text":"import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('dataset')\nparser.add_argument('--transformations', nargs='*', default=[])\nparser.add_argument('--batchsize', type=int, default=128)\nparser.add_argument('--burn-epochs', type=int, default=0)\nparser.add_argument('--epochs', type=int, default=250)\nparser.add_argument('--step', type=float, default=0.1)\nparser.add_argument('--out', default='out')\nargs = parser.parse_args()\nprint(args)\n\nimport mydatasets, mymodels, mymetrics\nfrom sklearn.metrics import jaccard_similarity_score, balanced_accuracy_score\nfrom time import time\nimport numpy as np\nimport uuid\nimport sys\nimport os\n\nif args.transformations == ['all']:\n print('Using all transformations!')\n args.transformations = [\n 'rotation', 'shift', 'brightness', 'shear', 'zoomin', 'zoomout', 'channel']\n\ndef segmentation_metric(Y, Yhat):\n return jaccard_similarity_score((Y >= 0.5).ravel(), (Yhat >= 0.5).ravel())\n\ndef classification_metric(Y, Yhat):\n return balanced_accuracy_score(Y.argmax(1), Yhat.argmax(1))\n\ndef create_transformation(t, v):\n if t == 'rotation': # [0, 180]\n return {'rotation_range': int(v*180)}\n if t == 'shift': # [0, 1]\n return {'width_shift_range': v, 'height_shift_range': v}\n if t == 'brightness': # [0.5, 2]\n if v == 0:\n return {'brightness_range': None}\n return {'brightness_range': (1-v*0.5, 1+v*1)}\n if t == 'shear': # [0, 60]\n return {'shear_range': v*60}\n if t == 'channel': # [0, 50]\n return {'channel_shift_range': v*50}\n sys.error('Unknown transformation: %s' % t)\n\nclass ModelAug:\n # Each value within the transformation is within [0, 1]\n def __init__(self, with_noise):\n # we may want to force noise because it ensures some data augmentation is\n # always applied. This is a hack to ensure that the random seed is consistent.\n self.min_value = 1e-8 if with_noise else 0\n self.values = [self.min_value] * len(args.transformations)\n self.filename = 'temp-%s.h5' % uuid.uuid4()\n\n def __del__(self):\n os.remove(self.filename)\n\n def load(self):\n backend.clear_session()\n self.model = models.load_model(self.filename, custom_objects={'jaccard_distance': mymetrics.jaccard_distance, 'balanced_binary_crossentropy': mymodels.balanced_binary_crossentropy})\n return self.model\n\n def save(self):\n self.model.save(self.filename)\n\n def inc(self, i):\n self.values[i] = min(1, self.values[i] + args.step)\n\n def dec(self, i):\n self.values[i] = max(self.min_value, self.values[i] - args.step)\n\n def todict(self):\n d = {'fill_mode': 'constant', 'rescale': 1/255}\n zoom_range = [1, 1] # zoom is a special case\n for t, v in zip(args.transformations, self.values):\n if t == 'zoomin': # [0.333, 1]\n zoom_range[0] = 1-(2*v/3)\n elif t == 'zoomout': # [1, 3]\n zoom_range[1] = 1+(v*2)\n else:\n d.update(create_transformation(t, v))\n if zoom_range != [1, 1]:\n d['zoom_range'] = zoom_range\n return d\n\nfrom tensorflow.keras import models, backend, utils\nfrom mydatagen import ImageGenerator, SegmentationGenerator\n\ndataname = args.dataset.strip('/').split('/')[-1]\nfilename = '%s/%s-%s' % (args.out, dataname, '-'.join(args.transformations))\n\n(Xtr, Ytr), (Xval, Yval), (Xts, Yts) = mydatasets.load(args.dataset, False)\nprint('Data sizes:')\nprint('Train: ', len(Xtr))\nprint('Validation:', len(Xval))\nprint('Test: ', len(Xts))\nassert Xtr.max() > 1\n\nif len(Ytr.shape) < 3: # classification\n print('-> Classification dataset')\n W = len(Ytr) / ((Ytr.max()+1)*np.bincount(Ytr.ravel()))\n class_weight = {i: v for i, v in enumerate(W)}\n print('class weight:', class_weight)\n\n Ytr = utils.to_categorical(Ytr)\n Yval = utils.to_categorical(Yval)\n Yts = utils.to_categorical(Yts)\n Ytr2 = Ytr\n print('Number of classes:', Ytr.shape[1])\n model = mymodels.create_model(Xtr.shape[1:], Ytr.shape[1])\n evaluate_metric = classification_metric\nelse: # segmentation\n print('-> Segmentation dataset')\n class_weight = None\n\n Ytr2 = (Ytr / 255).astype(np.float32)\n Yval = (Yval / 255).astype(np.float32)\n Yts = (Yts / 255).astype(np.float32)\n model = mymodels.create_unet(Xtr.shape[1:], Ytr.shape[1])\n evaluate_metric = segmentation_metric\n\nmodel.summary()\nsteps = 2 * int(np.ceil(len(Xtr) / args.batchsize))\n\nmodel.fit(Xtr/255, Ytr2, args.batchsize, args.burn_epochs, 2, class_weight=class_weight)\n\nmodel1 = ModelAug(args.transformations != [])\nmodel.save(model1.filename)\n\nif args.transformations:\n model2 = ModelAug(True)\n model.save(model2.filename)\n\npmodels = [model1, model2] if args.transformations else [model1]\nhistory_transformations = []\nstate = np.random.RandomState(123)\n\nfor epoch in range(args.burn_epochs, args.epochs):\n print('Epoch %d/%d' % (epoch+1, args.epochs))\n tic = time()\n seed = state.randint(2**32-1, dtype=np.uint32)\n if args.transformations:\n t = state.randint(len(args.transformations))\n pmodels[0].dec(t)\n pmodels[1].inc(t)\n\n val_metric = [0, 0] # maximize\n val_loss = [0, 0] # minimize (if tied)\n\n for i, model in enumerate(pmodels):\n #print('train model:', i)\n #print(model.values)\n #print(model.todict())\n\n D = model.todict()\n last_policy = D\n if len(Ytr.shape) < 3: # classification\n gen = ImageGenerator(D, Xtr, Ytr, args.batchsize, seed)\n else: # segmentation\n gen = SegmentationGenerator(D, Xtr, Ytr, args.batchsize, seed)\n\n model.load()\n model.model.fit_generator(gen, steps, epoch+1, verbose=0, initial_epoch=epoch,\n class_weight=class_weight)\n\n Yhat = model.model.predict(Xval/255, args.batchsize)\n val_metric[i] = evaluate_metric(Yval, Yhat)\n val_loss[i] = model.model.evaluate(Xval/255, Yval, args.batchsize, 0)[0]\n model.save()\n\n best = 0\n if args.transformations:\n # check which metric is higher; if tied, use loss\n if val_metric[0] == val_metric[1]:\n print('TIE!')\n best = np.argmin(val_loss)\n else:\n best = np.argmax(val_metric)\n worst = 1 - best\n print(' - %d beats %d | %s' % (best, worst, ' - '.join(map(str, pmodels[best].values))))\n\n if best == 0:\n pmodels[best].load()\n pmodels[best].model.save(pmodels[worst].filename)\n pmodels[worst].values = pmodels[best].values.copy()\n\n line = [epoch] + pmodels[best].values + [val_loss[best], val_metric[best]]\n else:\n line = [epoch, val_loss[0], val_metric[0]]\n history_transformations.append(line)\n toc = time()\n print(' - Elapsed time: %ds - Val metric: %f' % (toc-tic, val_metric[best]))\n\nheader = 'epoch,' + ','.join(args.transformations) + ',val_loss,val_metric'\nnp.savetxt(filename + '.csv', history_transformations, delimiter=',', header=header, comments='')\nmodel = pmodels[0].load()\nmodel.save(filename + '.h5')\n\nprint(filename)\nYhat = model.predict(Xts/255, args.batchsize)\nprint('final score:', evaluate_metric(Yts, Yhat))\nprint()\n\nwith open('evaluation.txt', 'a') as f:\n print(args, file=f)\n\n Yhat = model.predict(Xtr/255, args.batchsize)\n print('train:', evaluate_metric(Ytr2, Yhat), file=f)\n Yhat = model.predict(Xval/255, args.batchsize)\n print('val:', evaluate_metric(Yval, Yhat), file=f)\n Yhat = model.predict(Xts/255, args.batchsize)\n print('test:', evaluate_metric(Yts, Yhat), file=f)\n print('', file=f)\n\n## TRAIN again with only the final policy\n# just to see if the impact is of the final or not\n\nif len(Ytr.shape) < 3: # classification\n model = mymodels.create_model(Xtr.shape[1:], Ytr.shape[1])\nelse: # segmentation\n model = mymodels.create_unet(Xtr.shape[1:], Ytr.shape[1])\n\nstate = np.random.RandomState(123)\nseed = state.randint(2**32-1, dtype=np.uint32)\nD = last_policy\nif len(Ytr.shape) < 3: # classification\n gen = ImageGenerator(D, Xtr, Ytr, args.batchsize, seed)\nelse: # segmentation\n gen = SegmentationGenerator(D, Xtr, Ytr, args.batchsize, seed)\n\nmodel.fit_generator(gen, steps, args.epochs, verbose=2, class_weight=class_weight)\n\nprint('MODEL WITH ONLY the last policy')\nYhat = model.predict(Xts/255, args.batchsize)\nprint('final score:', evaluate_metric(Yts, Yhat))\nprint()\n\nwith open('evaluation.txt', 'a') as f:\n print(args, file=f)\n\n Yhat = model.predict(Xtr/255, args.batchsize)\n print('last policy train:', evaluate_metric(Ytr2, Yhat), file=f)\n Yhat = model.predict(Xval/255, args.batchsize)\n print('last policy val:', evaluate_metric(Yval, Yhat), file=f)\n Yhat = model.predict(Xts/255, args.batchsize)\n print('last policy test:', evaluate_metric(Yts, Yhat), file=f)\n print('', file=f)\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"552802654","text":"import sys\nimport pymongo\n\nfrom ..election import Ballot\n\nclass MongoIterator:\n def __init__(self, cursor, election):\n self.cursor = cursor\n self.election = election\n\n def __iter__(self):\n return self\n\n def __next__(self):\n try:\n n = next(self.cursor)\n\n x = n['ballot']['elections'][self.election]\n for k, v in x.items():\n\n # Check for blank field\n if v == '':\n v = None\n\n if v is None:\n x[k] = v\n continue\n\n v = int(v)\n\n # If your ballot exceeds maxsize, there might be a problem.\n if v > sys.maxsize:\n raise ValueError(\"candidate value exceeds maxsize\")\n x[k] = v\n\n return Ballot(n['_id'], x)\n\n except StopIteration as e:\n self.cursor.rewind()\n raise e\n\n def __len__(self):\n return self.cursor.count()\n\ndef get_elections(slug, db=\"stopgap\"):\n db = pymongo.Connection()[db]\n election = db.elections.find_one({\"slug\": slug})\n\n ballot = db.ballots.find_one({\"election_id\": election['_id']})\n return list(ballot['ballot']['elections'].keys())\n\ndef get_election_iterator(slug, election_name, db=\"stopgap\"):\n db = pymongo.Connection()[db]\n election = db.elections.find_one({\"slug\": slug})\n\n return MongoIterator(db.ballots.find({\n \"election_id\": election[\"_id\"]}), election_name)\n\n\ndef get_election_candidates(slug, election_name, db=\"stopgap\"):\n db = pymongo.Connection()[db]\n election = db.elections.find_one({\"slug\": slug})\n\n ballot = db.ballots.find_one({\"election_id\": election['_id']})\n return list(ballot['ballot']['elections'][election_name].keys())\n\n","sub_path":"countgap/util/iterator.py","file_name":"iterator.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"568715479","text":"from django.contrib import admin\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\n\nfrom . import forms, models, exporters, email\nfrom utils.admin import EmailParticipantsMixin\n\n\nclass UserAdmin(admin.ModelAdmin):\n\n def get_form(self, request, obj=None, **kwargs):\n if obj is None:\n # use a separate form for user-creation\n self.readonly_fields = ()\n return forms.CreateUserForm\n\n # use default form for editing users\n self.readonly_fields = ('first_name', 'last_name', 'email')\n return super(UserAdmin, self).get_form(request, obj, **kwargs)\n\n\nclass ParticipantAdmin(EmailParticipantsMixin, admin.ModelAdmin):\n model = models.Participant\n list_display = [\n 'user',\n 'affiliation',\n 'sector',\n 'experience',\n 'degree',\n 'degree_field',\n 'accepted_terms',\n 'selected_for_1',\n 'selected_for_2']\n list_editable = ['selected_for_1', 'selected_for_2']\n actions = [\n 'export_xlsx',\n 'export_phase_1_xlsx',\n 'export_phase_2_xlsx',\n 'export_study_xlsx',\n 'email_phase_1_participants',\n 'email_phase_2_participants',\n ]\n email_url = 'users:email_participants'\n\n def email_phase_1_participants(self, request, queryset):\n email.send_phase_emails(queryset, 1)\n self.message_user(request, \"Welcome and Thank you emails were successfully sent.\")\n email_phase_1_participants.short_description = \"Send Welcome/Thank you emails for Phase 1.\"\n\n def email_phase_2_participants(self, request, queryset):\n email.send_phase_emails(queryset, 2)\n self.message_user(request, \"Welcome and Thank you emails were successfully sent.\")\n email_phase_2_participants.short_description = \"Send Welcome/Thank you emails for Phase 2.\"\n\n def email_participants(self, request, queryset):\n return super(ParticipantAdmin, self).email_participants(request, queryset)\n email_participants.short_description = \"Email selected participants\"\n\n def export_xlsx(self, request, queryset):\n exporter = exporters.ParticipantExcelExport(\n queryset,\n export_format='excel',\n filename='participants')\n return exporter.build_response()\n export_xlsx.short_description = 'Generate Excel report of all selected participants'\n\n def export_phase_1_xlsx(self, request, queryset):\n queryset = queryset.filter(selected_for_1=True)\n exporter = exporters.ParticipantExcelExport(\n queryset,\n export_format='excel',\n filename='participants'\n )\n return exporter.build_response()\n export_phase_1_xlsx.short_description = \"Generate Excel report of participants selected for phase 1 of the study from selected participants\"\n\n def export_phase_2_xlsx(self, request, queryset):\n queryset = queryset.filter(selected_for_2=True)\n exporter = exporters.ParticipantExcelExport(\n queryset,\n export_format='excel',\n filename='participants'\n )\n return exporter.build_response()\n export_phase_2_xlsx.short_description = \"Generate Excel report of participants selected for phase 2 of the study from selected participants\"\n\n def export_study_xlsx(self, request, queryset):\n queryset = queryset.filter(Q(selected_for_1=True) | Q(selected_for_2=True))\n exporter = exporters.ParticipantExcelExport(\n queryset,\n export_format='excel',\n filename='participants'\n )\n return exporter.build_response()\n export_study_xlsx.short_description = \"Generate Excel report of participants selected for either phase of the study from selected participants\"\n\n\nclass EncryptedUserAdmin(admin.ModelAdmin):\n model = models.EncryptedUser\n list_display = ['user', 'first_name', 'last_name', 'email', 'phone_number']\n\n def has_add_permission(self, request):\n return False\n\n\nadmin.site.unregister(User)\nadmin.site.register(User, UserAdmin)\nadmin.site.register(models.Participant, ParticipantAdmin)\nadmin.site.register(models.EncryptedUser, EncryptedUserAdmin)\n","sub_path":"project/myuser/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"556556752","text":"\"\"\"\n@Author : sean cheng\n@Email : aya234@163.com\n@CreateTime : 2019/6/30\n@Program : 游戏的初始化数值模块\n\"\"\"\n\nclass init_var:\n def __init__(self):\n self.WHITE = 255, 255, 255\n self.BLACK = 0, 0, 0\n self.ORANGE = 255, 165, 0\n self.GRAY = 127, 127, 127\n self.RED = 255, 0, 0\n\n self.ROW = 15\n self.COL = 15\n\n self.WINFONT = 'c:/windows/Fonts/SimHei.ttf'\n self.MACFONT = '/System/Library/Fonts/STHeiti Light.ttc'\n self.LINUXFONT = '/usr/share/fonts/'\n\n self.WHITEFIRST = True\n","sub_path":"gobang/init_var.py","file_name":"init_var.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"192671090","text":"#!/usr/bin/env python\n\nimport json\nimport os\nimport sys\nimport subprocess\nimport argparse\nimport signal\nimport collections\n\nQUERY_URL_TEMPLATE = 'https://www.encodeproject.org/experiments/{}/?format=json'\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(prog='exp_id.txt (exp_id) -> \\\n exp_to_ctl.txt (exp_id\\\\tctl_id)',\n description='')\n parser.add_argument('--exp-acc-ids-file', type=str, required=True,\n help='File with experiment accession id in each line.')\n parser.add_argument('--out-filename-exp-to-ctl', type=str, default='exp_to_ctl.txt',\n help='exp_to_ctl.txt')\n parser.add_argument('--out-filename-ctl', type=str, default='ctl_ids.txt',\n help='ctl_ids.txt')\n args = parser.parse_args()\n\n return args\n\ndef read_acc_ids(f):\n acc_ids=[]\n with open(f,'r') as fp:\n lines = fp.readlines()\n for line in lines:\n acc_ids.append(line.strip())\n return acc_ids\n\ndef get_ctl_acc_id_from_exp_acc_id(exp_acc_id): \n json_file = '{}.json'.format(exp_acc_id)\n try:\n run_shell_cmd('wget {} -O {}'.format(\n QUERY_URL_TEMPLATE.format(exp_acc_id),\n json_file))\n json_obj = json.load(open(json_file,'r'))\n ctl_acc_ids = []\n for possible_control in json_obj[\"possible_controls\"]:\n ctl = possible_control[\"@id\"]\n ctl_acc_id = ctl.split('/')[2]\n ctl_acc_ids.append(ctl_acc_id)\n rm_f(json_file)\n except:\n rm_f(json_file)\n return 'NO_PERMISSION'\n return ctl_acc_ids\n\ndef rm_f(files):\n if files:\n if type(files)==list:\n run_shell_cmd('rm -f {}'.format(' '.join(files)))\n else:\n run_shell_cmd('rm -f {}'.format(files))\n\ndef run_shell_cmd(cmd): \n try:\n p = subprocess.Popen(cmd, shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True,\n preexec_fn=os.setsid)\n pid = p.pid\n pgid = os.getpgid(pid)\n print('run_shell_cmd: PID={}, CMD={}'.format(pid, cmd))\n ret = ''\n while True:\n line = p.stdout.readline()\n if line=='' and p.poll() is not None:\n break\n # log.debug('PID={}: {}'.format(pid,line.strip('\\n')))\n print('PID={}: {}'.format(pid,line.strip('\\n')))\n ret += line\n p.communicate() # wait here\n if p.returncode > 0:\n raise subprocess.CalledProcessError(\n p.returncode, cmd)\n return ret.strip('\\n')\n except:\n # kill all child processes\n log.exception('Unknown exception caught. '+ \\\n 'Killing process group {}...'.format(pgid))\n os.killpg(pgid, signal.SIGKILL)\n p.terminate()\n raise Exception('Unknown exception caught. PID={}'.format(pid))\n\ndef main():\n args = parse_arguments()\n exp_acc_ids = read_acc_ids(args.exp_acc_ids_file)\n\n ctl_acc_ids = set()\n with open(args.out_filename_exp_to_ctl,'w') as fp:\n for exp_acc_id in exp_acc_ids:\n ctl_acc_id = get_ctl_acc_id_from_exp_acc_id(exp_acc_id)\n fp.write('{}\\t{}\\n'.format(exp_acc_id, ','.join(ctl_acc_id)))\n ctl_acc_ids.update(ctl_acc_id)\n\n with open(args.out_filename_ctl,'w') as fp:\n for ctl_acc_id in ctl_acc_ids:\n fp.write('{}\\n'.format(ctl_acc_id))\n\nif __name__=='__main__':\n main()\n","sub_path":"get_ctl_from_exp.py","file_name":"get_ctl_from_exp.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"219987364","text":"from flask import Flask\nfrom flask import request\nimport json\n\napp = Flask(__name__)\n\nMEMBERS = {\n 'denis': {'age': 25, 'gender': 'male', 'name': 'denis'},\n 'anton': {'age': 30, 'gender': 'male', 'name': 'anton'}\n}\n\n# Task 2\ndef get_member(name):\n if name not in MEMBERS:\n return json.dumps({\"error\": {\"code\": -32602, \"message\": \"Invalid method parameter(s)\"}})\n else:\n response_data = {\"jsonrpc\": \"2.0\"}\n response_data[\"result\"] = MEMBERS[name]\n return json.dumps(response_data)\n\ndef ping():\n response_data = {\"jsonrpc\": \"2.0\"}\n response_data[\"result\"] = 'pong'\n return json.dumps(response_data)\n\n\nMETHODS = {\n \"getMember\": get_member,\n \"ping\": ping\n}\n\n\n@app.route('/', methods=['POST'])\ndef handle():\n data = json.loads(request.data.decode('utf-8'))\n method_view = METHODS.get(data.get('method'))\n if not method_view:\n return json.dumps({\"error\": {\"code\": -32601, \"message\": \"Method not found\"}})\n\n result = method_view(**data.get(\"params\"))\n return result\n\n# Task1\n@app.route('/dump')\ndef dump_to_json():\n with open(\"dumped.json\", \"w\") as write_file:\n json.dump(MEMBERS, write_file)\n return 'JSON dumped succesfully'\n\nif __name__ == '__main__':\n with open('settings.json', 'r') as config:\n setting = json.load(config)\n app.run(port=setting['PORT'], host=setting['HOST'], debug=setting['DEBUG'])\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"349249947","text":"import hickle as hkl\r\nimport numpy as np\r\nfrom keras import backend as K\r\nfrom keras.preprocessing.image import Iterator\r\n\r\n# Data generator that creates sequences for input into PredNet.\r\nclass SequenceGenerator(Iterator):\r\n def __init__(self, data_file, source_file, nt,\r\n batch_size=8, shuffle=False, seed=None,\r\n output_mode='error', sequence_start_mode='all', N_seq=None,\r\n data_format=K.image_data_format()):\r\n \r\n # X.shape will be (n_images, nb_cols, nb_rows, nb_channels)\r\n # (after transposition if K.image_data_format() is 'channels_first')\r\n self.X = hkl.load(data_file)\r\n\r\n # source for each image so when creating sequences can assure that \r\n # consecutive frames are from same video\r\n self.sources = hkl.load(source_file)\r\n self.nt = nt\r\n self.batch_size = batch_size\r\n self.data_format = data_format\r\n assert sequence_start_mode in {'all', 'unique'}, 'sequence_start_mode must be in {all, unique}'\r\n self.sequence_start_mode = sequence_start_mode\r\n assert output_mode in {'error', 'prediction'}, 'output_mode must be in {error, prediction}'\r\n self.output_mode = output_mode\r\n\r\n if self.data_format == 'channels_first':\r\n self.X = np.transpose(self.X, (0, 3, 1, 2))\r\n self.im_shape = self.X[0].shape\r\n\r\n if self.sequence_start_mode == 'all': # allow for any possible sequence, starting from any frame\r\n self.possible_starts = np.array(\r\n [i for i in range(self.X.shape[0] - self.nt) \r\n if self.sources[i] == self.sources[i + self.nt - 1]])\r\n\r\n elif self.sequence_start_mode == 'unique': #create sequences where each unique frame is in at most one sequence\r\n curr_location = 0\r\n possible_starts = []\r\n while curr_location < self.X.shape[0] - self.nt + 1:\r\n if self.sources[curr_location] == self.sources[curr_location + self.nt - 1]:\r\n possible_starts.append(curr_location)\r\n curr_location += self.nt\r\n else:\r\n curr_location += 1\r\n self.possible_starts = possible_starts\r\n\r\n if shuffle:\r\n self.possible_starts = np.random.permutation(self.possible_starts)\r\n if N_seq is not None and len(self.possible_starts) > N_seq: # select a subset of sequences if want to\r\n self.possible_starts = self.possible_starts[:N_seq]\r\n self.N_sequences = len(self.possible_starts)\r\n super(SequenceGenerator, self).__init__(len(self.possible_starts), batch_size, shuffle, seed)\r\n\r\n # Michael Ala 28/6/2018: Not sure if this is how the original creator intended\r\n # this to be used, but it's how I'm using it now, because the original implementation\r\n # doesn't work anymore.\r\n # self.X_all = self.create_all()\r\n\r\n def next(self):\r\n with self.lock:\r\n index_array, current_index, current_batch_size = next(self.index_generator)\r\n batch_x = np.zeros((current_batch_size, self.nt) + self.im_shape, np.float32)\r\n for i, idx in enumerate(index_array):\r\n idx = self.possible_starts[idx]\r\n batch_x[i] = self.preprocess(self.X[idx:idx+self.nt])\r\n if self.output_mode == 'error': # model outputs errors, so y should be zeros\r\n batch_y = np.zeros(current_batch_size, np.float32)\r\n elif self.output_mode == 'prediction': # output actual pixels\r\n batch_y = batch_x\r\n return batch_x, batch_y\r\n\r\n def preprocess(self, X):\r\n return X.astype(np.float32) / 255\r\n\r\n def create_all(self):\r\n X_all = np.zeros((self.N_sequences, self.nt) + self.im_shape, np.float32)\r\n for i, idx in enumerate(self.possible_starts):\r\n X_all[i] = self.preprocess(self.X[idx:idx+self.nt])\r\n return X_all\r\n\r\n def _get_batches_of_transformed_samples(self, index_array):\r\n # The first element of the tuple we're returning is the input batch,\r\n # a set of sequences of self.nt consecutive images (where the indices \r\n # in the given index_array are elements of self.possible_starts, meaning \r\n # we never have the issue of fetching a batch of images that belong to\r\n # two separate videos).\r\n #\r\n # The second element of the tuple we're returning represents the labels\r\n # for each input image. The reason we send in zeros is because the outputs\r\n # of the model in kitti_train.py is the weighted sum over time, over each\r\n # layer, of the errors at that time-step and layer, which we wish to minimize,\r\n # so clearly the target for any input is zero.\r\n\r\n X_batch = np.zeros((len(index_array), self.nt) + self.im_shape, np.float32)\r\n for i, index in enumerate(index_array):\r\n X_batch[i] = self.preprocess(self.X[index:index+self.nt])\r\n\r\n return X_batch, np.zeros(len(index_array))\r\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"428172941","text":"import time\nfrom random import Random\nimport pickle\nfrom functional import seq\nimport math\nimport msgpack\nimport numpy as np\nimport numba\n\nclass DataBlock:\n FINENESS = 100000\n PROTOCOL_V1 = \"DataBlock_V1\"\n DEFAULT_PROTOCOL = PROTOCOL_V1\n\n @classmethod\n def create(cls, content, creationTime, dataTimeBegin, dataTimeEnd, resolution=1e-12):\n dataBlock = DataBlock(creationTime, dataTimeBegin, dataTimeEnd, [len(channel) for channel in content], resolution)\n dataBlock.content = content\n return dataBlock\n\n @classmethod\n def generate(cls, generalConfig, channelConfig):\n creationTime = generalConfig['CreationTime'] if generalConfig.__contains__('Creationtime') else time.time() * 1000\n dataTimeBegin = generalConfig['DataTimeBegin'] if generalConfig.__contains__('DataTimeBegin') else 0\n dataTimeEnd = generalConfig['DataTimeEnd'] if generalConfig.__contains__('DataTimeEnd') else 0\n content = []\n for channel in range(16):\n channelData = []\n if channelConfig.__contains__(channel):\n config = channelConfig[channel]\n if config[0] == 'Period':\n count = config[1]\n period = (dataTimeEnd - dataTimeBegin) / count\n channelData = [int(i * period) for i in range(count)]\n elif config[0] == 'Random':\n count = config[1]\n averagePeriod = (dataTimeEnd - dataTimeBegin) / count\n rnd = Random()\n randomGaussians = [(1 + rnd.gauss(0, 1) / 3) * averagePeriod for i in range(count)]\n randGaussSumRatio = (dataTimeEnd - dataTimeBegin) / sum(randomGaussians)\n randomDeltas = [rg * randGaussSumRatio for rg in randomGaussians]\n times = []\n suma = dataTimeBegin\n for delta in randomDeltas:\n suma += delta\n times.append(int(suma))\n channelData = times\n elif config[0] == 'Pulse':\n print('is Pulse')\n raise RuntimeError('Not Imped')\n # val pulseCount: Int = config(1)\n # val eventCount: Int = config(2)\n # val sigma: Double = config(3)\n # val period = (dataTimeEnd - dataTimeBegin) / pulseCount\n # val random = new Random()\n # Range(0, eventCount).toArray.map(_ => random.nextInt(pulseCount) * period + (random.nextGaussian() * sigma).toLong).sorted\n else:\n raise RuntimeError('Bad mode')\n content.append(channelData)\n return DataBlock.create(content, creationTime, dataTimeBegin, dataTimeEnd)\n\n @classmethod\n def deserialize(cls, data):\n unpacker = msgpack.Unpacker(raw=False)\n unpacker.feed(data)\n recovered = unpacker.__next__()\n protocol = recovered['Format']\n if protocol != cls.PROTOCOL_V1: raise RuntimeError(\"Data format not supported: {}\".format(recovered(\"Format\")))\n sizes = recovered['Sizes']\n dataBlock = DataBlock(recovered['CreationTime'], recovered['DataTimeBegin'], recovered['DataTimeEnd'], sizes, recovered['Resolution'])\n chDatas = recovered['Content']\n if chDatas is not None:\n content = []\n for chData in chDatas:\n recoveredChannel = []\n for section in chData:\n recoveredChannel += DataBlockSerializer.instance(protocol).deserialize(section)\n content.append(recoveredChannel)\n dataBlock.content = content\n else:\n dataBlock.content = None\n return dataBlock\n\n def __init__(self, creationTime, dataTimeBegin, dataTimeEnd, sizes, resolution=1e-12):\n self.creationTime = creationTime\n self.dataTimeBegin = dataTimeBegin\n self.dataTimeEnd = dataTimeEnd\n self.sizes = sizes\n self.resolution = resolution\n self.content = None\n\n def release(self):\n self.content = None\n\n def isReleased(self):\n return self.content is None\n\n def serialize(self, protocol=DEFAULT_PROTOCOL):\n if self.content is None:\n serializedContent = None\n else:\n serializedContent = []\n for ch in self.content:\n sectionNum = math.ceil(len(ch) / DataBlock.FINENESS)\n channelSC = []\n for i in range(sectionNum):\n dataSection = ch[i * DataBlock.FINENESS: (i + 1) * DataBlock.FINENESS]\n channelSC.append(DataBlockSerializer.instance(protocol).serialize(dataSection))\n serializedContent.append(channelSC)\n result = {\n \"Format\": DataBlock.PROTOCOL_V1,\n \"CreationTime\": self.creationTime,\n \"Resolution\": self.resolution,\n \"DataTimeBegin\": self.dataTimeBegin,\n \"DataTimeEnd\": self.dataTimeEnd,\n \"Sizes\": self.sizes,\n \"Content\": serializedContent\n }\n return msgpack.packb(result, use_bin_type=True)\n\n def convertResolution(self, resolution):\n ratio = self.resolution / resolution\n newDB = DataBlock(self.creationTime, int(self.dataTimeBegin * ratio), int(self.dataTimeEnd * ratio), self.sizes, resolution)\n if self.content is not None:\n newDB.content = []\n for ch in self.content:\n newDB.content.append([int(d * ratio) for d in ch])\n else:\n newDB.content = None\n return newDB\n\n\nclass DataBlockSerializer:\n class DataBlockSerializerImp:\n def serialize(self, data):\n raise RuntimeError('Not Implemented')\n\n def deserialize(self, data):\n raise RuntimeError('Not Implemented')\n\n class PV1DBS(DataBlockSerializerImp):\n def __init__(self):\n self.MAX_VALUE = 1e16\n\n def serialize(self, data):\n return serializeJIT(np.array(data))\n\n # if len(data) == 0:\n # return b''\n # buffer = bytearray(data[0].to_bytes(8, byteorder='big', signed=True))\n # unitSize = 15\n # unit = bytearray([0] * (unitSize + 1))\n # hasHalfByte = False\n # halfByte = 0\n # i = 0\n # while (i < len(data) - 1):\n # delta = (data[i + 1] - data[i])\n # i += 1\n # if (delta > self.MAX_VALUE or delta < -self.MAX_VALUE):\n # raise RuntimeError(\"The value to be serialized exceed MAX_VALUE: {}\".format(delta))\n # value = delta\n # length = 0\n # keepGoing = True\n # valueBase = 0 if delta >= 0 else -1\n # while (keepGoing):\n # unit[unitSize - length] = value & 0xf\n # value >>= 4\n # length += 1\n # if value == valueBase:\n # keepGoing = ((unit[unitSize - length + 1] & 0x8) == (0x8 if delta >= 0 else 0x0))\n # elif length >= unitSize:\n # keepGoing = False\n\n # unit[unitSize - length] = length\n # p = 0\n # while p <= length:\n # if hasHalfByte:\n # buffer.append(((halfByte << 4) | unit[unitSize - length + p]))\n # else:\n # halfByte = unit[unitSize - length + p]\n # hasHalfByte = not hasHalfByte\n # p += 1\n # if (hasHalfByte):\n # buffer.append(halfByte << 4)\n # return bytes(buffer)\n\n def deserialize(self, data):\n if len(data) == 0:\n return []\n offset = int.from_bytes(data[:8], byteorder='big', signed=True)\n longBuffer = [offset]\n previous = offset\n\n positionC = 8\n positionF = 0\n\n def hasNext():\n return positionC < len(data)\n\n def getNext():\n nonlocal positionC, positionF\n b = data[positionC]\n if positionF == 0:\n positionF = 1\n return (b >> 4) & 0xf\n else:\n positionF = 0\n positionC += 1\n return b & 0xf\n\n while (hasNext()):\n length = getNext() - 1\n if length >= 0:\n value = (getNext() & 0xf)\n if (value & 0x8) == 0x8:\n value |= -16\n while length > 0:\n value <<= 4\n value |= (getNext() & 0xf)\n length -= 1\n previous += value\n longBuffer.append(previous)\n\n return longBuffer\n \n DBS = {DataBlock.PROTOCOL_V1: PV1DBS()}\n\n @classmethod\n def instance(cls, name): \n return cls.DBS[name]\n\n\n@numba.jit(nopython=True)\ndef serializeJIT(data):\n buffer = numba.float32[:]\n # if len(data) == 0:\n # return b''\n # bytearray(data[0].to_bytes(8, byteorder='big', signed=True))\n # unitSize = 15\n # unit = bytearray([0] * (unitSize + 1))\n # hasHalfByte = False\n # halfByte = 0\n # i = 0\n # while (i < len(data) - 1):\n # delta = (data[i + 1] - data[i])\n # i += 1\n # if (delta > self.MAX_VALUE or delta < -self.MAX_VALUE):\n # raise RuntimeError(\"The value to be serialized exceed MAX_VALUE: {}\".format(delta))\n # value = delta\n # length = 0\n # keepGoing = True\n # valueBase = 0 if delta >= 0 else -1\n # while (keepGoing):\n # unit[unitSize - length] = value & 0xf\n # value >>= 4\n # length += 1\n # if value == valueBase:\n # keepGoing = ((unit[unitSize - length + 1] & 0x8) == (0x8 if delta >= 0 else 0x0))\n # elif length >= unitSize:\n # keepGoing = False\n\n # unit[unitSize - length] = length\n # p = 0\n # while p <= length:\n # if hasHalfByte:\n # buffer.append(((halfByte << 4) | unit[unitSize - length + p]))\n # else:\n # halfByte = unit[unitSize - length + p]\n # hasHalfByte = not hasHalfByte\n # p += 1\n # if (hasHalfByte):\n # buffer.append(halfByte << 4)\n # return bytes(buffer)\n pass","sub_path":"InteractionFreeLocal/Instrument/tdc/universaltdc/DataBlock.py","file_name":"DataBlock.py","file_ext":"py","file_size_in_byte":10695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"250346252","text":"'''\nWrite a function that takes a string as input and reverse only the vowels of a string.\n\nExample 1:\nGiven s = \"hello\", return \"holle\".\n\nExample 2:\nGiven s = \"leetcode\", return \"leotcede\".\n\nNote:\nThe vowels does not include the letter \"y\".\n'''\n\nclass Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n order = ''\n res = ''\n for i in s :\n if i in 'aeiouAEIOU':\n order += i\n for j in s:\n if j in 'aeiouAEIOU':\n res += order[-1]\n order = order[:-1]\n else:\n res += j\n return res","sub_path":"345. Reverse Vowels of a String.py","file_name":"345. Reverse Vowels of a String.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"127802194","text":"f = open(\"test.txt\" , \"r\" )\nn = input(\"Enter the line number\\n\")\n\ncontent = f.readlines()\nprint(content[n - 1])\n\n#method 2\n#for i in range(1 , n + 1):\n # content = f.readline()\n # if i is n:\n # print(content)\n","sub_path":"readNthLine.py","file_name":"readNthLine.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"551973597","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-i386/egg/Editra/src/syntax/_make.py\n# Compiled at: 2011-08-30 21:43:47\n\"\"\"\nFILE: make.py \nAUTHOR: Cody Precord \n@summary: Lexer configuration module for Makefiles.\n\n\"\"\"\n__author__ = 'Cody Precord '\n__svnid__ = '$Id: _make.py 68798 2011-08-20 17:17:05Z CJP $'\n__revision__ = '$Revision: 68798 $'\nimport wx.stc as stc, syndata\nSYNTAX_ITEMS = [\n (\n stc.STC_MAKE_DEFAULT, 'default_style'),\n (\n stc.STC_MAKE_COMMENT, 'comment_style'),\n (\n stc.STC_MAKE_IDENTIFIER, 'scalar_style'),\n (\n stc.STC_MAKE_IDEOL, 'ideol_style'),\n (\n stc.STC_MAKE_OPERATOR, 'operator_style'),\n (\n stc.STC_MAKE_PREPROCESSOR, 'pre2_style'),\n (\n stc.STC_MAKE_TARGET, 'keyword_style')]\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Makefiles\"\"\"\n\n def __init__(self, langid):\n super(SyntaxData, self).__init__(langid)\n self.SetLexer(stc.STC_LEX_MAKEFILE)\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [\n '#']","sub_path":"pycfiles/Editra-0.7.20-py2.6/_make.py","file_name":"_make.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"368619636","text":"import logging\nimport os\nimport sys\nfrom pathlib import Path\nimport click\nimport yfinance as yf\nfrom sqlalchemy.exc import SQLAlchemyError\nimport pandas_datareader.data as web\nfrom datetime import datetime as dt\n\napp_home = str(Path(__file__).parents[1])\nsys.path.append(app_home)\n\nfrom conf.stock_info_getter_conf import MyAssets\nfrom conf.database import Session, Engine\nfrom entity.stock_info_getter_entity import AssetInfoEntity, CurrencyEntity\n\n\n########## ログ出力設定 ##########\nprog_name = os.path.splitext(os.path.basename(__file__))[0]\n# フォーマット\nlog_format = logging.Formatter(\"%(asctime)s [%(levelname)8s] %(message)s\")\n\n# レベル\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n# 標準出力へのハンドラ\nstdout_handler = logging.StreamHandler(sys.stdout)\nstdout_handler.setFormatter(log_format)\nlogger.addHandler(stdout_handler)\n\n# ログファイルへのハンドラ\ntdatetime = dt.now()\ntstr = tdatetime.strftime('%Y-%m-%d')\nfile_handler = logging.FileHandler(\n os.path.join(app_home, \"log\", tstr + \"_\" + prog_name + \".log\"), \"a+\")\nfile_handler.setFormatter(log_format)\nlogger.addHandler(file_handler)\n\n#################################\n\n\n@click.command()\ndef cmd():\n logger.info(\"cmd start\")\n try:\n asset_list = MyAssets.asset_list\n asset_info_list = []\n for asset in asset_list:\n info = yf.Ticker(asset.get(\"ticker\")).info\n long_name = info.get(\"longName\") or \"\"\n short_name = info.get(\"shortName\") or \"\"\n symbol = info.get(\"symbol\") or \"\"\n currency = info.get(\"currency\") or \"\"\n sector = info.get(\"sector\") or \"\"\n long_business_summary = info.get(\"longBusinessSummary\") or \"\"\n previous_close = float(info.get(\"previousClose\") or 0.0)\n fifty_day_average = float(info.get(\"fiftyDayAverage\") or 0.0)\n two_hundred_day_average = float(info.get(\"twoHundredDayAverage\") or 0.0)\n dividend_yield = float(info.get(\"dividendYield\") or 0.0)\n sub_yield = float(info.get(\"yield\") or 0.0)\n asset_info_list.append(\n AssetInfoEntity(long_name, short_name, symbol, currency, sector, long_business_summary, previous_close, fifty_day_average, two_hundred_day_average, dividend_yield, float(asset.get(\"num\")), asset.get(\"large_class\"), asset.get(\"middle_class\"), asset.get(\"small_class\"), sub_yield)\n )\n delete_all(AssetInfoEntity) # TODO: ここでエラー起きたとき戻せない\n bulk_insert(asset_info_list)\n\n df = web.get_data_yahoo(\"JPY=X\")\n delete_all(CurrencyEntity)\n bulk_insert([CurrencyEntity(\"USD/JPY\", df.iloc[-1].Close)])\n\n except Exception as e:\n logger.exception(e)\n sys.exit(1)\n finally:\n logger.info(\"cmd finished\")\n\n\ndef bulk_insert(asset_info):\n logger.info(\"bulkInsert start\")\n try:\n session = Session()\n session.bulk_save_objects(asset_info)\n session.commit()\n except Exception as e:\n session.rollback()\n raise Exception(e)\n finally:\n session.close()\n logger.info(\"bulkInsert finish\")\n\n\ndef delete_all(table):\n logger.info(\"deleteAll start\")\n try:\n session = Session()\n session.query(table).delete()\n session.commit()\n except Exception as e:\n session.rollback()\n raise Exception(e)\n finally:\n session.close()\n logger.info(\"deleteAll finish\")\n\n\ndef main():\n cmd()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"investTool/bin/stock_info_getter.py","file_name":"stock_info_getter.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"329072956","text":"#!/usr/bin/python3\n\"\"\"\nChange comes from within\n\"\"\"\nimport sys\n\n\ndef minCoins(coins, m, V): \n \"\"\" recursive \"\"\"\n # base case \n if (V == 0): \n return 0\n\n # Initialize result \n res = sys.maxsize \n \n # Try every coin that has smaller value than V \n for i in range(0, m): \n if (coins[i] <= V): \n sub_res = minCoins(coins, m, V-coins[i]) \n\n # Check for INT_MAX to avoid overflow and see if \n # result can minimized \n if (sub_res != sys.maxsize and sub_res + 1 < res): \n res = sub_res + 1\n\n return res \n\ndef makeChange(coins, total):\n \"\"\"\n ********************************************\n ****determine the fewest number of coins****\n *******needed to meet a given amount********\n ********************************************\n @coins: is a list of the values of the coins\n in the possession\n @total: given amount\n Return:\n fewest number of coins needed to meet total\n *** If total is 0 or less, return 0\n *** If total cannot be met by any number\n of coins you have, return -1\n \"\"\"\n m = len(coins) \n\n return minCoins(coins, m, total)\n\n\nprint(makeChange([1, 2, 25], 37))\n\nprint(makeChange([1256, 54, 48, 16, 102], 1453))\n\nprint(makeChange([1], 2))\n\nprint(makeChange([1,2,5], 11))","sub_path":"0x19-making_change/m.py","file_name":"m.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"174838633","text":"import yfinance as yf\nimport streamlit as st \nimport pandas as pd\n\nst.write(\"\"\"\n# Simple stock Price App\nShown are the stock **closing price** and ***volume*** of Google!\n\"\"\")\n\nticker = 'GOOGL'\n\nticker_data = yf.Ticker(ticker)\ntickerDf = ticker_data.history(period='1d', start='2010-5-31', end='2020-5-31')\n\nst.line_chart(tickerDf.Close)\nst.line_chart(tickerDf.Volume)","sub_path":"myapp.py","file_name":"myapp.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"589193984","text":"#!/usr/bin/env python\n# vim: ai ts=4 sts=4 et sw=4\n\nfrom rapidsms.contrib.handlers.handlers.keyword import KeywordHandler\nfrom logistics.models import StockTransfer\nfrom logistics.const import Reports\nfrom logistics.util import config\nfrom logistics_project.apps.malawi import util\nfrom logistics.decorators import logistics_contact_and_permission_required\nfrom logistics_project.apps.malawi.shortcuts import send_transfer_responses\nfrom logistics.shortcuts import create_stock_report\n\n\nclass TransferHandler(KeywordHandler):\n \"\"\"\n HSA --> HSA transfers\n \"\"\"\n\n keyword = \"give\"\n\n def help(self):\n self.respond(config.Messages.TRANSFER_HELP_MESSAGE)\n \n @logistics_contact_and_permission_required(config.Operations.MAKE_TRANSFER)\n def handle(self, text):\n words = text.split(\" \")\n # need at least a keyword and 1 product + amount\n if len(words) < 3: \n return self.help()\n hsa_id = words[0]\n remainder = \" \".join(words[1:])\n hsa = util.get_hsa(hsa_id)\n if hsa is None:\n self.respond(config.Messages.UNKNOWN_HSA, hsa_id=hsa_id)\n else:\n stock_report = create_stock_report(Reports.GIVE, \n self.msg.logistics_contact.supply_point,\n remainder, \n self.msg.logger_msg)\n transfers = StockTransfer.create_from_transfer_report(stock_report, hsa.supply_point)\n send_transfer_responses(self.msg, stock_report, transfers, self.msg.logistics_contact, hsa)","sub_path":"logistics_project/apps/malawi/handlers/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"557944334","text":"\"\"\"\nImplementing a queue using a stack, which in turn is implemented with an array\n\"\"\"\n\nclass Stack:\n ''' \n Implemented using a built-in Python array\n '''\n def __init__(self):\n self.list = []\n\n def peek(self):\n \"Returns top item without removing it from the stack\"\n if len(self.list) == 0:\n return None\n return self.list[len(self.list) - 1]\n\n def push(self, value):\n \"Returns stack with added value at the top\"\n self.list.append(value) # grows to the right\n return self\n\n def pop(self):\n \"Returns top item and removes it from the stack\"\n if len(self.list) == 0: # or if not self.top\n return None\n popped = self.list[len(self.list) - 1] # required if we want to return popped\n self.list.pop()\n return popped\n\n def is_empty(self):\n \"Returns true if stack is empty and false otherwise\"\n if len(self.list) == 0:\n return True\n else:\n return False\n\nclass Queue:\n def __init__(self):\n self.stack = Stack()\n\n def is_empty(self):\n if len(self.stack.list) == 0:\n return True\n else:\n return False\n\n def peek(self):\n if len(self.stack.list) == 0:\n return None\n return self.stack.list[0]\n\n def enqueue(self, value):\n self.stack.list.append(value)\n return self\n \n def dequeue(self):\n if len(self.stack.list) == 0:\n return None\n dequeued = self.stack.list[0] # holding pointer if we need the dequeued value. else it will be removed by the garbage collector\n del(self.stack.list[0])\n return dequeued\n\n\nqueue = Queue()\nprint(queue.is_empty())\nprint(queue.peek())\nqueue.enqueue(\"A\")\nprint(queue.is_empty())\nprint(queue.peek())\nqueue.enqueue(\"B\")\nprint(queue.peek())\nprint(\" \")\nprint(queue.dequeue())\nprint(queue.is_empty())\nprint(queue.peek())\nqueue.dequeue()\nprint(queue.peek())\nqueue.dequeue()\nprint(queue.is_empty())\nprint(queue.peek())\n","sub_path":"data_structures/stacks_queues/queues_using_stacks.py","file_name":"queues_using_stacks.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"42998302","text":"from aiogram import types\r\n\r\nfrom tools import tools, config\r\nfrom tools.database import get_users\r\nfrom tools.misc import dp, thinker, check_channel_sub\r\n\r\nfrom handlers import start_message\r\n\r\n\r\n@dp.message_handler(commands=['start'])\r\nasync def start(message: types.Message):\r\n text = f\"{tools.get_full_name(message)}, приветствую тебя\" \\\r\n f\" в моем новом приватном SMS Bombere в Telegram!\\n\\n\" \\\r\n f\"Ты - мой новый пользователь. \" \\\r\n f\"Поэтом��, предлагаю тебе {config.trial_start_count} бесплатных запусков. \" \\\r\n f'Очень надеюсь, что ты останешься с нами! ' \\\r\n f'Информация о снятии ограничений находится во вкладке \"Донат\".\\n\\nВыбери действие:' \\\r\n f'' if message.from_user.id not in get_users()['telegram_ids'] else 'Выбери действие:'\r\n\r\n if await check_channel_sub(message.from_user.id, True) and message.from_user.id in get_users()['telegram_ids']:\r\n text += f'\\n\\nПодпишись на наш канал @{config.channel}, что бы не пропускать самое интересное! ' \\\r\n f'(Это сообщение пропадет после подписки на канал).'\r\n\r\n if not await thinker(message):\r\n return\r\n\r\n return await message.reply(text, parse_mode='html',\r\n reply_markup=start_message.generate_start_kb(message.from_user.username))\r\n","sub_path":"handlers/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"124025679","text":"#!/usr/bin/env python\nimport sys,os\nfrom pylab import *\nfrom scipy.integrate import quad,fixed_quad, simps\nfrom matplotlib import pyplot as plt\n\n\n\n\nclass whatever(object):\n\n def __init__(self,typ=0):\n\n self.typ=typ\n self.set_constants()\n\n def set_constants(self):\n\n D={}\n\n \n # masses in GeV\n D['mN2'] = 0.93891897**2\n D['mPi2'] = 0.13803**2\n \n D['g_PiNN'] = sqrt(14.5 * 4 * pi)\n D['gg'] = D['g_PiNN']**2 / (16 * pi**2)\n \n D['pTmax'] = 0.2 # GeV\n D['pTmax2'] = D['pTmax']**2.\n\n\n self.D=D\n \n def integrand(self,y,kT2):\n D=self.D\n typ = self.typ\n\n #sPiN = (kT2+D['mPi2'])/y+(kT2+D['mN2'])/(1.-y)\n t = -kT2/(1.-y) - y**2*D['mN2']/(1.-y)\n \n if typ == 1: # f1 \n a = 0.\n R2 = 0.6**2.\n FF = exp( (t-D['mPi2'])*R2/y ) \n \n elif typ == 2: # f2 Bishari\n a = 1.\n FF = 1.\n \n elif typ == 3: # f3 t exponential\n a = 1.\n b = 0.3\n FF = exp( (t-D['mPi2'])*b )\n \n elif typ == 4: # f4 cov mon \n a = 0.\n L2 = 0.84**2.\n FF = ((L2-D['mPi2'])/(L2 - t)) \n \n elif typ == 5: # f5 cov dip \n a = 0.\n L2 = 1.2**2.\n FF = ((L2-D['mPi2'])/(L2 - t))**2. \n \n elif typ == 6:\n a = 0.\n FF = 1. \n \n return 2.*D['gg']*(y**(1.-2.*a*t))/(1.-y)*-t/(t-D['mPi2'])**2*FF**2 \n\n \n\n def get_integral(self,y,method='quad',ngauss=60):\n D=self.D\n\n if method=='quad':\n\n return quad(lambda kT2: self.integrand(y,kT2),0,D['pTmax2'])[0]\n\n elif method=='gauss':\n\n f=lambda kT2: self.integrand(y,kT2)\n f=vectorize(f)\n return fixed_quad(f,0,D['pTmax2'],n=ngauss)[0]\n\n\nif __name__== \"__main__\":\n\n w=whatever()\n \n # lets integrate kT for fixed y\n y = linspace(0.01, 0.99, 100)\n fy = zeros(100)\n ns = zeros(6)\n \n\n for j in range(1,7):\n w.typ = j\n if j == 1:\n bla = '$f_1$'\n col = 'g'\n styl = '-'\n elif j == 2:\n bla = '$f_2$'\n col = 'b'\n styl = '--'\n elif j == 3:\n bla = '$f_3$'\n col = 'r'\n styl = '--'\n elif j ==4:\n bla = '$f_4$'\n col = 'y'\n styl = '-.'\n elif j == 5:\n bla = '$f_5$'\n col = 'm'\n styl = '-.'\n elif j == 6:\n bla = '$f_6$'\n col = 'b'\n styl = '-.'\n \n\n \n for i in range(len(y)):\n fy[i] = w.get_integral(y[i],method='quad')\n \n ns[j-1] = simps(fy,y)\n plot(1-y,fy, label = bla + '$=$%0.2f' %ns[j-1], color=col, linestyle=styl)\n \n \n # integration using gaussian quadrature\n #for ngauss in range(5,50,5):\n # print 'gauss %d='%ngauss , w.get_integral(y,method='gauss',ngauss=ngauss)\n \n\nxlabel('$x_L$')\nylabel('$f(x_L)$')\nxlim([0,1])\ntitle('Splitting Functions with Brazilian Parameters')\nlegend(loc='best')\nshow()","sub_path":"more/summer/misc_codes/brazil.py","file_name":"brazil.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"38085271","text":"# import the necessary packages\nfrom collections import OrderedDict\nimport numpy as np\nimport cv2\n\n# define a dictionary that maps the indexes of the facial\n# landmarks to specific face regions\nFACIAL_LANDMARKS_IDXS = OrderedDict([\n\t(\"mouth\", (48, 68)),\n\t(\"right_eyebrow\", (17, 22)),\n\t(\"left_eyebrow\", (22, 27)),\n\t(\"right_eye\", (36, 42)),\n\t(\"left_eye\", (42, 48)),\n\t(\"nose\", (27, 35)),\n\t(\"jaw\", (0, 17))\n])\n\ndef rect_to_bb(rect):\n\t# take a bounding predicted by dlib and convert it\n\t# to the format (x, y, w, h) as we would normally do\n\t# with OpenCV\n\tx = rect.left()\n\ty = rect.top()\n\tw = rect.right() - x\n\th = rect.bottom() - y\n\n\t# return a tuple of (x, y, w, h)\n\treturn (x, y, w, h)\n\ndef shape_to_np(shape, dtype=\"int\"):\n\t# initialize the list of (x, y)-coordinates\n\tcoords = np.zeros((68, 2), dtype=dtype)\n\n\t# loop over the 68 facial landmarks and convert them\n\t# to a 2-tuple of (x, y)-coordinates\n\tfor i in range(0, 68):\n\t\tcoords[i] = (shape.part(i).x, shape.part(i).y)\n\n\t# return the list of (x, y)-coordinates\n\treturn coords\n\ndef visualize_facial_landmarks(image, shape, colors=None, alpha=0.75):\n\t# create two copies of the input image -- one for the\n\t# overlay and one for the final output image\n\toverlay = image.copy()\n\toutput = image.copy()\n\n\t# if the colors list is None, initialize it with a unique\n\t# color for each facial landmark region\n\tif colors is None:\n\t\tcolors = [(19, 199, 109), (79, 76, 240), (230, 159, 23),\n\t\t\t(168, 100, 168), (158, 163, 32),\n\t\t\t(163, 38, 32), (180, 42, 220)]\n\n\t# loop over the facial landmark regions individually\n\tfor (i, name) in enumerate(FACIAL_LANDMARKS_IDXS.keys()):\n\t\t# grab the (x, y)-coordinates associated with the\n\t\t# face landmark\n\t\t(j, k) = FACIAL_LANDMARKS_IDXS[name]\n\t\tpts = shape[j:k]\n\n\t\t# check if are supposed to draw the jawline\n\t\tif name == \"jaw\":\n\t\t\t# since the jawline is a non-enclosed facial region,\n\t\t\t# just draw lines between the (x, y)-coordinates\n\t\t\tfor l in range(1, len(pts)):\n\t\t\t\tptA = tuple(pts[l - 1])\n\t\t\t\tptB = tuple(pts[l])\n\t\t\t\tcv2.line(overlay, ptA, ptB, colors[i], 2)\n\n\t\t# otherwise, compute the convex hull of the facial\n\t\t# landmark coordinates points and display it\n\t\telse:\n\t\t\thull = cv2.convexHull(pts)\n\t\t\tcv2.drawContours(overlay, [hull], -1, colors[i], -1)\n\n\t# apply the transparent overlay\n\tcv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)\n\n\t# return the output image\n\treturn output\n\ndef blurout_faces(image, face_rects, blur_function, *args, **kwargs):\n\t\"\"\"\n\tBlur out faces in the image given the face_rects. This function DOES NOT perform face detection. It expects\n\tfaces rects to be given as argument.\n\t:param image: Image to be processed\n\t:param face_rects: Sequence of (x, y, w, h) of every face\n\t:param blur_function: One of cv2.GaussianBlur(), cv2.medianBlur(), etc...\n\t:param args: Args to be supplied to `blur_function`\n\t:param kwargs: Kwargs to be supplied to `blur_function`\n\t:return: Image with faces blurred out\n\n\t>>> blurout_faces(image, face_rects, cv2.GaussianBlur, (25, 25), 30)\n\t>>> blurout_faces(image, face_rects, cv2.medianBlur, 13)\n\t\"\"\"\n\tfor (x, y, w, h) in face_rects:\n\t\tcenter_x, center_y = x + (w // 2), y + (h // 2)\n\n\t\t# Create circular mask around a face\n\t\tmask = np.zeros(image.shape[:2], dtype=\"uint8\")\n\t\tcv2.circle(mask, (center_x, center_y), min(w, h), 1, -1)\n\n\t\t# Create the inverse of the circular mask\n\t\tmask_inverse = np.ones(image.shape[:2], dtype=\"uint8\")\n\t\tcv2.circle(mask_inverse, (center_x, center_y), min(w, h), 0, -1)\n\n\t\t# Blur the whole image\n\t\t# TODO: some optimization here would be helpful (not to blur the whole image)\n\t\tblurred = blur_function(image, *args, **kwargs)\n\t\tface_blurred = cv2.bitwise_and(blurred, blurred, mask=mask)\n\n\t\t# Apply the inverse mask to leave some room for the blurred face\n\t\timage_with_hole = cv2.bitwise_and(image, image, mask=mask_inverse)\n\t\timage = cv2.add(image_with_hole, face_blurred)\n\n\treturn image\n","sub_path":"imutils/face_utils.py","file_name":"face_utils.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"220328211","text":"import pandas as pd\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import svm\nimport numpy as np\nimport xgboost as xgb\n\nclass processor:\n def __init__(self):\n self.raw={}\n self.labels={}\n self.clean={}\n self.train={}\n self.test={}\n self.targetCol={}\n self.corr={}\n self.le=LabelEncoder()\n self.models={}\n self.testSplit=0.2\n self.corrCutOff=0.1\n self.PCADimensions=3\n \n def insertNewDf(self,df, name, tarCol, runPCA=False):\n self.targetCol[name]=tarCol\n self.raw[name]=df\n self.convertCategorical(name)\n self.removeLowCorr(name)\n if runPCA:\n cmp= self.runpca(name, parx=self.clean[name].drop(columns=tarCol), pary=self.clean[name][[tarCol]])\n self.clean[name]=cmp\n self.splitData(name)\n \n return self.clean[name], self.train[name],self.test[name]\n \n def convertCategorical(self, name):\n df=self.raw[name]\n \n dtypes=df.dtypes\n catCols=list(dtypes[dtypes=='object'].index)\n \n self.labels[name]={}\n \n for col in catCols:\n self.le.fit(df[col])\n df[col]=self.le.transform(df[col])\n self.labels[name][col]=list(self.le.classes_)\n \n self.clean[name]=df\n \n def splitData(self, name):\n train, test = train_test_split(self.clean[name], test_size=self.testSplit)\n train.reset_index(inplace=True, drop=True)\n test.reset_index(inplace=True, drop=True)\n self.train[name]={}\n self.train[name]['y']=train[self.targetCol[name]]\n self.train[name]['x']=train.drop(columns=self.targetCol[name])\n self.test[name]={}\n self.test[name]['y']=test[self.targetCol[name]]\n self.test[name]['x']=test.drop(columns=self.targetCol[name])\n \n def removeLowCorr(self, name):\n tarCol=self.targetCol[name]\n df=self.clean[name]\n corr=df.corr()[tarCol].to_frame()\n self.corr[name]=corr\n corr[tarCol]=[abs(x) for x in corr[tarCol]]\n \n keptLabels=list(corr[corr[tarCol]>=self.corrCutOff].index)\n self.clean[name]=self.clean[name][keptLabels]\n \n def runpca(self, name, parx=None, pary=None):\n if parx is None or pary is None:\n x=self.train[name]['x']\n y=self.train[name]['y']\n else:\n x=parx\n y=pary\n \n df=StandardScaler().fit_transform(x)\n components=self.PCADimensions\n pca=PCA(n_components=components)\n pc = pca.fit_transform(df)\n cmp=pd.DataFrame(data=pc, columns=['pc'+str(x+1) for x in range(components)])\n \n var=np.var(pc,axis=0)\n varRatio=var/np.sum(var)\n print('PAC variance ratio: %s' %str(varRatio))\n \n cmp[self.targetCol[name]]=y\n \n return cmp\n \n def cmpScore(self, prediction, ans, test, name):\n results=[1 if x==y else 0 for x,y in zip(prediction, ans)]\n accuracy=str(sum(results)/len(results))\n compilation=pd.DataFrame()\n compilation['prediction']=prediction\n compilation['ans']=ans\n compilation['result']=results\n \n print('%s-%s score: %s'%(name, test, accuracy))\n \n return compilation\n \n \n def runSVM(self, name):\n train_x=self.train[name]['x']\n train_y=self.train[name]['y']\n \n# params={\n# 'kernel':['linear'],\n# 'decision_function_shape':['ovo'],\n# 'gamma':[1e-1, 1, 1e1],\n# 'C':[1e-2, 1, 1e2]\n# }\n# clf=svm.SVC(probability=True)\n# grid=GridSearchCV(clf, param_grid=params, cv=2)\n# grid.fit(train_x,train_y)\n# print(grid.best_params_)\n# return grid.best_params_\n \n clf=svm.SVC(probability=True, kernel='linear', decision_function_shape='ovo', gamma=1e-1, C=0.01)\n \n clf.fit(train_x,train_y)\n \n try:\n self.models[name]['svm']=clf\n except:\n self.models[name]={}\n self.models[name]['svm']=clf\n \n test_x=self.test[name]['x']\n prediction=clf.predict(test_x)\n \n test_y=self.test[name]['y']\n \n compilation=self.cmpScore(prediction,test_y,'SVM',name)\n \n return compilation\n \n def runLogs(self,name):\n clf=LogisticRegression()\n clf.fit(self.train[name]['x'],self.train[name]['y'])\n \n test_x=self.test[name]['x']\n prediction=clf.predict(test_x)\n test_y=self.test[name]['y']\n \n compilation=self.cmpScore(prediction,test_y,'Logs',name)\n \n return compilation\n \n def runXGBoost(self, name):\n train=xgb.DMatrix(self.train[name]['x'].to_numpy(),self.train[name]['y'].to_numpy())\n test=xgb.DMatrix(self.test[name]['x'].to_numpy(), self.test[name]['y'].to_numpy())\n \n params={\n 'eta':0.3,\n 'max_depth':6,\n 'objective':'binary:logistic'\n# 'num_class':2\n }\n steps=20\n \n model = xgb.train(params, train, steps)\n probability=model.predict(test)\n prediction=[1 if x>=0.5 else 0 for x in probability]\n# print(accuracy_score(prediction,self.test[name]['y']))\n compilation=self.cmpScore(prediction,self.test[name]['y'],'XGBoost',name)\n return compilation\n \n def runRandomForest(self, name):\n params={\n 'n_estimators':[100],\n 'max_depth':[10, 50],\n 'min_samples_split':[2,5,10]\n }\n clf=RandomForestClassifier()\n grid=GridSearchCV(clf, param_grid=params, cv=2)\n grid.fit(self.train[name]['x'],self.train[name]['y'])\n \n print(grid.best_params_)\n \n clf=RandomForestClassifier(**grid.best_params_)\n clf.fit(self.train[name]['x'],self.train[name]['y'])\n pred=clf.predict(self.test[name]['x'])\n \n compilation=self.cmpScore(pred,self.test[name]['y'],'randomForrest', name)\n \n return compilation","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"247240553","text":"#\r\n'''\r\na = input()\r\nb = input()\r\na1 = \"\"\r\na2 = \"\"\r\nb1=\"\"\r\nb2=\"\"\r\nfor i in range(len(a)):\r\n if a[i] == '+' and a[i+1] !='-':\r\n if a[i+1]!='i':\r\n a1 = a[:i]\r\n a2 = a[i + 1:len(a)-1]\r\n break\r\n else:\r\n a1 = a[:i]\r\n a2 = '1'\r\n elif a[i]=='+' and a[i+1] =='-':\r\n if a[i+2]!='i':\r\n a1 = a[:i]\r\n a2 = a[i + 1:len(a) - 1]\r\n break\r\n else:\r\n a1=a[:i]\r\n a2='1'\r\nfor i in range(len(b)):\r\n if b[i] == '+' and b[i+1] !='-':\r\n if b[i+1]!='i':\r\n b1 = b[:i]\r\n b2 = b[i + 1:len(b)-1]\r\n break\r\n else:\r\n b1 = b[:i]\r\n b2 = '1'\r\n elif b[i]=='+' and b[i+1] =='-':\r\n if b[i+2]!='i':\r\n b1 = b[:i]\r\n b2 = b[i + 1:len(b) - 1]\r\n break\r\n else:\r\n b1=b[:i]\r\n b2='1'\r\n\r\n\r\nres1=int(a1)*int(b1)-int(a2)*int(b2)\r\nres2=int(a2)*int(b1)+int(a1)*int(b2)\r\n\r\nif res1>=0:\r\n res1=str(res1)\r\nelse:\r\n res1=\"-\"+str(res1)\r\nif res2>=0:\r\n res2=str(res2)\r\nelse:\r\n res2=\"-\"+str(res2)\r\n\r\nprint(res1, \"+\", res2,\"i\")\r\n\r\n'''\r\n\r\n\r\n\r\n'''\r\ntime=input()\r\n\r\nyear=int(time[:4])\r\nmonth=int(time[5:7])\r\nday=int(time[8:])\r\n\r\n\r\nif year%4==0 or year%100==0 and year % 400!=0:\r\n months=[31,29,31,30,31,30,31,31,30,31,30,31]\r\nelse:\r\n months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r\n\r\nfirst=day\r\nfor i in range(12):\r\n if i=end or end<=0: # 偶数阶矩阵和奇数阶矩阵最后的形式不同\r\n if n%2!=0:\r\n res.append(num[start][end])\r\n return\r\n i =start\r\n while i<=end: # 从上到下\r\n res.append(num[i][start])\r\n i+=1\r\n i=start+1\r\n while i<=end: # 从左到右\r\n res.append(num[end][i])\r\n i+=1\r\n i=end-1\r\n while i>=start: # 从下到上\r\n res.append(num[i][end])\r\n i-=1\r\n i=end-1\r\n while i>start: # 从右到左\r\n res.append(num[start][i])\r\n i-=1\r\n printMatrix(num,n,res,start+1,end-1) # 采用递归的形式\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # 读取第一行的n\r\n a = list(map(int, (sys.stdin.readline().strip().split(\" \"))))\r\n n = a[0]\r\n m = a[1]\r\n if m >= 1 and m <= 1000 and n >= 1 and m <= 1000:\r\n num = []\r\n res = []\r\n for i in range(n):\r\n # 读取每一行\r\n line = sys.stdin.readline().strip()\r\n # 把每一行的数字分隔后转化成int列表\r\n values = list(map(int, line.split(\" \")))\r\n num.append(values)\r\n\r\n printMatrix(num, n,res, 0, n-1)\r\n print(res)\r\n print(' '.join(map(str,res)))\r\n\r\n\r\n\r\n\r\n'''\r\ndef solution(total_disk, total_memory, app_list):\r\n # TODO Write your code here\r\n dp = []\r\n for i in range(total_disk):\r\n dp1=[]\r\n for j in range(total_memory):\r\n dp1.append(0)\r\n dp.append(dp1)\r\n pass\r\n\r\n\r\nif __name__ == \"__main__\":\r\n input1 = input()\r\n disk = int(input1.split()[0])\r\n memory = int(input1.split()[1])\r\n input2 = input1.split()[2]\r\n app_list = [[int(j) for j in i.split(',')] for i in input2.split('#')]\r\n print(len(app_list))\r\n app_list = sorted(app_list)\r\n print(app_list)\r\n print(solution(disk, memory, app_list))\r\n\r\n'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"code/aaa.py","file_name":"aaa.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"436179282","text":"import my_func as mf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport ethcal as e\nimport pickle\ndef return_e0met():\n\t'''Return compl. perm. for met at ~300Mhz'''\n\t# CONSTANTS FOUND IN PAPER FOR DIFFERENT CONC. OF METHANOL ~300MHz\n\t#echar={'00''10','28','55','75','88','100'};\n\te_p=[78.3,79.0,68.5,57.8,49.8,41.8,35.9];\n\te_pp=[1.19,2.1,1.6,1.4,2.15,2.5,2.75];\n\treturn [e_p,e_pp]\ndef leg_and_s(h,ustop=-8, start=\"met\"):\n\t'''Given filenames of the form _start_XXXyyyy.yyy in the header h, returns the number found in XXX and a legend made of the the name of each filename in the header '''\n\tustart=len(start)\n\tleg=[]\n\ts=[]\n\tfor i in h:\n\t\tj=i.split(' ')\n\t\tfor k in j:\n\t\t\tif k.find(start)!=-1:\n\t\t\t\tk=k[0:ustop]\n\t\t\t\tleg.append(k)\n\t\t\t\tk=k[ustart:]\n\t\t\t\ts.append(int(k))\n\treturn [leg, s]\ndef dump2pickle():\n\tfn=mf.find_file('metcal2.txt')\n\t[m,h]=mf.read_file2(fn[0])\n\tprint(m)\n\twith open(\"met.pickle\",\"wb\") as f:\n\t\tpickle.dump( [m,h], f)\n\treturn\ndef readpickle():\n\tscript_dir = os.path.dirname(__file__) #<-- absolute dir the script is in\n\trel_path = \"met.pickle\"\n\tabs_file_path = os.path.join(script_dir, rel_path)\n\t[m,h] = pickle.load(open(abs_file_path, \"rb\"))\n\treturn [m,h]\ndef sort_ind(s, v1i):\n\t'''sorts, s and then arrange vXo accordingly'''\n\tind=np.argsort(s)\n\tv1o=[]\n\tfor i in ind:\n\t\tv1o.append(v1i[i])\n\treturn v1o\ndef find_df_dq_kp_kpp(m,s=[]):\n\t'''Calculates df,dq,kp,kpp from the matrix m'''\n\tk=False\n\tif len(s)!=0:k=True\n\t[Q_0, f_0]=e.return_f0q0()\n\t[e_p, e_pp]=return_e0met()\n\tc=0\n\tdfv=[]\n\tdqv=[]\n\tkp=[]\n\tkpp=[]\n\tfor i in m:\n\t\tf_s=i[2]\n\t\tq_s=i[0]\n\t\tdf=(f_0-f_s)\n\t\tdq=(1/q_s-1/Q_0)\n\t\tK_p = 1/(e_p[c] - 1)*df/f_0;\n\t\tK_pp = 1/(2*e_pp[c])*dq;\n\t\tdfv.append(float(df))\n\t\tdqv.append(float(dq))\n\t\tkp.append(float(K_p))\n\t\tkpp.append(float(K_pp))\n\t\tc+=1\n\tif k:\n\t\tdfv=sort_ind(s,dfv)\n\t\tdqv=sort_ind(s,dqv)\n\t\tkp=sort_ind(s,kp)\n\t\tkpp=sort_ind(s,kpp)\n\treturn [dfv,dqv,kp,kpp]\ndef lin_fit(x,y):\n\t'''Returns a vector of the points on a linear fit'''\n\tp=np.poly1d(np.polyfit(x,y,1))\n\tpx=np.linspace(min(x)*(1-1e-3), max(x)*(1+1e-3), 100)\n\tpy=p(px)\n\treturn [px,py]\ndef get_k():\n\t'''returns functions Kpf(df) and Kppf(dq)'''\n\t[m,h]=readpickle()\n\t[leg, s]=leg_and_s(h)\n\tleg=sort_ind(s,leg)\n\t[dfv,dqv,kp,kpp]=find_df_dq_kp_kpp(m,s)\n\tKpf=np.poly1d(np.polyfit(dfv,kp,1))\n\tKppf=np.poly1d(np.polyfit(dqv,kpp,1))\t\n\treturn [Kpf,Kppf]\ndef show_cal():\n\t'''Plots the calibration'''\n\t[m,h]=readpickle()\n\t#[ep, epp]=find_e(m #constant k\n\t[leg, s]=leg_and_s(h)\n\t#[legs, eps, epps]=sort_ind(s, leg, ep, epp) # constant k.\n\t[dfv,dqv,kp,kpp]=find_df_dq_kp_kpp(m,s)\n\tplt.figure(1)\n\tdfv=np.array(dfv)/1e6\n\tfig=plt.plot([dfv],[kp],'*')\n\tspl=['+','*','x','s','d','^','v','>','<','p','h','o']\n\tc=0\n\tfor i in fig:\n\t\ti.set_marker(spl[c])\n\t\tc+=1\n\tplt.xlabel('$\\Delta$f [Mhz]')\n\tplt.ylabel(\"K'\")\n\t#plt.title(\"K'($\\Delta$f)\")\n\t#plt.legend(sort_ind(s,leg))\n\tnewleg=[]\n\tfor i in sort_ind(s,leg):\n\t\tnewleg.append(i[3:]+\"%\")\n\tplt.legend(newleg)\n\tplt.ticklabel_format(style='sci', axis='y', scilimits=(1,3))\n\t[px,py]=lin_fit(dfv,kp)\n\tplt.plot(px,py)\n\tplt.figure(2)\n\tfig=plt.plot([dqv],[kpp],'*')\n\tc=0\n\tfor i in fig:\n\t\ti.set_marker(spl[c])\n\t\tc+=1\n\tplt.xlabel('1/$\\Delta$Q')\n\tplt.ticklabel_format(style='sci', axis='y', scilimits=(1,3))\n\tplt.ylabel(\"K''\")\n\t#plt.title(\"K''(1/$\\Delta$Q)\")\n\tnewleg=[]\n\tfor i in sort_ind(s,leg):\n\t\tnewleg.append(i[3:]+\"%\")\n\tplt.legend(newleg)\n\t#plt.legend(sort_ind(s,leg))\n\t[px,py]=lin_fit(dqv,kpp)\n\tplt.plot(px,py)\n\tplt.show()\n\treturn","sub_path":"metcal.py","file_name":"metcal.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"98369809","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.modules.distance import PairwiseDistance\n\n\nclass AdjacencyLayer(nn.Module):\n def __init__(self, num_domains, batch_size, k, device):\n super(AdjacencyLayer, self).__init__()\n self.k = k\n self.num_domains = num_domains\n self.batch_size = batch_size\n self.pdist = PairwiseDistance(2, keepdim=False)\n self.device = device\n\n\n def forward(self, input):\n \"\"\"\n :param input: tensor with size [(num_domains+1) x batch_size, feature_dim].\n :return:\n \"\"\"\n N = (self.num_domains+1)*self.batch_size\n adj = torch.zeros(N, N)\n # adjacent matrix for targets\n j = self.num_domains\n for i in range(self.num_domains): # compute the pairwise interaction of source x target\n # indices = torch.tensor([i])\n x_i = input[i*self.batch_size:(i+1)*self.batch_size, :] # [batch_size, feature_dim]\n x_j = input[j*self.batch_size:(j+1)*self.batch_size, :] # [batch_size, feature_dim]\n x_i_norm = F.normalize(x_i)\n x_j_norm = F.normalize(x_j)\n sim = torch.mm(x_i_norm, torch.transpose(x_j_norm, 0, 1))\n\n # find k-NN\n topk, indices = torch.topk(sim, self.k, largest=True) # largest k samples\n neighbor = Variable(torch.zeros(self.batch_size, self.batch_size)).to(self.device)\n neighbor = neighbor.scatter_(1, indices, topk)\n adj[i*self.batch_size:(i+1)*self.batch_size, j*self.batch_size:(j+1)*self.batch_size] = neighbor\n # print (neighbor)\n\n # adjacent matrix for sources\n topk_ngh =[]\n for i in range(self.num_domains+1): # compute the pairwise interaction of source x source\n # indices = torch.tensor([i])\n x_i = input[i*self.batch_size:(i+1)*self.batch_size, :] # [batch_size, feature_dim]\n x_i_norm = F.normalize(x_i)\n sim = torch.mm(x_i_norm, torch.transpose(x_i_norm, 0, 1))\n\n # find k-NN\n topk, indices = torch.topk(sim, self.k, largest=True) # largest k samples for distance, contain itself\n neighbor = Variable(torch.zeros(self.batch_size, self.batch_size)).to(self.device)\n neighbor = neighbor.scatter_(1, indices, topk)\n adj[i*self.batch_size:(i+1)*self.batch_size, i*self.batch_size:(i+1)*self.batch_size] = neighbor\n topk_ngh.append(indices)\n # print (neighbor)\n # print (adj.size())\n return adj, topk_ngh # adj (N, N), topk_ngh (N, k)\n\n\nclass DistanceLayer(nn.Module):\n def __init__(self, num_domains, batch_size):\n super(DistanceLayer, self).__init__()\n\n self.num_domains = num_domains\n self.batch_size = batch_size\n self.pdist = PairwiseDistance(2)\n\n def intersection(self, lst1, lst2):\n return list(set(lst1).intersection(lst2))\n\n def forward(self, semb, slabels, topk_ngh):\n \"\"\"\n :param input: tensor with size [(num_domains) x batch_size, feature_dim].\n :return:\n pos_dist: store the largest neg similarity\n neg_dist: store the smallest pos similarity\n pos_embed: store the pos embedding with smallest similarity\n neg_embed: store the neg embedding with largest similarity\n \"\"\"\n\n hardest = False\n pos_dist, neg_dist, pos_embed, neg_embed, anc_embed = [], [], [], [], []\n for k in range(self.num_domains):\n emb, label = semb[k], slabels[k]\n # dist = self.pdist.forward(emb, emb)\n sim = torch.mm(emb, torch.transpose(emb, 0, 1))\n pos_indices = (label==1).nonzero().squeeze()\n neg_indices = (label==0).nonzero().squeeze()\n if len(pos_indices.size()) == 0 or len(neg_indices.size()) == 0: continue\n\n pdist, ndist, pembed, nembed = [], [], [], []\n aembed = []\n pembed = []\n nembed = []\n\n for i in range(self.batch_size): # for each sample, find hard pos and neg\n if label[i] == 1:\n same_indices, diff_indices = pos_indices, neg_indices\n elif label[i] == 0:\n same_indices, diff_indices = neg_indices, pos_indices\n # print (label[i])\n # print (\"---\")\n # print (same_indices)\n # print (diff_indices)\n same_indices_neighbor = self.intersection(topk_ngh[k][i].tolist(), same_indices.tolist())\n diff_indices_neighbor = self.intersection(topk_ngh[k][i].tolist(), diff_indices.tolist())\n # print (topk_ngh[k][i])\n # print (same_indices_neighbor)\n # print (diff_indices_neighbor)\n\n if len(same_indices_neighbor) == 0 or len(diff_indices_neighbor) == 0:\n # print (\"++\")\n # print (len(same_indices_neighbor))\n # print (len(diff_indices_neighbor))\n continue\n\n same_indices = same_indices[same_indices != i]\n # min_sim, min_index = torch.min(sim[i, same_indices], 0) # min similarity in positives, hard postive\n # max_sim, max_index = torch.max(sim[i, diff_indices], 0) # max similarity in negatives, hard negative\n\n if hardest:\n min_sim, min_index = torch.min(sim[i, torch.tensor(same_indices_neighbor)], 0) # min similarity in positives, hard postive\n max_sim, max_index = torch.max(sim[i, torch.tensor(diff_indices_neighbor)], 0) # max similarity in negatives, hard negative\n # print (sim[i])\n # print (min_sim)\n # print (same_indices_neighbor[min_index])\n # print (max_sim)\n # print (diff_indices_neighbor[max_index])\n pdist.append(min_sim)\n ndist.append(max_sim)\n # pembed[i, :] = emb[same_indices[min_index], :]\n # nembed[i, :] = emb[diff_indices[max_index], :]\n pembed.append(emb[same_indices_neighbor[min_index], :])\n nembed.append(emb[diff_indices_neighbor[max_index], :])\n aembed.append(emb[i, :])\n else:\n for sn in same_indices_neighbor:\n for dn in diff_indices_neighbor:\n pdist.append(sim[i, sn])\n ndist.append(sim[i, dn])\n aembed.append(emb[i, :])\n pembed.append(emb[sn, :])\n nembed.append(emb[dn, :])\n\n if len(aembed) != 0:\n pos_dist.append(torch.tensor(pdist))\n neg_dist.append(torch.tensor(ndist))\n pos_embed.append(torch.stack(pembed))\n neg_embed.append(torch.stack(nembed))\n anc_embed.append(torch.stack(aembed))\n # print (torch.stack(aembed).size())\n return pos_dist, neg_dist, anc_embed, pos_embed, neg_embed\n\n\nclass GraphAttentionLayer(nn.Module):\n \"\"\"\n Simple GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, weights, in_features, out_features, dropout, alpha, layer, device, concat=True):\n super(GraphAttentionLayer, self).__init__()\n self.device = device\n self.dropout = dropout\n self.in_features = in_features\n self.out_features = out_features\n self.alpha = alpha\n self.concat = concat\n\n self.W = weights[\"gat_W\"+str(layer)]\n nn.init.xavier_uniform_(self.W.data, gain=1.414)\n self.a = weights[\"gat_a\"+str(layer)]\n nn.init.xavier_uniform_(self.a.data, gain=1.414)\n\n # self.W = nn.Parameter(torch.zeros(size=(in_features, out_features)))\n # nn.init.xavier_uniform_(self.W.data, gain=1.414)\n # self.a = nn.Parameter(torch.zeros(size=(2*out_features, 1)))\n # nn.init.xavier_uniform_(self.a.data, gain=1.414)\n\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n\n def forward(self, input, adj):\n # print (self.W.size())\n # print (input.size())\n h = torch.mm(input, self.W)\n N = h.size()[0]\n # print (h.size()) # [80, 100]\n\n a_input = torch.cat([h.repeat(1, N).view(N * N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2 * self.out_features)\n e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))\n # print (self.a.size()) # [200, 1]\n # print (a_input.size()) # [80, 80, 200]\n # print (e.size()) # [80, 80]\n\n zero_vec = -9e15*torch.ones_like(e)\n attention = torch.where(adj.to(self.device) > 0, e, zero_vec) # adj < 0, position e == -9e15\n attention = F.softmax(attention, dim=1)\n attention = F.dropout(attention, self.dropout, training=self.training)\n h_prime = torch.matmul(attention, h)\n # print (\"--\")\n # print (attention.size())\n return h_prime\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'\n","sub_path":"meta-amazon/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":9351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"316250812","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2020, Vi Grey\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n\nimport sys\n\nhelp_flag = False\nfilepath = \"\"\n\ndef get_args():\n global help_flag, filepath\n if len(sys.argv) >= 2:\n i = 0\n for a in sys.argv[1:]:\n if a.upper() == \"--HELP\" or a.upper() == \"-H\":\n help_flag = True\n elif i == len(sys.argv[1:]) - 1:\n filepath = a\n i += 1\n\ndef print_help():\n help_string = (\"Usage: python3 ascii2bf.py [ OPTIONS ] [ \" +\n \"input_file ]\\r\\n\\r\\n\" +\n \"Prints a brainfu-- program that prints out the contents of \" +\n \"input_file\\r\\n\\r\\n\" +\n \"Options:\\r\\n\"\n \" -h, --help Print Help (this message) and exit\\r\\n\\r\\n\"\n \"Example:\\r\\n\" +\n \" python3 ascii2bf.py --help\\r\\n\" +\n \" python3 ascii2bf.py -h\\r\\n\" +\n \" python3 ascii2bf.py test.txt\")\n print(help_string)\n\ndef print_bf():\n global filepath\n if filepath == \"\":\n print(\"\\x1b[91mInput File Required. Use --help argument to learn more.\\x1b[0m\")\n exit(1)\n ascii_file = open(filepath, \"rb\")\n filecontent = ascii_file.read()\n ascii_file.close()\n uniquecount = {}\n unique = []\n for letter in filecontent:\n if letter not in unique:\n uniquecount[letter] = 1\n uniquecount[letter] += 1\n unique = sorted(uniquecount, key = uniquecount.get, reverse = True)\n setup = \">++[-<+>>++<]>[-<+>>++<]>[-<+>>++<]>[-<+>>++<]>[-<+>>++<]>[-<+>>++<]>[-<+>>++<]>[-]<\"\n leftarrow = 1\n for i in range(8):\n if i != 7:\n setup += \"<[-\"\n setup += \">\" * i\n else:\n setup += \">\" * (i - 1)\n leftarrow = 0\n for item in unique:\n binaryitem = format(item, '#010b')[2:]\n setup += \">\"\n if binaryitem[i] == \"1\":\n setup += \"+\"\n leftarrow += 1\n setup += \"<\" * leftarrow\n if i != 7:\n setup += \"<\" * i\n setup += \"]\"\n setup + \">\" * i\n else:\n setup += \">\"\n oldindex = 0\n for letter in filecontent:\n letterindex = unique.index(letter)\n right = letterindex - oldindex\n oldindex = letterindex\n if right > 0:\n setup += \">\" * right\n else:\n setup += \"<\" * -right\n setup += \".\"\n while \"<>\" in setup:\n setup = setup.replace(\"<>\", \"\")\n while \"><\" in setup:\n setup = setup.replace(\"><\", \"\")\n print(setup)\n\n\nget_args()\nif help_flag:\n print_help()\nelse:\n print_bf()\n","sub_path":"src/brainfu/ascii2bf.py","file_name":"ascii2bf.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"255709431","text":"from collections import Counter\nclass Quadruplets:\n\n # Returns the number of quadruplets that sum to zero.\n # a - [int]\n # b - [int]\n # c - [int]\n # d - [int]\n # worst = O(n^2 logn)\n def zero_quadruplets_count(a, b, c, d):\n ab = [i+j for i in a for j in b]\n cd = [-(k+l) for k in c for l in d]\n ab = Counter(ab).most_common()\n cd = Counter(cd).most_common()\n cd = sorted(cd)\n count = 0\n for i in range(len(ab)):\n lo = 0\n hi = len(cd)-1\n while lo <= hi:\n m = lo\n if cd[m][0] == ab[i][0]:\n count += cd[m][1]*ab[i][1]\n break\n else:\n if cd[m][0] <= ab[i][0]:\n lo += 1\n else:\n hi -= 1\n return count\n pass\n","sub_path":"week2/3-Quadruplets/quadruplets.py","file_name":"quadruplets.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"403021432","text":"# -*- coding: utf-8 -*-\nimport re\nimport argparse\nimport traceback\nimport requests\nfrom bs4 import BeautifulSoup\nimport multiprocessing\nfrom common.utils import CrawlerUtil\nfrom common.mysql_adapter import CrawlerBaseDb, CRAWLER_BOOKING_BASE\nfrom common.crawler_tables import DtBookingHotelUrl, DtBookingCityUrl\n\n\nclass BookingUrl:\n name = 'crawler_booking_url'\n db_name = 'crawler_booking'\n start_url = 'https://www.booking.com/destination.en-us.html'\n _base_url = 'https://www.booking.com'\n cn_patten = re.compile(u'[\\u4e00-\\u9fa5]')\n re_country = re.compile(r'/destination/country/(\\S+)\\.html')\n re_city = re.compile(r'/destination/city/(?:\\S+)/(\\S+)'\n r'(?:\\.zh-cn|\\.en-us)*\\.html')\n re_hotel = re.compile(r'/hotel/(?:\\S+)/(\\S+)(?:\\.zh-cn|\\.en-us)*\\.html')\n\n headers = {\n 'Accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n 'Accept-Encoding': \"gzip, deflate\",\n 'Accept-Language': \"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7\",\n 'Connection': \"keep-alive\",\n 'Host': \"www.booking.com\",\n 'Upgrade-Insecure-Requests': \"1\",\n 'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\",\n 'cache-control': \"no-cache\",\n }\n\n def __init__(self, mylogger=None, process_num=1, renew=False):\n self.process_num = process_num\n self.renew = renew\n if mylogger:\n self.mylogger = mylogger\n else:\n self.mylogger = CrawlerUtil.get_crawler_logger(self.name)\n\n def start_crawl_url(self):\n try:\n self.mylogger.info(\"----start crawl hotel urls!\")\n db_crawler = CrawlerBaseDb.get_db(self.db_name)\n if db_crawler.session is None:\n self.mylogger.error(\"fail to connect to the databases! exit program!\")\n exit(1)\n db_crawler.create_all_tables(CRAWLER_BOOKING_BASE)\n\n resp = requests.get(self.start_url)\n if resp.status_code == 200:\n num_compress_process = 0\n queue = multiprocessing.Queue()\n jobs = []\n\n soup = BeautifulSoup(resp.text, \"html.parser\")\n country_as = soup.select('.dest-sitemap__subsublist-item a.dest-sitemap__subsublist-link')\n for country_a in country_as:\n try:\n co_href = country_a['href']\n if co_href and self.re_country.findall(co_href):\n co_code = self.re_country.findall(co_href)[0]\n co_url = self._base_url + '/destination/country/' + co_code + '.en-us.html'\n resp1 = requests.get(co_url)\n if resp1.status_code == 200:\n soup1 = BeautifulSoup(resp1.text, \"html.parser\")\n city_as = soup1.select('.dest-sitemap__list a.dest-sitemap__subsublist-link')\n for city_a in city_as:\n ci_href = city_a['href']\n if ci_href and self.re_city.findall(ci_href):\n dt_city_url = DtBookingCityUrl()\n dt_city_url.country_code = co_code\n dt_city_url.city_code = self.re_city.findall(ci_href)[0]\n dt_city_url.url = self._base_url + '/destination/city/' + co_code + '/' + dt_city_url.city_code + '.en-us.html'\n dt_city_url.crawled_url = 0\n dt_city_url.flag = 1\n db_crawler.session.merge(dt_city_url)\n db_crawler.session.commit()\n\n job = multiprocessing.Process(target=self.parse_city,\n args=(dt_city_url, queue))\n job.start()\n jobs.append(job)\n num_compress_process += 1\n while num_compress_process == self.process_num:\n (country_name, status) = queue.get()\n num_compress_process -= 1\n if status < 0:\n self.mylogger.error(\"==exceptions occurs \"\n \"when parse country:{} \".format(country_name))\n elif status == 0:\n self.mylogger.error(\"escape country:{} \".format(country_name))\n except:\n self.mylogger.error(traceback.format_exc())\n\n # wait for all process done\n for job in jobs:\n job.join()\n else:\n self.mylogger.error(\"no response of {} \".format(self.start_url))\n except:\n self.mylogger.error(traceback.format_exc())\n finally:\n self.mylogger.info(\"----exit crawl hotel urls!\")\n\n def parse_city(self, dt_city_url, queue):\n try:\n sess = CrawlerBaseDb.get_wild_session(self.db_name)\n if sess is None:\n print(\"fail to get session of {} \"\n \"in parse_city\".format(self.db_name))\n self.mylogger.error(\"fail to get session of {} \"\n \"in parse_city\".format(self.db_name))\n exit(1)\n\n resp2 = requests.get(dt_city_url.url)\n if resp2.status_code == 200:\n soup2 = BeautifulSoup(resp2.text, \"html.parser\")\n hotel_as = soup2.select('ul.dest-sitemap__list a.dest-sitemap__subsublist-link')\n for hotel_a in hotel_as:\n ho_href = hotel_a['href']\n if ho_href and self.re_hotel.findall(ho_href):\n ho_code = self.re_hotel.findall(ho_href)[0]\n ho_url = self._base_url + '/hotel/' + dt_city_url.country_code + '/' + ho_code\n dt_hotel_url = DtBookingHotelUrl()\n dt_hotel_url.city_code = dt_city_url.city_code\n dt_hotel_url.country_code = dt_city_url.country_code\n dt_hotel_url.hotel_code = ho_code\n dt_hotel_url.url = ho_url\n self.update_hotel_url(sess, dt_hotel_url)\n # set flag\n self.check_city_code(sess, dt_city_url, 2)\n queue.put((dt_city_url.city_code, 1))\n else:\n queue.put((dt_city_url.city_code, -1))\n self.mylogger.error(\"no response of {} \".format(dt_city_url.url))\n except:\n self.mylogger.error(traceback.format_exc())\n queue.put((dt_city_url.city_code, -1))\n finally:\n if sess:\n CrawlerBaseDb.close_wild_session(sess)\n\n def check_city_code(self, sess, dt_city_url, value=None):\n try:\n rtn = False\n record = sess.query(DtBookingCityUrl).filter(\n DtBookingCityUrl.country_code == dt_city_url.country_code,\n DtBookingCityUrl.city_code == dt_city_url.city_code).first()\n if record:\n if record.crawled_url == 2:\n rtn = True\n if value:\n record.crawled_url = value\n sess.commit()\n except:\n self.mylogger.error(traceback.format_exc())\n return rtn\n\n def update_hotel_url(self, sess, dt_hotel_url):\n rtn = False\n try:\n record = sess.query(DtBookingHotelUrl).filter(DtBookingHotelUrl.country_code == dt_hotel_url.country_code,\n DtBookingHotelUrl.hotel_code == dt_hotel_url.hotel_code).first()\n if record:\n record.city_code = dt_hotel_url.city_code\n record.country_code = dt_hotel_url.country_code\n record.hotel_code = dt_hotel_url.hotel_code\n record.url = dt_hotel_url.url\n else:\n sess.add(dt_hotel_url)\n sess.commit()\n rtn = True\n except:\n self.mylogger.error(traceback.format_exc())\n finally:\n return rtn\n\n\ndef arg_parser():\n try:\n parser = argparse.ArgumentParser('./mafengwo_poi.py -h')\n parser.add_argument('-u', '--url', action='store_true', dest='url',\n default=True, help='get url')\n parser.add_argument('-p', '--process', action='store', dest='process', type=int,\n default=4, help='num of multi process')\n parser.add_argument('-r', '--renew', action='store_true', dest='renew',\n default=False, help='renew all of country')\n return parser\n except:\n print(traceback.format_exc())\n\n\nif __name__ == '__main__':\n parser = arg_parser()\n args = parser.parse_args()\n\n logger = CrawlerUtil.get_crawler_logger(BookingUrl.name)\n crawler = BookingUrl(logger, args.process, args.renew)\n if args.url:\n print('start get qyer dest[tasks:{}], {} mode!'.format(\n args.process, 'renew' if args.renew else 'update'))\n logger.info('start get qyer dest[tasks:{}], {} mode!'.format(\n args.process, 'renew' if args.renew else 'update'))\n crawler.start_crawl_url()\n else:\n logger.error('wrong params!!!')","sub_path":"crawlers/crawlers/crawler_booking_urls.py","file_name":"crawler_booking_urls.py","file_ext":"py","file_size_in_byte":9901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"462870757","text":"#!/usr/bin/env python3\nimport os\nimport re\nimport logging\nfrom pathlib import Path\n\nfrom nltk.corpus import stopwords\nfrom tqdm import tqdm\n\nglobal logger\n\ndef get_hotwords(regex_sets, stop_words, title, abstract):\n # clean up data\n chars = set(\" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\")\n \n text = \" \".join([title, abstract])\n text = text.split()\n \n clean_words = []\n for word in text:\n word_out = \"\".join([letter for letter in word if letter in chars])\n word_out = word_out.lower()\n if word_out not in stop_words:\n clean_words.append(word_out)\n\n clean_words = \" \".join(clean_words)\n\n out = []\n for regex_set in regex_sets:\n regex_hits = []\n for regex in regex_set:\n if regex.search(clean_words):\n regex_hits.append(regex.search(clean_words).group())\n regex_hits = \",\".join(regex_hits)\n out.append(regex_hits)\n\n return \"\\t\".join(out)\n\ndef parse_doc(doc, regex_sets, stop_words, doc_totals, logger):\n article_start = re.compile(r\"\\s*\")\n article_stop = re.compile(r\"\\s*\")\n pmid = re.compile(r\"\\s*(\\d*)\")\n mesh_list_start = re.compile(r\"\\s*\")\n mesh_list_stop = re.compile(r\"\\s*\")\n mesh_term_id = re.compile(r'\\s*')\n journal_start = re.compile(r\"\\s*\")\n journal_stop = re.compile(r\"\\s*\")\n journal_name = re.compile(r\"\\s*(.+)</Title\")\n pub_year = re.compile(r\"\\s*<Year>(\\d+)</Year>\")\n article_title = re.compile(r\"\\s*<ArticleTitle>(.+)</ArticleTitle\")\n abstract_start = re.compile(r\"\\s*<Abstract>\")\n abstract_stop = re.compile(r\"\\s*</Abstract>\")\n abstract_text = re.compile(r\"\\s*<AbstractText.*>(.*)</AbstractText\")\n edna = re.compile(r\"[Ee]nvironmental DNA\")\n\n doc_pmid = \"\"\n abstract = \"\"\n title = \"\"\n journal = \"\"\n term_ids = []\n year = \"\"\n\n doc_count = 0\n\n with open(doc, \"r\") as handle:\n line = handle.readline()\n while line:\n if article_start.search(line):\n doc_count += 1\n if doc_pmid:\n if edna.search(title) or edna.search(abstract):\n hotwords_out = get_hotwords(regex_sets, stop_words, title, abstract)\n term_ids = \",\".join(term_ids)\n yield (doc_pmid, journal, year, hotwords_out, term_ids)\n\n # reset vars\n doc_pmid = \"\"\n journal = \"\"\n abstract = \"\"\n title = \"\"\n term_ids = []\n year = \"\"\n\n while not article_stop.search(line):\n if not doc_pmid and pmid.search(line):\n doc_pmid = pmid.search(line).group(1)\n if mesh_list_start.search(line):\n while not mesh_list_stop.search(line):\n mesh_match = mesh_term_id.search(line)\n if mesh_match and mesh_match.group(1):\n term_ids.append(mesh_match.group(1))\n line = handle.readline()\n if journal_start.search(line):\n while not journal_stop.search(line):\n journal_match = journal_name.search(line)\n if journal_match and journal_match.group(1):\n journal = journal_match.group(1)\n year_match = pub_year.search(line)\n if year_match and year_match.group(1):\n year = year_match.group(1)\n line = handle.readline()\n if article_title.search(line):\n title = article_title.search(line).group(1)\n if abstract_start.search(line):\n abs_lines = []\n while not abstract_stop.search(line):\n abs_match = abstract_text.search(line)\n if abs_match and abs_match.group(1):\n abs_lines.append(abs_match.group(1))\n line = handle.readline()\n abstract = \" \".join(abs_lines)\n \n line = handle.readline()\n line = handle.readline()\n \n logger.info(f\"parsed: |{doc_count}|\")\n doc_totals.append(doc_count)\n\ndef main():\n # Set up logging\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n handler = logging.FileHandler(\"pubmed_parser.log\")\n formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n \n doc_totals = []\n\n stop_words = set(stopwords.words(\"english\"))\n \n organisms = []\n with open(\"clean_org_list\", \"r\") as handle:\n for line in handle:\n item = \"\".join([r\"\\b\", re.escape(line.strip(\"\\n\")), r\"\\b\"])\n organisms.append(re.compile(item, flags=re.IGNORECASE))\n\n common_names = []\n with open(\"org_list_common_names\", \"r\") as handle:\n for line in handle:\n item = \"\".join([r\"\\b\", re.escape(line.strip(\"\\n\")), r\"\\b\"])\n common_names.append(re.compile(item, flags=re.IGNORECASE))\n\n countries = []\n with open(\"countries\", \"r\") as handle:\n for line in handle:\n item = \"\".join([r\"\\b\", re.escape(line.strip(\"\\n\")), r\"\\b\"])\n countries.append(re.compile(item, flags=re.IGNORECASE))\n\n biomes = []\n with open(\"biomes\", \"r\") as handle:\n for line in handle:\n item = \"\".join([r\"\\b\", re.escape(line.strip(\"\\n\")), r\"\\b\"])\n biomes.append(re.compile(item, flags=re.IGNORECASE))\n\n tech = []\n with open(\"experimental_tech\", \"r\") as handle:\n for line in handle:\n item = \"\".join([r\"\\b\", re.escape(line.strip(\"\\n\")), r\"\\b\"])\n tech.append(re.compile(item, flags=re.IGNORECASE))\n\n sample_microenv = []\n with open(\"sample_types\", \"r\") as handle:\n for line in handle:\n item = \"\".join([r\"\\b\", re.escape(line.strip(\"\\n\")), r\"\\b\"])\n sample_microenv.append(re.compile(item, flags=re.IGNORECASE))\n \n hotwords = [\"mammals\", \"fish\", \"amphibians\", \"birds\", \"bryophytes\", \"arthropods\",\n \"copepods\", \"plants\", \"reptiles\", \"insects\"]\n \n hotwords = [re.compile(re.escape(hotword), flags=re.IGNORECASE) for hotword in hotwords]\n\n regex_sets = [organisms, common_names, countries, biomes, tech, sample_microenv, hotwords]\n\n doc_dir = \"/media/wkg/storage/FUSE/pubmed_bulk\"\n docs_list = os.listdir(doc_dir)\n containing_dir = Path(doc_dir).resolve()\n \n docs_list = [os.path.join(containing_dir, doc) for doc in docs_list]\n\n with open(\"relevant_metadata_w_common_names\", \"w\") as out:\n for doc in tqdm(docs_list):\n for doc_metadata in parse_doc(doc, regex_sets, stop_words, doc_totals, logger):\n out.write(\"\\t\".join([doc_metadata[0], doc_metadata[1], doc_metadata[2], \n doc_metadata[3], doc_metadata[4]]))\n out.write(\"\\n\")\n\n tot = sum(doc_totals)\n logger.info(f\"total articles: {tot}\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pubmed_parser.py","file_name":"pubmed_parser.py","file_ext":"py","file_size_in_byte":7448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"198910316","text":"from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\nX_estimate = np.asmatrix(np.zeros((1,4)))\nX_predict = np.asmatrix(np.zeros((1,4)))\nA = np.mat([[1,1,0,0],[0,1,0,0],[0,0,1,1],[0,0,0,1]])\nH = np.mat([[1,0,0,0],[0,0,1,0]])\nI = np.mat([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])\nR = np.mat([[10000,0],[0,10000]])\nP_estimate = np.mat([[10000,5000,0,0],[5000,5000,0,0],[0,0,10000,5000],[0,0,5000,5000]])\nP_predict = np.asmatrix(np.zeros((4,4)))\nnew_sample = np.mat([[0],[0]])\nkg = np.asmatrix(np.zeros((4,2)))\nx = []\ny = []\nx_cor = []\ny_cor = []\n\n#X_predict = np.mat([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])\n#P_estimate = np.mat([[1,1,0,0],[1,1,0,0],[1,1,0,0],[1,1,0,0]])\n#X_estimate[k-2,:] = X_est;\n#u[k-2] = u1;\nk = 2\ni = 0\ncoeff = 0.8\n\t\n\ndef kal_predict():\n #u(k-1) = u_trans\n\tglobal A,X_estimate,X_predict,P_estimate,P_predict\n\tX_predict = (A*X_estimate.transpose()).transpose()\n\tP_predict = A*P_estimate*(A.transpose())\n\t\ndef kal_update():\n\tglobal A,H,I,Kg,new_sample,X_estimate,X_predict,P_estimate,P_predict\n\tKg = P_predict*(H.transpose())*(np.linalg.inv(H*P_predict*(H.transpose()) + R))\n\tX_estimate = (X_predict.transpose() + Kg*(new_sample - H*(X_predict.transpose()))).transpose()\n\tP_estimate = (I - Kg*H)*P_predict\n\t#new_message[:,k] = new_sample - np.dot(H,X_predict[k,:].transpose())\n\t#new_deviation = np.dot(H,np.dot(P_predict,H.transpose())) + R\n\t#delta(k) = np.dot(np.dot(new_message[:,k].transpose(),np.linalg.inv(new_deviation)),new_message[:,k])\n\t#u(k) = coeff * u(k-1) + delta(k)\n\t#u_trans = u(k)\n\t\n\nwhile (i <= 80):\n\tx.append(i + random.uniform(1,5))\n\ty.append(4*i + random.uniform(1,5))\n\ti = i + 1\n\t\nX_estimate[0,0] = x[1]\nX_estimate[0,1] = (x[1] - x[0])/2\nX_estimate[0,2] = y[1]\nX_estimate[0,3] = (y[1] - y[0])/2\nx_cor.append(X_estimate[0,0])\ny_cor.append(X_estimate[0,2])\n\n\nwhile (k <= 80):\n\tnew_sample[0,:] = x[k]\n\tnew_sample[1,:] = y[k]\n\tkal_predict()\n\tkal_update()\n\tx_cor.append(X_estimate[0,0])\n\ty_cor.append(X_estimate[0,2])\n\tk = k + 1\n\nplt.figure(1)\nplt.plot(x_cor,y_cor)\nplt.show()\n\n#plt.figure(2)\n#plt.plot(x_cor,y_cor)\n#plt.show()\n\n","sub_path":"filter/kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"600103031","text":"import os\nimport numpy as np\nimport re\nimport pandas as pd\nimport json\n\nif False:\n\traw_listings = open(\"data/listings.csv\").readlines()\n\n\t# This will clean shifted ; that are in title and cause column mismatch\n\tfor i, line in enumerate(raw_listings):\n\t\tmatches = [(m.start(0), m.end(0)) for m in re.finditer(r\"(?![\\d+;]).*;(?=entire_home|private_room|shared_room)\", line)]\n\t\tif len(matches) == 0 or len(matches) > 1:\n\t\t\tcontinue\n\t\tm = matches[0]\n\t\tnew_line = line[:m[0]] + line[m[0]:m[1]-1].replace(\";\", \",\") + line[m[1]-1:]\n\t\traw_listings[i] = new_line\n\n\topen(\"clean/listings.csv\", \"w\").write(\"\".join(raw_listings))\n\ndataset = pd.read_csv(\"clean/listings.csv\", sep=\";\")\n\n# Now we consider features as variables :\nnew_columns = []\n\ndef get_value_of(data, key):\n\treturn 0 if key not in data else data[key]\n\nkeywords = [ \"beds\", \"bedrooms\", \"bathrooms\", \"is_rebookable\", \"is_new_listing\", \"is_fully_refundable\", \"is_host_highly_rated\", \"is_business_travel_ready\" ]\n\nfor key in keywords:\n\tvalues = []\n\n\tfor i, row in dataset.iterrows():\n\t\trow_data = json.loads(row[\"features\"])\n\t\tvalues.append(get_value_of(row_data, key))\n\n\tdataset[key] = pd.Series(data=values)\n\n# Same of pricing factor : the more your journey is long, the less you pay per day\nkeywords = [ \"weekly_factor\", \"monthly_factor\" ]\n\nfor key in keywords:\n\tvalues = []\n\n\tfor i, row in dataset.iterrows():\n\t\trow_data = json.loads(row[\"pricing\"])\n\t\tvalues.append(get_value_of(row_data, key))\n\n\tdataset[\"pricing_\" + key] = pd.Series(data=values)\n\ndataset = dataset.drop([\"pricing\", \"pictures\", \"features\", \"host_id\", \"host_name\", \"host_data\"], axis=1)\nprint(dataset)\ndataset.to_csv(\"clean/listings_final.csv\", sep=\";\")\n","sub_path":"s1-data/raw_cleaning.py","file_name":"raw_cleaning.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"611331062","text":"\"\"\" Compiled: 2020-09-18 10:38:46 \"\"\"\n\n#__src_file__ = \"extensions/accounting/etc/FAccountingAISelectDialog.py\"\nimport acm\nimport FUxCore\n\n\ndef OnAccountingInstructionDoubleClick(dialog, cd):\n dialog.AddAccountingInstruction()\n\ndef OnSelectedAccountingInstructionDoubleClick(dialog, cd):\n dialog.RemoveAccountingInstruction()\n\ndef OnAddButton(dialog, cd):\n dialog.AddAccountingInstruction()\n\ndef OnRemoveButton(dialog, cd):\n dialog.RemoveAccountingInstruction()\n\ndef OnRemoveAllButton(dialog, cd):\n dialog.RemoveAllAccountingInstructions()\n\ndef OnCancelButton(dialog, cd):\n dialog.m_fuxDialog.CloseDialogCancel()\n\ndef GetLayoutBuilder():\n b = acm.FUxLayoutBuilder()\n b.BeginVertBox()\n b. BeginHorzBox()\n b. AddSpace(3)\n b. BeginVertBox()\n b. AddLabel('labelAccountingInstructions', 'Accounting Instructions')\n b. AddList('accountingInstructions', 10, -1, 30, -1)\n b. EndBox()\n b. BeginVertBox()\n b. AddFill()\n b. AddButton('addButton', 'Add')\n b. AddButton('removeButton', 'Remove')\n b. AddSpace(3)\n b. AddButton('removeAllButton', 'Remove All')\n b. AddFill()\n b. EndBox()\n b. AddSpace(2)\n b. BeginVertBox()\n b. AddLabel('labelSelectedAccountingInstructions', 'Selected Accounting Instructions')\n b. AddList('selectedAccountingInstructions', 10, -1, 30, -1)\n b. EndBox()\n b. AddSpace(3)\n b. EndBox()\n b. AddSpace(5)\n b. BeginHorzBox()\n b. AddFill()\n b. AddButton('ok', 'OK')\n b. AddButton('cancelButton', 'Cancel')\n b. AddSpace(3)\n b. EndBox()\n b.EndBox()\n return b\n\nclass AISelectionDialog(FUxCore.LayoutDialog):\n\n def __init__(self):\n\n self.m_accountingInstructions = None\n self.m_selectedAccountingInstructions = None\n self.m_addButton = None\n self.m_removeButton = None\n self.m_removeAllButton = None\n self.m_fuxDialog = None\n self.m_cancelButton = None\n self.aiList = acm.FArray()\n self.aiSelectedList = acm.FArray()\n\n def HandleCreate(self, dialog, layout):\n self.m_fuxDialog = dialog\n self.m_fuxDialog.Caption('Select Accounting Instructions')\n\n self.m_accountingInstructions = layout.GetControl('accountingInstructions')\n self.m_accountingInstructions.AddCallback('DefaultAction', OnAccountingInstructionDoubleClick, self)\n\n self.m_selectedAccountingInstructions = layout.GetControl('selectedAccountingInstructions')\n self.m_selectedAccountingInstructions.AddCallback('DefaultAction', OnSelectedAccountingInstructionDoubleClick, self)\n\n self.m_addButton = layout.GetControl('addButton')\n self.m_addButton.AddCallback('Activate', OnAddButton, self)\n\n self.m_removeButton = layout.GetControl('removeButton')\n self.m_removeButton.AddCallback('Activate', OnRemoveButton, self)\n\n self.m_removeAllButton = layout.GetControl('removeAllButton')\n self.m_removeAllButton.AddCallback('Activate', OnRemoveAllButton, self)\n\n self.m_addButton = layout.GetControl('cancelButton')\n self.m_addButton.AddCallback('Activate', OnCancelButton, self)\n\n self.LoadAccountingInstructions()\n\n def AddAccountingInstruction(self):\n ai = self.m_accountingInstructions.GetData()\n if ai:\n self.m_accountingInstructions.RemoveItem(ai)\n self.aiList.Remove(ai)\n self.aiSelectedList.Add(ai)\n self.m_selectedAccountingInstructions.Populate(self.aiSelectedList.SortByProperty('Name', True))\n\n def RemoveAccountingInstruction(self):\n ai = self.m_selectedAccountingInstructions.GetData()\n if ai:\n self.m_selectedAccountingInstructions.RemoveItem(ai)\n self.aiSelectedList.Remove(ai)\n self.aiList.Add(ai)\n self.m_accountingInstructions.Populate(self.aiList.SortByProperty('Name', True))\n\n def RemoveAllAccountingInstructions(self):\n self.aiList.AddAll(self.aiSelectedList)\n self.m_selectedAccountingInstructions.RemoveAllItems()\n self.m_accountingInstructions.Populate(self.aiList.SortByProperty('Name', True))\n self.aiSelectedList.Clear()\n\n def LoadAccountingInstructions(self):\n if 0 == self.aiList.Size() and 0 == self.aiSelectedList.Size():\n accountingInstructions = acm.FAccountingInstruction.Select('')\n sortedByName = accountingInstructions.SortByProperty('Name', True)\n self.aiList.AddAll(sortedByName)\n self.m_accountingInstructions.Populate(sortedByName)\n else:\n self.m_accountingInstructions.Populate(self.aiList.SortByProperty('Name', True))\n self.m_selectedAccountingInstructions.Populate(self.aiSelectedList.SortByProperty('Name', True))\n\n def GetSelectedAccountingInstructions(self):\n return self.aiSelectedList\n\ndef ShowDialog(shell, aiSelectionDialog):\n layoutBuilder = GetLayoutBuilder()\n acm.UX().Dialogs().ShowCustomDialogModal(shell, layoutBuilder, aiSelectionDialog)\n\n\n\n\n","sub_path":"Extensions/Default/FPythonCode/FAccountingAISelectDialog.py","file_name":"FAccountingAISelectDialog.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"496883176","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 9 15:46:08 2017\n\n@author: cartemic\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.close(\"all\")\n\n# input desired pipe ID and whether 'nearest' or 'minimum' is desired\nrequestedDiam = 6\ndiamType = 'nearest'\nschedule = '80'\nDLF = np.array([2, 4])\ntolPercent = 10\nshockPR = 44.23\nrelaxP = 1#0.4\nFS = 1.5\nT = np.linspace(0, 400, num=1000)\n\n# tension vs temperature\nASME = {}\nASME['maxTens'] = 1000 * np.array([16.7, 16.7, 14.1, 12.7, 11.7, 10.9, 10.4,\n 10.2, 10, 9.8, 9.6, 9.4, 9.2, 8.9, 8.8, 8,\n 7.9, 6.5, 6.4])\nASME['T'] = np.array([0, 100, 200, 300, 400, 500, 600, 650, 700, 750, 800, 850,\n 900, 950, 1000, 1050, 1100, 1150, 1200])\n\nmaxTens = np.interp(T, ASME['T'], ASME['maxTens'])\n\n\n# get dynamic load factor for a given pipe geometry\ndef getDLF(thk, OD, Dcj, plusOrMinus):\n plusOrMinus = plusOrMinus / 100\n h = thk * 0.0254\n R = np.average([OD, OD-2 * thk]) / 2 * 0.0254\n E = np.average([134, 152]) * 1e9\n rho = 7970\n nu = 0.27\n\n Vc0 = (\n (E**2 * h**2) /\n (3 * rho**2 * R**2 * (1-nu**2))\n )**(1/4)\n\n if Dcj >= (1-plusOrMinus) * Vc0 and Dcj <= (1+plusOrMinus) * Vc0:\n return(4.)\n elif Dcj < Vc0:\n return(1.)\n else:\n return(2.)\n\n\n# collect thicknesses at desired diameter\ndef getPmax(requestedID, diamType):\n NPS = np.array([1/2, 3/4, 1, 1+1/4, 1+1/2, 2, 2+1/2, 3, 4, 5, 6, 8, 10,\n 12])\n OD = np.array([0.84, 1.05, 1.315, 1.66, 1.9, 2.375, 2.875, 3.5, 4.5, 5.563,\n 6.625, 8.625, 10.75, 12.75])\n thkList = {'40': np.array([0.109, 0.113, 0.133, 0.14, 0.145, 0.154, 0.203,\n 0.216, 0.237, 0.258, 0.280, 0.322, 0.365, 0.406\n ]),\n '80': np.array([0.147, 0.154, 0.179, 0.191, 0.2, 0.218, 0.276,\n 0.300, 0.337, 0.375, 0.432, 0.5, 0.5, 0.5\n ]),\n '160': np.array([0.187, 0.219, 0.25, 0.25, 0.281, 0.344, 0.375,\n 0.438, 0.531, 0.625, 0.719, 0.906, 1.125, 1.312\n ]),\n 'XXS': np.array([0.294, 0.308, 0.358, 0.382, 0.4, 0.436, 0.552,\n 0.6, 0.674, 0.75, 0.864, 0.875, 1, 1\n ])\n }\n\n # determine thickness, diameter, and NPS\n t = {}\n selectedDiam = {}\n selectedNPS = {}\n if diamType == 'nearest' or diamType == 'closest':\n for k in thkList:\n # find ID closest to requested ID\n theIndex = np.abs((OD-2*thkList[k])-requestedID).argmin()\n selectedDiam[k] = OD[theIndex]\n selectedNPS[k] = NPS[theIndex]\n t[k] = thkList[k][theIndex]\n elif diamType == 'minimum':\n for k in thkList:\n # find first ID where ID >= requested ID\n theIndex = np.min([i for i in range(len(OD)) if\n OD[i] - 2 * thkList[k][i] >= requestedID])\n selectedDiam[k] = OD[theIndex]\n selectedNPS[k] = NPS[k]\n t[k] = thkList[k][theIndex]\n else:\n t = 0\n selectedDiam = 0.01\n selectedNPS = 0\n\n\n# collect thicknesses at desired diameter\ndef pipeSpecs(requestedID, diamType, schedule):\n NPS = np.array([1/2, 3/4, 1, 1+1/4, 1+1/2, 2, 2+1/2, 3, 4, 5, 6, 8, 10,\n 12])\n OD = np.array([0.84, 1.05, 1.315, 1.66, 1.9, 2.375, 2.875, 3.5, 4.5, 5.563,\n 6.625, 8.625, 10.75, 12.75])\n thkList = {'40': np.array([0.109, 0.113, 0.133, 0.14, 0.145, 0.154, 0.203,\n 0.216, 0.237, 0.258, 0.280, 0.322, 0.365, 0.406\n ]),\n '80': np.array([0.147, 0.154, 0.179, 0.191, 0.2, 0.218, 0.276,\n 0.300, 0.337, 0.375, 0.432, 0.5, 0.5, 0.5\n ]),\n '160': np.array([0.187, 0.219, 0.25, 0.25, 0.281, 0.344, 0.375,\n 0.438, 0.531, 0.625, 0.719, 0.906, 1.125, 1.312\n ]),\n 'XXS': np.array([0.294, 0.308, 0.358, 0.382, 0.4, 0.436, 0.552,\n 0.6, 0.674, 0.75, 0.864, 0.875, 1, 1\n ])\n }\n\n # determine thickness, diameter, and NPS\n if diamType == 'nearest' or diamType == 'closest':\n # find ID closest to requested ID\n theIndex = np.abs((OD-2*thkList[schedule])-requestedID).argmin()\n elif diamType == 'minimum':\n # find first ID where ID >= requested ID\n theIndex = np.min([i for i in range(len(OD)) if\n OD[i] - 2 * thkList[schedule][i] >= requestedID])\n else:\n return()\n\n selectedOD = OD[theIndex]\n selectedID = selectedOD - 2 * thkList[schedule][theIndex]\n selectedNPS = NPS[theIndex]\n h = thkList[schedule][theIndex]\n return{\n 'OD': selectedOD,\n 'ID': selectedID,\n 'h': h,\n 'NPS': selectedNPS\n }\n\n\n# plot minimum schedule values\npDesign = np.array(range(1, 8))\nfor factor in DLF:\n sched = [1000 * pressure * relaxP * FS * factor * shockPR * 14.7 /\n maxTens for pressure in pDesign]\n '''\n for i in range(len(sched)):\n for j in range(len(sched[i])):\n if sched[i][j] < 80:\n sched[i][j] = 80\n elif sched[i][j] < 160:\n sched[i][j] = 160\n else:\n sched[i][j] = 0\n '''\n plt.figure()\n [plt.plot(T, sched[i], label='P0 = {} atm'\n .format(pDesign[i])) for i in\n range(len(sched))]\n plt.grid('on')\n plt.xlim([0, 400])\n plt.ylim([0, 180])\n plt.xlabel('T (°F)')\n plt.ylabel('Minimum Schedule')\n plt.title('DLF = {}'.format(factor))\n plt.plot([0, 400], [80, 80], 'k')\n plt.plot([0, 400], [160, 160], 'k')\n plt.legend()\n\n# plot DLF\nDcj = np.linspace(1, 3, num=1000) * 1000\npipe = pipeSpecs(requestedDiam, diamType, schedule)\nDLF = [getDLF(pipe['h'], pipe['OD'], velocity, tolPercent) for velocity in Dcj]\nplt.figure()\nplt.plot(Dcj, DLF)\nplt.grid('on')\nplt.xlabel('$D_{CJ}$ (m/s)')\nplt.ylabel('DLF')\nplt.title('Dynamic Load Factor (Schedule {0} NPS {1}, tolerance $\\pm${2}%)'\n .format(schedule, pipe['NPS'], tolPercent))\n","sub_path":"pressAnalysis.py","file_name":"pressAnalysis.py","file_ext":"py","file_size_in_byte":6453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"544266474","text":"# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 et:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Helper functionality and overloads for paths treatment\n\nOne of the reasons is also to robustify operation with unicode filenames\n\"\"\"\n\n# TODO: RF and move all paths related functions from datalad.utils in here\nimport os\nimport os.path as op\n\n# to not pollute API importing as _\nfrom collections import defaultdict as _defaultdict\n\nfrom functools import wraps\nfrom itertools import dropwhile\n\nfrom ..utils import (\n ensure_bytes,\n getpwd,\n)\n\n\ndef _get_unicode_robust_version(f):\n\n @wraps(f)\n def wrapped(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except UnicodeEncodeError:\n return f(ensure_bytes(*args, **kwargs))\n doc = getattr(f, '__doc__', None)\n # adjust only if __doc__ is not completely absent (None)\n if doc is not None:\n wrapped.__doc__ = doc + \\\n \"\\n\\nThis wrapper around original function would encode forcefully \" \\\n \"to utf-8 if initial invocation fails\"\n return wrapped\n\n\nabspath = op.abspath\nbasename = op.basename\ncurdir = op.curdir\ndirname = op.dirname\nexists = _get_unicode_robust_version(op.exists)\nisdir = _get_unicode_robust_version(op.isdir)\nisabs = _get_unicode_robust_version(op.isabs)\njoin = op.join\nlexists = _get_unicode_robust_version(op.lexists)\nnormpath = op.normpath\npardir = op.pardir\npathsep = op.pathsep\nrelpath = op.relpath\nrealpath = _get_unicode_robust_version(op.realpath)\nsep = op.sep\n\n\ndef robust_abspath(p):\n \"\"\"A helper which would not fail if p is relative and we are in non-existing directory\n\n It will rely on getpwd, which would rely on $PWD env variable to report\n the path. Desired for improved resilience during e.g. reporting as in\n https://github.com/datalad/datalad/issues/2787\n \"\"\"\n try:\n return abspath(p)\n except OSError as exc:\n if not isabs(p):\n try:\n os.getcwd()\n # if no exception raised it was not the reason, raise original\n raise\n except:\n return normpath(join(getpwd(), p))\n raise\n\n\ndef split_ext(filename):\n \"\"\"Use git-annex's splitShortExtensions rule for splitting extensions.\n\n Parameters\n ----------\n filename : str\n\n Returns\n -------\n A tuple with (root, extension)\n\n Examples\n --------\n >>> from datalad.local.addurls import split_ext\n >>> split_ext(\"filename.py\")\n ('filename', '.py')\n\n >>> split_ext(\"filename.tar.gz\")\n ('filename', '.tar.gz')\n\n >>> split_ext(\"filename.above4chars.ext\")\n ('filename.above4chars', '.ext')\n \"\"\"\n parts = filename.split(\".\")\n if len(parts) == 1:\n return filename, \"\"\n\n tail = list(dropwhile(lambda x: len(x) < 5,\n reversed(parts[1:])))\n\n file_parts = parts[:1] + tail[::-1]\n ext_parts = parts[1+len(tail):]\n return \".\".join(file_parts), \".\" + \".\".join(ext_parts)\n\n\ndef get_parent_paths(paths, parents, only_with_parents=False):\n \"\"\"Given a list of children paths, return their parent paths among parents\n or their own path if there is no known parent. A path is also considered its\n own parent (haven't you watched Predestination?) ;)\n\n All paths should be POSIX, relative, and not pointing outside (not starting\n with ../)\n\n Accent is made on performance to avoid O(len(paths) * len(parents))\n runtime. ATM should be typically less than O(len(paths) * len(log(parents)))\n\n Initial intended use - for a list of paths in the repository\n to provide their paths as files/submodules known to that repository, to\n overcome difference in ls-tree and ls-files, where ls-files outputs nothing\n for paths within submodules.\n It is coded, so it could later be applied even whenever there are nested\n parents, e.g. parents = ['sub', 'sub/sub'] and then the \"deepest\" parent\n is selected\n\n Parameters\n ----------\n parents: list of str\n paths: list of str\n only_with_parents: bool, optional\n If set to True, return a list of only parent paths where that path had\n a parent\n\n Returns\n -------\n A list of paths (without duplicates), where some entries replaced with\n their \"parents\" without duplicates. So for 'a/b' and 'a/c' with a being\n among parents, there will be a single 'a'\n \"\"\"\n # Let's do an early check even though then we would skip the checks on paths\n # being relative etc\n if not parents:\n return [] if only_with_parents else paths\n\n # We will create a lookup for known parent lengths\n parents = set(parents) # O(log(len(parents))) lookup\n\n # rely on path[:n] be quick, and len(parent_lengths) << len(parents)\n # when len(parents) is large. We will also bail checking any parent of\n # the length if at that length path has no directory boundary ('/').\n #\n # Create mapping for each length of\n # parent path to list of parents with that length\n parent_lengths = _defaultdict(set)\n for parent in parents:\n _get_parent_paths_check(parent)\n parent_lengths[len(parent)].add(parent)\n\n # Make it ordered in the descending order so we select the deepest/longest parent\n # and store them as sets for faster lookup.\n # Could be an ordered dict but no need\n parent_lengths = [(l, parent_lengths[l]) for l in sorted(parent_lengths, reverse=True)]\n\n res = []\n seen = set()\n\n for path in paths: # O(len(paths)) - unavoidable but could be parallelized!\n # Sanity check -- should not be too expensive\n _get_parent_paths_check(path)\n for parent_length, parents_ in parent_lengths: # O(len(parent_lengths))\n if (len(path) < parent_length) or (len(path) > parent_length and path[parent_length] != '/'):\n continue # no directory deep enough\n candidate_parent = path[:parent_length]\n if candidate_parent in parents_: # O(log(len(parents))) but expected one less due to per length handling\n if candidate_parent not in seen:\n res.append(candidate_parent)\n seen.add(candidate_parent)\n break # it is!\n else: # no hits\n if not only_with_parents:\n if path not in seen:\n res.append(path)\n seen.add(path)\n\n return res\n\n\ndef _get_parent_paths_check(path):\n \"\"\"A little helper for get_parent_paths\"\"\"\n if isabs(path) or path.startswith(pardir + sep) or path.startswith(curdir + sep):\n raise ValueError(\"Expected relative within directory paths, got %r\" % path)\n\n","sub_path":"datalad/support/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":6946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"424297172","text":"#!/usr/bin/env python\ndef gitstop():\n import subprocess, signal, os\n # This will look at all the processs that are goin to your computer\n p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)\n out, err = p.communicate()\n\n # Loop through the split lines and checks if it contains the gitStarted.py\n for line in out.splitlines():\n if 'gitStarted.py' in line:\n # in the 0 index is the process Id and sets that to pid\n pid = int(line.split(None, 1)[0])\n # os.kill will stop the process with the process id we set\n os.kill(pid, signal.SIGKILL)\n\nif __name__ == '__main__':\n gitstop()","sub_path":"GitAutomated/scripts/gitStop.py","file_name":"gitStop.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"483251100","text":"import pymongo\nimport json\nimport math\n\nfrom Modules.setting import * # Import Settings\n\nclient = pymongo.MongoClient(database)\ndb = client.rangyibot\ncollection = db.user\n\n\nclass UserLevel:\n def levelIncrease(self, user, message):\n userid = user.id\n isLevelup = False\n result = collection.find_one({\"userid\": user.id})\n if not result:\n result = {\n \"userid\": user.id,\n \"level\": 1,\n \"currentxp\": 0\n }\n collection.insert_one(result)\n result['currentxp'] += len(message) // 4 + 1 \n targetExp = self.LevelExpGetter(result['level'])\n\n while result['currentxp'] > targetExp:\n result['level'] += 1\n targetExp = self.LevelExpGetter(result['level'])\n isLevelup = True\n collection.update_one({\"userid\": userid}, {\"$set\": result})\n return isLevelup\n\n def showLevel(self, user, isLevelUp=False):\n result = collection.find_one({\"userid\": user.id})\n if isLevelUp:\n strings = \":fireworks: **{}**가 **{} 레벨**이 되었느니라!!.\\n다음 레벨까지 **{} XP** 남았느니라~~\".format(user.name,\n result['level'],\n self.LevelExpGetter(\n result['level']) -\n result['currentxp'])\n else:\n strings = \"**{}**는 **{} 레벨**이니라~\\n다음 레벨까지 **{} XP** 남았느니라~~\".format(user.name, result['level'],\n self.LevelExpGetter(result['level']) -\n result['currentxp'])\n return strings\n\n def showRanking(self, server):\n members = [str(x.id) for x in list(server.members)]\n output = collection.find({\"userid\": {\"$in\": members}}).sort('currentxp', pymongo.DESCENDING)\n return output\n\n def LevelExpGetter(self, currentLevel):\n currentLevel += 1\n nextLevel = currentLevel ** 2\n nextLevel //= math.log2(nextLevel) / 2\n\n return int((currentLevel + 100) * math.sqrt(currentLevel))","sub_path":"Modules/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"463370379","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Blueprint, render_template, abort, flash\nfrom jinja2 import TemplateNotFound\n\nfrom admin.models import *\nfrom admin.transaction.models import Transaction\nfrom admin.buyer.models import Buyer\nfrom admin.product.models import Product\n\nadmin_transaction = Blueprint('admin_transaction', __name__, template_folder='templates')\n\n@admin_transaction.route('/', methods=['GET'])\n@admin_transaction.route('', methods=['GET'])\ndef all():\n data_transaction = Transaction.query.all()\n data_list = []\n data_list_single = {}\n results = {}\n for t in data_transaction:\n data_product = Product.query.filter_by(product_id = t.product_id).first()\n data_list_single['transaction_id'] = t.transaction_id\n data_list_single['buyer_name'] = Buyer.query.filter_by(buyer_id = t.buyer_id).first().name\n data_list_single['brand_name'] = Brand.query.filter_by(id = data_product.brand_id).first().name\n data_list_single['product_name'] = data_product.name\n data_list_single['product_stylenumber'] = data_product.stylenumber\n data_list_single['selling_price'] = t.selling_price\n data_list_single['buying_price'] = t.buying_price\n data_list_single['tracking_id'] = t.shipment_id\n data_list_single['buying_date'] = t.buying_date\n data_list_single['is_paid'] = t.is_paid\n\n data_list.append(data_list_single)\n results[\"list\"] = enumerate(data_list)\n\n try:\n return render_template('admin/transaction/all.html', results = results)\n except TemplateNotFound:\n abort(404)\n\n@admin_transaction.route('/insert/')\ndef transaction_insert():\n try:\n return render_template('admin/transaction/insert.html')\n except TemplateNotFound:\n abort(404)\n","sub_path":"admin/transaction/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"588484822","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nglobalDTwidth = 4.2\nglobalDTheight = 1.3\nSLgap = 29 - globalDTheight*8\n#NUMERO CELDAS\nnDTMB1 = 47\nnDTMB2 = 59\nnDTMB3 = 73\nnDTMB4 = 102\n\nclass Muon(object):\n def __init__(self, x0,y0, m):\n self.x0 = x0\n self.y0 = y0\n self.m = m\n self.cellHits = []\n self.semicells = []\n self.color = \"r-\"\n\n def getY(self, x, ydef):\n if self.m == 100000: \n return (abs(x - self.x0) < 0.05*globalDTwidth)*ydef + (abs(x - self.x0) > 0.05*globalDTwidth)*10000000000 \n\n return self.m*(x-self.x0) + self.y0\n def plot(self, xmin = 0., xmax= 600):\n xr = np.linspace(xmin, xmax, 10000)\n plt.plot(xr, self.getY(xr, 0.), self.color) \n\n def printHits(self):\n for l in self.cellHits:\n print (l.parent.idx, l.idx)\n\n def getPattern(self):\n self.pattern = []\n for i in range(len(self.cellHits)):\n self.pattern.append([self.cellHits[i].parent.idx, self.cellHits[i].idx, self.semicells[i]])\n return self.pattern\n\n def getRecoPattern(self):\n self.recopattern = []\n for i in range(len(self.cellHits)):\n self.recopattern.append([self.cellHits[i].parent.idx, self.cellHits[i].idx])\n return self.recopattern\n \n\n \n def getDriftTime(self):\n \n self.times=[]\n \n vDrift=0.054 #mm/ns\n \n for i in range(len(self.cellHits)):\n \n #z=[self.cellHits[i].parent.idx, self.cellHits[i].idx]\n if (self.cellHits[i].parent.idx > 4):\n ypos=(self.cellHits[i].parent.idx-1)*globalDTheight + globalDTheight/2 + SLgap\n else:\n \n ypos=(self.cellHits[i].parent.idx-1)*globalDTheight + globalDTheight/2\n \n \n if self.cellHits[i].parent.idx % 2 == 0:\n xpos_center=(self.cellHits[i].idx ) * globalDTwidth + globalDTwidth\n else:\n xpos_center=(self.cellHits[i].idx ) * globalDTwidth + globalDTwidth/2\n \n xpos_ray=(ypos-self.y0)/self.m + self.x0\n \n xpos= abs(xpos_ray - xpos_center)*10 #cm -> mm\n \n \n self.times.append([self.cellHits[i].parent.idx,self.cellHits[i].idx,xpos/vDrift])\n \n \n return self.times \n\nclass DT(object):\n def __init__(self,x,y,height,width, parent=0, idx=-1):\n self.xmin = x\n self.ymin = y\n self.height = height\n self.width = width\n self.idx = idx\n self.parent = parent\n self.muons = []\n self.isMIn = False\n\n def plot(self, doSemi = True):\n if self.isMIn:\n color = \"g-\"\n else:\n color = \"k-\"\n plt.plot([self.xmin, self.xmin + self.width], [self.ymin, self.ymin], color)\n plt.plot([self.xmin, self.xmin + self.width], [self.ymin + self.height, self.ymin + self.height], color)\n plt.plot([self.xmin, self.xmin], [self.ymin, self.ymin+ self.height], color)\n plt.plot([self.xmin + self.width, self.xmin + self.width], [self.ymin, self.ymin+ self.height], color)\n if doSemi:\n plt.plot([self.xmin + 0.5*self.width, self.xmin + 0.5*self.width], [self.ymin, self.ymin+ self.height], \"k--\")\n def isIn(self, muon):\n semicellIzq = False\n semicellDer = False\n #print \"First Checks\"\n if max(muon.getY(self.xmin, self.ymin + self.height/2.), muon.getY(self.xmin + self.width, self.ymin + self.height/2.)) < self.ymin or min(muon.getY(self.xmin, self.ymin + self.height/2.), muon.getY(self.xmin + self.width, self.ymin + self.height/2.)) > (self.ymin + self.height) and not(muon.m == 100000): return \n xr = np.linspace(self.xmin, self.xmin + self.width,100)\n #print \"All in\"\n yr = muon.getY(xr, self.ymin + self.height/2.)\n self.isMIn = any(np.array([ y >= self.ymin-0.01*self.height and y <= self.ymin+self.height*1.01 for y in yr]))\n xr = np.linspace(self.xmin, self.xmin + self.width/2.,100)\n #print \"SemiIzq\"\n yr = muon.getY(xr, self.ymin + self.height/2.)\n semicellIzq = any(np.array([ y >= self.ymin and y <= self.ymin+self.height for y in yr]))\n xr = np.linspace(self.xmin+ self.width/2., self.xmin + self.width,100)\n #print \"SemiDer\"\n yr = muon.getY(xr, self.ymin + self.height/2.)\n semicellDer = any(np.array([ y >= self.ymin and y <= self.ymin+self.height for y in yr]))\n \n if self.isMIn: \n self.muons.append(muon)\n muon.cellHits.append(self)\n if semicellIzq and semicellDer:\n muon.semicells.append(0.)\n elif semicellIzq:\n muon.semicells.append(-1.)\n elif semicellDer:\n muon.semicells.append(1.)\n\n def center(self):\n return self.xmin + self.width/2., self.ymin + self.height/2.\n\nclass Layer(object): \n def __init__(self,xoff,yoff,nDTs, along = \"X\", parent=0, idx=-1, offset=0):\n self.xmin = xoff\n self.ymin = yoff\n self.nDTs = nDTs\n self.along = along\n self.offset = offset\n self.createDTs(nDTs)\n self.parent = parent\n self.idx = idx\n\n def createDTs(self, nDT, height=globalDTheight, width = globalDTwidth):\n x = self.xmin\n y = self.ymin\n self.DTlist = []\n for i in range(nDT):\n self.DTlist.append(DT(x,y,height, width, self, idx=i-self.offset))\n if self.along == \"X\":\n x += width\n else:\n y += height \n\n if self.along == \"X\":\n y += height\n else:\n x += width\n self.width = x - self.xmin\n self.height = y - self.ymin\n\n def plot(self):\n for d in self.DTlist: d.plot()\n\nclass MB(object):\n def __init__(self, layers):\n self.layers = layers\n def plot(self):\n for l in self.layers: l.plot()\n def checkIn(self, muon):\n for l in self.layers:\n for d in l.DTlist:\n d.isIn(muon)\n \n\n#We need to add \"Fake\" cells behind/after for the training\nl1 = Layer(0,0,nDTMB1, idx=1)\nl2 = Layer(0.5*globalDTwidth,globalDTheight,nDTMB1, idx=2)\nl3 = Layer(0,2*globalDTheight,nDTMB1, idx=3)\nl4 = Layer(0.5*globalDTwidth,3*globalDTheight,nDTMB1, idx=4)\nll1 = Layer(0,4*globalDTheight + SLgap,nDTMB1, idx=5)\nll2 = Layer(0.5*globalDTwidth,5*globalDTheight + SLgap,nDTMB1, idx=6)\nll3 = Layer(0,6*globalDTheight + SLgap,nDTMB1, idx=7)\nll4 = Layer(0.5*globalDTwidth,7*globalDTheight + SLgap,nDTMB1, idx=8)\n\nMB1 = MB([l1,l2,l3,l4,ll1,ll2,ll3,ll4])\n\n##### Extra things ####\nl1 = Layer(0,0,nDTMB2)\nl2 = Layer(0.5*globalDTwidth,globalDTheight,nDTMB2)\nl3 = Layer(0,2*globalDTheight,nDTMB2)\nl4 = Layer(0.5*globalDTwidth,3*globalDTheight,nDTMB2)\nll1 = Layer(0,4*globalDTheight + SLgap,nDTMB2)\nll2 = Layer(0.5*globalDTwidth,5*globalDTheight + SLgap,nDTMB2)\nll3 = Layer(0,6*globalDTheight + SLgap,nDTMB2)\nll4 = Layer(0.5*globalDTwidth,7*globalDTheight + SLgap,nDTMB2)\n\nMB2 = MB([l1,l2,l3,l4,ll1,ll2,ll3,ll4])\n\nl1 = Layer(0,0,nDTMB3)\nl2 = Layer(0.5*globalDTwidth,globalDTheight,nDTMB3)\nl3 = Layer(0,2*globalDTheight,nDTMB3)\nl4 = Layer(0.5*globalDTwidth,3*globalDTheight,nDTMB3)\nll1 = Layer(0,4*globalDTheight + SLgap,nDTMB3)\nll2 = Layer(0.5*globalDTwidth,5*globalDTheight + SLgap,nDTMB3)\nll3 = Layer(0,6*globalDTheight + SLgap,nDTMB3)\nll4 = Layer(0.5*globalDTwidth,7*globalDTheight + SLgap,nDTMB3)\n\nMB3 = MB([l1,l2,l3,l4,ll1,ll2,ll3,ll4])\n\nl1 = Layer(0,0,nDTMB4)\nl2 = Layer(0.5*globalDTwidth,globalDTheight,nDTMB4)\nl3 = Layer(0,2*globalDTheight,nDTMB4)\nl4 = Layer(0.5*globalDTwidth,3*globalDTheight,nDTMB4)\nll1 = Layer(0,4*globalDTheight + SLgap,nDTMB4)\nll2 = Layer(0.5*globalDTwidth,5*globalDTheight + SLgap,nDTMB4)\nll3 = Layer(0,6*globalDTheight + SLgap,nDTMB4)\nll4 = Layer(0.5*globalDTwidth,7*globalDTheight + SLgap,nDTMB4)\n\nMB4 = MB([l1,l2,l3,l4,ll1,ll2,ll3,ll4])\n\n","sub_path":"stationsObjects.py","file_name":"stationsObjects.py","file_ext":"py","file_size_in_byte":8025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"178648296","text":"import boto3\n\n\nclass S3():\n \"\"\"\n S3 Client.\n \"\"\"\n\n _resource = None\n\n @classmethod\n def get_resource(cls):\n \"\"\"\n Get boto3 client for S3.\n\n Usage::\n >>> from jeffy.sdk.sns import S3\n >>> S3.get_resource().upload_file(...)\n \"\"\"\n if S3._resource is None:\n S3._resource = boto3.client('s3')\n return S3._resource\n\n @classmethod\n def upload_file(cls, file_path: str, bucket_name: str, object_name: str, correlation_id: str = ''):\n \"\"\"\n Upload file to S3 bucket with correlationid.\n\n Usage::\n >>> from jeffy.sdk.s3 import S3\n >>> S3.upload_file(...)\n \"\"\"\n return cls.get_resource().upload_file(\n Filename=file_path,\n Bucket=bucket_name,\n Key=object_name,\n ExtraArgs={'Metadata': {'correlation_id': correlation_id}}\n )\n","sub_path":"jeffy/sdk/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"526603184","text":"import re\r\n\r\n#access keys\r\nACCESS_TOKEN = '62108407-zM4ZH0vaUKrRJ5U8KpX5iZHAWNNzb88orn3zHilis'\r\nACCESS_SECRET = 'puMdX9rKPTxW7YzF9jqQAgmFpzmlWgwG1BinCj6FoauvR'\r\nCONSUMER_KEY = 'QUZcKtPF3TQ0dGgnmCW2H1Bfd'\r\nCONSUMER_SECRET = 'WBW09ApG9CNpvb1ERZIkIgS6TYaZ1nrTeFsc5Y9diZZHxwhJfl'\r\n\r\n#query parameters\r\nlatitude = 41.4951147\t# geographical centre of search\r\nlongitude = -81.8459461\t# geographical centre of search\r\nmax_range = 100\t\t\t# search range in kilometres\r\nnum_results = 100000\t# minimum results to obtain\r\nqueries = \"#lebronjames OR #lebron OR lebron OR @kingjames\"\r\nqueries = \"#stephencurry OR #curry OR stephen curry OR curry OR steph curry OR @StephenCurry30\"\r\nqueries = \"#kyrieirving OR #irving OR kyrie irving OR irving OR @KyrieIrving\"\r\nqueries = \"#cavs OR #cavaliers OR cavs OR cavaliers OR @cavs\"\r\nqueries = \"#warriors OR #goldenstate OR warriors OR goldenstate OR @warriors\"\r\nqueries = \"#nbafinals OR #nba OR nbafinals OR nba finals OR nba\"\r\n\r\n#database name\r\ndb_name = \"twitter_\"+ re.findall('#(\\S+)\\s',queries)[0]\r\n\r\nday_ago_start, day_ago_end = 4,2\r\n\r\nprojection = {'user.name':1,\"geo\":1,\"_id\":0,'created_at':1,'text':1\r\n ,'place.full_name':1,'place.country_code':1}\r\nquery = {}\r\n\r\n","sub_path":"nsq/twitter_search-master/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"484542056","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport BornSeries\nimport LSEsolver\n\n\ndef potential(x):\n return (x < -potentialWidth / 2) * 0 + \\\n (x >= -potentialWidth / 2) * (x <= potentialWidth / 2) * potentialStrength + \\\n (x > potentialWidth / 2) * 0\n\n\ndef analyticScatteringCoefficients(k, V0, L):\n rho = np.sqrt(1 - V0 / k ** 2)\n T = 4 * rho ** 2 / ((1 - rho ** 2) ** 2 * (np.sin(np.sqrt(k ** 2 - V0) * L)) ** 2 + 4 * rho ** 2)\n return 1.0 - T, T\n\n\n## system parameters\ngridLength = 10.0\nnGridPoints = 201\npotentialWidth = 2.5\npotentialStrength = -2.5\nnumberWaveVectors = 200\n\nkConvergence = np.abs(potentialStrength) * potentialWidth * 0.5\n\n## calculation\n# order = np.linspace(0, 9, 10, dtype=int)\npotentialWell = BornSeries.BornSeries(gridLength, nGridPoints, potential)\norder = np.array([1, 2, 5, 10, 20, 50])\n\npotentialWell_LSE = LSEsolver.LSE(gridLength, nGridPoints, potential)\n_, _, T_LSE = potentialWell_LSE.scatteringCoefficients(0.1, 5, numberWaveVectors)\n\nfig = plt.figure(0)\nfor i in range(len(order)):\n k, R, T = potentialWell.scatteringCoefficients(0.1, 5, numberWaveVectors, order[i])\n plt.plot(k, T, label=r'order' + str(order[i]), lw=0.5)\nanalyticR, analyticT = analyticScatteringCoefficients(k, potentialStrength, potentialWidth)\nplt.plot(k, analyticT, label='analytic solution', lw=1)\nplt.plot(k, T_LSE, label=r'LSE', ls='', marker='x', markersize=1.2)\nplt.plot([kConvergence, kConvergence], [0.0, 1.5], label=r'$k_{min} = V_{0} L / 2$', ls='-.', lw=0.5, c='r')\nplt.ylim([0, 1.5])\nplt.xlabel(r'k')\nplt.ylabel(r'analytic / numeric transmission coefficient')\nplt.legend(loc=0)\nplt.title(\n r'Transmission coefficinets: analytic vs. numeric calculation' + '\\n' + r'$V_{0}$ = ' + str(potentialStrength) +\n r', $L = $' + str(potentialWidth))\nplt.savefig(\"bornSeries_transmissionCoefficients_orderSeries_2.pdf\", bbox_inches='tight')\n\nplt.show()\n","sub_path":"bornSeries_transmissionCoefficients.py","file_name":"bornSeries_transmissionCoefficients.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"601554608","text":"# import mantid algorithms, numpy and matplotlib\nfrom mantid.simpleapi import *\nfrom mantid.kernel import FloatTimeSeriesProperty\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#ws = LoadMD('HB3A_data.nxs')\nws = LoadMD('HB3A_exp0724_scan0182.nxs')\nSetGoniometer(ws, Axis0='omega,0,1,0,-1', Axis1='chi,0,0,1,-1', Axis2='phi,0,1,0,-1', Average=False)\nr = ws.getExperimentInfo(0).run()\nfor i in range(r.getNumGoniometers()):\n print(i,r.getGoniometer(i).getEulerAngles('YZY'))\n\nws = LoadILLDiffraction(Filename='ILL/D20/000017.nxs')\nSetGoniometer(ws, Axis0='omega.position,0,1,0,1', Average=False)\nfor i in range(ws.run().getNumGoniometers()):\n print(f'{i} omega = {ws.run().getGoniometer(i).getEulerAngles(\"YZY\")[0]:.1f}')\n\nSetGoniometer(ws, Axis0='omega.position,0,1,0,1')\nfor i in range(ws.run().getNumGoniometers()):\n print(f'{i} omega = {ws.run().getGoniometer(i).getEulerAngles(\"YZY\")[0]:.1f}')\n\n\nws=LoadMD('ExternalData/Testing/Data/SystemTest/HB2C_WANDSCD_data.nxs')\ns1 = ws.getExperimentInfo(0).run().getLogData('s1').value\n\ns1_log = FloatTimeSeriesProperty('s1')\nfor n, v in enumerate(s1):\n s1_log.addValue(n*1e6,v)\nws.getExperimentInfo(0).run()['s1'] = s1_log\nws.getExperimentInfo(0).run().getProperty('s1').units = 'deg'\n\nSetGoniometer(ws, Axis0='s1,0,1,0,1', Average=False)\n\nr = ws.getExperimentInfo(0).run()\nfor i in range(r.getNumGoniometers()):\n print(f'{i} omega = {r.getGoniometer(i).getEulerAngles(\"YZY\")[0]:.1f}')\n","sub_path":"multig.py","file_name":"multig.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"135509337","text":"#load-diabetes - DNN\n\nimport numpy as np\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n# from sklearn.datasets import load_diabetes #load_diabetes 당뇨병데이터\n\n#1. 데이터\n# Attribute Information (in order):\n# 0 - age 나이\n# 1 - sex 성별\n# 2 - bmi bmi 체질량 지수\n# 3 - bp bp 평균 혈압\n# 4 - s1 tc T- 세포 (백혈구의 일종)\n# 5 - s2 ldl 저밀도 지단백질\n# 6 - s3 hdl 고밀도 지단백질\n# 7 - s4 tch 갑상선 자극 호르몬\n# 8 - s5 ltg 라모트리진\n# 9 - s6 glu 혈당 수치\n# 10 - target 1년 후 질병 진행의 측정\n\n# dataset = load_diabetes()\n# x = dataset.data #(442,10), 인덱스 0~9의 값\n# y = dataset.target #(442,), 인덱스 10의 값- 1년 후 당뇨병 진행의 측정\n# #x의 데이터로 1년 후 당뇨병 진행을 측정하는 데이터셋이다.\n\n# from sklearn.model_selection import train_test_split\n# x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8) \n\nx_train = np.load('./data/npy/diabetes_x_train.npy')\nx_test = np.load('./data/npy/diabetes_x_test.npy')\ny_train = np.load('./data/npy/diabetes_y_train.npy')\ny_test = np.load('./data/npy/diabetes_y_test.npy')\n\n\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nscaler = MinMaxScaler()\nscaler.fit(x_train)\nx_train_standard = scaler.transform(x_train) \nx_test_standard = scaler.transform(x_test)\n\n#2. 모델 구성\nmodel = Sequential()\nmodel.add(Dense(200, activation='relu', input_shape=(10,)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(180, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(150, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(110, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(60, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1))\nmodel.summary()\n\nmodel.save('./save/diabetes_DNN_model.h5')\n\n#3. 컴파일, 훈련\nmodelpath = './model/diabetes_DNN-{epoch:02d}-{val_loss:.4f}.hdf5' # hdf5의 파일, {epoch:02d} - epoch의 2자리의 정수, {val_loss:.4f} - val_loss의 소수넷째자리까지가 네이밍됨\nmodel.compile(loss='mse', optimizer='adam', metrics=['acc'])\n\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint #ModelCheckpoint 추가\nearly_stopping = EarlyStopping(monitor='val_loss', patience=20, mode='min') \ncheck_point = ModelCheckpoint(filepath=modelpath, monitor='val_loss', save_best_only=True, mode='min')\n\nhist = model.fit(x_train_standard, y_train, epochs=500, batch_size=32, verbose=1, validation_split=0.2, callbacks=[early_stopping, check_point])\n\nmodel.save('./save/diabetes_DNN_model_fit.h5')\nmodel.save_weights('./save/diabetes_DNN_model_weight.h5')\n\nloss = hist.history['loss']\nval_loss = hist.history['val_loss']\nacc = hist.history['acc']\nval_acc = hist.history['val_acc']\n\n#4. 평가, 예측\nresult = model.evaluate(x_test_standard, y_test, batch_size=32)\nprint(\"loss : \", result[0])\nprint(\"acc : \", result[1])\n\ny_predict = model.predict(x_test_standard)\nprint(\"y_test : \", y_test)\nprint(\"y_predict : \\n\", np.round(y_predict.reshape(89,),1))\n\nfrom sklearn.metrics import mean_squared_error, r2_score\n\ndef RMSE(y_test, y_predict):\n return np.sqrt(mean_squared_error(y_test, y_predict))\nprint(\"RMSE : \", RMSE(y_test, y_predict))\n\nr2 = r2_score(y_test, y_predict)\nprint(\"R2 : \", r2)\n\n# 시각화\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(10,6)) #단위 무엇인지 찾아보기\nplt.subplot(2,1,1) #2장(2행1열) 중 첫번째\nplt.plot(hist.history['loss'], marker='.', c='red', label='loss')\nplt.plot(hist.history['val_loss'], marker='.', c='blue', label='val_loss')\nplt.grid()\nplt.title('loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(loc='upper right')\n\nplt.subplot(2,1,2) #2장(2행1열) 중 두번째\nplt.plot(hist.history['acc'], marker='.', c='red')\nplt.plot(hist.history['val_acc'], marker='.', c='blue')\nplt.grid()\nplt.title('acc')\nplt.ylabel('acc')\nplt.xlabel('epoch')\nplt.legend(['acc', 'val_acc'])\n\nplt.show()\n\n# 결과값\n# loss : 3101.2724609375\n# acc : 0.0\n# y_test : [ 69. 214. 179. 209. 59. 107. 235. 182. 96. 135. 200. 100. 253. 37.\n# 51. 174. 144. 68. 138. 86. 72. 89. 124. 147. 78. 118. 111. 90.\n# 303. 143. 65. 341. 262. 138. 91. 103. 132. 88. 83. 142. 311. 202.\n# 197. 321. 59. 244. 144. 229. 65. 233. 132. 115. 96. 196. 232. 48.\n# 92. 197. 137. 261. 58. 90. 72. 186. 77. 85. 173. 252. 53. 110.\n# 85. 187. 217. 83. 135. 236. 60. 273. 180. 93. 200. 163. 257. 104.\n# 91. 151. 125. 55. 258.]\n# y_predict :\n# [120. 129.6 156.9 147.3 154.5 160.9 155.2 125.9 85.3 115.7 128.9 149.5\n# 127.6 69.9 68.6 164.1 150. 149. 168.2 154.8 64. 114.1 110.9 161.4\n# 182.1 98.7 115. 125.4 239.2 75.9 66.9 236.4 145.3 71. 105.3 159.4\n# 125.4 109.3 62.5 133.8 167.4 121.1 152. 231.9 112.7 165.9 142.6 167.2\n# 86.1 193.5 228.7 101.2 74.7 176.3 213.9 85.2 118.8 201.7 170.8 212.\n# 141.9 161.8 84. 194.9 78.7 137.5 171.9 140.7 124.9 163.8 88. 126.\n# 184.4 126.9 96.5 216. 120.6 243. 150.4 82.4 192.1 211.9 170.4 65.4\n# 163.8 161. 92.9 161.9 259.7]\n# RMSE : 55.68906880321059\n# R2 : 0.4278195456121182","sub_path":"keras/keras57_6_load_npy_diabetes.py","file_name":"keras57_6_load_npy_diabetes.py","file_ext":"py","file_size_in_byte":5330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"122228438","text":"import os\nimport sys\nimport leds\nimport display\nimport buttons\n\nsys.path.append('/apps/digiclk/')\nimport monotime as utime\nimport draw\n\nDIGITS = [\n (True, True, True, True, True, True, False),\n (False, True, True, False, False, False, False),\n (True, True, False, True, True, False, True),\n (True, True, True, True, False, False, True),\n (False, True, True, False, False, True, True),\n (True, False, True, True, False, True, True),\n (True, False, True, True, True, True, True),\n (True, True, True, False, False, False, False),\n (True, True, True, True, True, True, True),\n (True, True, True, True, False, True, True)\n]\n\ndef renderNum(d, num, x):\n draw.Grid7Seg(d, x, 0, 7, DIGITS[num // 10], (255, 255, 255))\n draw.Grid7Seg(d, x + 5, 0, 7, DIGITS[num % 10], (255, 255, 255))\n\ndef renderColon(d):\n draw.GridVSeg(d, 11, 2, 7, 2, (255, 255, 255))\n draw.GridVSeg(d, 11, 4, 7, 2, (255, 255, 255))\n\ndef renderText(d, text, blankidx = None):\n bs = bytearray(text)\n\n if blankidx != None:\n bs[blankidx:blankidx+1] = b'_'\n\n d.print(MODES[MODE] + ' ' + bs.decode(), fg = (255, 255, 255), bg = None, posx = 0, posy = 7 * 8)\n\ndef renderBar(d, num):\n d.rect(20, 78, 20 + num * 2, 80, col = (255, 255, 255))\n\ndef render(d):\n ltime = utime.localtime()\n years = ltime[0]\n months = ltime[1]\n days = ltime[2]\n hours = ltime[3]\n mins = ltime[4]\n secs = ltime[5]\n\n d.clear()\n\n if MODE == CHANGE_YEAR:\n renderNum(d, years // 100, 1)\n renderNum(d, years % 100, 13)\n elif MODE == CHANGE_MONTH:\n renderNum(d, months, 13)\n elif MODE == CHANGE_DAY:\n renderNum(d, days, 13)\n else:\n renderNum(d, hours, 1)\n renderNum(d, mins, 13)\n\n if MODE not in (CHANGE_YEAR, CHANGE_MONTH, CHANGE_DAY) and secs % 2 == 0:\n renderColon(d)\n\n renderText(d, NAME, None)\n renderBar(d, secs)\n\n d.update()\n\nLONG_DELAY = 400\nBUTTON_UPDATE_TIME = 100\nBUTTON_SEL = 1 << 0\nBUTTON_SEL_LONG = 1 << 1\nBUTTON_UP = 1 << 2\nBUTTON_UP_LONG = 1 << 3\nBUTTON_DOWN = 1 << 4\nBUTTON_DOWN_LONG = 1 << 5\npressed_prev = 0\nbutton_long_prev = {\n BUTTON_SEL: False,\n BUTTON_UP: False,\n BUTTON_DOWN: False\n}\nbutton_times = {\n BUTTON_SEL: 0,\n BUTTON_UP: 0,\n BUTTON_DOWN: 0\n}\ndef checkButton(button, button_long, osbutton, pressed, t):\n cur_buttons = 0\n\n if pressed & osbutton and not pressed_prev & osbutton:\n button_times[button] = t\n button_long_prev[button] = False\n elif pressed_prev & osbutton:\n if button_times[button] + LONG_DELAY < t:\n cur_buttons |= button_long\n button_times[button] = t\n button_long_prev[button] = True\n elif not pressed & osbutton and not button_long_prev[button]:\n cur_buttons |= button\n\n return cur_buttons\n\ndef checkButtons():\n global pressed_prev\n\n t = utime.time_monotonic_ms()\n pressed = buttons.read(buttons.BOTTOM_LEFT | buttons.TOP_RIGHT | buttons.BOTTOM_RIGHT)\n cur_buttons = 0\n\n cur_buttons |= checkButton(BUTTON_SEL, BUTTON_SEL_LONG, buttons.BOTTOM_LEFT, pressed, t)\n cur_buttons |= checkButton(BUTTON_UP, BUTTON_UP_LONG, buttons.TOP_RIGHT, pressed, t)\n cur_buttons |= checkButton(BUTTON_DOWN, BUTTON_DOWN_LONG, buttons.BOTTOM_RIGHT, pressed, t)\n\n pressed_prev = pressed\n return cur_buttons\n\ndef modTime(yrs, mth, day, hrs, mns, sec):\n ltime = utime.localtime()\n new = utime.mktime((ltime[0] + yrs, ltime[1] + mth, ltime[2] + day, ltime[3] + hrs, ltime[4] + mns, ltime[5] + sec, None, None))\n utime.set_time(new)\n\ndef ctrl_display(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = CHANGE_HOURS\n else:\n updated = False\n\ndef ctrl_chg_hrs(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = DISPLAY\n elif bs & BUTTON_SEL:\n MODE = CHANGE_MINUTES\n elif bs & BUTTON_UP_LONG:\n modTime(0, 0, 0, 10, 0, 0)\n elif bs & BUTTON_DOWN_LONG:\n modTime(0, 0, 0, -10, 0, 0)\n elif bs & BUTTON_UP:\n modTime(0, 0, 0, 1, 0, 0)\n elif bs & BUTTON_DOWN:\n modTime(0, 0, 0, -1, 0, 0)\n else:\n updated = False\n\ndef ctrl_chg_mns(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = DISPLAY\n elif bs & BUTTON_SEL:\n MODE = CHANGE_SECONDS\n elif bs & BUTTON_UP_LONG:\n modTime(0, 0, 0, 0, 10, 0)\n elif bs & BUTTON_DOWN_LONG:\n modTime(0, 0, 0, 0, -10, 0)\n elif bs & BUTTON_UP:\n modTime(0, 0, 0, 0, 1, 0)\n elif bs & BUTTON_DOWN:\n modTime(0, 0, 0, 0, -1, 0)\n else:\n updated = False\n\ndef ctrl_chg_sec(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = DISPLAY\n elif bs & BUTTON_SEL:\n MODE = CHANGE_YEAR\n elif bs & BUTTON_UP_LONG:\n modTime(0, 0, 0, 0, 0, 10)\n elif bs & BUTTON_DOWN_LONG:\n modTime(0, 0, 0, 0, 0, -10)\n elif bs & BUTTON_UP:\n modTime(0, 0, 0, 0, 0, 1)\n elif bs & BUTTON_DOWN:\n modTime(0, 0, 0, 0, 0, -1)\n else:\n updated = False\n\ndef ctrl_chg_yrs(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = DISPLAY\n elif bs & BUTTON_SEL:\n MODE = CHANGE_MONTH\n elif bs & BUTTON_UP_LONG:\n modTime(10, 0, 0, 0, 0, 0)\n elif bs & BUTTON_DOWN_LONG:\n modTime(-10, 0, 0, 0, 0, 0)\n elif bs & BUTTON_UP:\n modTime(1, 0, 0, 0, 0, 0)\n elif bs & BUTTON_DOWN:\n modTime(-1, 0, 0, 0, 0, 0)\n else:\n updated = False\n\ndef ctrl_chg_mth(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = DISPLAY\n elif bs & BUTTON_SEL:\n MODE = CHANGE_DAY\n elif bs & BUTTON_UP_LONG:\n modTime(0, 6, 0, 0, 0, 0)\n elif bs & BUTTON_DOWN_LONG:\n modTime(0, -6, 0, 0, 0, 0)\n elif bs & BUTTON_UP:\n modTime(0, 1, 0, 0, 0, 0)\n elif bs & BUTTON_DOWN:\n modTime(0, -1, 0, 0, 0, 0)\n else:\n updated = False\n\ndef ctrl_chg_day(bs):\n global MODE, updated\n updated = True\n if bs & BUTTON_SEL_LONG:\n MODE = DISPLAY\n elif bs & BUTTON_SEL:\n MODE = CHANGE_HOURS\n elif bs & BUTTON_UP_LONG:\n modTime(0, 0, 10, 0, 0, 0)\n elif bs & BUTTON_DOWN_LONG:\n modTime(0, 0, -10, 0, 0, 0)\n elif bs & BUTTON_UP:\n modTime(0, 0, 1, 0, 0, 0)\n elif bs & BUTTON_DOWN:\n modTime(0, 0, -1, 0, 0, 0)\n else:\n updated = False\n\nNAME = None\nFILENAME = 'nickname.txt'\ndef load_nickname():\n global NAME\n if FILENAME in os.listdir('.'):\n with open(\"nickname.txt\", \"rb\") as f:\n name = f.read().strip()\n else:\n name = b'no nick'\n\n if len(name) > 7:\n name = name[0:7]\n else:\n name = b' ' * (7 - len(name)) + name\n\n NAME = name\n\n# MODE values\nDISPLAY = 0\nCHANGE_HOURS = 1\nCHANGE_MINUTES = 2\nCHANGE_SECONDS = 3\nCHANGE_YEAR = 4\nCHANGE_MONTH = 5\nCHANGE_DAY = 6\n\nMODE = DISPLAY\nMODES = {\n DISPLAY: '---',\n CHANGE_HOURS: 'HRS',\n CHANGE_MINUTES: 'MNS',\n CHANGE_SECONDS: 'SEC',\n CHANGE_YEAR: 'YRS',\n CHANGE_MONTH: 'MTH',\n CHANGE_DAY: 'DAY',\n}\nupdated = False\n\nCTRL_FNS = {\n DISPLAY: ctrl_display,\n CHANGE_HOURS: ctrl_chg_hrs,\n CHANGE_MINUTES: ctrl_chg_mns,\n CHANGE_SECONDS: ctrl_chg_sec,\n CHANGE_YEAR: ctrl_chg_yrs,\n CHANGE_MONTH: ctrl_chg_mth,\n CHANGE_DAY: ctrl_chg_day,\n}\n\ndef main():\n global updated\n try:\n load_nickname()\n with display.open() as d:\n last_secs, secs = 0, 0\n last_msecs, msecs = 0, 0\n while True:\n updated = False\n\n bs = checkButtons()\n CTRL_FNS[MODE](bs)\n\n last_secs, secs = secs, utime.time_monotonic()\n if updated or secs > last_secs:\n render(d)\n\n last_msecs, msecs = msecs, utime.time_monotonic_ms()\n if msecs - last_msecs < BUTTON_UPDATE_TIME:\n utime.sleep_ms(BUTTON_UPDATE_TIME - (msecs - last_msecs))\n except KeyboardInterrupt:\n pass\n\nmain()\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"534466925","text":"#!/usr/bin/env python3\n\"\"\"PCA9685 / pigpio unified interface\"\"\"\n__author__ = \"Daniel Casner <www.danielcasner.org>\"\n\nimport pigpio\nfrom PCA9685_pigpio import PCA9685\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nclass GpioNumException(Exception):\n pass\n\nclass PCA9685Pi(pigpio.pi):\n \"Subclass for pigpio Pi interface with unified PCA9685 control\"\n \n EXTENDER_OFFSET = 0x100\n EXTENDER_MASK = 0xF00\n EXTENDER_SHIFT = 8\n GPIO_MASK = 0x0FF\n \n def __init__(self, i2c_bus=1, extender_addresses=[PCA9685.PCA9685_ADDRESS], *args, **kwargs):\n pigpio.pi.__init__(self, *args, **kwargs)\n self.extenders = [PCA9685.PCA9685(addr, self, i2c_bus) for addr in extender_addresses]\n\n def _extendedGPIO(self, gpioNum):\n \"Returns the extender index (or None) and gpio number\"\n if gpioNum & self.EXTENDER_MASK == 0:\n return None, gpioNum\n else:\n extInd = (gpioNum >> self.EXTENDER_SHIFT) - 1\n if extInd > len(self.extenders):\n raise GpioNumException(\"No extender that high\", gpioNum)\n elif (gpioNum & self.GPIO_MASK) >= PCA9685.NUM_CHANNELS:\n raise GpioNumException(\"Invalid gpio number\", gpioNum)\n else:\n return self.extenders[extInd], gpioNum & self.GPIO_MASK\n\n def set_PWM_frequency(self, user_gpio, frequency):\n try:\n extender, gpioNum = self._extendedGPIO(user_gpio)\n except GpioNumException as e:\n logger.warn(str(e))\n return pigpio.PI_BAD_USER_GPIO\n else:\n if extender is None:\n return pigpio.pi.set_PWM_frequency(self, user_gpio, frequency)\n elif user_gpio & self.GPIO_MASK != 0:\n logger.error(\"Extender PWM frequency can only be set on base extender address\")\n return pigpio.PI_BAD_USER_GPIO\n else:\n return extender.set_pwm_freq(frequency)\n \n def set_PWM_range(self, user_gpio, range):\n try:\n extender, gpioNum = self._extendedGPIO(user_gpio)\n except GpioNumException as e:\n logger.warn(str(e))\n return pigpio.PI_BAD_USER_GPIO\n else:\n if extender is None:\n return pigpio.pi.set_PWM_range(self, user_gpio, range)\n else:\n return extender.set_pwm_range(gpioNum, range)\n \n def get_PWM_range(self, user_gpio):\n try:\n extender, gpioNum = self._extendedGPIO(user_gpio)\n except GpioNumException as e:\n logger.warn(str(e))\n return pigpio.PI_BAD_USER_GPIO\n else:\n if extender is None:\n return pigpio.pi.get_PWM_range(self, user_gpio)\n else:\n return extender.get_pwm_range(gpioNum)\n \n def set_PWM_dutycycle(self, user_gpio, dutycycle, delay=0):\n try:\n extender, gpioNum = self._extendedGPIO(user_gpio)\n except GpioNumException as e:\n logger.warn(str(e))\n return pigpio.PI_BAD_USER_GPIO\n else:\n if extender is None:\n return pigpio.pi.set_PWM_dutycycle(self, user_gpio, dutycycle)\n else:\n dutyRange = extender.get_pwm_range(gpioNum)\n if dutycycle > dutyRange:\n return pigpio.PI_BAD_DUTYCYCLE\n elif delay > dutyRange:\n return pigpio.PI_BAD_DUTYCYCLE\n else:\n on = delay\n off = (dutycycle + delay) % (dutyRange+1)\n return extender.set_pwm(gpioNum, on, off)\n\n def write(self, gpio, level):\n try:\n extender, gpioNum = self._extendedGPIO(gpio)\n except GpioNumException as e:\n logger.warn(str(e))\n return pigpio.PI_BAD_USER_GPIO\n else:\n if extender is None:\n return pigpio.pi.write(self, gpio, level)\n else:\n return extender.set(gpioNum, level)\n","sub_path":"PCA9685_pigpio.py","file_name":"PCA9685_pigpio.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"52208250","text":"# encoding: utf-8\n\nimport numpy as np\n\n# Bind question text with alternatives text\ndef bind_question_text_alternatives(question):\n s = question[\"question_text\"]\n for alternative in question[\"options\"]:\n s = s + \" \" + alternative[\"text\"]\n return s\n\n# Convert each set of tokens into a data vector\ndef tokens_to_vector(tokens, label, word_index_map):\n row_vec = np.zeros(len(word_index_map) + 1) # setting bag of words frequency then increase last column for true label\n for t in tokens:\n i = word_index_map[t]\n row_vec[i] += 1\n\n if row_vec.sum() > 0:\n row_vec = row_vec / row_vec.sum() # normalize it before setting true label\n row_vec[-1] = label\n\n # index = 0\n # for w_vec_qty in row_vec:\n # if np.isnan(w_vec_qty):\n # print(index, w_vec_qty)\n # index += 1\n\n return row_vec\n\ndef hasNumbers(s):\n return any(c.isdigit() for c in s)\n\n","sub_path":"training/misc_snippets.py","file_name":"misc_snippets.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"366173079","text":"import logging\nimport random\nfrom ciphers import Cipher\nfrom helper_functions import divide_by_five, remove_encryption_spaces\n\nlogging.basicConfig(filename=\"cipherlogs.log\", level=logging.INFO)\n\n\nclass Alberti(Cipher):\n \"\"\"Encodes a message by using two different lists of letters / characters and matching the index value of the \"movable\" list to that of the fixed\"\"\"\n\n encrpyted_message = []\n\n fixed = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"i\", \"l\", \"m\", \"n\",\n \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"v\", \"x\", \"z\",\n 1, 2, 3, 4]\n\n movable = [\"d\", \"l\", \"g\", \"a\", \"z\", \"e\", \"n\", \"b\", \"o\", \"s\",\n \"f\", \"c\", \"h\", \"t\", \"y\", \"q\", \"i\", \"x\", \"k\", \"v\",\n \"p\", \"&\", \"m\", \"r\"]\n\n digraph = {\"h\":\"f\",\n \"j\":\"i\",\n \"k\":\"q\",\n \"u\":\"v\",\n \"w\":\"x\",\n \"y\":\"z\"\n }\n\n pointer = \"k\"\n shift_range = 5\n\n @classmethod\n def create_alberti(cls, *args, **kwargs):\n \"\"\"creates an instance of Alberti by getting message from user\"\"\"\n message = input(\"Enter a message to encrypt / decrypt: \")\n logging.info(\"User message created: {}\".format(message))\n return cls(message)\n\n def spin(self):\n \"\"\"Spins movable \"wheel\" in relation to fixed wheel for encryption\"\"\"\n pointer_index = self.movable.index(self.pointer)\n letter_shift = random.choice(self.fixed[:20])\n shift_index = self.fixed.index(letter_shift)\n diff_index = pointer_index - shift_index\n spin = self.movable[diff_index:] + self.movable[:diff_index]\n add_key_letter = self.encrpyted_message.append(letter_shift.upper())\n logging.info(\"pointer index: {}, letter shift: {}, shift index: {}, diff index: {}, spin: {}\".format(pointer_index, letter_shift, shift_index, diff_index, spin))\n return spin\n\n def decrypt_spin(self, letter):\n \"\"\"Spins movable \"wheel\" in relation to fixed wheel for decryption\"\"\"\n pointer_index = self.movable.index(self.pointer)\n code = letter.lower()\n code_index = self.fixed.index(code)\n diff_index = pointer_index - code_index\n spin = self.movable[diff_index:] + self.movable[:diff_index]\n logging.info(\"Decrypted spin pointer index: {}, code: {}, code index: {}, diff_index{} spin{}\".format(pointer_index, code, code_index,diff_index, spin))\n return spin\n\n def add_digraphs(self):\n \"\"\"The cipher requires that certain letters be replaced with digraphs before the message can be encoded. This makes the message harder to crack.\"\"\"\n lower_case = self.message.lower()\n message_with_digraphs = []\n\n for letter in lower_case:\n if letter == \" \":\n continue\n elif letter in self.digraph:\n message_with_digraphs.append(self.digraph[letter])\n message_with_digraphs.append(self.digraph[letter])\n else:\n message_with_digraphs.append(letter)\n\n logging.info(\"With digraph is {}\".format(message_with_digraphs))\n return message_with_digraphs\n\n def encrypt(self):\n \"\"\"Encrypts the message from user\"\"\"\n add_digraphs = self.add_digraphs()\n start_spin = self.spin()\n\n for letter in add_digraphs:\n if len(self.encrpyted_message) != 0 and len(self.encrpyted_message) % self.shift_range == 0:\n start_spin = self.spin()\n get_letter_index = self.fixed.index(letter)\n get_coded_letter = start_spin[get_letter_index]\n space = self.encrpyted_message.append(\" \")\n encrypt = self.encrpyted_message.append(get_coded_letter)\n else:\n get_letter_index = self.fixed.index(letter)\n get_coded_letter = start_spin[get_letter_index]\n encrypt = self.encrpyted_message.append(get_coded_letter)\n\n if self.size.upper() == \"Y\":\n final_encryption = divide_by_five(self.encrpyted_message)\n logging.info(\"Encrypted Msg is: {}\".format(final_encryption))\n return final_encryption\n else:\n logging.info(\"Encrypted Msg is: {}\".format(\"\".join(self.encrpyted_message)))\n return \"\".join(self.encrpyted_message)\n\n def decrypt(self):\n \"\"\"Decrypts the message from user\"\"\"\n start_spin = []\n message_with_digraphs = []\n remove_spaces = remove_encryption_spaces(self.message)\n logging.info(\"Remove spaces for decryption = {}\".format(remove_spaces))\n\n for letter in remove_spaces:\n if letter.istitle():\n start_spin = self.decrypt_spin(letter)\n else:\n get_letter_index = start_spin.index(letter)\n get_coded_letter = self.fixed[get_letter_index]\n message_with_digraphs.append(get_coded_letter)\n\n join_list = \"\".join(message_with_digraphs)\n logging.info(\"Message with digraphs: {}\".format(join_list))\n\n double_digraphs = {\n \"h\":\"ff\",\n \"j\":\"ii\",\n \"k\":\"qq\",\n \"u\":\"vv\",\n \"w\":\"xx\",\n \"y\":\"zz\"\n }\n\n digraphs = double_digraphs.items()\n\n for letter, code in digraphs:\n if code in join_list:\n join_list = join_list.replace(code, letter)\n\n logging.info(\"Message without digraphs: {}\".format(join_list))\n return join_list\n","sub_path":"alberti.py","file_name":"alberti.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"509409969","text":"#!/usr/bin/env python3\n\n# ╔═════════════════════════════════════════════════╗\n# ║ ║\n# ║ 26444444444444444822 ║\n# ║ 2222222222222222 6 ║\n# ║ 644444444444444444882 68 4 ║\n# ║ 62 222222222 8 2 8 ║\n# ║ 2 6 6 666666646 8 24 ║\n# ║ 844 4 8 4 ║\n# ║ 6 6 8 2 4 ║\n# ║ 24 2 4 2 4 ║\n# ║ 2 2 24 2 4 ║\n# ║ 2 2 4 2 4 ║\n# ║ 2 2 4 2 4 ║\n# ║ 2 2 attocube 4 2 4 4 ║\n# ║ 2 2 nanopositioners 4 2 4 4 ║\n# ║ 2 6 4 2 4 ║\n# ║ 2 4 4 2 6 ║\n# ║ 2 4 42 ║\n# ║ 2 8 44 ║\n# ║ 62 68 ║\n# ║ 4 84444444444444444444 ║\n# ║ 8 26 ║\n# ║ 6862222222222222222284 ║\n# ║ ║\n# ╚═════════════════════════════════════════════════╝\n#\n\n# based on\n# PyANC350 written by Rob Heath\n# rob@robheath.me.uk\n# 24-Feb-2015\n# robheath.me.uk\n#\n# PyANC350v4 by Brian Schaefer\n# bts72@cornell.edu\n# 5-Jul-2016\n# http://nowack.lassp.cornell.edu/\n#\n# https://github.com/Laukei/pyanc350\n\nimport ctypes, math, os\nfrom time import sleep, time\nfrom tqdm.notebook import tqdm\n\nanc350v3 = ctypes.windll.LoadLibrary('D:\\\\Google Drive\\\\Zia Lab\\\\Codebase\\\\zialab\\\\instruments\\\\DLLs\\\\anc350v3.dll')\n\n# aliases for the functions in the dll\n\n###############################\n#### Aliases for dll funcs ####\n\ndiscover = getattr(anc350v3,\"ANC_discover\")\ngetDeviceInfo = getattr(anc350v3,\"ANC_getDeviceInfo\")\nconnect = getattr(anc350v3,\"ANC_connect\")\ndisconnect = getattr(anc350v3,\"ANC_disconnect\")\n\ngetDeviceConfig = getattr(anc350v3,\"ANC_getDeviceConfig\")\ngetAxisStatus = getattr(anc350v3,\"ANC_getAxisStatus\")\nsetAxisOutput = getattr(anc350v3,\"ANC_setAxisOutput\")\nsetAmplitude = getattr(anc350v3,\"ANC_setAmplitude\")\n\nsetFrequency = getattr(anc350v3,\"ANC_setFrequency\")\nsetDcVoltage = getattr(anc350v3,\"ANC_setDcVoltage\")\ngetAmplitude = getattr(anc350v3,\"ANC_getAmplitude\")\ngetFrequency = getattr(anc350v3,\"ANC_getFrequency\")\n\nstartSingleStep = getattr(anc350v3,\"ANC_startSingleStep\")\nstartContinousMove = getattr(anc350v3,\"ANC_startContinousMove\")\nstartAutoMove = getattr(anc350v3,\"ANC_startAutoMove\")\nsetTargetPosition = getattr(anc350v3,\"ANC_setTargetPosition\")\n\nsetTargetRange = getattr(anc350v3,\"ANC_setTargetRange\")\ngetPosition = getattr(anc350v3,\"ANC_getPosition\")\ngetFirmwareVersion = getattr(anc350v3,\"ANC_getFirmwareVersion\")\nconfigureExtTrigger = getattr(anc350v3,\"ANC_configureExtTrigger\")\n\nconfigureAQuadBIn = getattr(anc350v3,\"ANC_configureAQuadBIn\")\nconfigureAQuadBOut = getattr(anc350v3,\"ANC_configureAQuadBOut\")\nconfigureRngTriggerPol = getattr(anc350v3,\"ANC_configureRngTriggerPol\")\nconfigureRngTrigger = getattr(anc350v3,\"ANC_configureRngTrigger\")\n\nconfigureRngTriggerEps = getattr(anc350v3,\"ANC_configureRngTriggerEps\")\nconfigureNslTrigger = getattr(anc350v3,\"ANC_configureNslTrigger\")\nconfigureNslTriggerAxis = getattr(anc350v3,\"ANC_configureNslTriggerAxis\")\nselectActuator = getattr(anc350v3,\"ANC_selectActuator\")\n\ngetActuatorName = getattr(anc350v3,\"ANC_getActuatorName\")\ngetActuatorType = getattr(anc350v3,\"ANC_getActuatorType\")\nmeasureCapacitance = getattr(anc350v3,\"ANC_measureCapacitance\")\nsaveParams = getattr(anc350v3,\"ANC_saveParams\")\n\n#### Aliases for dll funcs ####\n###############################\n\n###############################\n##### List of error types #####\n\nANC_Ok = 0 # No error\nANC_Error = -1 # Unknown / other error\nANC_Timeout = 1 # Timeout during data retrieval\nANC_NotConnected = 2 # No contact with the Nanocube via USB\nANC_DriverError = 3 # Error in the driver response\nANC_DeviceLocked = 7 # A connection attempt failed because the device is already in use\nANC_Unknown = 8 # Unknown error.\nANC_NoDevice = 9 # Invalid device number used in call\nANC_NoAxis = 10 # Invalid axis number in function call\nANC_OutOfRange = 11 # Parameter in call is out of range\nANC_NotAvailable = 12 # Function not available for device type\n\n##### List of error types #####\n###############################\n\ndef checkError(code,func,args):\n '''checks the errors returned from the dll'''\n if code == ANC_Ok:\n return\n elif code == ANC_Error:\n raise Exception(\"Error: unspecific in\"+str(func.__name__)+\"with parameters:\"+str(args))\n elif code == ANC_Timeout:\n raise Exception(\"Error: comm. timeout in\"+str(func.__name__)+\"with parameters:\"+str(args))\n elif code == ANC_NotConnected:\n raise Exception(\"Error: not connected\")\n elif code == ANC_DriverError:\n raise Exception(\"Error: driver error\")\n elif code == ANC_DeviceLocked:\n raise Exception(\"Error: device locked\")\n elif code == ANC_NoDevice:\n raise Exception(\"Error: invalid device number\")\n elif code == ANC_NoAxis:\n raise Exception(\"Error: invalid axis number\")\n elif code == ANC_OutOfRange:\n raise Exception(\"Error: parameter out of range\")\n elif code == ANC_NotAvailable:\n raise Exception(\"Error: function not available\")\n else:\n raise Exception(\"Error: unknown in\"+str(func.__name__)+\"with parameters:\"+str(args))\n return code\n\n###############################\n#set error checking & handling#\n\ndiscover.errcheck = checkError\nconnect.errcheck = checkError\ndisconnect.errcheck = checkError\ngetDeviceConfig.errcheck = checkError\n\ngetAxisStatus.errcheck = checkError\nsetAxisOutput.errcheck = checkError\nsetAmplitude.errcheck = checkError\nsetFrequency.errcheck = checkError\n\nsetDcVoltage.errcheck = checkError\ngetAmplitude.errcheck = checkError\ngetFrequency.errcheck = checkError\nstartSingleStep.errcheck = checkError\n\nstartContinousMove.errcheck = checkError\nstartAutoMove.errcheck = checkError\nsetTargetPosition.errcheck = checkError\nsetTargetRange.errcheck = checkError\n\ngetPosition.errcheck = checkError\ngetFirmwareVersion.errcheck = checkError\nconfigureExtTrigger.errcheck = checkError\nconfigureAQuadBIn.errcheck = checkError\n\nconfigureAQuadBOut.errcheck = checkError\nconfigureRngTriggerPol.errcheck = checkError\nconfigureRngTrigger.errcheck = checkError\nconfigureRngTriggerEps.errcheck = checkError\n\nconfigureNslTrigger.errcheck = checkError\nconfigureNslTriggerAxis.errcheck = checkError\nselectActuator.errcheck = checkError\ngetActuatorName.errcheck = checkError\n\ngetActuatorType.errcheck = checkError\nmeasureCapacitance.errcheck = checkError\nsaveParams.errcheck = checkError\n\n#set error checking & handling#\n###############################\n\nclass Nanocube:\n\n def __init__(self, config_params):\n self.discover()\n self.device = self.connect()\n self.y_lim = config_params['y_lim'] # approx 5000 - thickness_of_sample\n self.sample_thickness = config_params['sample_thickness']\n self.rough_focus = 4720 - config_params['sample_thickness']\n print(\"x-axis = horizontal axis; y-axis = optical axis; z-axis = up-down\")\n\n def configureAQuadBIn(self, axisNo: int, enable: int, resolution: float) -> None:\n '''\n Enables and configures the A-Quad-B (quadrature) input for the target position.\n\n Args:\n axisNo: Axis number (0 ... 2)\n enable: Enable (1) or disable (0) A-Quad-B input\n resolution: A-Quad-B step width in m. Internal resolution is 1 nm.\n\n Returns:\n None\n '''\n configureAQuadBIn(self.device, axisNo, enable, ctypes.c_double(resolution))\n\n def configureAQuadBOut(self, axisNo: int, enable: int, resolution: float, clock: float) -> None:\n '''\n Enables and configures the A-Quad-B output of the current position.\n\n Args:\n axisNo: Axis number (0 ... 2)\n enable: Enable (1) or disable (0) A-Quad-B output\n resolution: A-Quad-B step width in m; internal resolution is 1 nm\n clock: Clock of the A-Quad-B output [s].\n Allowed range is 40ns ... 1.3ms; internal resulution is 20ns.\n\n Returns:\n None\n '''\n configureAQuadBOut(self.device, axisNo, enable, ctypes.c_double(resolution), ctypes.c_double(clock))\n\n def configureExtTrigger(self, axisNo: int, mode: int) -> None:\n '''\n Enables the input trigger for steps.\n\n Args:\n axisNo:\tAxis number (0 ... 2)\n mode:\tDisable (0), Quadrature (1), Trigger(2) for external triggering\n\n Returns:\n None\n '''\n configureExtTrigger(self.device, axisNo, mode)\n\n def configureNslTrigger(self, enable: int) -> None:\n '''\n Enables NSL Input as Trigger Source.\n\n Args:\n enable:\tdisable(0), enable(1)\n\n Returns:\n None\n '''\n configureNslTrigger(self.device, enable)\n\n def configureNslTriggerAxis(self, axisNo: int) -> None:\n '''\n Selects Axis for NSL Trigger.\n\n Args:\n axisNo:\tAxis number (0 ... 2)\n\n Returns:\n None\n '''\n configureNslTriggerAxis(self.device, axisNo)\n\n def configureRngTrigger(self, axisNo: int, lower: float, upper: float) -> None:\n '''\n Configure lower position for range Trigger.\n\n Args:\n axisNo:\tAxis number (0 ... 2)\n lower:\tLower position for range trigger (nm)\n upper:\tUpper position for range trigger (nm)\n\n Returns:\n None\n '''\n configureRngTrigger(self.device, axisNo, lower, upper)\n\n def configureRngTriggerEps(self, axisNo: int, epsilon: float) -> None:\n '''\n Configure hysteresis for range Trigger.\n\n Args:\n axisNo:\t Axis number (0 ... 2)\n epsilon:\thysteresis in nm / mdeg\n\n Returns:\n None\n '''\n configureRngTriggerEps(self.device, axisNo, epsilon)\n\n def configureRngTriggerPol(self, axisNo: int, polarity: int):\n '''\n Configure lower position for range Trigger.\n\n Args:\n axisNo:\t Axis number (0 ... 2)\n polarity:\tPolarity of trigger signal when position is between\n lower and upper low(0) and high(1)\n Returns:\n None\n '''\n configureRngTriggerPol(self.device, axisNo, polarity)\n\n def connect(self, devNo=0):\n '''\n Initializes and connects the selected device. This has to be done\n before any access to control variables or measured data.\n\n Args:\n devNo (int):\tSequence number of the device. Must be smaller\n than the devCount from the last ANC_discover call.\n Default: 0\n\n Returns:\n device (ctypes_c_void_p): Handle to the opened device,\n NULL on error\n '''\n device = ctypes.c_void_p()\n connect(devNo, ctypes.byref(device))\n return device\n\n def close(self) -> None:\n '''\n Closes the connection to the device. The device handle becomes invalid.\n\n Args:\n None\n\n Returns:\n None\n '''\n disconnect(self.device)\n\n def discover(self, ifaces: int = 3) -> int:\n '''\n The function searches for connected ANC350RES devices on USB\n and LAN and initializes internal data structures per device.\n Devices that are in use by another application or PC are not found.\n The function must be called before connecting to a device and must\n not be called as long as any devices are connected.\n\n The number of devices found is returned. In subsequent functions,\n devices are identified by a sequence number that must be less than\n the number returned.\n\n Args:\n ifaces:\tInterfaces where devices are to be searched.\n {0 -> None, 1 -> USB, 2 -> ethernet, 3 -> all}\n\n Returns:\n devCount:\tnumber of devices found\n '''\n devCount = ctypes.c_int()\n discover(ifaces, ctypes.byref(devCount))\n return devCount.value\n\n def getActuatorName(self, axisNo: int) -> str:\n '''\n Get the name of the currently selected actuator\n\n Args:\n axisNo:\tAxis number (0 ... 2)\n\n Returns:\n name:\tName of the actuator\n '''\n name = ctypes.create_string_buffer(20)\n getActuatorName(self.device, axisNo, ctypes.byref(name))\n return name.value.decode('utf-8').strip()\n\n def getActuatorType(self, axisNo: int) -> str:\n '''\n Get the type of the currently selected actuator\n\n Args:\n axisNo:\tAxis number (0 ... 2)\n Returns:\n type:\tType of the actuator {0: linear, 1: goniometer, 2: rotator}\n '''\n type_ = ctypes.c_int()\n getActuatorType(self.device, axisNo, ctypes.byref(type_))\n return {0:'linear', 1:'goniometer', 2:'rotator'}[type_.value]\n\n def getAmplitude(self, axisNo:int) -> float:\n '''\n Reads back the amplitude parameter of an axis.\n\n Args:\n axisNo:\t Axis number (0 ... 2)\n Returns:\n amplitude:\tAmplitude [V]\n '''\n amplitude = ctypes.c_double()\n getAmplitude(self.device, axisNo, ctypes.byref(amplitude))\n return amplitude.value\n\n def getAxisStatus(self, axisNo: int) -> tuple:\n '''\n Reads status information about an axis of the device.\n\n Args:\n axisNo:\tAxis number (0 ... 2)\n\n Returns: (connected, enabled, moving, target, eotFwd, eotBwd, error)\n connected: If the axis is connected to a sensor.\n enabled: If the axis voltage output is enabled.\n moving: If the axis is moving.\n target: If the target is reached in automatic positioning\n eotFwd: If end of travel detected in forward direction.\n eotBwd: If end of travel detected in backward direction.\n error: If the axis' sensor is in error state.\n '''\n stat_names = ['connected','enabled','moving','target','eotFwd','eotBwd','error']\n connected, enabled = ctypes.c_int(), ctypes.c_int()\n moving = ctypes.c_int()\n target, eotFwd = ctypes.c_int(), ctypes.c_int()\n eotBwd, error = ctypes.c_int(), ctypes.c_int()\n getAxisStatus(self.device, axisNo, ctypes.byref(connected),\n ctypes.byref(enabled), ctypes.byref(moving),\n ctypes.byref(target), ctypes.byref(eotFwd),\n ctypes.byref(eotBwd), ctypes.byref(error))\n stat_values = (bool(connected.value), bool(enabled.value),\n bool(moving.value), bool(target.value), bool(eotFwd.value),\n bool(eotBwd.value), bool(error.value))\n status_dict = {stat: stat_value for stat, stat_value in zip(stat_names,stat_values)}\n\n return status_dict\n\n def getDeviceConfig(self) -> dict:\n '''\n Reads static device configuration data\n\n Args:\n None\n Returns:\n featureSync\t\"Sync\": Ethernet enabled (1) or disabled (0)\n featureLockin\t\"Lockin\": Low power loss measurement enabled (1) or disabled (0)\n featureDuty\t\"Duty\": Duty cycle enabled (1) or disabled (0)\n featureApp\t\"App\": Control by IOS app enabled (1) or disabled (0)\n '''\n features = ctypes.c_int()\n getDeviceConfig(self.device, features)\n\n featureSync = {1:'enabled',0:'disabled'}[int(0x01&features.value)]\n featureLockin = {1:'enabled',0:'disabled'}[int((0x02&features.value)/2)]\n featureDuty = {1:'enabled',0:'disabled'}[int((0x04&features.value)/4)]\n featureApp = {1:'enabled',0:'disabled'}[int((0x08&features.value)/8)]\n\n return {'sync':featureSync, 'lock-in': featureLockin,\n 'duty': featureDuty, 'app': featureApp}\n\n def getDeviceInfo(self, devNo: int = 0) -> dict:\n '''\n Returns: available information about a device.The function cannot be\n called before ANC_discover but the devices don't have to be connected.\n All Pointers to output parameters may be zero to ignore the respective\n value.\n\n Args:\n devNo: Sequence number of the device. Must be smaller than the\n devCount: From the last ANC_discover call. Default: 0\n Returns:\n devType\tOutput: Type of the ANC350 device.\n {0: Anc350Res, 1:Anc350Num, 2:Anc350Fps, 3:Anc350None}\n id: Programmed hardware ID of the device\n serialNo: The device's serial number. The string buffer should\n be NULL or at least 16 bytes long.\n address: The device's interface address if applicable.\n Returns the IP address in dotted-decimal notation or the string \"USB\", respectively. The string buffer should be NULL or at least 16 bytes long.\n connected: If the device is already connected\n '''\n devType = ctypes.c_int()\n id_ = ctypes.c_int()\n serialNo = ctypes.create_string_buffer(16)\n address = ctypes.create_string_buffer(16)\n connected = ctypes.c_int()\n\n getDeviceInfo(devNo, ctypes.byref(devType), ctypes.byref(id_),\n ctypes.byref(serialNo), ctypes.byref(address),\n ctypes.byref(connected))\n return {'devType': devType.value,\n 'devID': id_.value,\n 'serialNo': serialNo.value.decode('utf-8'),\n 'address': address.value.decode('utf-8'),\n 'connected': connected.value}\n\n def getFirmwareVersion(self) -> int:\n '''\n Retrieves the version of currently loaded firmware.\n\n Args:\n None\n Returns:\n version: Version number\n '''\n version = ctypes.c_int()\n getFirmwareVersion(self.device, ctypes.byref(version))\n return version.value\n\n def getFrequency(self, axisNo: int) -> float:\n '''\n Reads back the frequency parameter of an axis.\n\n Args:\n axisNo: Axis number (0 ... 2)\n Returns:\n frequency: Frequency in Hz\n '''\n frequency = ctypes.c_double()\n getFrequency(self.device, axisNo, ctypes.byref(frequency))\n return frequency.value\n\n def getPosition(self, axisNo: int) -> float:\n '''\n Retrieves the current actuator position in um.\n\n Args:\n axisNo: Axis number (0 ... 2)\n Returns:\n position: Current position [um].\n '''\n position = ctypes.c_double()\n getPosition(self.device, axisNo, ctypes.byref(position))\n return 1e6*position.value\n\n def getAllPositions(self):\n return self.getPosition(0), self.getPosition(1), self.getPosition(2)\n\n def measureCapacitance(self, axisNo: int) -> float:\n '''\n Performs a measurement of the capacitance of the piezo motor and\n returns the result. If no motor is connected, the result will be 0.\n The function doesn't return before the measurement is complete;\n this will take a few seconds of time.\n\n Args:\n axisNo: Axis number (0 ... 2)\n Returns:\n cap: Capacitance [uF]\n '''\n cap = ctypes.c_double()\n measureCapacitance(self.device, axisNo, ctypes.byref(cap))\n return 1e6*cap.value\n\n def saveParams(self):\n '''\n Saves parameters to persistent flash memory in the device.\n They will be present as defaults after the next power-on.\n The following parameters are affected: Amplitude, frequency,\n actuator selections as well as Trigger and quadrature settings.\n\n Args:\n None\n Returns:\n None\n '''\n saveParams(self.device)\n\n def selectActuator(self, axisNo: int, actuator: int) -> None:\n '''\n Selects the actuator to be used for the axis from actuator presets.\n\n Args:\n axisNo: Axis number (0 ... 2)\n actuator: Actuator selection (0 ... 255)\n 0: ANPg101res\n 1: ANGt101res\n 2: ANPx51res\n 3: ANPx101res\n 4: ANPx121res\n 5: ANPx122res\n 6: ANPz51res\n 7: ANPz101res\n 8: ANR50res\n 9: ANR51res\n 10: ANR101res\n 11: Test\n Returns:\n None\n '''\n selectActuator(self.device, axisNo, actuator)\n\n def setAmplitude(self, axisNo: int, amplitude: float) -> None:\n '''\n Sets the amplitude voltage fir the given axis\n\n Args:\n axisNo (int): Axis number (0 ... 2)\n amplitude (float): Amplitude in V, internal resolution is 1 mV\n Returns:\n None\n '''\n setAmplitude(self.device, axisNo, ctypes.c_double(amplitude))\n\n def setAxisOutput(self, axisNo: int, enable: int, autoDisable: int):\n '''\n Enables or disables the voltage output of an axis.\n\n Args:\n axisNo: Axis number (0 ... 2)\n enable: Enable (1) or disable (0) the voltage output.\n autoDisable: If the voltage output is to be deactivated\n automatically when end of travel is detected.\n Returns:\n None\n '''\n setAxisOutput(self.device, axisNo, enable, autoDisable)\n\n def setDcVoltage(self, axisNo: int, voltage: float) -> None:\n '''\n Sets the DC level on the voltage output when no sawtooth based motion is active.\n\n Args:\n axisNo: Axis number (0 ... 2)\n voltage: \tDC output voltage [V], internal resolution is 1 mV\n Returns:\n None\n '''\n setDcVoltage(self.device, axisNo, ctypes.c_double(voltage))\n\n def setFrequency(self, axisNo: int, frequency: float) -> None:\n '''\n Sets the frequency parameter for an axis\n\n Args:\n axisNo: Axis number (0 ... 2)\n frequency\tFrequency [Hz], internal resolution is 1 Hz\n Returns:\n None\n '''\n setFrequency(self.device, axisNo, ctypes.c_double(frequency))\n\n def setTargetPosition(self, axisNo: int, target_in_um: float) -> None:\n '''\n Sets the target position for automatic motion, see ANC_startAutoMove.\n Target unit is um.\n\n Args:\n axisNo: Axis number (0 ... 2)\n target:\t Target position [um]. Internal resulution is 1 nm.\n\n Returns:\n None\n '''\n assert target_in_um > 0, 'Positioners are unipolar, pos must be > 0.'\n setTargetPosition(self.device, axisNo, ctypes.c_double(target_in_um*1e-6))\n\n def setTargetRange(self, axisNo: int, targetRg_in_um: float) -> None:\n '''\n Defines the range around the target position where the target is considered to be reached.\n\n Args:\n axisNo: Axis number (0 ... 2)\n targetRg\tTarget range [um]. Internal resulution is 0.001 um.\n Returns:\n None\n '''\n setTargetRange(self.device, axisNo, ctypes.c_double(targetRg_in_um*1e-6))\n\n def startAutoMove(self, axisNo: int, enable: int, relative: int) -> None:\n '''\n Switches automatic moving (i.e. following the target position) on or off\n\n Args:\n axisNo: Axis number (0 ... 2)\n enable: Enables (1) or disables (0) automatic motion\n relative: If the target position is to be interpreted absolute\n (0) or relative to the current position (1)\n Returns:\n None\n '''\n startAutoMove(self.device, axisNo, enable, relative)\n\n # no real reason to ever use this\n # def startContinuousMove(self, axisNo: int, start: int, backward:int) -> None:\n # '''\n # Starts or stops continous motion in the given direction.\n # Other kinds of motions are stopped.\n #\n # Args:\n # axisNo: Axis number (0 ... 2)\n # start: Start (1) or stop (0) motion\n # backward: If the move direction is forward (0) or backward (1)\n #\n # Returns:\n # None\n # '''\n # startContinousMove(self.device, axisNo, start, backward)\n\n def startSingleStep(self, axisNo: int, backward: int) -> None:\n '''\n Triggers a single step in desired direction.\n\n Args:\n axisNo: Axis number (0 ... 2)\n backward: If the step direction is forward (0) or backward (1)\n Returns:\n None\n '''\n startSingleStep(self.device, axisNo, backward)\n\n def moveto(self,\n axisNo: int,\n target_position: float,\n target_range: float = 0.1,\n frequency: float = 400.,\n amplitude: float = 45.,\n block: bool = False) -> None:\n '''\n Enable closed-loop motion after settting target position, and target range.\n If the axis is the y-axis, the target has to be <= y_lim\n\n Args:\n axisNo: Axis number (0 ... 2)\n target_position: Target position in um.\n target_range: Range within which target is considered as reached.\n frequency: Frequency of operation [Hz]\n amplitude: Amplitude of operation [V]\n block: If function blocks until target is reached.\n Returns:\n None\n '''\n if axisNo == 1:\n assert target_position <= self.y_lim, 'y out of range'\n self.setFrequency(axisNo,frequency)\n self.setAmplitude(axisNo,amplitude)\n self.setAxisOutput(axisNo, 1, 1)\n self.setTargetPosition(axisNo, target_position)\n self.setTargetRange(axisNo, target_range)\n self.startAutoMove(axisNo, 1, 0)\n sleep(0.5)\n stuck_gap = 50.\n if block:\n bar_fmt = '{percentage:.1f}%{bar}({n:.1f}/{total:.1f}) [{elapsed}<{remaining}]'\n current_position = self.getPosition(axisNo)\n gap = abs(current_position-target_position)\n pbar = tqdm(total = gap, bar_format = bar_fmt)\n positions = [current_position]\n times = [time()]\n stuck = False\n while (not self.getAxisStatus(axisNo)['target']):\n current_position = self.getPosition(axisNo)\n positions.append(current_position)\n times.append(time())\n dif = abs(target_position - current_position)\n newgap = gap - dif\n pbar.n = newgap\n pbar.display()\n if (len(positions) > 10) & (dif < stuck_gap) & (not stuck):\n stuck = True\n print(\"Stuck?...\")\n stuck_time = time()\n if stuck:\n ds = abs(positions[-10] - positions[-1])\n dt = abs(times[-10] - times[-1])\n speed = ds / dt\n time_stuck = time() - stuck_time\n if (time_stuck > 60) and speed < 1:\n print(\"Stuck, stopping Automove ...\")\n self.startAutoMove(axisNo, 0, 0)\n break\n sleep(0.05)\n pbar.close()\n\n def disengange_all(self):\n '''\n Disable output on all axes.\n '''\n self.setAxisOutput(0,0,1)\n self.setAxisOutput(1,0,1)\n self.setAxisOutput(2,0,1)\n\n def voyageto(self, axisNo, target_position, target_precision=0.5, verbose=False):\n '''\n Moves the given axis to the given target position within\n a given precision.\n If the target position is at a larger distance than rough_precision\n the target is initially approached with autoMove,\n once the target is reached within this range, single steps are used\n to get within 3 um,\n after this the DC bias is used to fine tune the position to within\n a precision of target_precision.\n\n Parameters:\n\n axisNo (int): 0 -> x, 1-> y, 2-> z\n target_position (float): given in um\n target_precision (float): given in um\n verbose (bool): if verbose prints or not\n\n Returns:\n\n trajectory (list): [positions during mid and fine tuning]\n\n If at any point the y-axis goes beyond its safe range\n the axis is disengaged.\n If at any time the function is interrupted\n the axis is disengaged.\n '''\n rough_precision = 50 # how close to target with automoving\n mid_range = 3.0 # distance to target for single step approach\n frequency_in_Hz = 200\n mid_amplitude = 30. # voltage amplitude for mid steps\n dc_voltage = 30. # dc voltage for fine tune\n\n # get close using autoMove\n print(\"automoving ...\")\n self.moveto(axisNo, target_position, rough_precision, block = True)\n self.startAutoMove(axisNo, 0, 0)\n self.setAxisOutput(axisNo, 1, True)\n self.setFrequency(axisNo, frequency_in_Hz)\n self.setDcVoltage(axisNo, dc_voltage)\n trajectory = []\n\n try:\n # get closer using single steps\n print(\"mid stepping ...\")\n gap = abs(self.getPosition(axisNo) - target_position)\n newgap = gap\n bar_fmt = '{percentage:.1f}%{bar}({n:.1f}/{total:.1f}) [{elapsed}<{remaining}]'\n pbar = tqdm(total = gap, bar_format = bar_fmt)\n while newgap >= mid_range:\n current_position = self.getPosition(axisNo)\n newgap = abs(current_position - target_position)\n pbar.n = gap - newgap\n pbar.display()\n if axisNo == 1:\n if current_position > self.y_lim:\n raise Exception(\"reached y-axis limit\")\n trajectory.append(current_position)\n if current_position > target_position:\n direction = 1 # backward\n else:\n direction = 0 # forward\n self.setAmplitude(axisNo, mid_amplitude)\n self.startSingleStep(axisNo, direction)\n sleep(0.05)\n\n print(\"fine tuning ...\")\n # fine tune the DC voltage, and use single steps here and there\n while abs(self.getPosition(axisNo) - target_position) >= target_precision:\n current_position = self.getPosition(axisNo)\n newgap = abs(current_position - target_position)\n pbar.n = gap - newgap\n pbar.display()\n if axisNo == 1:\n if current_position > self.y_lim:\n raise Exception(\"reached y-axis limit\")\n if verbose:\n print(\".\", end='')\n trajectory.append(current_position)\n if current_position > target_position:\n dc_voltage = dc_voltage - 1\n else:\n dc_voltage = dc_voltage + 1\n if dc_voltage < 0:\n dc_voltage = 30\n print(\"leaping\")\n self.startSingleStep(axisNo, 1)\n if dc_voltage > 60:\n dc_voltage = 30\n print(\"leaping\")\n self.startSingleStep(axisNo, 0)\n self.setDcVoltage(axisNo, dc_voltage)\n sleep(0.05)\n pbar.close()\n except Exception as e:\n print(e)\n self.setAxisOutput(axisNo,0,1)\n return trajectory\n return trajectory\n\n # def travelto(self, axisNo, target_position, target_precision = 0.5):\n # '''\n # Moves the given axis to the given target position within\n # a given precision by using a mixture of continous motions\n # and single steps. Fine-stepping is regulated by changing\n # the single-step voltage accordingly.\n #\n # Parameters:\n #\n # axisNo (int): 0 -> x, 1-> y, 2-> z\n # target_position (float): given in um\n # target_precision (float): given in um\n #\n # Retruns:\n #\n # trajectory (list): [[step_idx_0, position_0] ... []]\n #\n # If at any point the axis goes beyond its safe range\n # motion is immediately stopped.\n # If at any time the function is interrupted\n # the axis is stopped.\n # '''\n # big_range = 3000./2. # distance to target that enforces continous motion\n # mid_range = 20./2. # distance to target that enforces single steps\n # fine_range = 5./2. # distance to target that hones in using DC voltage\n # max_voltage = 60 # this is the maximum voltage that can be set\n # dc_voltage = 0. # this is the starting voltage for fine stepping\n # frequency_in_Hz = 200\n # min_coarse = 20 # for big stepping voltage shan't be smaller than this\n # dc_delta = 1 # initial step size for finding fine step voltage\n # coarse_amplitude = 50.\n # coarse_delta = 1 # amount by which the continouse motion is increased/decreased\n # current_position = self.getPosition(axisNo)\n # delta = self.getPosition(axisNo) - target_position\n # previous_position = current_position\n # self.setAxisOutput(axisNo, 1, True)\n # self.setFrequency(axisNo, frequency_in_Hz)\n # start_time = time.time()\n # trajectory = []\n # try:\n # while abs(delta) >= target_precision:\n # current_position = self.getPosition(axisNo)\n # trajectory.append([time.time()-start_time, current_position])\n # if ((-fine_range) < (current_position-target_position) < 0) : # target must be approached from below\n # print(\"fine stepping...\", end='|')\n # if dc_voltage >= max_voltage:\n # dc_voltage = 0\n # print(\"mid stepping out of snag...\", end='|')\n # if current_position > target_position:\n # direction = 1 # backward\n # else:\n # direction = 0 # forward\n # self.setAmplitude(axisNo, coarse_amplitude)\n # self.startSingleStep(axisNo,direction)\n # if (target_position-current_position)*(target_position-self.getPosition(axisNo)) < 0:\n # coarse_amplitude = coarse_amplitude - coarse_delta\n # if coarse_amplitude < min_coarse:\n # coarse_amplitude = min_coarse\n # self.setDcVoltage(axisNo,dc_voltage)\n # # fine tuning mode\n # if (previous_position - target_position)*(current_position - target_position) < 0:\n # dc_delta = dc_delta/2.\n # if current_position > target_position:\n # dc_voltage = abs(dc_voltage - dc_delta)\n # self.setDcVoltage(axisNo, dc_voltage)\n # # print(\"V=\"+str(dc_voltage))\n # else:\n # dc_voltage = dc_voltage + dc_delta\n # self.setDcVoltage(axisNo, dc_voltage)\n # # print(\"V=\"+str(dc_voltage))\n # elif abs(current_position-target_position) <= mid_range:\n # print(\"mid stepping...\", end='|')\n # if current_position > target_position:\n # direction = 1 # backward\n # else:\n # direction = 0 # forward\n # self.setAmplitude(axisNo, coarse_amplitude)\n # self.startSingleStep(axisNo,direction)\n # if (target_position-current_position)*(target_position-self.getPosition(axisNo)) < 0:\n # coarse_amplitude = coarse_amplitude - coarse_delta\n # if coarse_amplitude < min_coarse:\n # coarse_amplitude = min_coarse\n # elif abs(current_position-target_position) <= big_range:\n # # if very far away, approach target with\n # # a continous move using the coarse_amplitied voltage\n # print(\"big stepping...\", end='|')\n # self.setAmplitude(axisNo, coarse_amplitude)\n # if current_position > target_position:\n # direction = 1 # backward\n # else:\n # direction = 0 # forward\n # self.startContinuousMove(axisNo,1,direction)\n # while (target_position-current_position)*(target_position-self.getPosition(axisNo)) > 0:\n # # keep moving until the target has been crossed\n # pass\n # else:\n # coarse_amplitude = coarse_amplitude - coarse_delta\n # if coarse_amplitude < min_coarse:\n # coarse_amplitude = min_coarse\n # self.startContinuousMove(axisNo,0,direction)\n # previous_position = current_position\n # delta = current_position - target_position\n # time.sleep(0.1)\n # else:\n # print(\"Target reached!\")\n # if abs(self.getPosition(axisNo) - target_position) > target_precision:\n # print(\"Repeating...\")\n # self.travelto(axisNo, target_position)\n # except:\n # print(\"stopping the axis\")\n # self.startContinuousMove(axisNo,0,direction)\n # return trajectory\n # return trajectory\n","sub_path":"instruments/nanocube.py","file_name":"nanocube.py","file_ext":"py","file_size_in_byte":39253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"248755496","text":"# Tabellenprogramm https://github.com/TheChymera/matrix2latex\nimport os\nimport sys\nsys.path.insert(0, '../global/matrix2latex-master/')\nfrom matrix2latex import matrix2latex\n\nimport matplotlib as mpl\nmpl.use('pgf')\nmpl.rcParams.update({\n 'font.family': 'serif',\n 'text.usetex': True,\n 'pgf.rcfonts': False,\n 'pgf.texsystem': 'lualatex',\n 'pgf.preamble': r'\\usepackage{unicode-math}\\usepackage{siunitx}',\n 'errorbar.capsize': 3\n})\nimport numpy as np\nimport uncertainties.unumpy as unp\nfrom uncertainties import ufloat\nfrom uncertainties.unumpy import (nominal_values as noms, std_devs as stds)\nfrom scipy.optimize import curve_fit\nimport scipy.constants as const\nimport matplotlib.pyplot as plt\nimport math as m\n\n\ndef fehler(x):\n return np.std(x, ddof=1) / len(x)\n\ndef lin(x, a, b):\n return a*x + b\n\nx_1 = np.linspace(0.06, 5, 1000)\ny_1 = np.ones(len(x_1))*8.7\ny_1eo = np.ones(len(x_1))*(8.7 + 0.8)\ny_1eu = np.ones(len(x_1))*(8.7 - 0.8)\nx_2 = np.linspace(0.02, 0.04, 1000)\ny_2 = np.ones(len(x_1))*1.0\ny_2eo = np.ones(len(x_1))*(1.0 + 0.2)\ny_2eu = np.ones(len(x_1))*(1.0 - 0.2)\nplt.plot(x_1, y_1, \"-\", color = \"C1\", label=\"Sauggeschwindigkeit aus Evakuierungskurve\")\nplt.plot(x_1, y_1eo, \"--\", color = \"C1\")\nplt.plot(x_1, y_1eu, \"--\", color = \"C1\")\nplt.plot(x_2, y_2, \"-\", color = \"C1\")\nplt.plot(x_2, y_2eo, \"--\", color = \"C1\")\nplt.plot(x_2, y_2eu, \"--\", color = \"C1\")\nplt.errorbar([0.05, 0.1, 0.15, 0.2], [15, 26, 26, 27], xerr = [0.005, 0.01, 0.015, 0.02], yerr = [2, 3, 3, 3], fmt = \".\", label=\"Sauggeschwindigkeit aus Leckratenmessung\", color = \"C0\")\nplt.legend(loc=\"best\")\nplt.grid()\n#plt.xlim(-0.8, 21)\n#plt.ylim(-0.2, 11.4)\nplt.xlabel(r\"$p \\, / \\, \\text{µbar}$\")\nplt.ylabel(r\"$S \\, / \\, \\text{(l / s)}$\")\nplt.xscale(\"log\")\nplt.tight_layout()\nplt.savefig(\"img/TurboSaug.pdf\")\n","sub_path":"V70_Vakuumphysik/auswertung3.py","file_name":"auswertung3.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"336780614","text":"class Person:\n def __init__(self, id: int, first_name: str, last_name: str):\n self.id = id\n self.first_name = first_name\n self.last_name = last_name\n\n\nclass Account:\n def __init__(self, number: int, type: str, owner: Person, balance: int = 0):\n self.number = number\n self.type = type\n self.owner = owner\n self.balance = balance\n\n\nclass Bank():\n customers = {}\n accounts = {}\n\n def add_customer(self, customer: Person):\n if customer.id not in self.customers:\n x = customer.id\n self.customers[customer.id] = customer\n\n else:\n print(\"Customer already exsists\")\n\n def add_account(self, account: Account):\n if account.number not in self.accounts:\n x = account.owner.id\n if x in self.customers:\n self.accounts[account.number] = accounts\n else:\n raise TypeError(\"Customer not registered\")\n else:\n raise TypeError(\"This account is already created\")\n\n def remove_account(self, account: int):\n if account.number in self.accounts == True:\n pop(account.number)\n\n def deposit(self, account: Account, deposit_amount: int):\n new_amount = self.accounts.get(account).balance + deposit_amount\n self.accounts[account].balance = new_amount\n\n def withdrawal(self, account: int, withdraw_amount: int):\n new_amount = self.accounts.get(account).balance - withdraw_amount\n self.accounts[account].balance = new_amount\n\n def balance_inquiry(self, account: int):\n print(round(self.accounts.get(account).balance),2)\n\n def save_data(self):\n PersistenceUtils.write_pickle(customers.pickle, customers)\n PersistenceUtils.write_pickle(accounts.pickle, accounts)\n\n def load_pickle(self):\n PersistenceUtils.load_pickle(customers.pickle)\n PersistenceUtils.load_pickle(accounts.pickle)\n\n\nclass PersistenceUtils():\n def __int__(self):\n pass\n\n @staticmethod\n def write_pickle(file_path, data):\n with open(file_path, \"wb\") as handler:\n pickle.dump(data, handler)\n\n @staticmethod\n def load_pickle(file_path):\n with open(file_path, 'rb') as handler:\n data = pickle.load(handler)\n return data\n\n\nzc_bank = Bank()\nbob = Person(1, \"Bob\", \"Smith\")\nzc_bank.add_customer(bob)\nbob_savings = Account(1001, \"SAVINGS\", bob)\nzc_bank.add_account(bob_savings)\nzc_bank.balance_inquiry(1001)\n# 0\nzc_bank.deposit(1001, 256.02)\nzc_bank.balance_inquiry(1001)\n# 256.02\nzc_bank.withdrawal(1001, 128)\nzc_bank.balance_inquiry(1001)\n\n\n\n\n","sub_path":"persistent_small_town_teller.py","file_name":"persistent_small_town_teller.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"73107219","text":"from typing import Optional, TypeVar\nfrom .converter import Converter\nfrom ..typing import Schema, Schemable\nfrom ...share.entity import Entity\n\n\nT = TypeVar('T', bound=Entity)\n\n\nclass SchemablePython(Schemable):\n __schema__ = None\n\n @classmethod\n def _do_from_dict(clazz,\n from_dict: dict,\n schema: Optional[Schema] = None,\n **kargs) -> Optional[T]:\n if not clazz.__schema__ and not schema:\n raise NotImplementedError\n from_dict = clazz.pre_schema(from_dict, **kargs)\n if not from_dict:\n return None\n instance = Converter.instance().convert(from_dict, schema or clazz.__schema__, clazz)\n return clazz.post_schema(from_dict, instance, **kargs)\n\n @classmethod\n def pre_schema(clazz,\n from_dict: dict,\n **kargs) -> Optional[dict]:\n return from_dict\n\n @classmethod\n def post_schema(clazz,\n from_dict: dict,\n instance: T,\n **kargs) -> Optional[T]:\n return instance\n","sub_path":"dio/schemable/schemable_python/schemable_python.py","file_name":"schemable_python.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"443750969","text":"import os \r\nfrom PIL import Image\r\n\r\nimg = []\r\nfilepath = './original'\r\nfor i in range(100):\r\n full_name = os.path.join(filepath, str(i)+'.png')\r\n if os.path.isfile(full_name):\r\n im = Image.open(full_name)\r\n im.thumbnail(size=(24,24),resample= Image.ANTIALIAS)\r\n img.append(im)\r\n # plt.imshow(im)\r\n im.save('./' + str(i) + '.png')\r\n else: \r\n continue","sub_path":"xml_generator_data/positive/compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"103047531","text":"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport argparse\n\nimport logging\n\nimport pytest\n\nfrom yo.db_utils import init_db\n\n\nlogging.basicConfig(level='DEBUG')\n\n@pytest.fixture\ndef parsed_args():\n parser = argparse.ArgumentParser(description=\"Steem notification service\")\n parser.add_argument('--log_level',\n default=os.environ.get('LOG_LEVEL', 'INFO'))\n parser.add_argument('--steemd_url', default=os.environ.get('STEEMD_URL',\n 'https://api.steemit.com'))\n parser.add_argument('--database_url',\n default=os.environ.get('DATABASE_URL', 'sqlite://'))\n parser.add_argument('--sendgrid_priv_key',\n default=os.environ.get('SENDGRID_PRIV_KEY', None))\n parser.add_argument('--sendgrid_templates_dir',\n default=os.environ.get('SENDGRID_TEMPLATES_DIR',\n 'mail_templates'))\n parser.add_argument('--twilio_account_sid',\n default=os.environ.get('TWILIO_ACCOUNT_SID', None))\n parser.add_argument('--twilio_auth_token',\n default=os.environ.get('TWILIO_AUTH_TOKEN', None))\n parser.add_argument('--twilio_from_number',\n default=os.environ.get('TWILIO_FROM_NUMBER', None))\n parser.add_argument('--steemd_start_block',\n default=os.environ.get('STEEMD_START_BLOCK', None))\n parser.add_argument('--http_host',\n default=os.environ.get('HTTP_HOST', '0.0.0.0'))\n parser.add_argument('--http_port', type=int,\n default=os.environ.get('HTTP_PORT', 8080))\n return parser.parse_args([])\n\n\n@pytest.fixture\ndef basic_mock_app(parsed_args, sqlite_db):\n class MockApp:\n def __init__(self, db):\n self.db = db\n self.config = parsed_args\n return MockApp(sqlite_db)\n\ndef add_test_users(sqlite_db):\n sqlite_db.create_user('test_user1')\n sqlite_db.create_user('test_user2')\n sqlite_db.create_user('testuser_3')\n\n\n@pytest.fixture(scope='function')\ndef sqlite_db():\n \"\"\"Returns a new instance of YoDatabase backed by sqlite3 memory with the mock data preloaded\"\"\"\n yo_db = init_db(db_url='sqlite://', reset=True)\n return yo_db\n\n\n@pytest.fixture(scope='function')\ndef sqlite_db_with_data():\n yield init_db(db_url='sqlite://', reset=True)\n\n\n@pytest.fixture\ndef fake_notifications():\n return [\n {\n 'notify_type': 'reward',\n 'to_username': 'test_user',\n 'json_data': {\n 'reward_type': 'curation',\n 'item': dict(\n author='test_user',\n category='test',\n permlink='test-post',\n summary='A test post'),\n 'amount': dict(SBD=6.66, SP=13.37)\n },\n }\n ]\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"273057728","text":"import csv\n\nfrom contato import Contato\nfrom pycel.pycel import Pycel\n\nc1 = Contato(\"Eder\", \"testando@outlook.com\", \"(21) 99999-1234\")\nc2 = Contato(\"Adriano\", \"testando@gmail.com\", \"(21) 99999-1234\")\nc3 = Contato(\"Daniel\", \"testando@hotmail.com\", \"(21) 99999-1234\")\nc4 = Contato(\"Manoel\", \"manoel@gmail.com\", \"(21) 23213213-123213\")\n\n# print(len(c2))\nlista_contatos = [c1, c2, c3]\n\nwith Pycel(lista_contatos) as pc:\n\n with open(\"contatos.csv\", \"w\") as w:\n for row in pc.read():\n csv.writer(w).writerow(row)\n","sub_path":"example/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"323781476","text":"from tkinter import *\nfrom PIL import Image, ImageTk\nfrom tkinter import ttk\nimport mysql.connector\nfrom tkinter import messagebox\nimport random\nfrom time import strftime\nfrom datetime import datetime\n\n\n\nclass Roombooking:\n def __init__(self, root):\n\n self.root = root\n self.root.title(\"Room Booking Page\")\n self.root.geometry(\"1140x480+225+220\")\n\n ##variables\n self.var_contact = StringVar()\n self.var_checkin = StringVar()\n self.var_checkout = StringVar()\n self.var_roomtype = StringVar()\n self.var_roomavailable = StringVar()\n self.var_meal = StringVar()\n self.var_noofdays = StringVar()\n self.var_paidtax = StringVar()\n self.var_actualtotal = StringVar()\n self.var_total = StringVar()\n\n\n ####title*****\n lbl_title = Label(self.root, text='ROOM BOOKING DETAILS', font=('times new roman', 18, 'bold'), fg='gold',\n bg='black', relief=RIDGE)\n lbl_title.place(x=0, y=0, width=1400, height=50)\n\n ####logo***\n img2 = Image.open(\"F:\\Hotel\\Images\\logo.jpg\")\n img2 = img2.resize((230, 50), Image.ANTIALIAS)\n self.photoimg2 = ImageTk.PhotoImage(img2)\n\n lbling = Label(self.root, image=self.photoimg2, bd=0, relief=RIDGE)\n lbling.place(x=0, y=0, width=200, height=50)\n\n\n\n\n ####label frame*****\n labelframeleft = LabelFrame(self.root, bd=2, relief=RIDGE,text='Room Booking Details',font=('times new roman',12,'bold'),padx=2)\n labelframeleft.place(x=5, y=50, width=425, height=490)\n\n\n #Labels and entry fields\n # customer contact\n lbl_cust_contact = Label(labelframeleft, text='Customer Contact', font=('times new roman', 12, 'bold'), padx=2, pady=6)\n lbl_cust_contact.grid(row=0, column=0, sticky=W)\n\n entry_contact = ttk.Entry(labelframeleft, textvariable=self.var_contact,width=20, font=('arial', 13, 'bold'))\n entry_contact.grid(row=0, column=1,sticky=W)\n\n #Fetch data Button\n btnFetchData = Button(labelframeleft, text='Fetch Data',command=self.Fetch_contact, font=('times new roman', 12, 'bold'), bg='black',\n fg='gold', width=8)\n btnFetchData.place(x=330,y=4)\n\n # check in date\n check_in_date = Label(labelframeleft, text='Check In Date', font=('times new roman', 12, 'bold'), padx=2, pady=6)\n check_in_date.grid(row=1, column=0, sticky=W)\n\n txtcheck_in_date = ttk.Entry(labelframeleft,width=29,textvariable=self.var_checkin ,font=('arial', 13, 'bold'))\n txtcheck_in_date.grid(row=1, column=1)\n\n # check out date\n lbl_Check_out = Label(labelframeleft, text='Check Out Date', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lbl_Check_out.grid(row=2, column=0, sticky=W)\n\n txt_Check_out = ttk.Entry(labelframeleft, width=29,textvariable=self.var_checkout, font=('arial', 13, 'bold'))\n txt_Check_out.grid(row=2, column=1)\n\n #room type\n label_RoomType = Label(labelframeleft, text='Room Type', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n label_RoomType.grid(row=3, column=0, sticky=W)\n\n conn = mysql.connector.connect(host='localhost', user='root', password='2589', database='management')\n\n my_cursor = conn.cursor()\n my_cursor.execute('select RoomType from details')\n ide = my_cursor.fetchall()\n\n\n\n combo_RoomType = ttk.Combobox(labelframeleft,textvariable=self.var_roomtype,font=('arial', 12, 'bold'), width=27,\n state='readonly')\n combo_RoomType['value'] = ide\n combo_RoomType.current(0)\n combo_RoomType.grid(row=3, column=1)\n\n\n # available room\n lblRoomAvailable = Label(labelframeleft,text='Available Room',font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lblRoomAvailable.grid(row=4, column=0, sticky=W)\n\n # txtRoomAvailable = ttk.Entry(labelframeleft,textvariable=self.var_roomavailable, width=29, font=('arial', 13, 'bold'))\n #txtRoomAvailable.grid(row=4, column=1)\n\n conn = mysql.connector.connect(host='localhost', user='root', password='2589', database='management')\n\n my_cursor = conn.cursor()\n my_cursor.execute('select RoomNo from details')\n rows = my_cursor.fetchall()\n\n combo_RoomNo = ttk.Combobox(labelframeleft, textvariable=self.var_roomavailable, font=('arial', 12, 'bold'),\n width=27,\n state='readonly')\n combo_RoomNo['value'] = rows\n combo_RoomNo.current(0)\n combo_RoomNo.grid(row=4, column=1)\n\n #Meal\n lblMeal = Label(labelframeleft, text='Meal', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lblMeal.grid(row=5, column=0, sticky=W)\n\n txtMeal = ttk.Entry(labelframeleft, textvariable=self.var_meal,width=29, font=('arial', 13, 'bold'))\n txtMeal.grid(row=5, column=1)\n\n # No of days\n lblNoOfDays = Label(labelframeleft, text='No of Days', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lblNoOfDays.grid(row=6, column=0, sticky=W)\n\n txtNoOfDays = ttk.Entry(labelframeleft,textvariable=self.var_noofdays, width=29, font=('arial', 13, 'bold'))\n txtNoOfDays.grid(row=6, column=1)\n\n\n #Paid tax\n lblPaidTax = Label(labelframeleft, text='Paid Tax', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lblPaidTax.grid(row=7, column=0, sticky=W)\n\n txtPaidTax = ttk.Entry(labelframeleft,textvariable=self.var_paidtax, width=29, font=('arial', 13, 'bold'))\n txtPaidTax.grid(row=7, column=1)\n\n #Sub Total\n lblSubTotal = Label(labelframeleft, text='Sub Total', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lblSubTotal.grid(row=8, column=0, sticky=W)\n\n txtSubTotal = ttk.Entry(labelframeleft,textvariable=self.var_actualtotal, width=29, font=('arial', 13, 'bold'))\n txtSubTotal.grid(row=8, column=1)\n\n # Total Cost\n lblTotalCost = Label(labelframeleft, text='Total Cost', font=('times new roman', 12, 'bold'), padx=2,\n pady=6)\n lblTotalCost.grid(row=9, column=0, sticky=W)\n\n txtTotalCost = ttk.Entry(labelframeleft,textvariable=self.var_total, width=29, font=('arial', 13, 'bold'))\n txtTotalCost.grid(row=9, column=1)\n\n\n #bill button\n\n btnBill = Button(labelframeleft, text='Bill',command=self.total, font=('times new roman', 12, 'bold'), bg='black',\n fg='gold', width=10)\n btnBill.grid(row=10, column=0,sticky=W)\n\n # buttons\n btn_frame = Frame(labelframeleft, bd=2, relief=RIDGE)\n btn_frame.place(x=0, y=380, width=412, height=40)\n\n btnAdd = Button(btn_frame, text='Add',command=self.add_data,font=('times new roman', 12, 'bold'), bg='black',\n fg='gold', width=10)\n btnAdd.grid(row=0, column=0)\n\n btnUpdate = Button(btn_frame, text='Update',command=self.update,font=('times new roman', 12, 'bold'),\n bg='black', fg='gold', width=10)\n btnUpdate.grid(row=0, column=1)\n\n btnDelete = Button(btn_frame, text='Delete',command=self.mDelete, font=('times new roman', 12, 'bold'),\n bg='black', fg='gold', width=10)\n btnDelete.grid(row=0, column=2)\n\n btnReset = Button(btn_frame, text='Reset',command=self.reset, font=('times new roman', 12, 'bold'), bg='black',\n fg='gold', width=10)\n btnReset.grid(row=0, column=3)\n\n #right side image\n img3 = Image.open(\"F:\\Hotel Management System\\images\\Room.jpg\")\n img3 = img3.resize((360,200), Image.ANTIALIAS)\n self.photoimg3 = ImageTk.PhotoImage(img3)\n\n lbling = Label(self.root, image=self.photoimg3, bd=0, relief=RIDGE)\n lbling.place(x=760, y=55, width=360, height=200)\n\n ##table frame search system\n Table_Frame = LabelFrame(self.root, bd=2, relief=RIDGE, text='View Details and Search System',\n font=('times new roman', 12, 'bold'), padx=2)\n Table_Frame.place(x=435, y=270, width=860, height=260)\n\n lblSearchBy = Label(Table_Frame, text='Search By', font=('Arial', 12, 'bold'),bg='red',fg='white')\n lblSearchBy.grid(row=0, column=0, sticky=W,padx=2)\n\n\n self.search_var =StringVar()\n combo_Search= ttk.Combobox(Table_Frame,textvariable=self.search_var,\n font=('arial', 12, 'bold'), width=20, state='readonly')\n combo_Search['value'] = ('Contact', 'Room')\n combo_Search.current(0)\n combo_Search.grid(row=0, column=1,padx=2)\n\n\n self.txt_search= StringVar()\n txtSearch = ttk.Entry(Table_Frame, width=20,textvariable=self.txt_search, font=('arial', 13, 'bold'))\n txtSearch.grid(row=0, column=2,padx=2)\n\n btnSearch = Button(Table_Frame, text='Search',command=self.search,font=('arial', 11, 'bold'), bg='black', fg='gold', width=7)\n btnSearch.grid(row=0, column=3,padx=1)\n\n btnShowAll = Button(Table_Frame, text='Show All',command=self.fetch_data, font=('arial', 11, 'bold'), bg='black', fg='gold',\n width=7)\n btnShowAll.grid(row=0, column=4,padx=1)\n\n\n ####show data table\n details_table = Frame(Table_Frame, bd=2, relief=RIDGE)\n details_table.place(x=0, y=50, width=690, height=140)\n\n scroll_x = ttk.Scrollbar(details_table, orient=HORIZONTAL)\n scroll_y = ttk.Scrollbar(details_table, orient=VERTICAL)\n\n self.room_table = ttk.Treeview(details_table, column=('contact', 'checkin', 'checkout', 'roomtype',\n 'roomavailable', 'meal', 'noOfdays'), xscrollcommand=scroll_x.set,\n yscrollcommand=scroll_y.set)\n\n scroll_x.pack(side=BOTTOM, fill=X)\n scroll_y.pack(side=RIGHT, fill=Y)\n\n scroll_x.config(command=self.room_table.xview)\n scroll_y.config(command=self.room_table.yview)\n\n self.room_table.heading('contact', text='Contact')\n self.room_table.heading('checkin', text='Check-in')\n self.room_table.heading('checkout', text='Check-out')\n self.room_table.heading('roomtype', text='Room Type')\n self.room_table.heading('roomavailable', text='Room No')\n self.room_table.heading('meal', text='Meal')\n self.room_table.heading('noOfdays', text='NoOfDays')\n\n\n self.room_table['show'] = 'headings'\n self.room_table.pack(fill=BOTH, expand=1)\n self.room_table.bind(\"<ButtonRelease-1>\", self.get_cursor)\n self.fetch_data()\n\n #add data\n def add_data(self):\n if self.var_contact.get() == \"\" or self.var_checkin.get() == \"\":\n messagebox.showerror('Error', 'all fields required',parent=self.root)\n\n else:\n try:\n conn=mysql.connector.connect(host=\"localhost\",user=\"root\",\n password=\"2589\",database='management')\n\n my_cursor = conn.cursor()\n my_cursor.execute('insert into room values(%s,%s,%s,%s,%s,'\n '%s,%s)',( self.var_contact.get(),\n self.var_checkin.get(),\n self.var_checkout.get(),\n self.var_roomtype.get(),\n self.var_roomavailable.get(),\n self.var_meal.get(),\n self.var_noofdays.get()\n ))\n\n conn.commit()\n self.fetch_data()\n conn.close()\n messagebox.showinfo('Success','room has been booked',parent=self.root)\n\n except Exception as es:\n messagebox.showwarning(\"warning\",f\"something went wrong:{str(es)}\",parent=self.root)\n\n\n\n #get cursor\n\n def get_cursor(self, event=''):\n cursor_row = self.room_table.focus()\n content = self.room_table.item(cursor_row)\n row = content['values']\n\n self.var_contact.set(row[0]),\n self.var_checkin.set(row[1]),\n self.var_checkout.set(row[2]),\n self.var_roomtype.set(row[3]),\n self.var_roomavailable.set(row[4]),\n self.var_meal.set(row[5]),\n self.var_noofdays.set(row[6])\n\n\n # update function\n def update(self):\n if self.var_contact.get() == \"\":\n messagebox.showerror(\"Error\", \"please enter mobile number\", parent=self.root)\n\n else:\n\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n my_cursor.execute(\n 'update room set check_in=%s,check_out=%s,roomtype=%s,roomavailable=%s,meal=%s,noOfdays=%s where Contact=%s',\n (\n\n self.var_checkin.get(),\n self.var_checkout.get(),\n self.var_roomtype.get(),\n self.var_roomavailable.get(),\n self.var_meal.get(),\n self.var_noofdays.get(),\n self.var_contact.get()\n ))\n\n\n conn.commit()\n self.fetch_data()\n conn.close()\n messagebox.showinfo('Update', 'Room details has been udated successfully', parent=self.root)\n\n # Delete function\n def mDelete(self):\n mDelete = messagebox.askyesno('Hotel Management System', 'Do you want to delete this customer?',\n parent=self.root)\n if mDelete > 0:\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n query = 'delete from room where Contact=%s'\n value = (self.var_contact.get(),)\n my_cursor.execute(query, value)\n else:\n if not mDelete:\n return\n\n conn.commit()\n self.fetch_data()\n conn.close()\n\n #reset\n def reset(self):\n self.var_contact.set(\"\"),\n self.var_checkin.set(\"\"),\n self.var_checkout.set(\"\"),\n self.var_roomtype.set(\"\"),\n self.var_roomavailable.set(\"\"),\n self.var_meal.set(\"\"),\n self.var_noofdays.set(\"\")\n self.var_paidtax.set(\"\")\n self.var_actualtotal.set(\"\")\n self.var_total.set(\"\")\n\n\n # FETCH DATA\n def fetch_data(self):\n conn = mysql.connector.connect(host='localhost', user='root', password='2589', database='management')\n\n my_cursor = conn.cursor()\n my_cursor.execute('select * from room')\n\n rows = my_cursor.fetchall()\n if len(rows) != 0:\n self.room_table.delete(*self.room_table.get_children())\n for i in rows:\n self.room_table.insert('', END, values=i)\n\n conn.commit()\n conn.close()\n\n\n\n\n # fetch CONTACT\n def Fetch_contact(self):\n if self.var_contact.get() == \"\":\n messagebox.showerror(\"Error\", \"please enter contact number\", parent=self.root)\n\n else:\n\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n query=(\"select Name from customer where Mobile=%s\")\n value=(self.var_contact.get(),)\n my_cursor.execute(query,value)\n row= my_cursor.fetchone()\n\n if row == None:\n messagebox.showerror('Error','This number not found',parent=self.root)\n\n else:\n conn.commit()\n conn.close()\n\n showDataframe = Frame(self.root, bd=4, relief=RIDGE,padx=2)\n showDataframe.place(x=450, y=55, width=300, height=180)\n\n #name\n lblName=Label(showDataframe,text='Name:',font=('arial',12,'bold'))\n lblName.place(x=0,y=0)\n\n lbl= Label(showDataframe,text=row,font=('arial',12,'bold'))\n lbl.place(x=90,y=0)\n\n #gender\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n query = (\"select Gender from customer where Mobile=%s\")\n value = (self.var_contact.get(),)\n my_cursor.execute(query, value)\n row = my_cursor.fetchone()\n\n lblGender = Label(showDataframe, text='Gender:', font=('arial', 12, 'bold'))\n lblGender.place(x=0, y=30)\n\n lbl2 = Label(showDataframe, text=row, font=('arial', 12, 'bold'))\n lbl2.place(x=90, y=30)\n\n #Email\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n query = (\"select Email from customer where Mobile=%s\")\n value = (self.var_contact.get(),)\n my_cursor.execute(query, value)\n row = my_cursor.fetchone()\n\n lblemail = Label(showDataframe, text='Email:', font=('arial', 12, 'bold'))\n lblemail.place(x=0, y=60)\n\n lbl3 = Label(showDataframe, text=row, font=('arial', 12, 'bold'))\n lbl3.place(x=90, y=60)\n\n\n #nationality\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n query = (\"select Nationality from customer where Mobile=%s\")\n value = (self.var_contact.get(),)\n my_cursor.execute(query, value)\n row = my_cursor.fetchone()\n\n lblNationality = Label(showDataframe, text='Nationality:', font=('arial', 12, 'bold'))\n lblNationality.place(x=0, y=90)\n\n lbl4 = Label(showDataframe, text=row, font=('arial', 12, 'bold'))\n lbl4.place(x=90, y=90)\n\n #address\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n query = (\"select Address from customer where Mobile=%s\")\n value = (self.var_contact.get(),)\n my_cursor.execute(query, value)\n row = my_cursor.fetchone()\n\n lbladdress = Label(showDataframe, text='Address:', font=('arial', 12, 'bold'))\n lbladdress.place(x=0, y=120)\n\n lbl5 = Label(showDataframe, text=row, font=('arial', 12, 'bold'))\n lbl5.place(x=90, y=120)\n\n\n #search system Function\n def search(self):\n conn = mysql.connector.connect(host='localhost', user='root',\n password='2589', database='management')\n\n my_cursor = conn.cursor()\n my_cursor.execute(\n \"select * from room where \" + str(self.search_var.get()) + \" LIKE '%\" + str(\n self.txt_search.get()) + \"%'\")\n rows = my_cursor.fetchall()\n if len(rows) != 0:\n self.room_table.delete(*self.room_table.get_children())\n for i in rows:\n self.room_table.insert(\"\", END, values=i)\n\n conn.commit()\n conn.close()\n\n def total(self):\n inDate = self.var_checkin.get()\n outDate=self.var_checkout.get()\n inDate = datetime.strptime(inDate,\"%d/%m/%Y\")\n outDate = datetime.strptime(outDate, \"%d/%m/%Y\")\n self.var_noofdays.set(abs(outDate-inDate).days)\n\n if self.var_meal.get()=='Breakfast' and self.var_roomtype.get()=='Luxury':\n q1=float(600)\n q2=float(5000)\n q3=float(self.var_noofdays.get())\n q4=float(q1+q2)\n q5=float(q3+q4)\n Tax=\"TK. \"+str(\"%.2f\"%((q5)*0.1))\n ST=\"TK. \"+str(\"%.2f\"%((q5)))\n TT=\"TK. \"+str(\"%.2f\"%(q5+((q5)*0.1)))\n self.var_paidtax.set(Tax)\n self.var_actualtotal.set(ST)\n self.var_total.set(TT)\n\n elif self.var_meal.get() == 'Beakfast' and self.var_roomtype.get() == 'Single':\n q1 = float(600)\n q2 = float(2000)\n q3 = float(self.var_noofdays.get())\n q4 = float(q1 + q2)\n q5 = float(q3 + q4)\n Tax = \"TK. \" + str(\"%.2f\" % ((q5) * 0.1))\n ST = \"TK. \" + str(\"%.2f\" % ((q5)))\n TT = \"TK. \" + str(\"%.2f\" % (q5 + ((q5) * 0.1)))\n self.var_paidtax.set(Tax)\n self.var_actualtotal.set(ST)\n self.var_total.set(TT)\n\n elif self.var_meal.get() == 'Breakfast' and self.var_roomtype.get() == 'Double':\n q1 = float(600)\n q2 = float(3500)\n q3 = float(self.var_noofdays.get())\n q4 = float(q1 + q2)\n q5 = float(q3 + q4)\n Tax = \"TK. \" + str(\"%.2f\" % ((q5) * 0.1))\n ST = \"TK. \" + str(\"%.2f\" % ((q5)))\n TT = \"TK. \" + str(\"%.2f\" % (q5 + ((q5) * 0.1)))\n self.var_paidtax.set(Tax)\n self.var_actualtotal.set(ST)\n self.var_total.set(TT)\n\n elif self.var_meal.get() == 'Lunch' and self.var_roomtype.get() == 'Single':\n q1 = float(1000)\n q2 = float(2000)\n q3 = float(self.var_noofdays.get())\n q4 = float(q1 + q2)\n q5 = float(q3 + q4)\n Tax = \"TK. \" + str(\"%.2f\" % ((q5) * 0.1))\n ST = \"TK. \" + str(\"%.2f\" % ((q5)))\n TT = \"TK. \" + str(\"%.2f\" % (q5 + ((q5) * 0.1)))\n self.var_paidtax.set(Tax)\n self.var_actualtotal.set(ST)\n self.var_total.set(TT)\n\n elif self.var_meal.get() == 'Dinner' and self.var_roomtype.get() == 'Double':\n q1 = float(1200)\n q2 = float(3500)\n q3 = float(self.var_noofdays.get())\n q4 = float(q1 + q2)\n q5 = float(q3 + q4)\n Tax = \"TK. \" + str(\"%.2f\" % ((q5) * 0.1))\n ST = \"TK. \" + str(\"%.2f\" % ((q5)))\n TT = \"TK. \" + str(\"%.2f\" % (q5 + ((q5) * 0.1)))\n self.var_paidtax.set(Tax)\n self.var_actualtotal.set(ST)\n self.var_total.set(TT)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n root=Tk()\n obj=Roombooking(root)\n root.mainloop()","sub_path":"Model/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":23901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"381485890","text":"import pygame, random\r\nclass Pipe(pygame.sprite.Sprite):\r\n def __init__(self):\r\n super().__init__()\r\n #add random here to randomize the height\r\n self.h = random.randrange(150,350)\r\n self.image = pygame.Surface((20,self.h))\r\n self.image.fill([0,255,0])\r\n self.rect = self.image.get_rect()\r\n self.spacing = 125\r\n\r\n def update(self):\r\n if self.rect.x <= 0:\r\n if self.rect.y == 0:\r\n self.__init__()\r\n self.rect.y = 0\r\n else:\r\n self.__init__()\r\n self.rect.y = 500 - self.h\r\n self.rect.x = 8 * self.spacing\r\n #self.image = pygame.Surface((20, self.h))\r\n #self.image.fill([0,255,0])\r\n self.rect.x+=-2\r\n","sub_path":"Sappy_bird/Pipe.py","file_name":"Pipe.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"342523413","text":"from pathlib import Path\nimport numpy as np\nfrom imageio import imwrite\n\nimport cv2\nimport os\nimport utils.viz_utils as vu\n\n\n\ndef visualize(case_name, vol, seg, destination, hu_min=vu.DEFAULT_HU_MIN, hu_max=vu.DEFAULT_HU_MAX,\n k_color=vu.DEFAULT_KIDNEY_COLOR, t_color=vu.DEFAULT_TUMOR_COLOR,\n alpha=vu.DEFAULT_OVERLAY_ALPHA):\n\n # Prepare output location\n out_path = Path(destination)\n if not out_path.exists():\n out_path.mkdir()\n\n print(\"Volume with id: \", case_name)\n # Convert to a visual format\n vol_ims = vu.hu_to_grayscale(vol, hu_min, hu_max)\n seg_ims = vu.class_to_color(seg, k_color, t_color)\n\n print(\"creating video...\")\n\n # Overlay the segmentation colors\n viz_ims = vu.overlay(vol_ims, seg_ims, seg, alpha)\n height, width, layers = viz_ims[0].shape\n\n frame_rate = 10\n\n video_file_name = (str(out_path / case_name) + \"_pred.mp4v\")\n print(video_file_name)\n\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n video = cv2.VideoWriter(video_file_name, fourcc, frame_rate, (width, height))\n print(vol.shape)\n print(viz_ims.shape)\n for i in range(viz_ims.shape[0]):\n video.write(viz_ims[i])\n video.release()\n\n if os.path.exists(video_file_name):\n print(\"video file created\")\n else:\n print(\"The video file failed to get created\")\n png_path = out_path / case_name\n png_path.mkdir()\n for i in range(viz_ims.shape[0]):\n fpath = png_path / (\"{:05d}.png\".format(i))\n imwrite(str(fpath), viz_ims[i])\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"269838205","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\n#from sklearn.model_selection import train_test_split\r\nimport shutil\r\n\r\ndef filter_jpg(file_dir):\r\n\r\n J=[] #jpg_list\r\n J1 = []\r\n for root, dirs, files in os.walk(file_dir):\r\n \"\"\"循环当前目录下的文件名,将jpg图片名循环存入J列表中\"\"\"\r\n for file in files:\r\n if os.path.splitext(file)[1] == '.jpg':\r\n J.append(file)\r\n if os.path.splitext(file)[1] == '.xml':\r\n J1.append(file)\r\n\r\n # \"\"\"分离训练集、验证集 3:1\"\"\"\r\n # result = train_test_split(J, test_size=0.25, random_state=0)\r\n # train_list = result[0]\r\n # eval_list = result[1] #预测试图片列表\r\n #\r\n # \"\"\"把标记出的训练xml文件复制到新文件夹即可,注意比较下复制和移动\"\"\"\r\n # for train in train_list:\r\n # shutil.copy(root + \"/\" + train, \"D:/ship/ship_name/test/gao_data/test_img1707/train_jpg\")\r\n #\r\n # \"\"\"把标记出的eval、test图片复制到新文件夹即可,注意比较下复制和移动\"\"\"\r\n # for eval in eval_list:\r\n # shutil.copy(root + \"/\" + eval, \"D:/ship/ship_name/test/gao_data/test_img1707/eval_jpg\")\r\n\r\n for jpg in J:\r\n shutil.copy(root + \"/\" + jpg, \"/home/workstation/darknet/VOCdevkit/VOC2019/JPEGImages\")\r\n\r\n for xml in J1:\r\n shutil.copy(root + \"/\" + xml, \"/home/workstation/darknet/VOCdevkit/VOC2019/Annotations\")\r\n\r\nfilter_jpg(\"/media/workstation/40A44BADA44BA3EE/杨庄系船柱标注\")\r\n\r\n\r\n","sub_path":"k-means-new-anchors/filter_jpg.py","file_name":"filter_jpg.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"486798733","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2020 Alibaba Group Holding Limited.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport base64\nimport json\nimport sys\nfrom typing import Dict\n\nimport fsspec\nimport pyarrow as pa\nimport pyorc\nimport vineyard\nfrom fsspec.utils import read_block\nfrom vineyard.io.byte import ByteStreamBuilder\n\nimport ossfs\n\nfsspec.register_implementation(\"oss\", ossfs.OSSFileSystem)\n\n\ndef read_bytes(\n vineyard_socket: str,\n path: str,\n storage_options: Dict,\n read_options: Dict,\n proc_num: int,\n proc_index: int,\n):\n client = vineyard.connect(vineyard_socket)\n builder = ByteStreamBuilder(client)\n\n header_row = read_options.get(\"header_row\", False)\n for k, v in read_options.items():\n if k in (\"header_row\", \"include_all_columns\"):\n builder[k] = \"1\" if v else \"0\"\n elif k == \"delimiter\":\n builder[k] = bytes(v, \"utf-8\").decode(\"unicode_escape\")\n else:\n builder[k] = v\n\n offset = 0\n chunk_size = 1024 * 1024 * 4\n of = fsspec.open(path, mode=\"rb\", **storage_options)\n with of as f:\n header_line = read_block(f, 0, 1, b'\\n')\n builder[\"header_line\"] = header_line.decode(\"unicode_escape\")\n if header_row:\n offset = len(header_line)\n stream = builder.seal(client)\n client.persist(stream)\n ret = {\"type\": \"return\", \"content\": repr(stream.id)}\n print(json.dumps(ret), flush=True)\n\n writer = stream.open_writer(client)\n try:\n total_size = f.size()\n except TypeError:\n total_size = f.size\n part_size = (total_size - offset) // proc_num\n begin = part_size * proc_index + offset\n end = min(begin + part_size, total_size)\n if proc_index == 0:\n begin -= int(header_row)\n\n while begin < end:\n buf = read_block(f, begin, min(chunk_size, end - begin), delimiter=b\"\\n\")\n size = len(buf)\n if not size:\n break\n begin += size - 1\n chunk = writer.next(size)\n buf_writer = pa.FixedSizeBufferWriter(chunk)\n buf_writer.write(buf)\n buf_writer.close()\n\n writer.finish()\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 7:\n print(\n \"usage: ./read_bytes <ipc_socket> <path> <storage_options> <read_options> <proc_num> <proc_index>\"\n )\n exit(1)\n ipc_socket = sys.argv[1]\n path = sys.argv[2]\n storage_options = json.loads(\n base64.b64decode(sys.argv[3].encode(\"utf-8\")).decode(\"utf-8\")\n )\n read_options = json.loads(\n base64.b64decode(sys.argv[4].encode(\"utf-8\")).decode(\"utf-8\")\n )\n proc_num = int(sys.argv[5])\n proc_index = int(sys.argv[6])\n read_bytes(ipc_socket, path, storage_options, read_options, proc_num, proc_index)\n","sub_path":"modules/io/adaptors/read_bytes.py","file_name":"read_bytes.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"16443285","text":"# Copyright (c) 2020, Xilinx, Inc.\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright \n# notice, this list of conditions and the following disclaimer in the \n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its \n# contributors may be used to endorse or promote products derived from \n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, \n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR \n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR \n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom brevitas.core.bit_width import BitWidthImplType\nfrom brevitas.core.quant import QuantType\nfrom brevitas.core.restrict_val import RestrictValueType\nfrom brevitas.core.scaling import ScalingImplType\nfrom brevitas.core.stats import StatsOp\nfrom brevitas.nn import QuantConv2d, QuantHardTanh, QuantLinear\n# Quant common\nBIT_WIDTH_IMPL_TYPE = BitWidthImplType.CONST\nSCALING_VALUE_TYPE = RestrictValueType.LOG_FP\nSCALING_IMPL_TYPE = ScalingImplType.PARAMETER\nNARROW_RANGE_ENABLED = True\n\n# Weight quant common\nSTATS_OP = StatsOp.MEAN_LEARN_SIGMA_STD\nBIAS_ENABLED = False\nWEIGHT_SCALING_IMPL_TYPE = ScalingImplType.STATS\nSIGMA = 0.001\n\n# QuantHardTanh configuration\nHARD_TANH_MIN = -1.0\nHARD_TANH_MAX = 1.0\nACT_PER_OUT_CH_SCALING = False\n\n# QuantConv2d configuration\nKERNEL_SIZE = 3\nCONV_PER_OUT_CH_SCALING = True\n\n\ndef get_stats_op(quant_type):\n if quant_type == QuantType.BINARY:\n return StatsOp.AVE\n else:\n return StatsOp.MAX\n\n\ndef get_quant_type(bit_width):\n if bit_width is None:\n return QuantType.FP\n elif bit_width == 1:\n return QuantType.BINARY\n else:\n return QuantType.INT\n\n\ndef get_act_quant(act_bit_width, act_quant_type):\n if act_quant_type == QuantType.INT:\n act_scaling_impl_type = ScalingImplType.PARAMETER\n else:\n act_scaling_impl_type = ScalingImplType.CONST\n return QuantHardTanh(quant_type=act_quant_type,\n bit_width=act_bit_width,\n bit_width_impl_type=BIT_WIDTH_IMPL_TYPE,\n min_val=HARD_TANH_MIN,\n max_val=HARD_TANH_MAX,\n scaling_impl_type=act_scaling_impl_type,\n restrict_scaling_type=RestrictValueType.LOG_FP,\n scaling_per_channel=ACT_PER_OUT_CH_SCALING,\n narrow_range=NARROW_RANGE_ENABLED)\n\n\ndef get_quant_linear(in_features, out_features, per_out_ch_scaling, bit_width, quant_type, stats_op):\n return QuantLinear(bias=BIAS_ENABLED,\n in_features=in_features,\n out_features=out_features,\n weight_quant_type=quant_type,\n weight_bit_width=bit_width,\n weight_bit_width_impl_type=BIT_WIDTH_IMPL_TYPE,\n weight_scaling_per_output_channel=per_out_ch_scaling,\n weight_scaling_stats_op=stats_op,\n weight_scaling_stats_sigma=SIGMA)\n\n\ndef get_quant_conv2d(in_ch, out_ch, bit_width, quant_type, stats_op):\n return QuantConv2d(in_channels=in_ch,\n kernel_size=KERNEL_SIZE,\n out_channels=out_ch,\n weight_quant_type=quant_type,\n weight_bit_width=bit_width,\n weight_narrow_range=NARROW_RANGE_ENABLED,\n weight_scaling_impl_type=WEIGHT_SCALING_IMPL_TYPE,\n weight_scaling_stats_op=stats_op,\n weight_scaling_stats_sigma=SIGMA,\n weight_scaling_per_output_channel=CONV_PER_OUT_CH_SCALING,\n weight_restrict_scaling_type=SCALING_VALUE_TYPE,\n weight_bit_width_impl_type=BIT_WIDTH_IMPL_TYPE,\n bias=BIAS_ENABLED)\n","sub_path":"trainablePreprocessing_examples/cifar_classification/models/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"97942917","text":"\"\"\" Paper-related APIs. \"\"\"\nimport os\nfrom flask import request, jsonify, g\nfrom sqlalchemy.exc import ProgrammingError\n\nfrom app import db\nfrom app.models import *\nfrom app.schemas import *\nfrom app.util.core import *\nfrom app.util.data import *\nfrom app.util.perm import auth_required\n\n@register_view(\"/papers\")\nclass PaperView(APIView):\n \"\"\" User view class. \"\"\"\n def list(self):\n \"\"\" List all users. \"\"\"\n papers = filter_user(Paper.query, Paper).all()\n # Success\n return jsonify(\n **SUCCESS_RESP,\n data=dump_data(PaperSchema, papers, many=True, nested_user=True)\n )\n @auth_required()\n def create(self):\n \"\"\" Create a new user. \"\"\"\n # Load user data\n paper = load_data(PaperSchema, {**get_data(), \"author\": g.user})\n # Add to database\n with map_error({ProgrammingError: handle_prog_error}):\n db.session.add(paper)\n db.session.commit()\n # Success\n return jsonify(\n **SUCCESS_RESP,\n data=dump_data(PaperSchema, paper)\n )\n def retrieve(self, id):\n \"\"\" Get existing user information. \"\"\"\n paper = get_pk(Paper, id)\n return jsonify(\n **SUCCESS_RESP,\n data=dump_data(PaperSchema, paper, nested_user=True)\n )\n def partial_update(self, id):\n \"\"\" Update user information. \"\"\"\n # Load update data, then find and update user\n paper = get_pk(Paper, id)\n with map_error({ProgrammingError: handle_prog_error}):\n load_data(PaperSchema, get_data(), instance=paper)\n db.session.commit()\n # Success\n return jsonify(\n **SUCCESS_RESP,\n data=dump_data(UserSchema, paper)\n )\n def destroy(self, id):\n \"\"\" Remove user. \"\"\"\n # Find and remove user\n paper = get_pk(Paper, id)\n db.session.delete(paper)\n db.session.commit()\n # Success\n return jsonify(**SUCCESS_RESP)\n @inst_action(\"toggle_collect_status\")\n @auth_required()\n def toggle_collect_status(self, id):\n \"\"\" Toggle paper collection status. \"\"\"\n # Find paper\n paper = get_pk(Paper, id)\n user = g.user\n # Cancel collection\n if user in paper.collectors:\n paper.collectors.remove(user)\n db.session.commit()\n return jsonify(\n **SUCCESS_RESP,\n collected=False\n )\n # Collect paper\n else:\n paper.collectors.append(user)\n db.session.commit()\n return jsonify(\n **SUCCESS_RESP,\n collected=True\n )\n","sub_path":"app/views/paper.py","file_name":"paper.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"254951548","text":"#Q.6 減色処理\nimport numpy as np\nimport cv2\n\ndef decrease_color(img):\n out = img.copy()\n\n out = out // 64 * 64 + 32\n\n return out\n\n#Read image\nimg = cv2.imread(\"imori.jpg\")\n\n#Dicrease color\nout = dicrease_color(img)\n\ncv2.imwrite(\"out.jpg\", out)\ncv2.imshow(\"result\",out)\ncv2.waitkey(0)\n \n","sub_path":"study/decrease_color.py","file_name":"decrease_color.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"523841942","text":"import random\n\ndef gcd(a, b):\n while a != 0:\n a, b = b % a, a\n return b\n\ndef FindInverse(n2, n1):\n if gcd(n1, n2) != 1:\n raise Exception(\"GCD of {} and {} aren't equal 1 so it don't have Inverse\".format(n1, n2))\n\n tempMod = n1\n r, q = (n1 % n2, n1 // n2)\n a1, b1, a2, b2 = (1, 0, 0, 1)\n while r != 0:\n tempA2 = a2\n tempB2 = b2\n a2 = a1 - q * a2\n b2 = b1 - q * b2\n a1, b1 = tempA2, tempB2\n n1, n2 = n2, r\n r, q = (n1 % n2, n1 // n2)\n if n2 != 1 :\n return \"GCD not equal 1\"\n return b2 % tempMod\n\n# FastExponential\ndef FastExponential(base, expo, mod):\n result = 1\n if 1 & expo:\n result = base \n while expo:\n expo = expo >> 1\n base = (base * base) % mod\n if expo & 1:\n result = (base * result) % mod\n return result\n\n# Lehmann Test\ndef isPrime(n, t):\n a = random.randint(2, n-1)\n expo = (n-1)//2\n\n while t>0:\n result = FastExponential(a,expo,n)\n\n if result == 1 or result == n-1:\n a = random.randint(2, n-1)\n t -= 1\n else: \n return False # Not Prime\n return True # Prime\n\n# RSA Key Generator\ndef generateLargePrime(keysize):\n while True:\n num = random.randrange(2**(keysize-1),2**(keysize))\n if isPrime(num, 1000):\n return num\n\ndef generateKey(keysize):\n p = generateLargePrime(keysize)\n q = generateLargePrime(keysize)\n n = p * q\n m = (p-1)*(q-1)\n\n while True:\n e = random.randrange(2**(keysize - 1), 2**(keysize))\n if gcd(e, m) == 1:\n break\n \n d = FindInverse(e, m)\n publicKey = (n, e)\n privateKey = (n, d)\n \n return (publicKey, privateKey)\n\n# publicKey, privateKey = generateKey(100)\n# print(\"generate publicKey \", publicKey)\n# print(\"generate privateKey \", privateKey)\n\ndef GenP(n, file):\n f = open(file, \"rb\")\n byte = f.read()\n readByte = n // 8\n\n skipZero = 0\n while byte[skipZero] == 0:\n skipZero += 1\n i = skipZero\n\n bitString = ''.join(format(i, '08b') for i in byte[skipZero:(skipZero+readByte+2)])\n\n startPos = 0\n for i in range(0, len(bitString)): \n if bitString[i] == '1': \n startPos = i + 1\n break\n\n bitString = bitString[(startPos - 1):n + (startPos - 1)]\n decimal = int(bitString, 2)\n\n if decimal >= 2**(n-1) or decimal <= 2**n:\n while True:\n if isPrime(decimal, 1000):\n return decimal\n decimal += 1\n else:\n return -1\n\ndef getGenerator(alpha, p):\n if isPrime(p, 1000) == False:\n raise Exception('To get generator of Zp P must be Prime')\n\n # if isPrime((p - 1)//2, 1000) == False:\n # return -1\n\n if FastExponential(alpha, (p - 1)//2, p) != 1:\n return alpha\n else: \n return -alpha % p\n\ndef FindGenerator(p):\n s = set()\n\n while len(s) <= 2:\n # alpha not equal to +-1 mod p\n alpha = random.randrange(2, p-1)\n g = getGenerator(alpha, p)\n s.add(g)\n \n return s\n\ndef GenG(p):\n alpha = random.randrange(2, p-1)\n g = getGenerator(alpha, p)\n return g\n\n\n# Elgamal Algorithm\ndef GenKey(p):\n key = random.randrange(1,p-1)\n while gcd(key, p-1) != 1:\n key = random.randrange(1,p-1)\n return key\n\ndef ElgamalKeyGenerator(keySize, file):\n p = GenP(keySize ,file)\n g = GenG(p)\n u = random.randrange(1, p)\n y = FastExponential(g,u,p)\n publicKey = (p, g, y)\n privateKey = u\n return (publicKey, privateKey)\n\ndef ElgamalEncrypt(plainText, publicKey):\n p, g, y = publicKey\n b = []\n print(\"Generate Key...\")\n k = GenKey(p)\n a = FastExponential(g,k,p)\n partB = FastExponential(y,k,p)\n\n for i in range(len(plainText)):\n b.append((partB * ord(plainText[i])) % p)\n # b = (FastExponential(y,k,p) * plainText) % p\n return (a, b), p\n\ndef ElgamalDecrypt(cipherText, privateKey, p):\n a, b = cipherText\n x = []\n for i in range(0, len(b)):\n x.append(b[i] * FindInverse(FastExponential(a,privateKey,p), p) % p)\n # x = b * FindInverse(FastExponential(a,privateKey,p), p) % p\n return x\n\nwhile True:\n print('Please Select')\n print('1.Generate Prime')\n print('2.Find Inverse')\n print('3.Find Generator')\n print('4.Elgamal')\n print('5.Elgamal Encrypt')\n print('6.Elgamal Decrypt')\n print('7.Exit')\n\n choice = input('Input : ')\n if choice == '1':\n keySize = input('Key Size :')\n file = input('File :')\n g = GenP(int(keySize), file)\n print('Prime is ', g)\n elif choice == '2':\n value = input('Value : ')\n mod = input('Mod With : ')\n inverse = FindInverse(int(value),int(mod))\n print('Inverse of {} % {} is {}'.format(value,mod,inverse))\n elif choice == '3':\n prime = input('Prime Value : ')\n g = FindGenerator(int(prime))\n print('Generator is ', g)\n elif choice == '4':\n # Bob\n plainText = input('Plaintext : ')\n keySize = input('KeySize : ')\n file = input('File to read and gen key : ')\n publicKey, privateKey = ElgamalKeyGenerator(int(keySize),file)\n cipherText, p = ElgamalEncrypt(plainText, publicKey)\n\n # Alice\n plainText = ElgamalDecrypt(cipherText, privateKey, p)\n\n print('Public Key', publicKey)\n print('Private Key', privateKey)\n print('Ciphertext', cipherText)\n print('Plaintext', plainText)\n\n # To String\n decryptString = \"\"\n for i in range(len(plainText)):\n decryptString += chr(plainText[i])\n\n print('To String:',decryptString)\n elif choice == '5':\n fname = input('File to encrypt : ')\n f = open(fname, 'rb')\n enc = f.read().decode()\n keySize = input('KeySize : ')\n file = input('File to read and gen key : ')\n publicKey, privateKey = ElgamalKeyGenerator(int(keySize),file)\n f = open(f'{fname}.key', 'w')\n f.write(hex(privateKey)[2:])\n f = open(f'{fname}.pub', 'w')\n f.write(','.join(hex(x)[2:] for x in publicKey))\n cipherText, p = ElgamalEncrypt(enc, publicKey)\n f = open(f'{fname}.enc', 'w')\n a = cipherText[0]\n b = cipherText[1]\n f.write(hex(a)[2:])\n f.write(',')\n f.write(','.join(hex(x)[2:] for x in b))\n f.write(',')\n f.write(hex(p)[2:])\n f.close()\n elif choice == '6':\n privateKeyf = input('Private key file: ')\n cipherTextf = input('Ciphertext file: ')\n\n f = open(privateKeyf, 'r')\n privateKeyhex = f.read()\n privateKey = int(privateKeyhex, 16)\n f = open(cipherTextf, 'r')\n cipherTextdump = f.read()\n cipherTextlist = cipherTextdump.split(',')\n a = int(cipherTextlist[0], 16)\n b = []\n bdump = cipherTextlist[1:-1]\n for i in bdump:\n b.append(int(i,16))\n p = int(cipherTextlist[-1], 16)\n cipherText = (a, b)\n\n plainText = ElgamalDecrypt(cipherText, privateKey, p)\n # To String\n decryptString = \"\"\n for i in range(len(plainText)):\n decryptString += chr(plainText[i])\n newfile = cipherTextf.split('enc')[0]\n f = open(f'{newfile}dec', 'w')\n f.write(decryptString)\n f.close()\n elif choice == '7':\n break\n else:\n continue\n","sub_path":"Crypto.py","file_name":"Crypto.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"306027241","text":"import cv2\nimport glob\nimport random\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\nfrom sklearn import metrics\n\nemotions = [\"neutral\", \"anger\", \"contempt\", \"disgust\", \"fear\", \"happy\", \"sadness\", \"surprise\"] #Emotion list\n#fishface = cv2.createFisherFaceRecognizer() #Initialize fisher face classifier\n\ndata = {}\n\ndef get_files(emotion): #Define function to get file list, randomly shuffle it and split 80/20\n files = glob.glob(\"dataset/%s/*\" %emotion)\n random.seed(1)\n random.shuffle(files)\n training = files[:int(len(files)*0.8)] #get first 80% of file list\n prediction = files[-int(len(files)*0.2):] #get last 20% of file list\n return training, prediction\n\ndef make_sets():\n training_data = []\n training_labels = []\n prediction_data = []\n prediction_labels = []\n for emotion in emotions:\n training, prediction = get_files(emotion)\n #Append data to training and prediction list, and generate labels 0-7\n for item in training:\n image = cv2.imread(item) #open image\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #convert to grayscale\n training_data.append(gray) #append image array to training data list\n training_labels.append(emotions.index(emotion))\n \n for item in prediction: #repeat above process for prediction set\n image = cv2.imread(item)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n prediction_data.append(gray)\n prediction_labels.append(emotions.index(emotion))\n\n return training_data, training_labels, prediction_data, prediction_labels\n\ntraining_data, training_labels, prediction_data, prediction_labels = make_sets()\n\nx=np.zeros((len(training_data),122500))\nfor i in xrange(0,len(training_data)):\n x[i]=np.ravel(training_data[i])\n\ny=np.array(training_labels)\n\nxtest=np.zeros((len(prediction_data),122500))\nfor i in xrange(0,len(prediction_data)):\n xtest[i]=np.ravel(prediction_data[i])\n\nytest=np.array(prediction_labels)\npca = PCA(n_components=100, svd_solver='randomized', whiten=True).fit(x)\n\nX_train_pca = pca.transform(x)\n\nX_test_pca = pca.transform(xtest)\n\nclf = SVC(kernel='linear',random_state=1)\n\nclf.fit(X_train_pca,y)\n\npredicted=clf.predict(X_test_pca)\n\nprint(\"Classification report:\")\nprint(metrics.classification_report(ytest, predicted))\nprint(\"Confusion Matrix\")\nprint( metrics.confusion_matrix(ytest, predicted))\nprint(\"\\nPrediction Score\")\nprint(clf.score(X_test_pca, ytest))","sub_path":"Final_Project/linear_svm_pca_all_emotions.py","file_name":"linear_svm_pca_all_emotions.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"98695984","text":"from bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport random\nimport time\nimport csv\n\n\n\nclass Google:\n def __init__(self):\n self.ID_URLS = list()\n with open('input.csv') as f:\n reader = csv.reader(f)\n for row in reader:\n self.ID_URLS.append([row[0], row[2]])\n del(self.ID_URLS[0])\n\n self.scraped_urls = set()\n try:\n with open('result.csv') as f:\n reader = csv.reader(f)\n for line in reader:\n self.scraped_urls.add(line[0])\n except FileNotFoundError:\n pass\n\n # print(self.scraped_urls)\n self.driver = webdriver.Chrome()\n input('Press enter...')\n\n def get_data(self, id_site, keyword):\n search = self.driver.find_element_by_id('lst-ib')\n search.clear()\n search.send_keys(keyword)\n search.submit()\n time.sleep(3)\n soup = BeautifulSoup(self.driver.page_source, 'lxml')\n if not soup.find('div', class_='g'):\n if 'не знайдено жодного документа' in self.driver.page_source:\n return [[id_site, None, None, None, None, None, None]]\n else:\n input('Press enter...')\n soup = BeautifulSoup(self.driver.page_source, 'lxml')\n if 'не знайдено жодного документа' in self.driver.page_source:\n return [[id_site, None, None, None, None, None, None]]\n result = []\n for g in soup.find_all('div', class_='g'):\n name = g.find('a').get_text().split('|')[0].strip()\n url = g.find('cite').get_text(strip=True)\n # location, job title, company\n slp_f = g.find('div', class_='slp f')\n if slp_f:\n slp_f = slp_f.get_text(strip=True).split(' - ')\n if len(slp_f) > 2:\n location, *job_title, company = slp_f\n else:\n location, *job_title = slp_f\n company = None\n\n if isinstance(job_title, list):\n job_title = ' '.join(job_title)\n else:\n location, job_title, company = None, None, None\n bio = g.find('span', class_='st').get_text()\n result.append([id_site, name, url, location, job_title, company, bio])\n return result\n\n def write_data_into_file(self, data):\n with open('result.csv', 'a') as f:\n writer = csv.writer(f)\n writer.writerows(data)\n\n def write_scraped_url(self, url):\n with open('scraped_urls.txt', 'a') as f:\n f.write(url + '\\n')\n\n def write_bad_url(self, url):\n with open('bad.txt', 'a') as f:\n f.write(url + '\\n')\n\n def main(self):\n for id_, url in self.ID_URLS:\n if id_ not in self.scraped_urls:\n data = self.get_data(id_, url)\n self.write_data_into_file(data)\n self.write_scraped_url(id_)\n print(id_, url)\n time.sleep(random.randint(5, 7))\n\n\nif __name__ == \"__main__\":\n g = Google()\n g.main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"115268634","text":"# Python3 code to Find the minimum\r\n# distance between two numbers\r\n\r\n\r\ndef minDist(arr, n, x, y):\r\n\tmin_dist = 99999999\r\n\tfor i in range(n):\r\n\t\tfor j in range(i + 1, n):\r\n\t\t\tif (x == arr[i] and y == arr[j] or\r\n\t\t\t\t\ty == arr[i] and x == arr[j]) and min_dist > abs(i-j):\r\n\t\t\t\tmin_dist = abs(i-j)\r\n\t\treturn min_dist\r\n\r\n\r\n# Driver code\r\narr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]\r\nn = len(arr)\r\nx = 3\r\ny = 6\r\nprint(\"Minimum distance between \", x, \" and \",\r\n\ty, \"is\", minDist(arr, n, x, y))\r\n\r\n# This code is contributed by \"Abhishek Sharma 44\"\r\n","sub_path":"Array/find_maxm_distance_between_two_number.py","file_name":"find_maxm_distance_between_two_number.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"61599835","text":"import os\nfrom pathlib import Path\n\nimport sounddevice as sd\nimport soundfile as sf\n\nfrom speechbrain.pretrained import TransformerASR\n\n\ndef audio_to_string(audio_path='record', duration=5, sample_rate=48000, voice_model_path='data/voice_model/'):\n voice_model_path = Path(voice_model_path)\n print('Loading voice recognition model...')\n\n asr_model = TransformerASR.from_hparams(\n source=\"speechbrain/asr-transformer-transformerlm-librispeech\",\n savedir=str(voice_model_path),\n )\n\n transcription = ''\n cleanup = False\n\n if audio_path == 'record':\n print(\"No audio files were provided, entering recording mode...\")\n input(f'Ready to record {duration} seconds of audio. Press [ENTER] ')\n selection = 'n'\n\n audio_path = str(voice_model_path / 'temp_recording.wav')\n recording = None\n\n while 'n' in selection:\n print('Recording...')\n recording = sd.rec(int(duration * sample_rate),\n samplerate=sample_rate,\n channels=2)\n sd.wait()\n\n print('Playing your recording...')\n sd.play(recording, sample_rate)\n selection = input('Keep this result? [y/n]: ').lower()\n\n sf.write(audio_path, recording, sample_rate, format='WAV')\n cleanup = True\n\n print('Performing transcription...')\n transcription = asr_model.transcribe_file(audio_path)\n print('The transcription: ', transcription)\n\n if cleanup:\n os.remove(audio_path)\n\n return [transcription]\n\n\nif __name__ == '__main__':\n print(audio_to_string())\n\n","sub_path":"src/voice_recognition.py","file_name":"voice_recognition.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"385637365","text":"from flask import Flask,jsonify,request\nimport json\nfrom pymongo import MongoClient\nfrom random import shuffle, random, sample\nimport utils\nimport cPickle as pickle\nimport redis\n\napp = Flask(__name__)\nsim_dicts = pickle.load(open('all_sim_dicts.pkl','r'))\ndb = utils.get_mongo_db()\nredcon = redis.StrictRedis()\n\ndistances = {\n ('Lands End','Sutro'):1000,\n ('Lands End','The Barbary'):2000,\n ('Lands End','The Dome'):800,\n ('Lands End','Twin Peaks'):3500,\n ('Lands End','Panhandle'):3000,\n ('Panhandle','Sutro'):3000,\n ('Panhandle','The Barbary'):1200,\n ('Panhandle','The Dome'):2700,\n ('Panhandle','Twin Peaks'):500,\n ('Sutro','The Barbary'):1700,\n ('Sutro','The Dome'):1000,\n ('Sutro','Twin Peaks'):3000,\n ('The Barbary','The Dome'):1300,\n ('The Barbary','Twin Peaks'):1400,\n ('The Dome','Twin Peaks'):2700 }\n\ndef get_distance(s1,s2):\n if s1 == s2:\n return 0\n ss = [s1,s2]\n ss.sort()\n ss = tuple(ss)\n return distances[ss]\n\ndef sum_artists(data):\n artist_plays = {}\n max_seen = 0\n\n for k,v in data.items():\n v = v.lower()\n cur_count = artist_plays.get(v,0)+1\n artist_plays[v] = cur_count\n max_seen = max(max_seen,cur_count)\n\n for k,v in artist_plays.items():\n artist_plays[k] = artist_plays[k]/float(max_seen)\n\n artist_plays = artist_plays.items()\n artist_plays.sort(key=lambda x: x[1],reverse=True)\n return artist_plays\n\ndef calc_ua_scores(listen_scores):\n \"\"\" calculates user to artist scores. takes artist plays\n and mulitplies them by artist to artist sim scores \"\"\"\n outside_artists = utils.get_all_artists()\n scores = []\n for oa in outside_artists:\n oa = oa.lower()\n if oa not in sim_dicts:\n continue\n oa_dict = sim_dicts[oa]\n cur_oa_score = 0\n for (artist,listen_score) in listen_scores:\n artist=artist.lower()\n if oa == artist:\n sim_score = 150\n else:\n sim_score = oa_dict.get(artist,random())\n cur_oa_score += listen_score * sim_score\n scores.append((oa,cur_oa_score))\n\n scores.sort(key=lambda x:x[1],reverse=True)\n return scores\n\n@app.route('/get_schedule',methods=['GET','POST'])\n@utils.crossdomain(origin='*')\ndef get_schedule():\n if request.method == 'POST':\n data = request.form\n scores = sum_artists(data)\n best_scores = calc_ua_scores(scores)\n\n shuf_scores1 = list(best_scores)\n shuf_scores1 = sample(shuf_scores1[:10],10) + shuf_scores1[10:]\n\n shuf_scores2 = list(best_scores)\n shuf_scores2 = sample(shuf_scores2[:10],10) + shuf_scores2[10:]\n\n shuf_scores3 = list(best_scores)\n shuf_scores3 = sample(shuf_scores3[:10],10) + shuf_scores3[10:]\n \n redcon.set('tmpscores',json.dumps(best_scores))\n best_schedule = make_schedule_from_scores(best_scores)\n #shuf_schedule1 = make_schedule_from_scores(shuf_scores1)\n #shuf_schedule2 = make_schedule_from_scores(shuf_scores2)\n #shuf_schedule3 = make_schedule_from_scores(shuf_scores3)\n\n redcon.set('tmp',json.dumps(best_schedule))\n #print best_schedule\n return ''\n # save this somewhere\n else:\n setlist = json.loads(redcon.get('tmp'))\n best_scores = json.loads(redcon.get('tmpscores'))\n\n shuffs = []\n shuff_scores = []\n shuff_scheds = []\n for i in range(7): \n num_shuf = 15\n shuffs.append(list(best_scores))\n shuff_scores.append(sample(shuffs[i][:num_shuf],num_shuf) + shuffs[i][num_shuf:])\n shuff_scheds.append(make_schedule_from_scores(shuff_scores[i]))\n \n best_schedule = make_schedule_from_scores(best_scores)\n\n lazy_schedule = make_lazy_schedule_from_scores(best_scores)\n lazy_distance = schedule_to_distance(lazy_schedule)\n\n min_distance = 100\n mid_sched=None\n for sched in shuff_scheds:\n dist = schedule_to_distance(sched)\n if dist<min_distance:\n mid_sched = sched\n min_distance = dist\n\n return jsonify({\"setlist\":setlist,'distance':schedule_to_distance(setlist),'mid_setlist':mid_sched,'mid_distance':min_distance,'lazy_setlist':lazy_schedule,'lazy_distance':lazy_distance})\n\n #TODO return json\n\ndef check_overlap(set_d1,set_d2):\n if set_d1['day'] != set_d2['day']:\n return False\n\n if set_d1['start'] >= set_d2['start'] and set_d1['start'] < set_d2['end']:\n return True\n if set_d2['start'] >= set_d1['start'] and set_d2['start'] < set_d1['end']:\n return True\n\n return False\n\ndef get_artist_set(artist):\n return db.sets.find_one({'artist_name_lower':artist.lower()})\n\ndef clean_sort_sets(sets):\n sets.sort(key = lambda x: (x['day'],x['start']))\n for aset in sets:\n del aset['_id']\n return sets\n\ndef make_schedule_from_scores(scores):\n \"\"\" scores is a list of (outside_artist,score) tuples \"\"\"\n user_sets = []\n #scores.sort(key=lambda x:x[1],reverse=True)\n max_score=0\n for (artist,score) in scores:\n max_score = max(max_score,score)\n\n for (artist,score) in scores:\n the_set = get_artist_set(artist)\n if not the_set:\n continue\n to_add = True\n for booked_set in user_sets:\n if check_overlap(booked_set,the_set):\n to_add = False\n break\n if to_add:\n the_set['score']=score/float(max_score)\n user_sets.append(the_set)\n user_sets = clean_sort_sets(user_sets)\n return user_sets\n\ndef make_lazy_schedule_from_scores(scores):\n \"\"\" scores is a list of (outside_artist,score) tuples \"\"\"\n user_sets = []\n #scores.sort(key=lambda x:x[1],reverse=True)\n max_score=0\n for (artist,score) in scores:\n max_score = max(max_score,score)\n\n day_stage={}\n for (artist,score) in scores:\n the_set = get_artist_set(artist)\n if not the_set:\n continue\n\n if not day_stage.get(the_set['day']):\n day_stage[the_set['day']] = the_set['stage']\n else:\n if day_stage[the_set['day']] != the_set['stage']:\n continue\n \n to_add = True\n for booked_set in user_sets:\n if check_overlap(booked_set,the_set):\n to_add = False\n break\n if to_add:\n the_set['score']=score/float(max_score)\n user_sets.append(the_set)\n\n user_sets = clean_sort_sets(user_sets)\n return user_sets\n\ndef schedule_to_distance(schedule):\n total_dist = 0\n prev_set = schedule[0]\n\n for cur_set in schedule[1:]:\n if cur_set['day']==prev_set['day']:\n total_dist += get_distance(prev_set['stage'],cur_set['stage'])\n \n return total_dist/5280.\n\n@app.route('/debug')\n@utils.crossdomain(origin='*')\ndef debug():\n sets = list(db.sets.find())\n shuffle(sets)\n sets = sets[:10]\n sets.sort(key = lambda x: (x['day'],x['start']))\n setlist = []\n \n setlist = clean_sort_sets(sets[:10])\n return jsonify({\"setlist\":setlist})\n\n@app.route('/debug2')\n@utils.crossdomain(origin='*')\ndef debug2():\n oa = utils.get_all_artists()\n shuffle(oa)\n scores =[]\n for artist in oa[:40]:\n scores.append((artist,random()))\n \n setlist=make_schedule_from_scores(scores)\n\n return jsonify({\"setlist\":setlist,'distance':schedule_to_distance(setlist)})\n\nif __name__==\"__main__\":\n app.run(host='0.0.0.0',port=8080,debug=True)\n","sub_path":"parse-artists/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"647146526","text":"from ..converter_utils import let_user_pick\nfrom ..converter_utils import print_message as prmsg\nfrom ..converter_utils import run_ffmpeg\nfrom .base import Base\n\n\nclass Video(Base):\n \"\"\"Get user input to execute different video conversions\"\"\"\n\n def __init__(self, options, *args, **kwargs):\n super().__init__(options, *args, **kwargs)\n self.conversion_map = {\n 1: {\n 'option_text': 'Convert to .mp4',\n 'extension': 'mp4',\n 'params': {\n 'vcodec': 'libx264',\n 'crf': 20,\n 'acodec': 'aac',\n 'strict': 'experimental',\n },\n },\n 2: {\n 'option_text': 'Convert to .mov',\n 'extension': 'mov',\n 'params': {\n 'vcodec': 'libx264',\n 'crf': 20,\n 'acodec': 'aac',\n 'f': 'mov',\n },\n },\n 3: {\n 'option_text': 'Convert to .flv',\n 'extension': 'flv',\n 'params': {'vcodec': 'flv1', 'acodec': 'aac', 'strict': 'experimental'},\n },\n 4: {\n 'option_text': 'Convert to .mkv',\n 'extension': 'mkv',\n 'params': {\n 'vcodec': 'copy',\n 'acodec': 'copy',\n },\n },\n 5: {\n 'option_text': 'Extract audio (output in .mp3)',\n 'extension': 'mp3',\n 'params': {\n 'ar': '44100',\n 'ac': '2',\n 'ab': '320k',\n 'f': 'mp3',\n },\n },\n }\n\n def run(self):\n \"\"\"Run the Video command.\"\"\"\n chosen_option = let_user_pick(self.conversion_map)\n source_paths, output_paths, params = self.get_user_input(\n self.conversion_map[chosen_option]\n )\n for (source_path, output_path) in list(zip(source_paths, output_paths)):\n run_ffmpeg(source_path, output_path, params, self.options)\n prmsg('completed')\n","sub_path":"convert/commands/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"388237389","text":"import sys\nreadline = lambda: sys.stdin.readline().rstrip()\n\nfrom collections import deque\n\nclass Queue:\n def __init__(self):\n self.q = deque()\n self.__size = 0\n\n\n def empty(self):\n if self.__size == 0:\n return 1\n \n else:\n return 0\n\n \n def push(self, num):\n self.q.append(num)\n self.__size += 1\n\n \n def pop(self):\n if self.empty():\n return -1\n \n else:\n item = self.q.popleft()\n self.__size -= 1\n return item\n\n\n def size(self):\n return self.__size\n\n\n def front(self):\n if self.__size == 0:\n return -1\n\n else:\n return self.q[0]\n\n\n def back(self):\n if self.__size == 0:\n return -1\n\n else:\n return self.q[self.__size - 1]\n\n\n\nif __name__ == '__main__':\n N = int(readline())\n q = Queue()\n\n for _ in range(N):\n cmd = readline()\n if cmd[:4] == 'push':\n cmd, operand = cmd.split()\n operand = int(operand)\n func = getattr(q, 'push')\n func(operand)\n \n else:\n func = getattr(q, cmd)\n print(func())\n","sub_path":"baekjoonOJ/10845/10845.py","file_name":"10845.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"551256740","text":"#!/usr/bin/python\n\nimport sys\nsys.path.append('lib')\n\nfrom api import init_api\nfrom db import init_db\nfrom flask import Flask, request, redirect, g, render_template\nfrom flask.ext.assets import Environment, Bundle\nimport os\nfrom os import environ\nfrom werkzeug.exceptions import *\nimport yaml\n\n# Create and configure the app\napp = Flask(__name__)\napp.debug = environ.get('APP_ENV', 'devlopment') != 'production'\napp.config['PORT'] = int(environ.get('PORT', 8000))\napp.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE_URL', None)\napp.config['YT_API_KEY'] = environ.get('YOUTUBE_API_KEY', None)\napp.config['LASTFM_API_KEY'] = environ.get('LASTFM_API_KEY', None)\napp.config['LASTFM_API_SECRET'] = environ.get('LASTFM_API_SECRET', None)\n\n# Add route for language redirect\n@app.route('/')\ndef redirectLanguage():\n default = '/nl'\n acceptLanguage = request.headers.get('Accept-Language')\n if (acceptLanguage is None):\n return redirect(default)\n preferences = []\n for preference in acceptLanguage.split(','):\n if ';' in preference:\n preference = preference.split(';')\n if len(preference) != 2:\n continue\n if preference[1][0:1] == 'q=':\n preference[1] = int(preference[1][2:])\n else:\n preference[1] = 1\n preference = (preference[0].strip(), preference[1])\n else:\n preference = (preference.strip(), 1)\n preferences.append(preference)\n # Sort \n preferences.sort(key=lambda pref: pref[1], reverse=True)\n for preference in preferences:\n if os.path.isfile('i18n/' + preference[0] + '.yaml'):\n return redirect('/' + preference[0])\n redirect(default)\n\n# Register template filter\n@app.template_filter('i18n')\ndef i18n(s):\n translation = g.i18n\n for key in s.split('.'):\n if not key in translation:\n return s\n translation = translation[key]\n return translation\n \n# Add a route for the html page\n@app.route('/<string:lang>')\ndef index(lang):\n fname = 'i18n/' + lang + '.yaml'\n if not os.path.isfile(fname):\n raise NotFound()\n g.i18n = yaml.load(open(fname))\n return render_template('index.html', lang=lang)\n\n# Define the assets\nassets = Environment(app)\nassets.register('js', Bundle(\n 'js/index.js',\n 'js/Api.js',\n 'js/EventListener.js',\n 'js/Player.js',\n 'js/Playlist.js',\n 'js/Song.js',\n 'js/Controls.js',\n 'js/Queue.js',\n filters='jsmin',\n output='app.js'));\nassets.register('css', Bundle('css/style.css', output='app.css', filters='cssmin'));\n\n# Initialize the database\ninit_db(app)\n\n# Initialize the youtube api\nfrom youtube import YT\nYT(app.config['YT_API_KEY'])\n\n# Initialize the lastFM api\nfrom lastfm import LastFM\nLastFM(app.config['LASTFM_API_KEY'], app.config['LASTFM_API_SECRET'])\n\n# Initialize the api\ninit_api(app)\n\n# Start the app if this script is runned directly\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=app.config['PORT'])","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"219930580","text":"import math\r\nimport time\r\nfrom action import *\r\n\r\n\r\nMOTORRATIO = 1 #Speed of right wheel compared to left one.\r\nBASESPEED = 40 #Speed of robot.\r\nTURNSPEED = 1\r\nMAXDIST = 200 #Distance that can be covered in between one camera update at full power.\r\nMAXANGLE = 120 #Angle that can be convered between one camera update at full power.\r\nPOWERCHANGEDELAY = 0.2 #Number of seconds to wait between power shifts\r\n \r\ndef move(robot,action,tokens):\r\n \r\n CUBEMULTIPLIER = 1 + 0.5 * tokens #Compensate for drag of cube\r\n #Generates leftSpeed and rightSpeed from motor ratio(To go straight)\r\n if MOTORRATIO < 1:\r\n leftSpeed = BASESPEED\r\n rightSpeed = BASESPEED * MOTORRATIO \r\n else:\r\n leftSpeed = BASESPEED / MOTORRATIO\r\n rightSpeed = BASESPEED ## At this point LeftSpeed / RightSpeed = MOTORRATIO\r\n \r\n if leftSpeed * CUBEMULTIPLIER < 100 and rightSpeed * CUBEMULTIPLIER < 100:\r\n leftSpeed *= CUBEMULTIPLIER\r\n rightSpeed *= CUBEMULTIPLIER #Apply CUBEMULTIPLIER if possible\r\n elif leftSpeed > rightSpeed:\r\n rightSpeed *= 100 / leftSpeed\r\n leftSpeed = 100\r\n elif rightSpeed > leftSpeed:\r\n leftSpeed *= 100 / rightSpeed\r\n rightSpeed = 100\r\n \r\n if action.type == \"move\":\r\n if action.dist < MAXDIST * (BASESPEED/100.0): #If distance is too short\r\n multiplier = action.dist / (MAXDIST * (BASESPEED/100.0))\r\n leftSpeed *= multiplier\r\n rightSpeed *= multiplier\r\n \r\n turn = clamp(float(action.angle)/ float(MAXANGLE),-1,1) #Proportion to turn\r\n if turn < 0: #Turn left\r\n print(\"Turn left\")\r\n ###robot.motors[0].m0.power = leftSpeed * (1 + turn) / TURNSPEED\r\n powerMotor(robot, 0, leftSpeed * (1 + turn) / TURNSPEED)\r\n ###robot.motors[0].m1.power = rightSpeed\r\n powerMotor(robot, 1, rightSpeed)\r\n\r\n \r\n print(\"left speed: \" + str(leftSpeed * (1 + turn) / TURNSPEED))\r\n print(\"right speed: \" + str(rightSpeed))\r\n elif turn > 0: #Turn right\r\n print(\"Turn right\")\r\n ###robot.motors[0].m0.power = leftSpeed\r\n powerMotor(robot, 0, leftSpeed)\r\n ###robot.motors[0].m1.power = rightSpeed * (1 - turn) / TURNSPEED\r\n powerMotor(robot, 1, rightSpeed * (1 - turn) / TURNSPEED)\r\n \r\n print(\"left speed: \" + str(leftSpeed * (1 + turn) / TURNSPEED))\r\n print(\"right speed: \" + str(rightSpeed))\r\n else:\r\n ###robot.motors[0].m0.power = leftSpeed\r\n powerMotor(robot, 0, leftSpeed)\r\n\r\n \r\n ###robot.motors[0].m1.power = rightSpeed\r\n powerMotor(robot, 1, rightSpeed)\r\n\r\n \r\n elif action.type == \"stop\":\r\n ###robot.motors[0].m0.power = 0\r\n LChange = powerMotor(robot, 0, 0)\r\n ###robot.motors[0].m1.power = 0\r\n RChange = powerMotor(robot, 1, 0)\r\n\r\n \r\n \r\n elif action.type == \"turn\":\r\n \r\n if action.angle < 0:\r\n leftSpeed *= -1\r\n else:\r\n rightSpeed *= -1\r\n \r\n if action.angle < MAXANGLE:\r\n proportion = clamp(float(action.angle)/float(MAXANGLE) , -1 , 1) #Generate speed multiplier\r\n leftSpeed *= proportion\r\n rightSpeed *= proportion\r\n \r\n ###robot.motors[0].m0.power = leftSpeed\r\n powerMotor(robot, 0, leftSpeed)\r\n ###robot.motors[0].m1.power = rightSpeed\r\n powerMotor(robot, 1, rightSpeed)\r\n \r\n \r\n \r\n \r\n \r\ndef clamp(val,minimum,maximum):\r\n if val < minimum:\r\n return minimum\r\n if val > maximum:\r\n return maximum\r\n return val\r\n\r\nMotorList = [0,0] # Both motors start at 0\r\nMAXSAFECHANGE = 0.5 # Adjust as needed\r\n\r\ndef powerMotor(SInstance, MotorToChange, Value):\r\n # SInstance = Self instance, i.e. The robot instance from the API\r\n # MotorToChange = The index of the motor being powered\r\n # Value = The value of the change being done \r\n\r\n if Value == \"coast\": Value = 0 #Change to brake\r\n OldValue = Value\r\n\r\n if abs(Value - MotorList[MotorToChange]) > MAXSAFECHANGE:\r\n if Value - MotorList[MotorToChange] >= 0: Value = MotorList[MotorToChange] + MAXSAFECHANGE\r\n if Value - MotorList[MotorToChange] < 0: Value = MotorList[MotorToChange] - MAXSAFECHANGE\r\n\r\n Value = clamp(Value, -1, 1)\r\n\r\n # Value is now acceptable\r\n \r\n MotorList[MotorToChange] = Value\r\n if MotorToChange == 0: SInstance.motor_board.m0 = Value\r\n if MotorToChange == 1: SInstance.motor_board.m1 = Value\r\n\r\n if Value != OldValue: return False\r\n return True\r\n\r\n #Returns whether or not the value requested is the new power\r\n \r\n","sub_path":"hardware.py","file_name":"hardware.py","file_ext":"py","file_size_in_byte":4795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"222609144","text":"#!/usr/bin/python2\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport pickle\nimport seaborn as sns\nimport os.path\nimport corner\nimport copy\nimport sys\nimport pandas\nfrom astropy.io import fits\n\n#Set this to True for some debug output\ndebug = False\nif len(sys.argv) < 2:\n print(\"python2.7 do.py file file ...\")\n exit()\n\nfit_models = {}\nif debug:\n print(\"[debug] Pricessing \"+str(len(sys.argv)-1)+\" filenames to determine models needing plotting...\")\n\ndef bitFlagString(bitflags):\n remainders = []\n while bitflags != 0:\n remainders.append(bitflags % 2)\n bitflags = bitflags // 2\n string = \"\"\n for x in remainders[::-1]:\n string += str(x)\n return string\n\ndef openCatalog(filename):\n data = fits.open(filename)\n return data[1].data\n\ndef getCatalogValue(catalog,ID,field):\n intermediate = catalog[field]\n idx = np.where( catalog['ID']==ID )[0]\n return intermediate[idx]\n\ndef openPickle(filename):\n file = filename\n t_pkl = open(file, 'rb')\n params = pickle.load(t_pkl)\n t_pkl.close()\n return params\n\ndef savePickle(obj, filename):\n return pickle.dump( obj, open( filename, \"wb\" ))\n \n\ndef samplesPlot(filename):\n coeff = openPickle(filename)\n ndims = coeff.shape[0]\n nwalkers = coeff.shape[1]\n nsteps = coeff.shape[2]\n samples = np.swapaxes(copy.copy( coeff[:, :, nsteps/2:]).reshape((ndims, -1), order='F'), axis1=0, axis2=1)\n return samples\n\ndef doubleMADsfromMedian(y,thresh=4):\n # warning: this function does not check for NAs\n # nor does it address issues when\n # more than 50% of your data have identical values\n m = np.median(y)\n abs_dev = np.abs(y - m)\n left_mad = np.median(abs_dev[y <= m])\n right_mad = np.median(abs_dev[y >= m])\n y_mad = left_mad * np.ones(len(y))\n y_mad[y > m] = right_mad\n modified_z_score = 0.6745 * abs_dev / y_mad\n modified_z_score[y == m] = 0\n return np.where(modified_z_score < thresh)[0]\n\ndef cleanLocMin(filename):\n samples = samplesPlot(filename)\n for i in range(3):\n #print(len(samples[:,i]))\n keep_indecies = doubleMADsfromMedian(samples[:,i],thresh=3.0)\n samples = samples[keep_indecies,:]\n return samples\n\n\ncatalog = openCatalog('catalogs/combinedCatalog.fits')\n\noutdir = \"median_plots\"\npwd = os.getcwd()\noutdir = os.path.join(pwd,outdir)\ntry:\n os.stat(outdir)\nexcept:\n os.mkdir(outdir)\n\nfilenames = sys.argv[1:]\nlabels_timescales = [r\"$\\tau_1$\",r\"$\\tau_2$\",r\"$\\Sigma_{SF}$\",r\"$\\tau_{MA}$\"]\nlabels_chains = [r\"$\\alpha_1$\", r\"$\\alpha_2$\", r\"$\\beta_0$\",r\"$\\beta_1$\"]\ni = 0\nnumfiles = len(filenames)\n\nplt_labels = labels_timescales\nif \"Chains\" in filenames[0]:\n plt_labels = labels_chains\n\nsamples_a1 = []\nsamples_a2 = []\nsamples_b1 = []\nsamples_b2 = []\nids = []\nredshifts = []\n\n\nclass classifier():\n def __init__(self):\n self.memo = []\n \n def getClass(self,name):\n if name not in self.memo:\n self.memo.append(name)\n return self.memo.index(name)\n\nclassy = classifier()\n\nug = []\niz = []\n\nlogedd_ratios = []\nlogbhs = []\nloglbols = []\nredshifts = []\n\nfitme = []\n\ndef catalogToValue(x):\n if len(x) == 0:\n return -1\n return x[0]\n\nfor file in filenames:\n print(\"[\"+str(i)+\"/\"+str(numfiles)+\"](\"+str(int(float(i)/float(numfiles)*100))+\"%) \"+os.path.basename(os.path.dirname(os.path.abspath(file))) + \" \" + os.path.basename(file))\n current = openPickle(file)\n sample_a1 = [math.log(x) for x in current[0]]\n samples_a1.append(sample_a1)\n #samples_a2.append([ math.log(x) for x in current[1] ])\n #samples_b1.append([ math.log(x) for x in current[2] ])\n #samples_b2.append([ math.log(x) for x in current[3] ])\n\n id = os.path.basename(file).split('-')[0]\n ids.append(id)\n\n #logedd_ratios.append(catalogToValue(getCatalogValue(catalog,int(id),r'LOGEDD_RATIO')))\n #logbhs.append(catalogToValue(getCatalogValue(catalog,int(id),r'LOGBH')))\n #loglbols.append(catalogToValue(getCatalogValue(catalog,int(id),r'LOGLBOL')))\n redshift = catalogToValue(getCatalogValue(catalog,int(id),r'REDSHIFT'))\n luminosity = catalogToValue(getCatalogValue(catalog,int(id),r'LOGLBOL'))\n virialBHmass = catalogToValue(getCatalogValue(catalog,int(id),r'LOGBH'))\n #civ_fwhm = catalogToValue(getCatalogValue(catalog,int(id),r'LOGBH'))\n a1 = sample_a1[0]\n a2 = sample_a1[1]\n b0 = sample_a1[2]\n b1 = sample_a1[3]\n \n\n fitme.append([a1, a2, b0, b1, redshift, luminosity, virialBHmass])\n i += 1\n\nfitme = np.array(fitme)\n\ndef isDefault(x):\n x = float(x)\n if x == -1 or x == -9.9 or x == 0.0:\n return True\n return False\n\nimport time\nfrom sklearn import cluster\n\n\nfor i in range(10):\n j = 0.5 + 0.05*i\n print(j)\n dbscan = cluster.DBSCAN(eps=j)\n t0 = time.time()\n dbscan.fit(fitme)\n t1 = time.time()\n print(t1-t0)\n y_pred = dbscan.labels_.astype(np.int)\n \n \n title = r'~2200 AGNs and other Variables, CARMA 2-1, log($\\alpha_1$) vs.log($\\alpha_2$) DBSCAN Clustered'\n file_pre = \"loglog_alpha1_by_2_medians_together_clustered\"\n \n jet = plt.get_cmap('jet')#'tab20')\n fig = plt.figure()\n ax = plt.gca()\n plot_x = []\n plot_y = []\n plot_c = []\n for i in range(len(fitme[:,0])):\n if y_pred[i] != -1:\n plot_x.append(fitme[:,0][i])\n plot_y.append(fitme[:,1][i])\n plot_c.append(y_pred[i])\n cax = ax.scatter( plot_x, plot_y, c=plot_c, alpha = 0.5, edgecolors='none', cmap=jet )\n #cax = ax.scatter( fitme[:,0], fitme[:,1], c=y_pred, alpha = 0.5, edgecolors='none', cmap=jet )\n cbar = fig.colorbar(cax)\n ax.set_title(title)\n ax.set_xlabel(r'log($\\alpha_1$)')\n ax.set_ylabel(r'log($\\alpha_2$)')\n fig.savefig(os.path.join(outdir,file_pre))\n plt.show()\n plt.close(fig)\n\nsaveme = [ids, fitme, y_pred]\nsavePickle(saveme,\"pickled_fit_data_array.pkl\")\n\ndef plot(filename, colors, title):\n fig = plt.figure()\n ax = plt.gca()\n xs = [ x[0] for x in samples_a1 ]\n ys = [ x[1] for x in samples_a1 ]\n cs = colors\n jet = plt.get_cmap('jet')#'tab20')\n #jet = plt.get_cmap('rainbow')#'tab20')\n \n black_x = []\n black_y = []\n black_c = []\n color_x = []\n color_y = []\n color_c = []\n for i in range(len(xs)):\n if isDefault(cs[i]):\n black_x.append(xs[i])\n black_y.append(ys[i])\n black_c.append('black')\n else:\n color_x.append(xs[i])\n color_y.append(ys[i])\n color_c.append(cs[i])\n \n cax = ax.scatter( color_x, color_c, c=color_y, alpha = 0.5, edgecolors='none', cmap=jet )\n #cax = ax.scatter( xs, ys, c=cs, alpha=0.2, edgecolors='none', cmap=jet )\n #cax = ax.scatter( xs, cs, c=ys, alpha=0.2, edgecolors='none', cmap=jet )\n cbar = fig.colorbar(cax)\n #ax.scatter( black_x, black_y, c=black_c, alpha=0.1, edgecolors='none' )\n \n ax.set_title(title)\n ax.set_xlabel(r'log($\\alpha_1$)')\n ax.set_ylabel(r'log($\\alpha_2$)')\n ax.set_ylim([-15,25])\n ax.set_xlim([-10,15])\n \n fig.savefig(os.path.join(outdir,filename))#\"loglog_alpha1_by_2_redshift_medians_together.png\"))\n plt.show()\n plt.close(fig)\n\n#title = r'~2200 AGNs and other Variables, CARMA 2-1, log($\\alpha_1$) vs.log($\\alpha_2$)'\n#file_pre = \"loglog_alpha1_by_2_medians_together_\"\n#plot(file_pre + \"logedd_ratio.png\", logedd_ratios, title + r' Eddington Ratios')\n#plot(file_pre + \"logbh.png\", logbhs, title + r' Adopted Fiducial Virial BH Mass (Msum)')\n#plot(file_pre + \"loglbols.png\", loglbols, title + r' LBOL')\n#plot(file_pre + \"redshifts.png\", redshifts, title + r' Redshift')\n\n","sub_path":"plot_medians_all.py","file_name":"plot_medians_all.py","file_ext":"py","file_size_in_byte":7641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"320029357","text":"import arcade\nimport random\nimport snake\nimport apples\n\nclass Game(arcade.Window):\n def __init__(self, window_width, window_height, title):\n # sets up the window -got from arcade website\n super().__init__(window_width, window_height, title)\n # Display Variables\n self.window_width, self.window_height = window_width, window_height\n\n self.unit_row, self.unit_col = window_width//16, window_height//16 #separate the heigh and width into regular parts\n\n # Logic Variable\n self.score = 0\n self.lives = 3\n self.snake = snake.Snake(self.unit_row//2, self.unit_col//2) #creates snake\n self.apple_list = apples.Apples(self.unit_row, self.unit_col) #creates apples\n # 0: Start, 1: Running, 2: Pause, 3: End\n self.state = 0\n\n self.set_update_rate(0.12) #how fast game is running\n\n arcade.set_background_color(arcade.color.ASH_GREY) \n \n\n def check_eat(self):\n if self.state in (2,3) or len(self.apple_list) == 0:\n return #if game is paused, ended, or no apples, then it'll skip the whole function\n\n\n for apple_i, apple in enumerate(self.apple_list.apple_list):\n if self.snake.head() == apple: #when snake head touches apple\n self.score += 1\n self.apple_list.eat_apple(apple_i)\n self.snake.grow()\n self.apple_list.new_apple(self.snake.get_body()) #makes new apple not on snake\n\n # New Game\n def new_game(self):\n self.reset()\n self.score = 0\n self.lives = 3\n self.state = 0\n\n def reset(self):\n self.snake.clear() #snake in center with just the head\n self.apple_list.clear() #one new apple\n self.apple_list.new_apple(self.snake.get_body())\n \n def death(self):\n if self.lives > 1: \n self.lives -= 1\n self.reset()\n else:\n self.state = 3 #if no lives left then game is ended\n\n\n # COLLISIONS\n def isOutOfBoundaries(self, pos):\n if pos[0] in range(0, self.unit_row) and pos[1] in range(0, self.unit_col): #position is tested to check if it's in window\n return False #if it is then false\n return True\n\n def checkPositionAllowed(self): #checks if snake is dead\n if self.state in (2,3):\n return #if paused or ended, skip this function\n collides_with_body = False\n\n for i in range(1, len(self.snake)): #checks if snake runs into itself\n if self.snake.head() == self.snake.get_part(i):\n collides_with_body = True\n break\n if (collides_with_body or self.isOutOfBoundaries(self.snake.head())):\n self.death() #if snake runs into wall or itself, it dies\n\n def on_update(self, delta_time): #redraws snake\n if self.state in (0,1):\n self.snake.move()\n self.check_eat()\n self.checkPositionAllowed() #game logic\n\n \"\"\"Game I/O - Display Info\"\"\"\n def on_draw(self):\n \"\"\" Called whenever we need to draw the window. \"\"\"\n arcade.start_render()\n self.snake.draw()\n self.apple_list.draw()\n if self.state not in (2,3): #if not paused or ended, it shows score and lives\n stats_overlay(self.width, self.height-20, self.score, self.lives)\n if self.state == 2:\n pause_overlay(self.width//2, 7*self.height//12) #shows that it is paused\n if self.state == 3: #shows game over\n game_over_overlay(self.width//2, 7*self.height//12, self.score)\n\n def on_key_press(self, key, modifiers):\n \"\"\" Called whenever the user presses a key. \"\"\"\n if self.state == 0 and key in (arcade.key.UP, arcade.key.DOWN, arcade.key.LEFT, arcade.key.RIGHT):\n self.state = 1 #state of game turns to one when a game begins \n \n if key == arcade.key.P: #p pauses and unpauses the game\n if self.state in (1,2): #toggle math\n self.state = 3 - self.state\n elif self.state == 0: \n self.state = 2\n elif not self.state in (2,3): #if game is not paused or ended, direction is changed\n if key == arcade.key.DOWN:\n self.snake.set_direction(0)\n elif key == arcade.key.LEFT:\n self.snake.set_direction(1)\n elif key == arcade.key.UP:\n self.snake.set_direction(2)\n elif key == arcade.key.RIGHT:\n self.snake.set_direction(3)\n elif self.state == 3: #if game is ended, pressing space starts a new game\n if key == arcade.key.SPACE:\n self.new_game()\n\ndef stats_overlay(width, y, score, lives): #displays score and lives\n arcade.draw_text(\"Score: %d\" % (score), 20, y, arcade.color.ARSENIC, font_size=16)\n arcade.draw_text(\"Lives %d\" % (lives), width-20, y, arcade.color.ARSENIC, font_size=16, anchor_x=\"right\")\n\ndef pause_overlay(x, y): #displays the word pause\n arcade.draw_text(\"PAUSED\", x, y,arcade.color.ARSENIC,font_size=40, align=\"center\", anchor_x=\"center\")\n arcade.draw_text(\"Press P to continue.\", x, y-100, arcade.color.ARSENIC, font_size=16, align=\"center\", anchor_x=\"center\")\n\n\ndef game_over_overlay(x, y, score): #displays the game over\n arcade.draw_text(\"Game Over!\\nYou score %d points.\" % (score), x, y,arcade.color.ARSENIC,font_size=40, align=\"center\", anchor_x=\"center\")\n arcade.draw_text(\"Press SPACE to start a new game.\", x, y-100, arcade.color.ARSENIC, font_size=16, align=\"center\", anchor_x=\"center\")","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"29385209","text":"#\n# Example file for working with loops\n#\n\ndef main():\n x = 0\n\n# define a while loop: \n # executes a block of code while a particular condition evalutes true\n while (x<5):\n print(x)\n x = x+1\n\n# define a for loop:\n # A for loop is used for iterating over a sequence \n # (that is either a list, a tuple, a dictionary, a set, or a string). ... \n # With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.\n for x in range(5,10):\n print(x)\n\n\n # use a for loop over a collection\n days=[\"Monday\", \"Tue\", \"Wed\", \"Thurs\", \"Fri\", \"Sat\", \"Sun\"]\n for d in days:\n print(d)\n \n \n # use the break and continue statements\n # A break is used to \"break/stop\" the executon of a loop if a condition is met\n for x in range(5,10):\n # if(x == 7): break\n if(x % 2 == 0): continue\n print(x)\n\n\n #using the enumerate() function to get index \n days=[\"Monday\", \"Tue\", \"Wed\", \"Thurs\", \"Fri\", \"Sat\", \"Sun\"]\n for i,d in enumerate(days):\n print(i,d)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python Exercise Files/Ch2/loops_start.py","file_name":"loops_start.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"276875727","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom math import sqrt\nfrom tqdm import tqdm_notebook as tqdm\n\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\nimport statsmodels.formula.api as smf\n\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n\n\ndef eval(true, pred, metric):\n '''\n For arrays TRUE and PRED, calculates METRIC and returns \n the result as a single value\n '''\n \n # Use a mask to remove any nan or inf values\n mask = ( (true.isna()==False) & (pred.isna()==False) )\n true = true[mask]\n pred = pred[mask]\n \n # Confirm that there is at least one value for the calculation\n if len(true)>0:\n \n if metric==\"pred_acc\":\n val = pred/true\n val = val.replace([np.inf, -np.inf], np.nan)\n\n elif metric==\"mape\":\n val = np.abs((pred - true)/true)*100\n val = val.replace([np.inf, -np.inf], np.nan)\n\n elif metric==\"mae\":\n val = mean_absolute_error(true,pred)\n\n elif metric==\"mse\":\n val = mean_squared_error(true,pred)\n\n elif metric==\"rmse\":\n val = np.array(sqrt(mean_squared_error(true,pred)))\n \n elif metric==\"r2\":\n val = r2_score(true,pred)\n \n elif metric==\"pcc\":\n #return pred,true\n val = pred/true\n val = val.replace([np.inf, -np.inf], np.nan)\n \n '''\n elif metric==\"sign_acc\":\n # NEED TO REVISIT -> THIS IS IN RELATION TO PREVIOUS MONTH\n true_pos = [true>=0]\n pred_pos = [pred>=0]\n \n val = (true_pos==pred_pos).mean()\n '''\n return val.mean()\n \n else:\n return np.nan\n \n \ndef make_train_test(df, datecol, split_date):\n '''\n Takes a dataframe and splits it into a train and test set\n '''\n \n dates = df.index.get_level_values(datecol).unique().tolist()\n train_dates = [i for i in dates if i<=pd.to_datetime(split_date)]\n test_dates = [i for i in dates if i>pd.to_datetime(split_date)]\n\n train_df = df.loc[train_dates]\n test_df = df.loc[test_dates]\n \n return train_df, test_df\n\n\ndef make_results(fpath, split_date):\n '''\n Produces a dataframe of results\n '''\n master=pd.read_csv(f\"ml/output_data/master_{fpath}.csv\", \n parse_dates=['date'], \n index_col=['date', 'region'])\n\n master.drop(columns=['dataset','ml_dataset',\n #'ml_true', 'eur_true', \n #'internal_true', 'external_true', 'h2o_true'\n ], inplace=True)\n \n train_df, test_df = make_train_test(master, 'date', split_date)\n \n models = [i for i in train_df.columns.tolist() if i!='true']\n metrics = ['pred_acc', 'mape', 'mae', 'mse', 'rmse', 'r2', 'pcc']\n\n results = pd.DataFrame(columns=[fpath],\n index=pd.MultiIndex.from_arrays([\n sorted(models*len(metrics)*2),\n sorted(metrics*2)*len(models),\n ['train', 'test']*len(models)*len(metrics)\n ]))\n \n results.index.names=['model', 'metric', 'dataset']\n\n for m in tqdm(models):\n for metric in metrics:\n results.loc[(m, metric, 'train')] = eval(train_df['true'], \n train_df[m], \n metric)\n results.loc[(m, metric, 'test')] = eval(test_df['true'], \n test_df[m], \n metric)\n\n return results\n\n\ndef plot_results(results, metric='mape',ylim=[1,1000], lb=0.5, ub=2, logy=True):\n '''\n Plots results by region, where each row in the plot is a different model\n '''\n \n fig, ax = plt.subplots(1, 1, figsize=[15,5], sharex=True)\n\n (results.unstack(level=0).loc[metric].T[['train', 'test']]\n .plot(kind='bar', width=0.9, ax=ax, \n logy=logy, ylim=ylim, alpha=0.5, \n color=['green', 'blue']))\n \n ax.axhline(lb, color='black', alpha=0.5)\n ax.axhline(ub, color='black', alpha=0.5)\n\n \n","sub_path":"experiment_2/src/ml_helpers/.ipynb_checkpoints/scorers-checkpoint.py","file_name":"scorers-checkpoint.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"43265661","text":"#!/usr/bin/python3\n# written by: atholcomb\n# MaxNumbers.py\n# Asks user to input integers and counts the number of times the largest appears\n\nmaxnums = []\n\nwhile True:\n\task = eval(input(\"Enter a number (0: to end input): \"))\n\tmaxnums.append(ask)\n\tlargest = max(maxnums)\n\toccurances = maxnums.count(largest)\n\tif ask == 0:\n\t\tbreak\n\nprint(\"The list of number is\", maxnums)\nprint(\"The largest number is\", largest)\nprint(\"The number of occurances is\", occurances)\n","sub_path":"sec5/exercises/MaxNumbers.py","file_name":"MaxNumbers.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"155263883","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 9 19:43:41 2020\n\n@author: enix3\n\"\"\"\n\nimport numpy as np\n\nimport h5py\nimport torch.utils.data as data\nimport torch\nimport random\nimport cv2\n\n\n# Must with key as 'in_data' and 'gt'\n# patch_size is the patch size of lr image\nclass DatasetHDF5(data.Dataset):\n def __init__(self, h5_path, length=None, patch_size=48, scale=2, enlarge=False):\n super(DatasetHDF5, self).__init__()\n self.length = length\n # self.batch_size = batch_size\n self.patch_size = patch_size\n self.scale = scale\n self.enlarge = enlarge\n self.h5_path = h5_path\n\n with h5py.File(h5_path, 'r') as h5_file:\n self.keys = list(h5_file['in_data'].keys())\n self.num_images = len(self.keys)\n\n def __getitem__(self, index):\n ind_im = random.randint(0, self.num_images - 1)\n with h5py.File(self.h5_path, 'r') as h5_file:\n indices = self.keys[ind_im]\n im_gt = np.array(h5_file['gt'][indices])\n in_data = np.array(h5_file['in_data'][indices])\n in_data, im_gt = self._get_patch(in_data, im_gt)\n im_gt = torch.from_numpy(im_gt.transpose((2, 0, 1)))\n in_data = torch.from_numpy(in_data.transpose((2, 0, 1)))\n\n return in_data, im_gt\n\n def __len__(self):\n if self.length is not None:\n return self.length\n else:\n return self.num_images\n\n def _get_patch(self, lr, hr):\n h, w, c = lr.shape\n ip = self.patch_size\n tp = ip * self.scale\n ix = random.randrange(0, w - ip + 1) # LR patch index\n iy = random.randrange(0, h - ip + 1)\n tx = self.scale * ix # HR patch index\n ty = self.scale * iy\n lr = lr[iy:iy + ip, ix:ix + ip, :].astype(np.float32)\n hr = hr[ty:ty + tp, tx:tx + tp, :].astype(np.float32)\n lr, hr = random_augmentation(lr, hr)\n if self.enlarge:\n lr = cv2.resize(lr, (tp, tp), interpolation=cv2.INTER_CUBIC)\n return lr / 255., hr / 255.\n\n\nclass TestDataHDF5(data.Dataset):\n def __init__(self, h5_path, enlarge=False, scale=2, patch_size=0):\n super(TestDataHDF5, self).__init__()\n self.h5_path = h5_path\n self.scale = scale\n self.enlarge = enlarge\n self.patch_size = patch_size\n with h5py.File(h5_path, 'r') as h5_file:\n self.keys = list(h5_file['in_data'].keys())\n self.num_images = len(self.keys)\n\n def __len__(self):\n return self.num_images\n\n def __getitem__(self, index):\n with h5py.File(self.h5_path, 'r') as h5_file:\n indices = self.keys[index]\n im_gt = np.array(h5_file['gt'][indices])\n in_data = np.array(h5_file['in_data'][indices])\n\n if self.patch_size > 0:\n in_data, im_gt = self._get_patch(in_data, im_gt)\n\n if self.enlarge:\n h, w, c = in_data.shape\n in_data = cv2.resize(in_data, (h * self.scale, w * self.scale), interpolation=cv2.INTER_CUBIC)\n\n im_gt = im_gt.transpose((2, 0, 1)).astype(np.float32)\n in_data = in_data.transpose((2, 0, 1)).astype(np.float32)\n\n im_gt = torch.from_numpy(im_gt)\n in_data = torch.from_numpy(in_data)\n\n return in_data / 255., im_gt / 255.\n\n def _get_patch(self, lr, hr):\n h, w, c = lr.shape\n ip = self.patch_size\n tp = ip * self.scale\n ix = random.randrange(0, w - ip + 1) # LR patch index\n iy = random.randrange(0, h - ip + 1)\n tx = self.scale * ix # HR patch index\n ty = self.scale * iy\n lr = lr[iy:iy + ip, ix:ix + ip, :]\n hr = hr[ty:ty + tp, tx:tx + tp, :]\n lr, hr = random_augmentation(lr, hr)\n if self.enlarge:\n lr = cv2.resize(lr, (tp, tp), interpolation=cv2.INTER_CUBIC)\n return lr, hr\n\n\ndef data_augmentation(image, mode):\n '''\n Performs dat augmentation of the input image\n Input:\n image: a cv2 (OpenCV) image\n mode: int. Choice of transformation to apply to the image\n 0 - no transformation\n 1 - flip up and down\n 2 - rotate counterwise 90 degree\n 3 - rotate 90 degree and flip up and down\n 4 - rotate 180 degree\n 5 - rotate 180 degree and flip\n 6 - rotate 270 degree\n 7 - rotate 270 degree and flip\n '''\n if mode == 0:\n # original\n pass\n elif mode == 1:\n # flip up and down\n out = np.flipud(image)\n elif mode == 2:\n # rotate counterwise 90 degree\n out = np.rot90(image)\n elif mode == 3:\n # rotate 90 degree and flip up and down\n out = np.rot90(image)\n out = np.flipud(out)\n elif mode == 4:\n # rotate 180 degree\n out = np.rot90(image, k=2)\n elif mode == 5:\n # rotate 180 degree and flip\n out = np.rot90(image, k=2)\n out = np.flipud(out)\n elif mode == 6:\n # rotate 270 degree\n out = np.rot90(image, k=3)\n elif mode == 7:\n # rotate 270 degree and flip\n out = np.rot90(image, k=3)\n out = np.flipud(out)\n else:\n raise Exception('Invalid choice of image transformation')\n\n return out\n\n\ndef random_augmentation(img1, img2):\n # if random.randint(0,1) == 1:\n flag_aug = random.randint(0, 7)\n if flag_aug > 0:\n img1 = data_augmentation(img1, flag_aug)\n img2 = data_augmentation(img2, flag_aug)\n return img1, img2\n","sub_path":"DCPS/datasets/dataset_sr.py","file_name":"dataset_sr.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"492800827","text":"import os\r\nfrom peewee import *\r\nif os.path.exists('test.db'):\r\n os.remove('test.db')\r\n\r\nbaza = SqliteDatabase('test.db')\r\n\r\nclass BazaModel(Model):\r\n class Meta:\r\n database = baza\r\n\r\nclass Klasa(BazaModel):\r\n\r\n nazwa = CharField(null=False)\r\n profil = CharField(default='')\r\n\r\nclass Uczen(BazaModel):\r\n imie = CharField(null=False)\r\n nazwisko = CharField(null=False)\r\n klasa = ForeignKeyField(Klasa,related_name='uczniowie')\r\n\r\nbaza.connect()\r\nbaza.create_tables([Klasa, Uczen])\r\n\r\n# jeseli tabela jest pusta dodajemy dwa wiersze\r\nif Klasa().select().count() == 0:\r\n inst_klasa = Klasa(nazwa='1A', profil='matematyczny')\r\n inst_klasa.save()\r\n inst_klasa = Klasa(nazwa='1B', profil='humanistyczny')\r\n inst_klasa.save()\r\n inst_klasa = Klasa(nazwa='1C', profil='informatyczny')\r\n inst_klasa.save()\r\n\r\n# tworzymy instancje klasy Klasa reprezentująca szkolna klasę 1A\r\ninst_klasa = Klasa.select().where(Klasa.nazwa == '1A').get()\r\nprint(inst_klasa)\r\n# get() zwraca tu rekordu dla nazwa='1A' ,natomiast samo inst_klasa zwraca id tak samo jak bys napisał inst_klasa.id\r\n# ale mozna tez tak inst_klasa.id lub inst_klasa.nazwa\r\n\r\n# przygotowujemy liste uczniow\r\nuczniowie = [\r\n {'imie':'Tomasz','nazwisko':'Nowak','klasa': inst_klasa},\r\n {'imie':'Jan','nazwisko':'Kos','klasa': inst_klasa},\r\n {'imie':'Piotr','nazwisko':'Kowalski','klasa':2}\r\n]\r\n\r\n# dodamy teraz do bazy liste uczniow wczesniej przygotowaną\r\nUczen.insert_many(uczniowie).execute()\r\n\r\n# odczytujemy dane z klasy\r\ndef czytajdane():\r\n for uczen in Uczen.select().join(Klasa):\r\n print(uczen.id, uczen.imie, uczen.nazwisko, uczen.klasa.nazwa)\r\n print()\r\nczytajdane()\r\n\r\n# zmiana klasy przypisanej uczniow o identyfikatorze id=2\r\ninst_uczen = Uczen().select().join(Klasa).where(Uczen.id == 2).get()\r\nprint(inst_uczen.klasa)\r\nprint(Uczen().select().join(Klasa).where(Uczen.id == 2))\r\nwynik = Uczen().select().join(Klasa).where(Uczen.id == 2)\r\nprint(\"tak tez mozna\",wynik[0].id,wynik[0].nazwisko,wynik[0].imie,wynik[0].klasa)\r\ninst_uczen.klasa = Klasa.select().where(Klasa.nazwa == '1B').get()\r\n\r\n\r\n# usuniecie ucznia o identyfikatorze 3\r\nUczen.select().where(Uczen.id == 3).get().delete_instance()\r\n\r\ninst_uczen.save()\r\nczytajdane()\r\nprint(inst_uczen)\r\nprint(inst_uczen.klasa)\r\nbaza.close()\r\n\r\n\r\n# ok ale jak zrobic by nie tworzyl nowej bazy danych a wykorzystal istniejaca i odczytał jej strukture.","sub_path":"ormpw.py","file_name":"ormpw.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"493977440","text":"import enum\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Any, Callable, Optional, cast\n\nfrom PyQt5.QtCore import (QEasingCurve, QEvent, QObject, QPoint,\n QPropertyAnimation, Qt, QTimer)\nfrom PyQt5.QtGui import QHideEvent, QKeyEvent\nfrom PyQt5.QtWidgets import (QAbstractItemView, QFrame, QGraphicsOpacityEffect,\n QLabel, QLineEdit, QListWidget, QScrollArea,\n QSizePolicy, QVBoxLayout, QWidget)\n\nfrom .cli import ArgumentRules, Command, CommandLineInterface\nfrom .widgets import Signal0, VBoxLayout, mk_signal0, mk_signal3\n\n\nclass MessageType(enum.Enum):\n PRINT = enum.auto()\n ERROR = enum.auto()\n INPUT = enum.auto()\n\n\nclass Terminal(QFrame):\n error_triggered = mk_signal0()\n show_message = mk_signal3(datetime, MessageType, str)\n\n class InputField(QLineEdit):\n def setFocus(self) -> None: # type: ignore\n self.parentWidget().show()\n super().setFocus()\n\n def __init__(self, parent: QWidget,\n help_command: str = 'h', log_command: str = 'l',\n history_file: Optional[Path] = None) -> None:\n super().__init__(parent)\n self.input_field = self.InputField(self)\n self.input_field.setObjectName('terminal_input')\n self.output_field = QLineEdit(self)\n self.output_field.setObjectName('terminal_output')\n self.output_field.setDisabled(True)\n self.cli = CommandLineInterface(\n get_input=self.input_field.text,\n set_input=self.on_input,\n get_cursor_pos=self.input_field.cursorPosition,\n set_cursor_pos=self.input_field.setCursorPosition,\n set_output=self.on_print,\n show_error=self.on_error,\n history_file=history_file\n )\n self.add_command = self.cli.add_command\n self.add_autocompletion_pattern = self.cli.add_autocompletion_pattern\n self.print_ = self.cli.print_\n self.error = self.cli.error\n self.prompt = self.cli.prompt\n # Help\n self.help_command = help_command\n if help_command:\n self.add_command(Command(\n 'toggle-help',\n 'Show or hide the help view.',\n self.toggle_extended_help,\n args=ArgumentRules.OPTIONAL,\n short_name=self.help_command,\n arg_help={\n '': 'Toggle extended help view.',\n 'X': 'Show help for command X, which should be one from the list below.',\n },\n ))\n self.help_view = HelpView(self, self.cli.commands, help_command)\n self.help_view.show_help(help_command)\n # Log\n self.log_history = LogHistory(self)\n if log_command:\n self.add_command(Command(\n 'toggle-terminal-log',\n 'Show or hide the log of all input and output in the terminal.',\n self.log_history.toggle_visibility,\n args=ArgumentRules.NONE,\n short_name=log_command,\n ))\n VBoxLayout(\n self.help_view,\n self.input_field,\n self.output_field,\n self.log_history,\n parent=self,\n )\n self.log_history.show_message.connect(self.show_message.emit)\n self.watch_terminal()\n\n def toggle_extended_help(self, arg: str) -> None:\n if not arg and self.help_view.isVisible():\n self.help_view.hide()\n else:\n success = self.help_view.show_help(arg or self.help_command)\n if success:\n self.help_view.show()\n else:\n self.error('Unknown command')\n self.help_view.hide()\n\n def on_input(self, text: str) -> None:\n self.input_field.setText(text)\n if text:\n self.log_history.add_input(text)\n\n def on_print(self, text: str) -> None:\n self.output_field.setText(text)\n if text:\n self.log_history.add(text)\n\n def on_error(self, text: str) -> None:\n self.error_triggered.emit()\n self.output_field.setText(text)\n self.log_history.add_error(text)\n\n def watch_terminal(self) -> None:\n class EventFilter(QObject):\n backtab_pressed = mk_signal0()\n tab_pressed = mk_signal0()\n reset_completion = mk_signal0()\n up_pressed = mk_signal0()\n down_pressed = mk_signal0()\n reset_history = mk_signal0()\n\n def eventFilter(self_, obj: object, event: QEvent) -> bool:\n catch_keys = [\n (Qt.Key_Backtab, Qt.ShiftModifier, self_.backtab_pressed),\n (Qt.Key_Tab, Qt.NoModifier, self_.tab_pressed),\n (Qt.Key_Up, Qt.NoModifier, self_.up_pressed),\n (Qt.Key_Down, Qt.NoModifier, self_.down_pressed),\n ]\n modkeys = (Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt,\n Qt.Key_AltGr)\n if event.type() == QEvent.KeyPress:\n key_event = cast(QKeyEvent, event)\n if key_event.key() not in modkeys + (Qt.Key_Tab, Qt.Key_Backtab):\n self_.reset_completion.emit()\n if key_event.key() not in modkeys + (Qt.Key_Up, Qt.Key_Down):\n self_.reset_history.emit()\n if key_event.key() in {Qt.Key_PageUp, Qt.Key_PageDown}:\n self.help_view.keyPressEvent(key_event)\n return True\n for key, mod, signal in catch_keys:\n if key_event.key() == key and int(key_event.modifiers()) == mod:\n signal.emit()\n return True\n return False\n self.term_event_filter = EventFilter()\n self.input_field.installEventFilter(self.term_event_filter)\n self.term_event_filter.tab_pressed.connect(self.cli.next_autocompletion)\n self.term_event_filter.backtab_pressed.connect(self.cli.previous_autocompletion)\n self.term_event_filter.reset_completion.connect(self.cli.stop_autocompleting)\n self.term_event_filter.up_pressed.connect(self.cli.older_history)\n self.term_event_filter.down_pressed.connect(self.cli.newer_history)\n self.term_event_filter.reset_history.connect(self.cli.reset_history_travel)\n cast(Signal0, self.input_field.returnPressed).connect(self.cli.run_command)\n\n def hideEvent(self, event: QHideEvent) -> None:\n self.output_field.setText('')\n super().hideEvent(event)\n\n def confirm_command(self, text: str, callback: Callable[[str], Any],\n arg: str) -> None:\n self.input_field.setFocus()\n self.cli.confirm_command(text, callback, arg)\n\n def exec_command(self, command_string: str) -> None:\n \"\"\"\n Parse and run or prompt a command string from the config.\n\n If command_string starts with a space, set the input field's text to\n command_string (minus the leading space), otherwise run the command.\n \"\"\"\n if command_string.startswith(' '):\n self.input_field.setText(command_string[1:])\n self.input_field.setFocus()\n else:\n self.cli.run_command(command_string, quiet=True)\n\n\nclass MessageTrayItem(QLabel):\n def __init__(self, text: str, name: str, parent: QWidget) -> None:\n super().__init__(text, parent)\n self.setObjectName(name)\n self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)\n # Fade out animation\n effect = QGraphicsOpacityEffect(self)\n effect.setOpacity(1)\n self.setGraphicsEffect(effect)\n a1 = QPropertyAnimation(effect, b'opacity')\n a1.setEasingCurve(QEasingCurve.InOutQuint)\n a1.setDuration(500)\n a1.setStartValue(1)\n a1.setEndValue(0)\n cast(Signal0, a1.finished).connect(self.deleteLater)\n self.fade_animation = a1\n # Move animation\n a2 = QPropertyAnimation(self, b'pos')\n a2.setEasingCurve(QEasingCurve.InQuint)\n a2.setDuration(300)\n self.move_animation = a2\n\n def kill(self) -> None:\n self.fade_animation.start()\n self.move_animation.setStartValue(self.pos())\n self.move_animation.setEndValue(self.pos() - QPoint(0, 50))\n self.move_animation.start()\n\n\nclass MessageTray(QFrame):\n def __init__(self, parent: QWidget) -> None:\n super().__init__(parent)\n # TODO: put this in settings\n self.seconds_alive = 5\n layout = QVBoxLayout(self)\n layout.addStretch()\n self.setAttribute(Qt.WA_TransparentForMouseEvents)\n\n def add_message(self, timestamp: datetime, msgtype: MessageType, text: str) -> None:\n if msgtype == MessageType.INPUT:\n return\n classes = {\n MessageType.ERROR: 'terminal_error',\n MessageType.PRINT: 'terminal_print',\n }\n lbl = MessageTrayItem(text, classes[msgtype], self)\n self.layout().addWidget(lbl)\n QTimer.singleShot(1000 * self.seconds_alive, lbl.kill)\n\n\nclass LogHistory(QListWidget):\n show_message = mk_signal3(datetime, MessageType, str)\n\n def __init__(self, parent: Terminal) -> None:\n super().__init__(parent)\n self.setAlternatingRowColors(True)\n self.setFocusPolicy(Qt.NoFocus)\n self.setSelectionMode(QAbstractItemView.NoSelection)\n self.setDragDropMode(QAbstractItemView.NoDragDrop)\n self.hide()\n\n def toggle_visibility(self) -> None:\n self.setVisible(not self.isVisible())\n\n def add(self, message: str) -> None:\n self._add_to_log(MessageType.PRINT, message)\n\n def add_error(self, message: str) -> None:\n self._add_to_log(MessageType.ERROR, message)\n\n def add_input(self, text: str) -> None:\n self._add_to_log(MessageType.INPUT, text)\n\n def _add_to_log(self, type_: MessageType, message: str) -> None:\n timestamp = datetime.now()\n self.show_message.emit(timestamp, type_, message)\n if type_ == MessageType.ERROR:\n message = '< [ERROR] ' + message\n elif type_ == MessageType.INPUT:\n message = '> ' + message\n else:\n message = '< ' + message\n self.addItem(f'{timestamp.strftime(\"%H:%M:%S\")} - {message}')\n\n\nclass HelpView(QScrollArea):\n def __init__(self, parent: QWidget, commands: dict[str, Command],\n help_command: str) -> None:\n super().__init__(parent)\n self.commands = commands\n self.help_command = help_command\n self._label = QLabel(self)\n self.setWidget(self._label)\n self.setWidgetResizable(True)\n self.set_help_text()\n self._label.setWordWrap(True)\n self.hide()\n\n def set_help_text(self) -> None:\n def escape(s: str) -> str:\n return s.replace('<', '<').replace('>', '>')\n # TODO: make this into labels and widgets instead maybe?\n main_template = ('<h2 style=\"margin:0\">{command}: {desc}</h2>'\n '<hr><table>{rows}</table>{extra}')\n row_template = ('<tr><td><b>{command}{arg}</b></td>'\n '<td style=\"padding-left:10px\">{subdesc}</td></tr>')\n\n def gen_arg_help(cmd: Command) -> list[str]:\n err_template = '<tr><td colspan=\"2\"><b><i>ERROR: {}</i></b></td></tr>'\n if not cmd.arg_help and cmd.args == ArgumentRules.NONE:\n return [\"<tr><td>This command doesn't take any arguments.</td></tr>\"]\n elif not cmd.arg_help:\n return [err_template.format('missing help for args')]\n else:\n out = [\n row_template.format(\n command=escape(cmd.short_name),\n arg=escape(arg),\n subdesc=escape(subdesc)\n )\n for arg, subdesc in (cmd.arg_help or {}).items()\n ]\n if cmd.args == ArgumentRules.NONE:\n out.append(err_template.format(\n 'command takes no arguments but there are still help lines!'\n ))\n return out\n\n self.help_html = {\n id_: main_template.format(\n command=escape(id_),\n desc=cmd.help_text,\n rows=''.join(gen_arg_help(cmd)),\n extra=cmd.raw_extra_help,\n )\n for id_, cmd in self.commands.items()\n if cmd.short_name\n }\n command_template = ('<div style=\"margin-left:5px\">'\n '<h3>list of {} commands</h3>'\n '<table style=\"margin-top:2px\">{}</table></div>')\n categories = {cmd.category for cmd in self.commands.values()}\n for group in sorted(categories):\n command_rows = (\n row_template.format(command=escape(cmd), arg='', subdesc=meta.help_text)\n for cmd, meta in self.commands.items()\n if meta.category == group and cmd\n )\n self.help_html[self.help_command] += command_template.format(\n group or 'misc',\n ''.join(command_rows)\n )\n\n def show_help(self, arg: str) -> bool:\n self.set_help_text()\n if arg not in self.help_html:\n return False\n self._label.setText(self.help_html[arg])\n return True\n","sub_path":"libsyntyche/terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":13588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"339507121","text":"from math import log, exp, fabs\n\nsimpleData = [[0, -1], [1, 1], [1, 1]]\ncomplexData = [[0, 1], [1, -1], [2, 1], [3, -1],\n [4, -1], [5, -1], [6, 1], [7, -1], [8, 1],\n [9, -1], [10, -1], [11, -1], [12, -1], [13, -1],\n [14, -1], [15, -1], [16, -1], [17, -1], [18, 1],\n [19, -1], [20, 1], [21, -1], [22, -1], [23, -1],\n [24, 1], [25, -1], [26, 1]]\n\ndef error(data, h, prob):\n errors = [p for (i, p) in zip(data, prob) if i[1] != h(i[0])]\n return sum(errors)\n\ndef alpha(e):\n return 0.5 * log((1.0 - e)/e)\n\ndef classifierF(data, prob, classifiers):\n e = 0.0\n h = None\n def f(x):\n return fabs(0.5 - x)\n for c in classifiers:\n ce = f(error(data, c, prob))\n if ce > e:\n e = ce\n h = c\n return h\n\ndef classifier(data, prob, classifiers):\n e = 100\n h = None\n for c in classifiers:\n ce = error(data, c, prob)\n if ce < e:\n e = ce\n h = c\n return h\n\n\nconstClassifiers = [lambda x: 1, lambda x: -1]\n\ndef lessThanOrEq(x):\n return lambda y: 1 if (y <= x) else -1\nlessThanOrEqClassifiers = [lessThanOrEq(d[0]) for d in complexData]\n\ndef greaterThanOrEq(x):\n return lambda y: -1 if (y <= x) else 1\ngreaterThanOrEqClassifiers = [greaterThanOrEq(d[0]) for d in complexData]\n\ndef equal(x):\n return lambda y: 1 if (x == y) else -1\nequalClassifiers = [equal(d[0]) for d in complexData]\n\ndef notEqual(x):\n return lambda y: 1 if (x != y) else -1\nnotEqualClassifiers = [notEqual(d[0]) for d in complexData]\n\ndef boosting(data, classifiers):\n dPrev = [0 for i in data]\n dCur = [1.0/len(data) for i in data]\n h = []\n e = []\n a = []\n i = 1\n while (dPrev != dCur) and (i < 50):\n h.append(classifier(data, dCur, classifiers))\n print(\"h%d = %s\" % (i, \", \".join([\"%.0f\" % h[-1](d[0]) for d in data])))\n print(\"d%d = %s\" % (i, \", \".join([\"%.2f\" % f for f in dCur])))\n dPrev = dCur\n e.append(error(data, h[-1], dCur))\n print(\"e%d = %.2f\" % (i, e[-1]))\n a.append(alpha(e[-1]))\n print(\"a%d = %.2f\" % (i, a[-1]))\n i = i + 1\n dCur = [(d * exp((-1.) * a[-1] * h[-1](p[0]) * p[1])) for (d, p) in zip(dPrev, data)]\n dCurSum = sum(dCur)\n dCur = [d / dCurSum for d in dCur]\n return [a, h]\n\ndef classify(booster, arg):\n a = booster[0]\n h = booster[1]\n s = sum([ai * hi(arg) for (ai, hi) in zip(a, h)])\n if s < 0:\n return -1\n else:\n return 1\n\n#booster = boosting(simpleData, constClassifiers)\n#classified = [classify(booster, d[1]) for d in simpleData]\n#print(\"Classified: %s\" % classified)\n#print(\" Results: %s\" % [d[1] for d in simpleData])\n\n#booster = boosting(complexData, lessThanOrEqClassifiers) # 40\n#booster = boosting(complexData, equalClassifiers) # 50\n#booster = boosting(complexData, notEqualClassifiers) # 50\nlessThanOrEqClassifiers.extend(greaterThanOrEqClassifiers) # 40\nbooster = boosting(complexData, lessThanOrEqClassifiers)\nclassified = [classify(booster, d[0]) for d in complexData]\nprint(\"Classified: %s\" % classified)\nprint(\" Results: %s\" % [d[1] for d in complexData])\n","sub_path":"rLabs/lab08-boosting.py","file_name":"lab08-boosting.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"639827968","text":"#! /usr/bin/env python\nimport sys\nimport vtk\nfrom numpy import random\n\nclass VtkPointCloud:\n\n def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):\n self.maxNumPoints = maxNumPoints\n self.vtkPolyData = vtk.vtkPolyData()\n self.clearPoints()\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInput(self.vtkPolyData)\n mapper.SetColorModeToDefault()\n mapper.SetScalarRange(zMin, zMax)\n mapper.SetScalarVisibility(1)\n self.vtkActor = vtk.vtkActor()\n self.vtkActor.SetMapper(mapper)\n # Setup the colors array\n self.colors = vtk.vtkUnsignedCharArray()\n self.colors.SetNumberOfComponents(3)\n self.colors.SetName(\"colors\")\n\n def addPoint(self, point, color):\n # Add the self.colors we created to the self.colors array\n self.colors.InsertNextTupleValue(color)\n # print self.colors\n if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:\n pointId = self.vtkPoints.InsertNextPoint(point[:])\n self.vtkCells.InsertNextCell(1)\n self.vtkCells.InsertCellPoint(pointId)\n \n else:\n r = random.randint(0, self.maxNumPoints)\n self.vtkPoints.SetPoint(r, point[:])\n self.vtkCells.Modified()\n self.vtkPoints.Modified()\n\n def clearPoints(self):\n self.vtkPoints = vtk.vtkPoints()\n self.vtkCells = vtk.vtkCellArray()\n self.vtkPolyData.SetPoints(self.vtkPoints)\n self.vtkPolyData.SetVerts(self.vtkCells)\n \n def readFile(self, filename):\n self.points = []\n r = [255, 0, 0]\n g = [0, 255, 0]\n b = [0, 0, 255]\n y = [0, 255, 255]\n w = [255, 255, 255]\n p = [100, 100, 100]\n\n colorCode = dict({1100: w, 1004: g, 1103: r, 1200: p, 1400: b})\n\n with open(filename, 'r') as fh:\n for i, line in enumerate(fh.readlines()):\n item = line.rstrip() # strip off newline and any other trailing whitespace\n if len(item) == 0 or item[0] == '#':\n # Comment or blank item\n continue\n lvals = item.split()\n pos = [float(x) for x in lvals[0:3]]\n lidx = 4 if len(lvals) > 4 else 3\n\n color = int(lvals[lidx])\n # self.points.append(pos)\n # print colorCode[color]\n self.addPoint(pos, colorCode[color])\n print(self.colors)\n self.vtkPolyData.GetPointData().SetScalars(self.colors)\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"440572082","text":"a=[45,67,56,78]\nprint(\"Hign score :\")\na.sort(reverse = True)\nfor i,a in enumerate(a):\n print(i+1,'.',a)\nc=[45,67,56,78]\nb=int(input(\"Enter your new highscore:\"))\nc.append(b)\nc.sort(reverse = True)\nfor i,c in enumerate(c):\n print(i+1,'.',c)","sub_path":"session9/part8/sort1.py","file_name":"sort1.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"190721927","text":"#!/usr/bin/env python\r\n#-*- coding:utf-8 -*-\r\n\r\nimport os\r\nfrom core import logger\r\n\r\nlilv = 0.05\r\n\r\ndef auth(base_dir):\r\n while True:\r\n name = input('请输入用户名:')\r\n pwd = input('请输入密码:')\r\n lie = os.listdir(\"%s\\db\" % base_dir)\r\n if name not in lie:\r\n print('用户名或密码错误!')\r\n else:\r\n with open('%s\\db\\%s_back' % (base_dir,name), 'r', encoding='utf-8') as f2:\r\n data = f2.readline()\r\n data = eval(data)\r\n if data['name'] != name or data['pwd'] != pwd:\r\n print('用户名或密码错误!')\r\n else:\r\n balance = data['balance']\r\n print('您的当前信用卡可用额度为:%s' % balance)\r\n return (balance,data,name)\r\n\r\ndef file_update(base_dir,fh,name=None,num=0):\r\n with open('%s\\db\\%s' % (base_dir, name), 'r', encoding='utf-8') as read_f, \\\r\n open('%s\\db\\%s.swap' % (base_dir, name), 'w', encoding='utf-8') as write_f:\r\n data = read_f.readline()\r\n data = eval(data)\r\n if fh == \"+\":\r\n data['balance'] = data['balance'] + num\r\n write_f.write(str(data))\r\n logger.loger(\"back\", name, num, 0)\r\n elif fh == \"-\":\r\n data['balance'] = num\r\n write_f.write(str(data))\r\n os.remove('%s\\db\\%s' % (base_dir, name))\r\n os.rename('%s\\db\\%s.swap' % (base_dir, name), '%s\\db\\%s' % (base_dir, name))\r\n\r\n\r\n\r\ndef enchashment(base_dir,name,yu_e):\r\n balance,data,name = auth(base_dir)\r\n num = input(\"请输入要取现的金额:\").strip()\r\n if len(num) > 0 and num.isdigit():\r\n num = int(num)\r\n balance = balance - num - num*lilv\r\n if balance >= 0:\r\n data['balance'] = balance\r\n with open('%s\\db\\%s_back' % (base_dir, name), 'w', encoding='utf-8') as f:\r\n f.write(str(data))\r\n file_update(base_dir,\"+\",name,num)\r\n else:\r\n print('取款额度超支!')\r\n return\r\n\r\ndef repayment():\r\n pass\r\n# with open('%s\\db\\%s_back' % (base_dir, name), 'r', encoding='utf-8') as read_f:\r\n# data = read_f.readline()\r\n# data = eval(data)\r\n# credit\r\n# print(\"dang前用户的信用额度为%d,需要还款\" %)\r\n\r\ndef transfer_accounts():\r\n pass\r\n\r\ndef bill():\r\n pass\r\n\r\nmsg = '''\r\n 1.取现(已实现)\r\n 2.还款\r\n 3.转账\r\n 4.账单\r\n 5.退出\r\n'''\r\nmenu_dic = {\r\n \"1\":enchashment,\r\n \"2\":repayment,\r\n \"3\":transfer_accounts,\r\n \"4\":bill,\r\n \"5\":5\r\n}\r\ndef atm(base_dir,name,yu_e):\r\n while True:\r\n print(msg)\r\n choice = input('选项>>>').strip()\r\n if len(choice) == 0 or choice not in menu_dic: continue\r\n if choice == \"5\":break\r\n menu_dic[choice](base_dir,name,yu_e)\r\n\r\n\r\n","sub_path":"python_program/day06/ATM/core/back.py","file_name":"back.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"79912452","text":"import turtle as t\n\n\ndef koch(size, n):\n t.pendown()\n if n == 0:\n t.fd(size)\n else:\n for angle in [0, 60, -120, 60]:\n t.left(angle)\n koch(size / 3, n - 1)\n\n\ndef main():\n t.setup(800, 600)\n t.penup()\n t.goto(-200, 100)\n t.pendown()\n t.pensize(5)\n t.pencolor('purple')\n n = 3\n koch(200, n)\n t.right(120)\n koch(200, n)\n t.right(120)\n koch(200, n)\n t.right(120)\n t.hideturtle()\n t.done()\n\n\nmain()\n","sub_path":"former/kehe-snow.py","file_name":"kehe-snow.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"346910201","text":"class MultiDict(dict):\n \"\"\"\n An ordered dictionary that can have multiple values for each key.\n Adds the methods getall, getone, mixed, and add to the normal\n dictionary interface.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if args:\n if hasattr(args[0], 'iteritems'):\n self.update(arg[0])\n else:\n for key, value in args[0]:\n self.add(key, value)\n if kwargs:\n self.update(kwargs)\n\n @classmethod\n def fromkeys(cls, keys, defaults=None):\n return cls(dict([(key, defaults) for key in keys]))\n\n def __getitem__(self, key):\n return dict.__getitem__(self, key)[-1]\n\n def __setitem__(self, key, value):\n dict.__setitem__(self, key, [value])\n\n def __repr__(self):\n return \"%s(%r)\" % (self.__class__.__name__, self.items())\n\n def add(self, key, value):\n \"\"\"\n Add the key and value, not overwriting any previous value.\n \"\"\"\n if key not in self:\n self[key] = value\n else:\n dict.__getitem__(self, key).append(value)\n\n def getall(self, key):\n \"\"\"\n Return a list of all values matching the key (may be an empty list)\n \"\"\"\n return dict.get(self, key, [])\n\n def getone(self, key):\n \"\"\"\n Get one value matching the key, raising a KeyError if multiple\n values were found.\n \"\"\"\n value = dict.__getitem__(self, key)\n if len(value) > 1:\n raise ValueError\n return value[0]\n\n def mixed(self):\n \"\"\"\n Returns a dictionary where the values are either single\n values, or a list of values when a key/value appears more than\n once in this dictionary. This is similar to the kind of\n dictionary often used to represent the variables in a web\n request.\n \"\"\"\n output = {}\n for key, value in dict.iteritems(self):\n if len(value) == 1:\n output[key] = value[0]\n else:\n output[key] = value\n return output\n\n def dict_of_lists(self):\n \"\"\"\n Returns a dictionary where each key is associated with a\n list of values.\n \"\"\"\n output = {}\n for key, value in dict.iteritems(self):\n output[key] = value\n return\n\n def copy(self):\n return self.__class__(self)\n\n def setdefault(self, key, default=None):\n if key not in self:\n self[key] = default\n return self.get(key, default)\n\n def update(self, other=None, **kwargs):\n if hasattr(other, 'keys'):\n for key in other.keys():\n self.add(key, other[key])\n else:\n for key, value in other:\n self.add(key, value)\n\n if kwargs:\n self.update(kwargs)\n\n def items(self):\n output = []\n for key, value in dict.iteritems(self):\n for item in value:\n output.append((key, item))\n return output\n\n def iteritems(self):\n for key, value in dict.iteritems(self):\n for item in value:\n yield (key, item)\n\n def values(self):\n output = []\n for value in dict.itervalues(self):\n output.extend(value)\n return output\n\n def itervalues(self):\n for value in dict.itervalues(self):\n for item in value:\n yield item\n\n__test__ = {\n 'general': \"\"\"\n >>> d = MultiDict(a=1, b=2)\n >>> d['a']\n 1\n >>> d.getall('c')\n []\n >>> d.add('a', 2)\n >>> d['a']\n 2\n >>> d.getall('a')\n [1, 2]\n >>> d['b'] = 4\n >>> d.getall('b')\n [4]\n >>> d.keys()\n ['a', 'b']\n >>> d.items()\n [('a', 1), ('a', 2), ('b', 4)]\n >>> d.mixed() == {'a': [1, 2], 'b': 4}\n True\n >>> MultiDict([('a', 'b')], c=2)\n MultiDict([('a', 'b'), ('c', 2)])\n \"\"\"}\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n","sub_path":"python/dict_multidict.py","file_name":"dict_multidict.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"158947100","text":"\n#%%\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport random\nimport tables\nimport cv2\n\nfrom config import *\n\nH5 = '/srv/workplace/tjurica/tasks/1544-ANY_defects_detection/pc_dataset/ann_train.h5'\n\nIMG_TABLE = 'images'\nANNOT_TABLE = 'annotations'\n\nDF_IMG_ID = 'img_id'\nDF_IMG_PATH = 'img_path'\nCENTER_X = 'center_x'\nBBOX_LEFT = 'bbox_left'\nBBOX_RIGHT = 'bbox_right'\nCENTER_Y = 'center_y'\nBBOX_UP = 'bbox_up'\nBBOX_DOWN = 'bbox_down'\nDF_INDICES = 'indices'\nDF_CLS_ID = 'cls_id'\n\nclass Cropper:\n def __init__(self, h5, dim=(64,64), crops_per_img=50,\n ann_ids=[0,1], driver=\"H5FD_CORE\"): \n \n self.h5 = h5\n self.dim = dim\n self.crops_per_img = crops_per_img\n self.ith_crop = 0\n self.ann_ids = ann_ids\n self.dirname = os.path.dirname(h5)\n\n self.pos_radius = int(min(self.dim)/4) #int(min(self.dim)/2)\n self.neg_radius = int(2*np.sqrt((self.dim[0]/2) * (self.dim[0]/2) \\\n + (self.dim[1]/2) * (self.dim[1]/2)))\n\n with pd.HDFStore(h5, \"r\") as hdf_store:\n self.img_df = hdf_store[IMG_TABLE]\n self.ann_df = hdf_store[ANNOT_TABLE]\n\n self.img_ids = self.img_df[DF_IMG_ID].unique()\n\n # filter ann ids\n self.ann_df = self.ann_df[\n self.ann_df[DF_CLS_ID].isin(self.ann_ids)]\n self.ann_df = self.ann_df[\n self.ann_df[DF_IMG_ID].isin(self.img_ids)]\n \n self.ann_df[CENTER_X] = (self.ann_df[BBOX_RIGHT] \\\n + self.ann_df[BBOX_LEFT])//2\n self.ann_df[CENTER_Y] = (self.ann_df[BBOX_DOWN] \\\n + self.ann_df[BBOX_UP])//2\n\n self.h5 = tables.open_file(h5, mode='r', driver=driver)\n self.reload_img()\n\n def reload_img(self):\n rnd_id = random.choice(self.img_ids)\n \n self.img_row = self.img_df[self.img_df[DF_IMG_ID] == rnd_id]\n self.img_annots = self.ann_df[self.ann_df[DF_IMG_ID] == rnd_id]\n \n rel_path = getattr(self.img_row, DF_IMG_PATH).values[0]\n abs_path = os.path.join(self.dirname, rel_path)\n\n self.img = cv2.imread(abs_path, cv2.IMREAD_UNCHANGED)/255.0\n\n self.init_annots()\n \n def init_annots(self):\n n = len(self.img_annots)\n\n mask_shape = (self.img.shape[0], self.img.shape[1], 1)\n pos_mask = np.zeros(mask_shape, dtype=np.float32)\n neg_mask = np.ones(mask_shape, dtype=np.float32)\n bin_mask = np.zeros(mask_shape, dtype=np.float32)\n \n for ann_row in self.img_annots.itertuples():\n ctr_x = int(getattr(ann_row, CENTER_X))\n ctr_y = int(getattr(ann_row, CENTER_Y))\n \n indices_node = getattr(ann_row, DF_INDICES) \n idcs = self.h5.get_node(indices_node)\n idcs = np.array(idcs)\n\n bin_mask[idcs[0], idcs[1], 0] = 1.0\n cv2.circle(pos_mask, (ctr_x, ctr_y), self.pos_radius, (1.0), -1)\n cv2.circle(neg_mask, (ctr_x, ctr_y), self.neg_radius, (0.0), -1)\n\n # remove borders from imgs\n pos_mask[:self.dim[0]//2, :,:] = 0.0\n pos_mask[pos_mask.shape[0]-self.dim[0]//2:, :,:] = 0.0\n pos_mask[:,:self.dim[1]//2,:] = 0.0\n pos_mask[:,pos_mask.shape[1]-self.dim[1]//2:,:] = 0.0\n \n neg_mask[:self.dim[0]//2, :,:] = 0.0\n neg_mask[neg_mask.shape[0]-self.dim[0]//2:, :,:] = 0.0\n neg_mask[:,:self.dim[1]//2,:] = 0.0\n neg_mask[:,neg_mask.shape[1]-self.dim[1]//2:,:] = 0.0\n\n self.pos_indices = pos_mask.nonzero()\n self.neg_indices = neg_mask.nonzero()\n self.bin_mask = bin_mask\n\n if len(self.pos_indices[0]) == 0 or len(self.neg_indices[0]) == 0:\n self.reload_img()\n \n def get_positive(self):\n self.ith_crop += 1\n if self.ith_crop > self.crops_per_img:\n self.ith_crop = 0\n self.reload_img()\n \n # get random pos\n n = self.pos_indices[0].shape[0]\n rnd = random.randint(0, n-1)\n ctr = (self.pos_indices[0][rnd],\n self.pos_indices[1][rnd],\n self.pos_indices[2][rnd])\n\n # crop mask\n crop_mask = self.bin_mask[\n ctr[0]-self.dim[0]//2:ctr[0]+self.dim[0]//2,\n ctr[1]-self.dim[1]//2:ctr[1]+self.dim[1]//2,:]\n \n # crop image\n crop_img = self.img[\n ctr[0]-self.dim[0]//2:ctr[0]+self.dim[0]//2,\n ctr[1]-self.dim[1]//2:ctr[1]+self.dim[1]//2,:]\n\n # stack together\n return np.dstack((crop_img, crop_mask))\n \n def get_negative(self):\n self.ith_crop += 1\n if self.ith_crop > self.crops_per_img:\n self.ith_crop = 0\n self.reload_img()\n \n # get random neg\n n = self.neg_indices[0].shape[0]\n rnd = random.randint(0, n-1)\n ctr = (self.neg_indices[0][rnd],\n self.neg_indices[1][rnd],\n self.neg_indices[2][rnd])\n\n # crop mask\n crop_mask = self.bin_mask[\n ctr[0]-self.dim[0]//2:ctr[0]+self.dim[0]//2,\n ctr[1]-self.dim[1]//2:ctr[1]+self.dim[1]//2,:]\n \n # crop image\n crop_img = self.img[\n ctr[0]-self.dim[0]//2:ctr[0]+self.dim[0]//2,\n ctr[1]-self.dim[1]//2:ctr[1]+self.dim[1]//2,:]\n\n # stack together\n return np.dstack((crop_img, crop_mask))\n\n\nclass PosGenerator:\n def __init__(self, cropper, batch_size):\n self.cropper = cropper\n self.batch_size = batch_size\n \n def next(self):\n batch = np.array([self.cropper.get_positive() \\\n for i in range(self.batch_size)])\n return batch\n\nclass NegGenerator:\n def __init__(self, cropper, batch_size):\n self.cropper = cropper\n self.batch_size = batch_size\n \n def next(self):\n batch = np.array([self.cropper.get_negative() \\\n for i in range(self.batch_size)])\n return batch \n","sub_path":"scripts/data_gen.py","file_name":"data_gen.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"135999429","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 18 17:51:47 2015\n\n@author: carlo-m\n\"\"\"\nimport ec_glb as glb\nimport PySide.QtGui as QtGui\nimport PySide.QtCore as QtCore\n\n\ndef init_ui(self):\n # Clear the upper labels\n for obj in (self.IL_1 , self.IL_2 , self.IL_3 , self.IL_4 , self.IL_5):\n obj.setText(\"\")\n\n # Set the units in the QEditText Boxes\n set_ui_unit(self)\n\n clear_model_tab(self)\n tool_ui_populate(self)\n mach_ui_populate(self)\n wp_ui_populate(self)\n init_processes_ui(self)\n init_gcode_ui(self)\n\n\ndef set_ui_unit(self):\n # set the Unit in the Tool Tab\n for obj in (self.TGSPRad , self.TGSPDia, self.TGSPOvl, self.TGSPShd,\n self.TGSPLen):\n obj.setSuffix(glb.tunit)\n # set the Unit in the Machine Tab (Machine Dimensions)\n for obj in (self.MGSPTX, self.MGSPTY, self.MGSPTZ):\n obj.setSuffix(glb.tunit)\n # set the Unit in the Machine Tab (Machine feedrate)\n for obj in (self.MGSPFX, self.MGSPFY, self.MGSPFZ):\n obj.setSuffix(glb.spunit)\n # set the Unit in the Model Tab\n for obj in (self.MdLdimx, self.MdLdimy, self.MdLdimz):\n obj.setText(glb.tunit)\n\n self.IL_5.setText(glb.dunit)\n\n################### GV actions\n\ndef clear_graphics_win(self):\n self.scene.clear()\n pass\n\ndef init_graphics_win(self):\n self.scene = QtGui.QGraphicsScene()\n self.scene.setSceneRect(0, 0, 378, 398)\n self.brush1 = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n self.brush1.setStyle(QtCore.Qt.SolidPattern)\n self.pen1 = QtGui.QPen(QtCore.Qt.green, 3, QtCore.Qt.DashDotLine,\n QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)\n #self.GV.setForegroundBrush()\n self.GV.setBackgroundBrush(self.brush1)\n self.GV.setScene(self.scene)\n\ndef tool_paint(self):\n self.RightTB.setCurrentIndex(0) # Image Tab\n rect1 = self.scene.addRect(150,100,40,80)\n #rect1.fill()\n #text = self.scene.addText('hello')\n #text.setDefaultTextColor(QtGui.QColor(QtCore.Qt.red))\n\n################### Model UI\n\n\ndef clear_model_tab(self):\n for obj in (self.MdTmX, self.MdTmY, self.MdTmZ,\n self.MdTMX, self.MdTMY, self.MdTMZ,\n self.MdTdimx, self.MdTdimy, self.MdTdimz):\n obj.setText(\"\")\n obj.setReadOnly(True)\n obj.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)\n\ndef write_model_data(self,dims):\n dimx,dimy,dimz = dims\n if glb.unit == 0 :\n dimformat=\"{0:10.3f}\"\n elif glb.unit == 1:\n dimformat = \"{0:10.4f}\"\n else:\n dimformat = \"{0:6.3f}\"\n\n self.MdTmX.setText(dimformat.format(dimx.min))\n self.MdTmY.setText(dimformat.format(dimy.min))\n self.MdTmZ.setText(dimformat.format(dimz.min))\n self.MdTMX.setText(dimformat.format(dimx.max))\n self.MdTMY.setText(dimformat.format(dimy.max))\n self.MdTMZ.setText(dimformat.format(dimz.max))\n self.MdTdimx.setText(dimformat.format(dimx.max-dimx.min))\n self.MdTdimy.setText(dimformat.format(dimy.max-dimy.min))\n self.MdTdimz.setText(dimformat.format(dimz.max-dimz.min))\n\n################## Tool UI\n\ndef init_tool_comboboxes(self):\n self.ToolCB.clear()\n self.ToolCB.addItems(sorted(glb.Tools.keys()))\n self.PCToolCB.clear()\n self.PCToolCB.addItems(sorted(glb.Tools.keys()))\n\n\ndef init_tool_shape_comboboxes(self):\n # populate the Tool Shape ComboBox\n self.TGCBTyp.clear()\n self.TGCBTyp.addItems(glb.shape)\n self.TGCBTyp.setInsertPolicy(QtGui.QComboBox.InsertPolicy.NoInsert)\n\n\ndef init_centercut_combobox(self):\n # populate the Center Cut ComboBox\n self.TGCBCc.clear()\n self.TGCBCc.addItems([glb.no,glb.yes])\n self.TGCBCc.setInsertPolicy(QtGui.QComboBox.InsertPolicy.NoInsert)\n\n\ndef write_tool_data(self,key):\n # http://www.anderswallin.net/2011/08/opencamlib-cutter-shapes/\n #0 = CylCutter(diameter, length)\n #1 = BallCutter(diameter, length)\n #2 = BullCutter(diameter, corner_radius, length)\n #3 = ConeCutter(diameter, angle, length)\n #\n data = glb.Tools[key]\n ttype = int(data[0])\n\n set_tool_limits(self,ttype)\n\n self.TGCBTyp.setCurrentIndex(ttype)\n self.TGSPDia.setValue(float(data[1]))\n self.TGSPRad.setValue(float(data[2]))\n self.TGSPLen.setValue(float(data[3]))\n self.TGSPOvl.setValue(float(data[4]))\n self.TGSPShd.setValue(float(data[5]))\n self.TGSPFlu.setValue(int(data[6]))\n self.TGCBCc.setCurrentIndex(int(data[7]))\n self.TGTnote.setText(str(data[8]))\n\n\ndef clear_tool_ui(self):\n for obj in (self.TGSPDia, self.TGSPRad, self.TGSPLen, self.TGSPOvl,\n self.TGSPShd ):\n obj.setValue(0.0)\n self.TGSPFlu.setValue(0)\n self.TGCBCc.setCurrentIndex(0)\n self.TGTnote.setText(\"\")\n\n\ndef set_tool_limits(self,ttype):\n if ttype in (0,1):\n self.TGLRad.setVisible(False)\n self.TGSPRad.setVisible(False)\n\n elif ttype == 2:\n self.TGLRad.setVisible(True)\n self.TGLRad.setText(glb.CorRad)\n self.TGSPRad.setVisible(True)\n if glb.unit == 1: # inches\n self.TGSPRad.setRange(0.0000, 1.0000)\n self.TGSPRad.setDecimals(4)\n self.TGSPRad.setSingleStep(0.001)\n else:\n self.TGSPRad.setRange(0.000, 25.000)\n self.TGSPRad.setDecimals(3)\n self.TGSPRad.setSingleStep(0.5)\n\n self.TGSPRad.setSuffix(glb.tunit)\n\n elif ttype == 3:\n self.TGLRad.setVisible(True)\n self.TGLRad.setText(glb.Angle)\n self.TGSPRad.setVisible(True)\n self.TGSPRad.setRange(0.0, 180.0)\n self.TGSPRad.setDecimals(1)\n self.TGSPRad.setSingleStep(1.0)\n\n self.TGSPRad.setSuffix(glb.degree)\n\n else:\n self.TGLRad.setVisible(True)\n self.TGLRad.setText(glb.Radius)\n self.TGSPRad.setVisible(True)\n if glb.unit == 1: # inches\n self.TGSPRad.setRange(0.0000, 1.0000)\n self.TGSPRad.setDecimals(4)\n self.TGSPRad.setSingleStep(0.001)\n else:\n self.TGSPRad.setRange(0.000, 25.000)\n self.TGSPRad.setDecimals(3)\n self.TGSPRad.setSingleStep(0.5)\n\n self.TGSPRad.setSuffix(glb.tunit)\n\n if glb.unit == 1: # inches\n for obj in (self.TGSPDia,self.TGSPShd ):\n obj.setRange(0.0000, 1.0000)\n obj.setDecimals(4)\n obj.setSingleStep(0.001)\n\n for obj in (self.TGSPLen,self.TGSPOvl):\n obj.setRange(0.0000, 5.0000)\n obj.setDecimals(4)\n obj.setSingleStep(0.001)\n\n else:\n for obj in (self.TGSPDia,self.TGSPShd ):\n obj.setRange(0.000, 25.000)\n obj.setDecimals(3)\n obj.setSingleStep(0.5)\n\n for obj in (self.TGSPLen,self.TGSPOvl):\n obj.setRange(0.000, 100.000)\n obj.setDecimals(3)\n obj.setSingleStep(0.5)\n\n\ndef read_tool_data(self):\n \"\"\"\n Read the tool mask (except for the tool name and return a list\n with this values\n [\"sha\",\"dia\",\"rad\",\"len\",\"ovl\",\"shd\",\"flu\",\"cc\",\"opt\"]\n \"\"\"\n data = []\n for i,v in enumerate((self.TGCBTyp, self.TGSPDia,self.TGSPRad, self.TGSPLen,\n self.TGSPOvl, self.TGSPShd,self.TGSPFlu, self.TGCBCc,\n self.TGTnote)):\n if i == 0: # Tool Shape\n data.append(v.currentIndex())\n elif i in (1,2,3,4,5,6): # Dia,Rad,Len,Flu\n data.append(v.value())\n elif i == 7: # Cc\n data.append(v.currentIndex())\n elif i == 8: #Notes\n data.append(v.toPlainText())\n return data\n\n\ndef tool_ui_mask(self,mskst):\n for f_object in (self.TGSPDia, self.TGSPRad,self.TGSPLen, self.TGSPOvl,\n self.TGSPShd, self.TGSPFlu, self.TGTnote ):\n f_object.setReadOnly(mskst)\n\n\ndef tool_ui_populate(self):\n init_tool_shape_comboboxes(self)\n init_centercut_combobox(self)\n init_tool_comboboxes(self)\n tool_ui_visibility(self,True)\n\n\ndef tool_ui_visibility(self,action):\n self.ToolNewPB.setVisible(action)\n self.ToolModPB.setVisible(action)\n self.ToolDelPB.setVisible(action)\n self.ToolCB.setEnabled(action)\n self.TTConf.setVisible(not action)\n self.TTConf.setEnabled(not action)\n\n\n\n################### Machine UI\n\ndef clear_mach_ui(self):\n for Eobject in (self.MGSPTX, self.MGSPTY, self.MGSPTZ, self.MGSPFX,\n self.MGSPFY, self.MGSPFZ ):\n Eobject.setValue(0.0)\n\n self.MGCoCB.setCurrentIndex(0)\n self.MGTnote.setText(\"\")\n self.MGTpre.setText(\"\")\n self.MGTpost.setText(\"\")\n\n\ndef mach_ui_populate(self):\n mach_ui_mask(self,True)\n init_machine_coordinate_combobox(self)\n init_machine_names_comboboxes(self)\n set_mach_limits(self)\n mach_ui_visibility(self,True)\n\n\ndef mach_ui_mask(self,mskst):\n for f_object in (self.MGSPTX, self.MGSPTY, self.MGSPTZ, self.MGSPFX,\n self.MGSPFY, self.MGSPFZ,self.MGTnote, self.MGTpre,\n self.MGTpost):\n f_object.setReadOnly(mskst)\n\n\ndef init_machine_coordinate_combobox(self):\n # populate the Machine coordinate ComboBox\n self.MGCoCB.clear()\n self.MGCoCB.addItems(glb.coord)\n self.MGCoCB.setInsertPolicy(QtGui.QComboBox.InsertPolicy.NoInsert)\n\n\ndef init_machine_names_comboboxes(self):\n # Populate the Machine Names ComboBox in Machine and Processes TAB\n self.MachCB.clear()\n self.MachCB.addItems(sorted(glb.Machs.keys()))\n self.PCMachCB.clear()\n self.PCMachCB.addItems(sorted(glb.Machs.keys()))\n\n\ndef set_mach_limits(self):\n if glb.unit == 1: # inches\n for f_object in (self.MGSPTX, self.MGSPTY, self.MGSPTZ, self.MGSPFX,\n self.MGSPFY, self.MGSPFZ ):\n f_object.setRange(0.0000, 100.0000)\n f_object.setDecimals(4)\n f_object.setSingleStep(0.25)\n else:\n for f_object in (self.MGSPTX, self.MGSPTY, self.MGSPTZ, self.MGSPFX,\n self.MGSPFY, self.MGSPFZ ):\n f_object.setRange(0.000, 2500.000)\n f_object.setDecimals(3)\n f_object.setSingleStep(5.00)\n\n\ndef read_mach_data(self):\n \"\"\"\n Read the machine mask (except for the machine name and return a list\n [\"mtx\",\"mty\",\"mtz\",\"mfx\",\"mfy\",\"mfz\",\"cot\",\"opt\"]\n \"\"\"\n data = []\n for i,v in enumerate((self.MGSPTX, self.MGSPTY, self.MGSPTZ, self.MGSPFX,\n self.MGSPFY, self.MGSPFZ, self.MGCoCB, self.MGTnote,\n self.MGTpre,self.MGTpost)):\n if i in (0,1,2,3,4,5): #\n data.append(v.value())\n elif i == 6: # Cc\n data.append(v.currentIndex())\n elif i in (7,8,9): # Notes , pre ,post\n data.append(v.toPlainText())\n return data\n\n\ndef write_mach_data(self,key):\n data = glb.Machs[key]\n\n f_object = (self.MGSPTX, self.MGSPTY, self.MGSPTZ, self.MGSPFX,\n self.MGSPFY, self.MGSPFZ )\n f_field = (0,1,2,3,4,5)\n for Eobject,idx in zip(f_object,f_field):\n Eobject.setValue(float(data[idx]))\n\n self.MGCoCB.setCurrentIndex(int(data[6]))\n self.MGTnote.setText(str(data[7]))\n self.MGTpre.setText(str(data[8]))\n self.MGTpost.setText(str(data[9]))\n\ndef mach_ui_visibility(self,action):\n self.MachNewPB.setVisible(action)\n self.MachModPB.setVisible(action)\n self.MachDelPB.setVisible(action)\n self.MachCB.setEnabled(action)\n self.MachConfPB.setVisible(not action)\n self.MachConfPB.setEnabled(not action)\n\n\n################### Workpiece UI\n\n\ndef clear_wp_ui(self):\n for obj in (self.WPGSBLDX, self.WPGSBUDX, self.WPGSBLDY, self.WPGSBUDY,\n self.WPGSBLDZ,self.WPGSBUDZ):\n obj.setValue(0.0)\n\n self.WPGCBMat.setCurrentIndex(0)\n self.WPGTNote.setText(\"\")\n\n\ndef write_wp_data(self,key):\n glb.wpdata = glb.WorkPCs[key]\n\n for idx,obj in enumerate((self.WPGSBLDX, self.WPGSBUDX, self.WPGSBLDY,\n self.WPGSBUDY, self.WPGSBLDZ,self.WPGSBUDZ)):\n obj.setValue(float(glb.wpdata[idx]))\n\n self.WPGCBMat.setCurrentIndex(int(glb.wpdata[6]))\n self.WPGTNote.setText(glb.wpdata[7])\n\ndef wp_ui_mask(self,mskst):\n for f_object in (self.WPGSBLDX, self.WPGSBLDY, self.WPGSBLDZ, self.WPGSBUDX,\n self.WPGSBUDY, self.WPGSBUDZ, self.WPGTNote):\n f_object.setReadOnly(mskst)\n\ndef init_wp_comboboxes(self):\n # populate the Workpiece ComboBox\n self.WPCB.clear()\n self.WPCB.addItems(sorted(glb.WorkPCs.keys()))\n self.PCWPCB.clear()\n self.PCWPCB.addItems(sorted(glb.WorkPCs.keys()))\n\ndef wp_ui_visibility(self,action):\n self.WPNewPB.setVisible(action)\n self.WPModPB.setVisible(action)\n self.WPDelPB.setVisible(action)\n self.WPCB.setEnabled(action)\n self.WPConfPB.setVisible(not action)\n self.WPConfPB.setEnabled(not action)\n\n\ndef wp_ui_populate(self):\n wp_ui_mask(self,True)\n init_wp_comboboxes(self)\n set_mach_limits(self)\n wp_ui_visibility(self,True)\n\n\ndef read_wp_data(self):\n \"\"\"\n Read the WP mask (except for the WP name and return a list\n [\"xmin\",\"xmax\",\"ymin\",\"ymax\",\"zmin\",\"zmax\",\"mat\",\"note\"]\n \"\"\"\n data = []\n for i,v in enumerate((self.WPGSBLDX, self.WPGSBUDX, self.WPGSBLDY,\n self.WPGSBUDY, self.WPGSBLDZ, self.WPGSBUDZ,\n self.WPGCBMat,self.WPGTNote)):\n if i in (0,1,2,3,4,5): #\n data.append(v.value())\n elif i == 6: # Material\n data.append(v.currentIndex())\n elif i == 7: # Notes\n data.append(v.toPlainText())\n return data\n\n\ndef set_mach_limits(self):\n\n if glb.unit == 1: # inches\n for obj in (self.WPGSBLDX, self.WPGSBUDX, self.WPGSBLDY, self.WPGSBUDY,\n self.WPGSBLDZ, self.WPGSBUDZ):\n obj.setRange(0.0000, 80.0000)\n obj.setDecimals(4)\n obj.setSingleStep(0.001)\n obj.setSuffix(glb.tunit)\n\n else:\n for obj in (self.WPGSBLDX, self.WPGSBUDX, self.WPGSBLDY, self.WPGSBUDY,\n self.WPGSBLDZ, self.WPGSBUDZ):\n obj.setRange(-2000.000, 2000.000)\n obj.setDecimals(3)\n obj.setSingleStep(0.5)\n obj.setSuffix(glb.tunit)\n\n################### Processes UI\n\ndef init_processes_ui(self):\n self.PCPDRB1.setEnabled(True)\n self.PCPDRB2.setEnabled(True)\n self.PCPDRB3.setEnabled(False)\n self.PCPDRB4.setEnabled(False)\n self.PCSTRB1.setEnabled(True)\n self.PCSTRB2.setEnabled(False)\n self.PCSTRB3.setEnabled(False)\n self.PCSTRB4.setEnabled(False)\n self.PCL01.setVisible(False)\n self.PCSB01.setVisible(False)\n self.PCPBGenG.setVisible(False)\n self.PCPBCt.setVisible(False)\n self.PCPBCal.setVisible(False)\n self.PCSTRB1.setChecked(True) # Check the SR Strategy\n self.PCPDRB1.setChecked(True) # Check the X direction\n self.PCTTd.setReadOnly(True) # it has no meaning to modify it in thr PC UI\n set_processes_limits(self)\n\ndef set_processes_limits(self):\n if glb.unit == 1: # inches\n for obj in (self.PCSBXYovl,self.PCSBZsd):\n obj.setRange(0.0000, 1.0000)\n obj.setDecimals(4)\n obj.setSingleStep(0.001)\n obj.setSuffix(glb.tunit)\n\n for obj in (self.PCSBXYfc,self.PCSBZfc):\n obj.setRange(0.0000, 20.0000)\n obj.setDecimals(4)\n obj.setSingleStep(0.001)\n obj.setSuffix(glb.spunit)\n\n else:\n for obj in (self.PCSBXYovl,self.PCSBZsd):\n obj.setRange(0.000, 25.000)\n obj.setDecimals(3)\n obj.setSingleStep(0.05)\n obj.setSuffix(glb.tunit)\n\n for obj in (self.PCSBXYfc,self.PCSBZfc):\n obj.setRange(0.000, 1600.000)\n obj.setDecimals(3)\n obj.setSingleStep(0.5)\n obj.setSuffix(glb.spunit)\n\ndef processes_data_populate(self):\n m_name = self.PCMachCB.currentText()\n glb.machdata = glb.Machs[m_name]\n t_name = self.PCToolCB.currentText()\n glb.t_data = glb.Tools[t_name]\n #TODO the WPiece data\n w_name = self.PCWPCB.currentText()\n glb.wpdata = glb.WorkPCs[w_name]\n\n\n################### G-Code UI\n\ndef init_gcode_ui(self):\n # disable the checkbox\n gcode_ui_visibility(self,False)\n\n for obj in (self.GCPB1, self.GCPB2, self.GCPB3 ):\n obj.setVisible(False)\n\ndef gcode_ui_visibility(self,action):\n for obj in (self.GCmodel, self.GCmachine, self.GCtool, self.GCwp,\n self.GCtp, self.GCverbose, self.GCview, self.GCSBd):\n obj.setEnabled(action)\n\n###################","sub_path":"ec_ui_act.py","file_name":"ec_ui_act.py","file_ext":"py","file_size_in_byte":16459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"534279286","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom nn.module import Module\nimport numpy as np\n\nclass ReLU(Module):\n\tcounter = 0\n\tdef __init__(self):\n\t\tsuper(ReLU,self).__init__()\n\t\tself.X = None\n\t\tReLU.counter += 1\n\t\tself.name = 'ReLU_{}'.format(ReLU.counter)\n\n\tdef relu(self,x):\n\t\treturn x*(x>0)\n\n\tdef forward(self,X,Y=None):\n\t\tself.X = X\n\t\treturn self.relu(X)\n\n\tdef backward(self, input_grad):\n\t\tgradient = self.update_grad_input(input_grad)\n\t\tself.update_parameters()\n\t\treturn gradient\n\n\tdef update_grad_input(self,input_grad):\n\t\t\"\"\"grad_input there should be equal to 1, because\n\t\t it's usually the last layer in NN\"\"\"\n\t\treturn input_grad*(self.X > 0)\n\n\tdef update_parameters(self):\n\t\tpass\n\n\tdef predict_proba(self,X):\n\t\t\"\"\"predict probability for each class\n\t\tthis is one-vs-all probability, so be careful -\n\t\tprobability vector isn't normalized\"\"\"\n\t\treturn self.relu(X)\n\n\tdef predict(self,X):\n\t\t\"\"\"predict label for given objects\"\"\"\n\t\treturn 1.*(self.relu(X) >= np.max(self.relu(X),axis=1,keepdims=True))\n\nif __name__ == \"__main__\":\n\n\tprint(\"running gradient check for ReLU layer!\")\n\tX = np.random.normal(loc=0.5,scale=0.5,size = (50,30))\n\tprint(\"initializing input matrix with shape {}\".format(X.shape))\n\tinput_grad = np.ones(shape=X.shape) #identity input gradient\n\teps = 1e-4 \n\ttol = 1e-4\n\tR = ReLU()\n\n\tnum_grad = np.zeros(shape=X.shape)\n\tfor i in xrange(X.shape[0]):\n\t\tfor j in xrange(X.shape[1]):\n\t\t\tX[i,j] += eps\n\t\t\tY_plus = R.forward(X)\n\t\t\tX[i,j] -= 2*eps\n\t\t\tY_minus = R.forward(X)\n\t\t\tX[i,j] += eps\n\t\t\tnum_grad[i,j] = (Y_plus[i,j] - Y_minus[i,j])/(2.*eps)\n\t\n\tR.forward(X) #memorize initial matrix\n\tprint(\"Frobenius norm of difference is equal to:\",np.linalg.norm(num_grad - R.backward(input_grad))) \n\tprint(\"Analytical and numerical gradient is equal:\",np.linalg.norm(num_grad - R.backward(input_grad))<tol)\n\tprint(\"sometimes it is false, because derivative in zero doesn't exist!\")","sub_path":"nn/relu.py","file_name":"relu.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"528457357","text":"#!/usr/bin/python\n\nfrom PyQt4 import QtGui\nimport consts\n\nclass AccusationDialog(QtGui.QDialog):\n \"\"\"\n Custom dialog for making an accusation.\n \"\"\"\n def __init__(self, parent=None):\n super(AccusationDialog, self).__init__(parent)\n self.setModal(True)\n # Create dialog widgets\n layout = QtGui.QFormLayout() \n label = QtGui.QLabel('Select the items for your accusation:')\n self.suspectCombo = QtGui.QComboBox()\n self.roomCombo = QtGui.QComboBox()\n self.weaponCombo = QtGui.QComboBox()\n self.button = QtGui.QPushButton('Make Accusation')\n self.button.setFixedSize(125, 25)\n cancel = QtGui.QPushButton('Cancel')\n cancel.setFixedSize(75, 25)\n cancel.clicked.connect(self.handleCancel)\n # Fill combo-boxes\n for suspect in consts.SUSPECTS:\n self.suspectCombo.addItem(suspect)\n for room in consts.ROOMS:\n self.roomCombo.addItem(room)\n for weapon in consts.WEAPONS:\n self.weaponCombo.addItem(weapon)\n # Add all widgets to the layout and set layout\n layout.addRow(label)\n layout.addRow(self.suspectCombo)\n layout.addRow(self.roomCombo)\n layout.addRow(self.weaponCombo)\n layout.addRow(self.button, cancel)\n self.setLayout(layout)\n\n def closeEvent(self, event, valid=False):\n \"\"\"\n Override closeEvent.\n Keyword Arguments:\n event -- QtGui.QCloseEvent().\n valid -- boolean value to determine whether or not to close widget.\n \"\"\"\n if not valid:\n event.ignore()\n else:\n super(AccusationDialog, self).closeEvent(event)\n \n def handleCancel(self):\n self.closeEvent(QtGui.QCloseEvent(), valid=True)\n\n\nclass CharacterDialog(QtGui.QDialog):\n \"\"\"\n Custom dialog for choosing a Clue-Less character.\n \"\"\"\n def __init__(self, parent=None):\n super(CharacterDialog, self).__init__(parent)\n self.setModal(True)\n # Create dialog widgets\n layout = QtGui.QFormLayout()\n label = QtGui.QLabel('Please choose your character:')\n self.characterList = QtGui.QListWidget()\n self.button = QtGui.QPushButton('Pick')\n self.button.setFixedSize(65, 25)\n # Add all widgets to layout and set layout\n layout.addRow(label)\n layout.addRow(self.characterList)\n layout.addRow(self.button) \n self.setLayout(layout)\n \n def closeEvent(self, event, valid=False):\n \"\"\"\n Override closeEvent.\n Keyword Arguments:\n event -- QtGui.QCloseEvent().\n valid -- boolean value to determine whether or not to close widget.\n \"\"\"\n if not valid:\n event.ignore()\n else:\n super(CharacterDialog, self).closeEvent(event)\n \n\nclass RevealDialog(QtGui.QDialog):\n \"\"\"\n Custom dialog for choosing which card to reveal to another player.\n \"\"\"\n def __init__(self, parent=None):\n super(RevealDialog, self).__init__(parent)\n self.setModal(True)\n # Create dialog widgets\n layout = QtGui.QFormLayout()\n self.player = ''\n self.label = QtGui.QLabel()\n self.cardList = QtGui.QListWidget()\n self.button = QtGui.QPushButton('Reveal')\n self.button.setFixedSize(75, 25)\n # Add all widget to layout and set layout\n layout.addRow(self.label)\n layout.addRow(self.cardList)\n layout.addRow(self.button)\n self.setLayout(layout)\n \n def closeEvent(self, event, valid=False):\n \"\"\"\n Override closeEvent.\n Keyword Arguments:\n event -- QtGui.QCloseEvent().\n valid -- boolean value to determine whether or not to close widget.\n \"\"\"\n if not valid:\n event.ignore()\n else:\n super(RevealDialog, self).closeEvent(event)\n \n \nclass SuggestionDialog(QtGui.QDialog):\n \"\"\"\n Custom dialog for making a suggestion.\n \"\"\"\n def __init__(self, parent=None):\n super(SuggestionDialog, self).__init__(parent)\n self.setModal(True)\n # Create dialog widgets\n layout = QtGui.QFormLayout()\n label = QtGui.QLabel('Select the items for your suggestion:')\n self.suspectCombo = QtGui.QComboBox()\n self.weaponCombo = QtGui.QComboBox()\n self.button = QtGui.QPushButton('Make Suggestion')\n self.button.setFixedSize(125, 25)\n # Fill combo-boxes\n for suspect in consts.SUSPECTS:\n self.suspectCombo.addItem(suspect)\n for weapon in consts.WEAPONS:\n self.weaponCombo.addItem(weapon)\n # Add all widgets to layout and set layout\n layout.addRow(label)\n layout.addRow(self.suspectCombo)\n layout.addRow(self.weaponCombo)\n layout.addRow(self.button)\n self.setLayout(layout)\n \n def closeEvent(self, event, valid=False):\n \"\"\"\n Override closeEvent.\n Keyword Arguments:\n event -- QtGui.QCloseEvent().\n valid -- boolean value to determine whether or not to close widget.\n \"\"\"\n if not valid:\n event.ignore()\n else:\n super(SuggestionDialog, self).closeEvent(event)\n \n\nclass UsernameDialog(QtGui.QDialog):\n \"\"\"\n Custom dialog for getting username.\n \"\"\"\n def __init__(self, parent=None):\n super(UsernameDialog, self).__init__(parent)\n self.setModal(True)\n # Create dialog widgets\n layout = QtGui.QFormLayout()\n label = QtGui.QLabel('Please enter your username:')\n self.edit = QtGui.QLineEdit(self)\n self.edit.setFocus()\n # Add all widgets to layout and set layout\n layout.addRow(label)\n layout.addRow(self.edit)\n self.setLayout(layout)\n \n def closeEvent(self, event):\n \"\"\"\n Override closeEvent.\n Keyword Arguments:\n event -- QtGui.QCloseEvent().\n \"\"\"\n # Only close dialog if text has been entered\n if len(self.edit.text()) == 0:\n event.ignore()\n else:\n event.accept()\n \n","sub_path":"dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":6166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"51256760","text":"#coding=UTF-8\n\n# See BuildArchetypes for details on environment\n# BuildDemos needs git in PATH and depends on gitpython library\n# gitpython can be installed with python installer script \"pip\":\n# pip install gitpython\t\n\nfrom git import Repo\nfrom BuildHelpers import updateRepositories, mavenValidate, copyWarFiles, VersionObject, getLogFile, parseArgs\n\n## Example of a non-staging test.\n#version = VersionObject()\n#version.version = \"7.4.8\"\n\n# Uncomment lines before this, and comment following line to make a non-staging test\nversion = None\n\ndemos = {\n\t\"dashboard\" : \"https://github.com/vaadin/dashboard-demo.git\",\n\t\"parking\" : \"https://github.com/vaadin/parking-demo.git\",\n\t\"addressbook\" : \"https://github.com/vaadin/addressbook.git\",\n\t\"confirmdialog\" : \"https://github.com/samie/Vaadin-ConfirmDialog.git\"\n}\n\ndef checkout(folder, url):\n\tRepo.clone_from(url, folder)\n\nif __name__ == \"__main__\":\n\tif version is None:\n\t\tversion = parseArgs()\n\tfor demo in demos:\n\t\tprint(\"Validating demo %s\" % (demo))\n\t\ttry:\n\t\t\tcheckout(demo, demos[demo])\n\t\t\tupdateRepositories(demo, repoIds = version)\n\t\t\tmavenValidate(demo, repoIds = version, logFile = getLogFile(demo))\n\t\t\tcopyWarFiles(demo)\n\t\t\tprint(\"%s demo validation succeeded!\" % (demo))\n\t\texcept:\n\t\t\tprint(\"%s demo validation failed\" % (demo))\n\t\tprint(\"\")\n","sub_path":"scripts/BuildDemos.py","file_name":"BuildDemos.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"448236797","text":"import unittest\nfrom devo.common import Buffer\n\n\nclass TestLtBuffer(unittest.TestCase):\n\n def test_proccess_first_line(self):\n self.assertTrue(self.buffer.proccess_first_line(self.first_line))\n self.assertIsNot(self.buffer.size(), 0)\n\n def test_proccess_data_line(self):\n self.buffer.proccess_recv(self.data_line)\n self.assertIsNot(self.buffer.size(), 0)\n\n def setUp(self):\n self.buffer = Buffer()\n self.data_first_line = '{\"eventdate\":1519913235053,' \\\n '\"clientIpAddress\":2452954210,' \\\n '\"timestamp\":\"01/Mar/2018:14:07:14 +0000\",' \\\n '\"method\":\"GET\",\"url\":' \\\n '\"/product.screen?product_id=235-40LSZ-09823&' \\\n 'JSESSIONID=SD8SL6FF10ADFF6\",\"protocol\":' \\\n '\"HTTP 1.1\",\"statusCode\":404,\"bytesTransfe' \\\n 'rred\":3069,\"referralUri\":\"http://www.yahoo.' \\\n 'com/cart.do?action=view&itemId=LOG-90&' \\\n 'product_id=235-40LSZ-09823&JSESSIONID=SD8SL' \\\n '6FF10ADFF6\",\"userAgent\":\"Mozilla/4.0 ' \\\n '(compatible; MSIE 6.0; Windows NT 5.1; SV1; ' \\\n '.NET CLR 1.1.4322)\",\"cookie\":\"gaqfse5dpcm' \\\n '690jdh5ho1f00o2:-\",\"timeTaken\":768}\\r\\n\\r\\n'\n\n self.first_line = 'HTTP/1.1 200 OK\\r\\nServer: nginx\\r\\nDate: Thu, ' \\\n '01 Mar 2018 14:08:15 GMT\\r\\nContent-Type: ' \\\n 'application/json\\r\\nTransfer-Encoding: ' \\\n 'chunked\\r\\nConnection: keep-alive\\r\\nVary: ' \\\n 'Accept-Encoding\\r\\nStrict-Transport-Security: ' \\\n 'max-age=15768000; includeSubDomains\\r\\n' \\\n 'X-Content-Type-Options: nosniff\\r\\n' \\\n 'X-Frame-Options: SAMEORIGIN\\r\\nX-XSS-Protection: ' \\\n '1; mode=block\\r\\nReferrer-Policy: ' \\\n 'same-origin\\r\\n\\r\\n20d\\r\\n' + self.data_first_line\n\n self.data_line = '190\\r\\n {\"eventdate\":1519913684245,\"clientIpAddress' \\\n '\":1142130470,\"timestamp\":\"01/Mar/2018:14:14:44 ' \\\n '+0000\",\"method\":\"GET\",\"url\":\"/\",\"protocol\":\"HTTP ' \\\n '1.1\",\"statusCode\":200,\"bytesTransferred\":523,' \\\n '\"referralUri\":\"http://www.devo.com/product.' \\\n 'screen?product_id=009-73CKH-JASKD&JSESSIONID=' \\\n 'SD2SL1FF3ADFF2\",\"userAgent\":\"Opera/9.20 (Windows ' \\\n 'NT 6.0; U; en)\",\"cookie\":\"3djv1l0ebi7cmsai1131p' \\\n 'f2a65:-\",\"timeTaken\":589}\\r\\n\\r\\n'\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/common/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"482141387","text":"from apps.order.utils import order_record_get, order_record_post\nfrom apps.user.utils import user_record_get, user_record_post\nfrom apps.product.utils import product_record_get, product_record_post\nfrom apps.finance.utils import finance_record_get, finance_record_post\nfrom apps.sln.utils import sln_record_get, sln_record_post\nfrom apps.aggregatorCase.utils import aggregator_case_record_get, aggregator_case_record_post\nfrom utils.response import res_code\nfrom utils.http import APIResponse\n\nfrom .common import OrderModuleList, FinanceModuleList, UserModuleList, ProductModuleList, \\\n SlnModuleList, AggregatorCaseModuleList\n\n\ndef switch_get(module, request):\n if module in OrderModuleList:\n data = order_record_get(request)\n elif module in UserModuleList:\n data = user_record_get(request)\n elif module in ProductModuleList:\n data = product_record_get(request)\n elif module in FinanceModuleList:\n data = finance_record_get(request)\n elif module in SlnModuleList:\n data = sln_record_get(request)\n elif module in AggregatorCaseModuleList:\n data = aggregator_case_record_get(request)\n else:\n data = 'Need a parameter of module.'\n return APIResponse(rescode=res_code['error'], data=data)\n return data\n\n\ndef switch_post(module, data):\n if module in OrderModuleList:\n return order_record_post(data)\n elif module in UserModuleList:\n return user_record_post(data)\n elif module in ProductModuleList:\n return product_record_post(data)\n elif module in FinanceModuleList:\n return finance_record_post(data)\n elif module in SlnModuleList:\n return sln_record_post(data)\n elif module in AggregatorCaseModuleList:\n return aggregator_case_record_post(data)\n else:\n return 'Mudule not found!', res_code['error']\n","sub_path":"apps/transfer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"421832014","text":"# 문자열 S가 주어졌을 때, 다솜이가 해야 하는 행동의 최소 횟수를 출력하기\nS = input()\n\nList = []\n\ns = S[0]\n\ncount = 0\n\nfor i in S[1:]:\n if s[-1] != i:\n List.append(s)\n s = i\n else:\n s += i\n\n# 마지막 문자열 삽입\nList.append(s)\n\nfor i in List:\n if '1' in i:\n count += 1\n\n# 최소 횟수 출력\nprint(min(count, len(List)-count))\n\n\n# 다른 코드\nS = input()\ncount0 = 0 # 전부 0으로 바꾸는 경우\ncount1 = 0 # 전부 1로 바꾸는 경우\n\n# 첫 번째 원소에 대해서 처리\nif S[0] == '1':\n count0 += 1\nelse:\n count1 += 1\n\n# 두 번째 원소부터 모든 원소를 확인하며\nfor i in range(len(S) - 1):\n if S[i] != S[i + 1]:\n # 다음 수에서 1로 바뀌는 경우\n if S[i + 1] == '1':\n count0 += 1\n # 다음 수에서 0으로 바뀌는 경우\n else:\n count1 += 1\n\nprint(min(count0, count1))\n","sub_path":"BAEKJOON/그리디/1439_뒤집기.py","file_name":"1439_뒤집기.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"256063720","text":"# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This scaffolding model makes your app work on Google App Engine too\n#########################################################################\n\nif request.env.web2py_runtime_gae: # if running on Google App Engine\n db = DAL('gae://mynamespace') # connect to Google BigTable\n session.connect(request, response, db = db) # and store sessions and tickets there\n ### or use the following lines to store sessions in Memcache\n # from gluon.contrib.memdb import MEMDB\n # from google.appengine.api.memcache import Client\n # session.connect(request, response, db = MEMDB(Client()))\nelse: # else use a normal relational database\n db = DAL('sqlite://storage.db') # if not, use SQLite or other DB\n## if no need for session\n# session.forget()\n\n#########################################################################\n## Here is sample code if you need for\n## - email capabilities\n## - authentication (registration, login, logout, ... )\n## - authorization (role based authorization)\n## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)\n## - crud actions\n## (more options discussed in gluon/tools.py)\n#########################################################################\n\nfrom gluon.tools import *\nmail = Mail() # mailer\nauth = Auth(globals(),db) # authentication/authorization\nauth.settings.create_user_groups = False\ncrud = Crud(globals(),db) # for CRUD helpers using auth\nservice = Service(globals()) # for json, xml, jsonrpc, xmlrpc, amfrpc\nplugins = PluginManager()\n\nmail.settings.server = 'smtp.gmail.com:587' # your SMTP server\nmail.settings.sender = 'vtsindia.contact@gmail.com' # your email\nmail.settings.login = 'vtsindia.contact:vtsadminpass' # your credentials or None\n\nauth.settings.hmac_key = 'sha512:aa8b643d-f9f8-4c07-a41a-3e74d05c7166' # before define_tables()\n\n#Changed the user table to add new fields (Date of birth,Gender,Place,Secret Question and Secret answer for recovering password\nauth.settings.table_user = db.define_table('auth_user',\n db.Field('first_name', 'string', length=128, default='', requires = IS_NOT_EMPTY(error_message=T('Please enter your First Name'))),\n db.Field('last_name', 'string', length=128, default='', requires = IS_NOT_EMPTY(error_message=T('Please Enter Last Name'))),\n db.Field('email', 'string', length=128, default='', requires = IS_NOT_EMPTY(error_message=T('Please Enter an E-Mail Id'))),\n db.Field('password', 'password', readable=False),\n db.Field('phone', 'string', length=128, default='', requires = IS_NOT_EMPTY(error_message=T('Enter your Contact Number'))), \n db.Field('place', 'string', length=128, default='', requires = IS_NOT_EMPTY(error_message=T('Enter your Place'))),\n db.Field('registration_key', 'string', length=128, writable=False, readable=False, default=''))\nt = auth.settings.table_user\nt.email.requires = [IS_EMAIL(error_message=T('Please Enter a valid E-Mail Id')), IS_NOT_IN_DB(db, 'auth_user.email')]\n\nauth.define_tables() # creates all needed tables\nauth.settings.mailer = mail # for user email verification\nauth.settings.registration_requires_verification = False\nauth.settings.registration_requires_approval = False\nauth.messages.verify_email = 'Click on the link http://'+request.env.http_host+URL(r=request,c='default',f='user',args=['verify_email'])+'/%(key)s to verify your email'\nauth.settings.reset_password_requires_verification = True\nauth.messages.reset_password = 'Click on the link http://'+request.env.http_host+URL(r=request,c='default',f='user',args=['reset_password'])+'/%(key)s to reset your password'\n\n#########################################################################\n## If you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc.\n## register with janrain.com, uncomment and customize following\n# from gluon.contrib.login_methods.rpx_account import RPXAccount\n# auth.settings.actions_disabled=['register','change_password','request_reset_password']\n# auth.settings.login_form = RPXAccount(request, api_key='...',domain='...',\n# url = \"http://localhost:8000/%s/default/user/login\" % request.application)\n## other login methods are in gluon/contrib/login_methods\n#########################################################################\n\ncrud.settings.auth = None # =auth to enforce authorization on crud\n\n#########################################################################\n## Define your tables below (or better in another model file) for example\n##\n## >>> db.define_table('mytable',Field('myfield','string'))\n##\n## Fields can be 'string','text','password','integer','double','boolean'\n## 'date','time','datetime','blob','upload', 'reference TABLENAME'\n## There is an implicit 'id integer autoincrement' field\n## Consult manual for more options, validators, etc.\n##\n## More API examples for controllers:\n##\n## >>> db.mytable.insert(myfield='value')\n## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)\n## >>> for row in rows: print row.id, row.myfield\n#########################################################################\n\ndb.define_table('vInfo',\n Field('user_id',db.auth_user,requires = IS_IN_DB(db,'auth_user.id','%(first_name)s')),\n Field('terminal_id', requires=IS_NOT_IN_DB(db,'vInfo.terminal_id')),\n Field('name'),\n Field('speed_lim','integer',default=80),\n Field('description','text'),\n Field('chassis_num',label='Chassis Number'),\n Field('engine_num',label='Engine Number')\n )\ndb.vInfo.user_id.writable = db.vInfo.user_id.readable = False\n\ndb.define_table('vTracking',\n Field('terminal_id',db.vInfo,requires=IS_IN_DB(db,'vInfo.terminal_id','vInfo.name')),\n Field('time'),\n Field('date'),\n Field('lat'),\n Field('ns'),\n Field('ew'),\n Field('long'),\n Field('speed','double'),\n Field('address','text'),\n Field('dist_p_n','double',label='Distance From Prev Point'),\n Field('state',requires=IS_IN_SET(['Start','Running','Stop'])))\n \ndb.define_table('vTrackingLatest',\n Field('terminal_id',db.vInfo,requires=IS_IN_DB(db,'vInfo.terminal_id','vInfo.name')),\n Field('lat'),\n Field('long'),\n Field('time'),\n Field('date'),\n Field('speed','double'),\n Field('address','text'),\n Field('state'))\n\ndb.define_table('feedback',\n Field('name'),\n Field('email',requires = IS_EMAIL(error_message=T('Enter a valid Email-Id'))),\n Field('done','boolean',default=False), \n Field('feedback','text',requires = IS_NOT_EMPTY(error_message=T('Enter the Feedback'))))\n\ndb.define_table('news',\n Field('title'),\n Field('date','integer'),\n Field('month'),\n Field('desc','text'))\n\ndb.define_table('alerts',\n Field('title'),\n Field('terminal_id',db.vInfo,requires=IS_IN_DB(db,'vInfo.terminal_id','vInfo.name')),\n Field('user_id',db.auth_user,requires = IS_IN_DB(db,'auth_user.id','%(first_name)s')),\n Field('date','date'),\n Field('time'),\n Field('done','boolean',default=False), \n Field('desc','text'))\n \ndb.news.title.requires = IS_NOT_EMPTY(error_message=T(\"Please Enter Title\"))\ndb.news.date.requires = IS_NOT_EMPTY(error_message=T(\"Please Enter Date\"))\ndb.news.date.requires = IS_IN_SET(range(1,32))\ndb.news.month.requires = IS_NOT_EMPTY(error_message=T(\"Please Enter Month\"))\ndb.news.month.requires = IS_IN_SET(('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'))\ndb.news.desc.requires = IS_NOT_EMPTY(error_message=T(\"Please Enter Description\"))\n","sub_path":"models/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"414801923","text":"from pathlib import Path\nfrom typing import Union\nimport json\nimport pickle\nfrom datetime import datetime, date, timedelta\nimport queue\n\nimport numpy as np\nimport pandas as pd\n\nfrom service.App import *\nfrom common.utils import *\nfrom common.classifiers import *\nfrom common.feature_generation import *\nfrom common.signal_generation import *\n\nimport logging\nlog = logging.getLogger('analyzer')\n\n\nclass Analyzer:\n \"\"\"\n In-memory database which represents the current state of the (trading) environment including its history.\n\n Properties of klines:\n - \"timestamp\" is a left border of the interval like \"2017-08-17 04:00:00\"\n - \"close_time\" is a right border of the interval in ms (last millisecond) like \"1502942459999\" equivalent to \"2017-08-17 04:00::59.999\"\n \"\"\"\n\n def __init__(self, config):\n \"\"\"\n Create a new operation object using its definition.\n\n :param config: Initialization parameters defining what is in the database including its persistent parameters and schema\n \"\"\"\n\n self.config = config\n\n #\n # Data state\n #\n\n # Klines are stored as a dict of lists. Key is a symbol and the list is a list of latest kline records\n # One kline record is a list of values (not dict) as returned by API: open time, open, high, low, close, volume etc.\n self.klines = {}\n\n self.queue = queue.Queue()\n\n #\n # Load models\n #\n model_path = App.config[\"model_folder\"]\n model_path = Path(model_path)\n if not model_path.is_absolute():\n model_path = PACKAGE_ROOT / model_path\n model_path = model_path.resolve()\n\n labels = App.config[\"labels\"]\n feature_sets = [\"kline\"]\n algorithms = [\"gb\", \"nn\", \"lc\"]\n self.models = load_models(model_path, labels, feature_sets, algorithms)\n\n #\n # Start a thread for storing data\n #\n\n #\n # Data state operations\n #\n\n def get_klines_count(self, symbol):\n return len(self.klines.get(symbol, []))\n\n def get_last_kline(self, symbol):\n if self.get_klines_count(symbol) > 0:\n return self.klines.get(symbol)[-1]\n else:\n return None\n\n def get_last_kline_ts(self, symbol):\n \"\"\"Open time of the last kline. It is simultaneously kline id. Add 1m if the end is needed.\"\"\"\n last_kline = self.get_last_kline(symbol=symbol)\n if not last_kline:\n return 0\n last_kline_ts = last_kline[0]\n return last_kline_ts\n\n def get_missing_klines_count(self, symbol):\n now_ts = now_timestamp()\n last_kline_ts = self.get_last_kline_ts(symbol)\n if not last_kline_ts:\n return App.config[\"signaler\"][\"analysis\"][\"features_horizon\"]\n end_of_last_kline = last_kline_ts + 60_000 # Plus 1m\n\n minutes = (now_ts - end_of_last_kline) / 60_000\n minutes += 2\n return int(minutes)\n\n def store_klines(self, data: dict):\n \"\"\"\n Store latest klines for the specified symbols.\n Existing klines for the symbol and timestamp will be overwritten.\n\n :param data: Dict of lists with symbol as a key, and list of klines for this symbol as a value.\n Example: { 'BTCUSDT': [ [], [], [] ] }\n :type dict:\n \"\"\"\n now_ts = now_timestamp()\n\n for symbol, klines in data.items():\n # If symbol does not exist then create\n klines_data = self.klines.get(symbol)\n if klines_data is None:\n self.klines[symbol] = []\n klines_data = self.klines.get(symbol)\n\n ts = klines[0][0] # Very first timestamp of the new data\n\n # Find kline with this or younger timestamp in the database\n # same_kline = next((x for x in klines_data if x[0] == ts), None)\n existing_indexes = [i for i, x in enumerate(klines_data) if x[0] >= ts]\n #print(f\"===>>> Existing tss: {[x[0] for x in klines_data]}\")\n #print(f\"===>>> New tss: {[x[0] for x in klines]}\")\n #print(f\"===>>> {symbol} Overlap {len(existing_indexes)}. Existing Indexes: {existing_indexes}\")\n if existing_indexes: # If there is overlap with new klines\n start = min(existing_indexes)\n num_deleted = len(klines_data) - start\n del klines_data[start:] # Delete starting from the first kline in new data (which will be added below)\n if len(klines) < num_deleted: # It is expected that we add same or more klines than deleted\n log.error(\"More klines is deleted by new klines added, than we actually add. Something woring with timestamps and storage logic.\")\n\n # Append new klines\n klines_data.extend(klines)\n\n # Remove too old klines\n kline_window = App.config[\"signaler\"][\"analysis\"][\"features_horizon\"]\n to_delete = len(klines_data) - kline_window\n if to_delete > 0:\n del klines_data[:to_delete]\n\n # Check validity. It has to be an ordered time series with certain frequency\n for i, kline in enumerate(self.klines.get(symbol)):\n ts = kline[0]\n if i > 0:\n if ts - prev_ts != 60_000:\n log.error(\"Wrong sequence of klines. They are expected to be a regular time series with 1m frequency.\")\n prev_ts = kline[0]\n\n # Debug message about the last received kline end and current ts (which must be less than 1m - rather small delay)\n log.debug(f\"Stored klines. Total {len(klines_data)} in db. Last kline end: {self.get_last_kline_ts(symbol)+60_000}. Current time: {now_ts}\")\n\n def store_depth(self, depths: list, freq):\n \"\"\"\n Persistently store order books from the input list. Each entry is one response from order book request for one symbol.\n Currently the order books are directly stored in a file (for this symbol) and not in this object.\n\n :param depths: List of dicts where each dict is an order book with such fields as 'asks', 'bids' and 'symbol' (symbol is added after loading).\n :type list:\n \"\"\"\n\n # File name like TRADE_HOME/COLLECT/DEPTH/depth-BTCUSDT-5s.txt\n TRADE_DATA = \".\" # TODO: We need to read it from the environment. It could be data dir or docker volume.\n # BASE_DIR = Path(__file__).resolve().parent.parent\n # BASE_DIR = Path.cwd()\n\n for depth in depths:\n # TODO: The result might be an exception or some other object denoting bad return (timeout, cancelled etc.)\n\n symbol = depth[\"symbol\"]\n\n path = Path(TRADE_DATA).joinpath(App.config[\"collector\"][\"folder\"])\n path = path.joinpath(App.config[\"collector\"][\"depth\"][\"folder\"])\n path.mkdir(parents=True, exist_ok=True) # Ensure that dir exists\n\n file_name = f\"depth-{symbol}-{freq}\"\n file = Path(path, file_name).with_suffix(\".txt\")\n\n # Append to the file (create if it does not exist)\n json_line = json.dumps(depth)\n with open(file, 'a+') as f:\n f.write(json_line + \"\\n\")\n\n def store_queue(self):\n \"\"\"\n Persistently store the queue data to one or more files corresponding to the stream (event) type, symbol (and frequency).\n\n :return:\n \"\"\"\n #\n # Get all the data from the queue\n #\n events = {}\n item = None\n while True:\n try:\n item = self.queue.get_nowait()\n except queue.Empty as ee:\n break\n except:\n break\n\n if item is None:\n break\n\n c = item.get(\"e\") # Channel\n if not events.get(c): # Insert if does not exit\n events[c] = {}\n symbols = events[c]\n\n s = item.get(\"s\") # Symbol\n if not symbols.get(s): # Insert if does not exit\n symbols[s] = []\n data = symbols[s]\n\n data.append(item)\n\n self.queue.task_done() # TODO: Do we really need this?\n\n # File name like TRADE_HOME/COLLECT/DEPTH/depth-BTCUSDT-5s.txt\n TRADE_DATA = \".\" # TODO: We need to read it from the environment. It could be data dir or docker volume.\n # BASE_DIR = Path(__file__).resolve().parent.parent\n # BASE_DIR = Path.cwd()\n\n path = Path(TRADE_DATA).joinpath(App.config[\"collector\"][\"folder\"])\n path = path.joinpath(App.config[\"collector\"][\"stream\"][\"folder\"])\n path.mkdir(parents=True, exist_ok=True) # Ensure that dir exists\n\n now = datetime.utcnow()\n #rotate_suffix = f\"{now:%Y}{now:%m}{now:%d}\" # Daily files\n rotate_suffix = f\"{now:%Y}{now:%m}\" # Monthly files\n\n #\n # Get all the data from the queue and store in file\n #\n for c, symbols in events.items():\n for s, data in symbols.items():\n file_name = f\"{c}-{s}-{rotate_suffix}\"\n file = Path(path, file_name).with_suffix(\".txt\")\n\n # Append to the file (create if it does not exist)\n data = [json.dumps(event) for event in data]\n data_str = \"\\n\".join(data)\n with open(file, 'a+') as f:\n f.write(data_str + \"\\n\")\n\n #\n # Analysis (features, predictions, signals etc.)\n #\n\n def analyze(self):\n \"\"\"\n 1. Convert klines to df\n 2. Derive (compute) features (use same function as for model training)\n 3. Derive (predict) labels by applying models trained for each label\n 4. Generate buy/sell signals by applying rule models trained for best overall trade performance\n \"\"\"\n symbol = App.config[\"symbol\"]\n\n klines = self.klines.get(symbol)\n last_kline_ts = self.get_last_kline_ts(symbol)\n\n log.info(f\"Analyze {symbol}. {len(klines)} klines in the database. Last kline timestamp: {last_kline_ts}\")\n\n #\n # 1.\n # Produce a data frame with înput data\n #\n try:\n df = klines_to_df(klines)\n except Exception as e:\n print(f\"Error in klines_to_df: {e}\")\n return\n\n #\n # 2.\n # Generate all necessary derived features (NaNs are possible due to short history)\n #\n try:\n features_out = generate_features(df)\n except Exception as e:\n print(f\"Error in generate_features: {e}\")\n return\n\n # Now we have as many additional columns as we have defined derived features\n\n #\n # 3.\n # Generate scores using existing models (trained in advance using latest history by a separate script)\n #\n\n # kline feature set\n features = App.config[\"features_kline\"]\n predict_df = df[features]\n # Do not drop nans because they will be processed by predictor\n\n # Do prediction by applying models to the data\n score_df = pd.DataFrame(index=predict_df.index)\n try:\n for score_column_name, model_pair in self.models.items():\n if score_column_name.endswith(\"_gb\"):\n df_y_hat = predict_gb(model_pair, predict_df)\n elif score_column_name.endswith(\"_nn\"):\n df_y_hat = predict_nn(model_pair, predict_df)\n elif score_column_name.endswith(\"_lc\"):\n df_y_hat = predict_lc(model_pair, predict_df)\n else:\n raise ValueError(f\"Unknown column name algorithm suffix {score_column_name[-3:]}. Currently only '_gb', '_nn', '_lc' are supported.\")\n score_df[score_column_name] = df_y_hat\n except Exception as e:\n print(f\"Error in predict: {e}\")\n return\n\n # Now we have all predictions (score columns) needed to make a buy/sell decision - many predictions for each true label column\n # We will need only the latest row for signal generation\n\n #\n # 4.\n # Generate buy/sell signals using rules and thresholds\n #\n all_scores = self.models.keys()\n high_scores = [col for col in all_scores if \"high_\" in col] # 3 algos x 3 thresholds x 1 k = 9\n low_scores = [col for col in all_scores if \"low_\" in col] # 3 algos x 3 thresholds x 1 k = 9\n\n # Compute final score column\n score_df[\"high\"] = score_df[high_scores].mean(axis=1)\n score_df[\"low\"] = score_df[low_scores].mean(axis=1)\n high_and_low = score_df[\"high\"] + score_df[\"low\"]\n score_df[\"score\"] = ((score_df[\"high\"] / high_and_low) * 2) - 1.0 # in [-1, +1]\n\n score = score_df.iloc[-1].score\n\n row = df.iloc[-1]\n close_price = row.close\n high_price = row.high\n low_price = row.high\n timestamp = row.name\n close_time = row.name+timedelta(minutes=1) # row.close_time\n\n # Thresholds\n model = App.config[\"signaler\"][\"model\"]\n\n signal = dict(side=None, score=score, close_price=close_price, close_time=close_time)\n if not score:\n signal = dict()\n elif score > model.get(\"buy_threshold\"):\n signal[\"side\"] = \"BUY\"\n elif score < model.get(\"sell_threshold\"):\n signal[\"side\"] = \"SELL\"\n else:\n signal[\"side\"] = \"\"\n\n App.signal = signal\n\n log.info(f\"Analyze finished. Score: {score:+.2f}. Signal: {signal['side']}. Price: {int(close_price):,}\")\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"service/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":13610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"300141218","text":"# Time Complexity : O(nm)\n# Space Complexity : O(nm) \n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n\n#store all 2s row,col in queue and 1s in a counter. If found in any direction change it to 2 and decrement countern (Normal BFS)\n\nclass Solution(object):\n def orangesRotting(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n if len(grid) == 0 or grid == None:\n return 0\n res = 0\n queue = []\n fresh = 0\n for i in range(0, len(grid)):\n for j in range(0, len(grid[0])):\n if grid[i][j] == 2:\n queue.append((i,j))\n elif grid[i][j] == 1:\n fresh += 1\n \n if fresh == 0:\n return 0\n count = 0\n dirs = [[1,0], [-1,0], [0,1], [0,-1]]\n while queue:\n size = len(queue)\n if fresh == 0:\n return count\n count += 1\n for i in range(0, size):\n r,c = queue.pop(0)\n for d in dirs:\n row = r + d[0]\n col = c + d[1]\n if 0 <= row < len(grid) and 0 <= col < len(grid[0]) and grid[row][col] == 1:\n grid[row][col] = 2\n fresh -= 1\n queue.append((row,col))\n \n return -1\n","sub_path":"RottingOranges-994.py","file_name":"RottingOranges-994.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"255700717","text":"from typing import List\nfrom argparse import Namespace\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom util.data import Movie\nfrom util.simulator import BaseConvMovieInterface\nfrom util.models.gmf import GeneralizedMatrixFactorization\nfrom util.models.mlp import MLPMatrixFactorization\nfrom util.models.mf import MatrixFactorization\nfrom util.models.neumf import NeuralMatrixFactorization\n\n\nclass MovieSelector(object):\n\n def __init__(self, movies: List[Movie], device='cpu'):\n \"\"\"\n\n :param movies: List of movies\n :param device: cpu/cuda for pytorch, defaults to CPU\n \"\"\"\n self.device = device\n self.movies = movies\n # Extract movie content vectors\n vectors = np.stack([movie.vector for movie in movies])\n self.vectors = torch.from_numpy(vectors.astype(np.float32)).to(self.device)\n self.embed_dim = self.vectors.shape[1]\n\n def query_vector(self, query_vec: np.ndarray, top_k: int = None, reverse: bool = False):\n \"\"\"\n Performs a simple inner product between query and all movies then\n returns the top-k\n\n :param query_vec: Single vector of the same dim as encoded vectors\n :param top_k: int, top_k to return if none return all\n :param reverse: bool, if we should sort ascending\n :return: similarity scores, movies\n \"\"\"\n # Inner product similarity\n # [N, D] [D, 1]\n if isinstance(query_vec, np.ndarray):\n query_vec = torch.from_numpy(query_vec.astype(np.float32))\n\n query_vec = query_vec.to(self.device).view(self.embed_dim, 1)\n scores = torch.matmul(self.vectors, query_vec).view(-1)\n\n # Sorted by similarity score\n if reverse:\n indices = torch.argsort(scores)\n else:\n indices = torch.argsort(-scores)\n scores = scores[indices]\n\n # Truncate\n if top_k is not None:\n scores = scores[:top_k]\n indices = indices[:top_k]\n return scores, [self.movies[i] for i in indices]\n\n\nclass AvgLatentFactorAgent(BaseConvMovieInterface):\n\n def __init__(self, opt: Namespace, movies_list: List[Movie]):\n \"\"\"\n Use averaged user latent factor rather than learning one\n\n :param opt:\n :param movies_list:\n \"\"\"\n states = torch.load(opt.model_file, 'cpu')\n model_type = opt.model\n self.model_params = states['params']\n if model_type == 'avggmf':\n model = GeneralizedMatrixFactorization(states['params'])\n elif model_type == 'avgmf':\n model = MatrixFactorization(states['params'])\n elif model_type == 'avgnmf':\n model = NeuralMatrixFactorization(states['params'])\n else:\n raise ValueError(f\"Unknown.... model: {model_type}\")\n model.load_state_dict(states['model'])\n\n model.eval()\n with torch.no_grad():\n if model_type in ['avggmf', 'avgmf']:\n # Set the new user latent rep to averaged version\n model.new_user.data = model.user_memory.weight.data.mean(0).squeeze()\n else:\n # NMF has two set, although they can be tied\n model.mf_new_user.data = model.mf_user.weight.data.mean(0).squeeze()\n model.mlp_new_user.data = model.mlp_user.weight.data.mean(0).squeeze()\n scores = model.new_user_recommend().cpu().numpy()\n self.predicted_ids = np.argsort(-scores).tolist()\n\n def reset(self):\n \"\"\"Nothing to reset\"\"\"\n return\n\n def observe(self, prev_state, is_seeker: bool, msg_length) -> dict:\n return {'rec': self.predicted_ids}\n\n\nclass LatentFactorConvMovieAgent(BaseConvMovieInterface):\n\n def __init__(self, opt: Namespace, movies_list: List[Movie]):\n \"\"\"\n\n :param opt: options/config\n :param movies_list: List of the movies for querying\n \"\"\"\n self.opt = opt\n self.selector = MovieSelector(movies_list, 'cpu')\n self.optimizer = None\n self.model = None\n self.verbose = getattr(opt, 'verbose', False)\n self.is_training = getattr(opt, 'train', False)\n self._sentiment_style = getattr(self.opt, 'sentiment', 'scale')\n if getattr(self.opt, 'replay', False):\n raise NotImplementedError(\"Reimbelement it if you want to use it\")\n assert getattr(self.opt, 'loss', 'bpr') == 'bpr', 'xent not supported'\n assert opt.weight_rescale == 'none', \"Meh no weight rescaling...\"\n states = torch.load(opt.model_file, 'cpu')\n model_type = opt.model\n self.model_params = states['params']\n\n if model_type == 'gmf':\n self.model = GeneralizedMatrixFactorization(states['params'])\n elif model_type == 'mf':\n self.model = MatrixFactorization(states['params'])\n elif model_type == 'mlp':\n self.model = MLPMatrixFactorization(states['params'])\n elif model_type == 'nmf':\n self.model = NeuralMatrixFactorization(states['params'])\n else:\n raise ValueError(f\"Unknown.... model: {model_type}\")\n self.model.load_state_dict(states['model'])\n\n if self.is_training:\n print(\"[Fine tunning model on dataset]\\n\")\n # self.model.v.requires_grad = False\n self.model.user_memory.weight.requires_grad = False\n else:\n self.model.freeze_params()\n self.reset()\n self.total_hits = 0\n # Rescale all weights by l2 norm\n # if opt.weight_rescale == 'l2':\n # for p in self.model.parameters():\n # if len(p.shape) == 2:\n # # [N, E] => [N, 1]\n # p.data /= p.data.norm(dim=1).unsqueeze(-1)\n # elif opt.weight_rescale == 'l2_item':\n # # Normalize only the item embeddings\n # self.model.item_memory.weight.data /= self.model.item_memory.weight.data.norm(dim=1).unsqueeze(-1)\n\n def reset(self):\n \"\"\"\n Reset the model's new user parameters and reinit the optimizer\n :return:\n \"\"\"\n # Init new user\n self.model.new_user_reset(self.opt.init)\n # eps = self.model.user_memory.weight.data.var()\n # self.model.new_user.data.uniform_(-eps, eps)\n\n if self.is_training:\n # Init only once, we zero out the cached momentum for new users\n if self.optimizer is None:\n self.optimizer = torch.optim.SGD(self.model.parameters(),\n lr=self.opt.lr, momentum=self.opt.momentum,\n weight_decay=self.opt.l2)\n # self.optimizer = torch.optim.Adam(self.model.parameters(),\n # weight_decay=self.opt.l2)\n # Reset momentum for new user parameters\n new_user_params = set(self.model.new_user_parameters())\n for group in self.optimizer.param_groups:\n for p in group['params']:\n if p in new_user_params:\n param_state = self.optimizer.state[p]\n # This is for SGD Momentum\n if 'momentum_buffer' in param_state:\n param_state['momentum_buffer'] = torch.zeros_like(p.data)\n\n # This is for Adam\n if 'step' in param_state:\n param_state['step'] = 0\n # Exponential moving average of gradient values\n param_state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n param_state['exp_avg_sq'] = torch.zeros_like(p.data)\n\n else:\n self.optimizer = torch.optim.SGD(self.model.new_user_parameters(),\n lr=self.opt.lr, momentum=self.opt.momentum,\n weight_decay=self.opt.l2)\n\n def _recommend(self):\n self.model.eval()\n with torch.no_grad():\n scores = self.model.new_user_recommend().cpu().numpy()\n predicted_ids = np.argsort(-scores).tolist()\n return predicted_ids\n\n def _sample_neg(self, retrieved, pos_matrix_ids=None):\n \"\"\"\n Sample negative items from the retrieved movies which assumed to be\n sorted\n\n For hard negative mining we require the ranking scores\n\n if pos_matrix_ids are passed we make sure these are not in the negative\n sample\n\n :param retrieved:\n :param pos_matrix_ids:\n :return:\n \"\"\"\n # Randomly select some negatives from the least similar\n neg_movies = retrieved[-self.opt.weighted_count:]\n if pos_matrix_ids:\n negs = []\n # Sample true negatives for training\n for _ in range(self.opt.neg_count):\n n = neg_movies[np.random.randint(self.opt.weighted_count)]\n while n.matrix_id in pos_matrix_ids:\n if n.matrix_id in pos_matrix_ids:\n self.total_hits += 1\n print(f\"[Neg Samples Hit: {self.total_hits}]\")\n n = neg_movies[np.random.randint(self.opt.weighted_count)]\n negs.append(n)\n else:\n # Random sample\n negs = np.random.choice(neg_movies, replace=False if len(neg_movies) >=\n self.opt.neg_count else True,\n size=self.opt.neg_count)\n return negs\n\n def query_item_lf(self, query_vec: np.ndarray, item_memory: torch.FloatTensor,\n reverse: bool=False, eps: float=1e-7):\n \"\"\"\n Given the query vector it computes the similarity against all movies from the\n selector, uses the model's item_memory weights to weight the latent factors\n\n :param query_vec: Conversation vector to query against the movies\n :param item_memory: [n_items, embed size], item latent factor values\n :param reverse: reverse the sorting from ascending/descending\n :param eps: For L2 normalization stability\n :return:\n \"\"\"\n scores, retrieved = self.selector.query_vector(query_vec, reverse=reverse)\n\n # Take only valid ones we have in our matrix\n # Valid score indices where we have the movie id\n\n # ignore missing movies\n # matrix_ids = [movie.matrix_id for movie in retrieved if movie.matrix_id < item_memory.shape[0]]\n matrix_ids = [movie.matrix_id for movie in retrieved]\n\n if self.opt.weighted_count is not None:\n scores = scores[:self.opt.weighted_count]\n matrix_ids = matrix_ids[:self.opt.weighted_count]\n\n # Get all item latent factors that are relevant\n raw_item_lf = item_memory[matrix_ids]\n\n # attention, softmax normalize\n if self.opt.norm == 'softmax':\n attn = nn.functional.softmax(scores, dim=-1)\n elif self.opt.norm == 'l2':\n # w / ||w||_2 + epsilon\n attn = scores / (torch.norm(scores) + eps)\n else:\n raise ValueError(\"Unknown normalization scheme\")\n\n # Broadcast and weighted sum\n item_latent_factor = (attn.unsqueeze(-1) * raw_item_lf).sum(0)\n\n return item_latent_factor, retrieved\n\n def observe(self, prev_state, is_seeker: bool, train_labels: set=None):\n \"\"\"\n\n :param prev_state:\n :param is_seeker:\n :param train_labels: only passed if training\n :return:\n \"\"\"\n obs = {}\n\n # Update style: always, seeker or recommender\n if prev_state is not None and self.opt.update == 'all' \\\n or (self.opt.update == 'seeker' and is_seeker) \\\n or (self.opt.update == 'rec' and not is_seeker):\n # if msg_length > self.opt.update_length:\n self.model.train()\n\n item_lf, retrieved = self.query_item_lf(prev_state['query_vec'],\n self.model.item_memory.weight)\n # Compute the loss\n neg_movies = self._sample_neg(retrieved) # Sample negatives\n\n # If we have sentiment scale else does nothing\n sentiment = torch.tensor(prev_state.get('sentiment', 1.0))\n obs['loss'] = 0.0\n\n # True SGD updates\n for neg_movie in neg_movies:\n self.optimizer.zero_grad()\n neg_ids = torch.LongTensor([neg_movie.matrix_id])\n neg_item_lf = self.model.item_memory(neg_ids) # Lookup neg item lf\n\n pos = self.model.new_user_score(item_lf)\n neg = self.model.new_user_score(neg_item_lf)\n if self._sentiment_style == 'xent':\n diff = pos-neg\n loss = torch.nn.BCEWithLogitsLoss()(diff.reshape(-1), sentiment.reshape(-1))\n elif self._sentiment_style == 'scale':\n loss = -torch.log(torch.sigmoid(pos - neg) + 1e-12) * sentiment\n # elif self._sentiment_style == 'gate':\n # pos = sentiment * pos\n # neg = (1.0-sentiment) * neg\n # loss = -torch.log(torch.sigmoid(pos - neg) + 1e-12)\n elif self._sentiment_style == 'none':\n loss = -torch.log(torch.sigmoid(pos - neg) + 1e-12)\n else:\n raise ValueError(\"Unknown sentiment style.....\")\n\n # retain_graph=True is for item_lf/retrieved\n loss.backward(retain_graph=True)\n # Update\n self.optimizer.step()\n obs['loss'] += loss.item()\n\n if self.verbose:\n print(f\" Loss: {loss.item():.4f}\")\n print(\"{:<4}Pos: {}\".format(\"\", \" | \".join([m.title for m in retrieved[:10]])))\n print(\"{:<4}Neg: {}\".format(\"\", \" | \".join([m.title for m in neg_movies[:10]])))\n\n obs['rec'] = self._recommend()\n return obs\n\n\nclass NeuMFAgent(LatentFactorConvMovieAgent):\n\n def observe(self, prev_state, is_seeker: bool, train_labels: set=None):\n \"\"\"\n Recommendation is slightly different for NeuMF since we have\n two embeddings instead of one, so we implement a new observe\n \"\"\"\n obs = {}\n\n # Update always, seeker or recommender\n # if prev_state is not None and self.opt.update == 'all' \\\n # or (self.opt.update == 'seeker' and is_seeker) \\\n # or (self.opt.update == 'rec' and not is_seeker):\n\n # if train_labels:\n # print(train_labels)\n # if train_labels > self.opt.update_length:\n # self.model.train()\n # # We have two item embeddings to learn since they are not shared\n # mf_item_lf, retrieved = self.query_item_lf(prev_state, self.model.mf_item.weight)\n # # TODO: this is doing redundant computation, we can optimize it\n # mlp_item_lf, _ = self.query_item_lf(prev_state, self.model.mlp_item.weight)\n #\n # # Compute the loss\n # neg_movies = self._sample_neg(retrieved) # Sample negatives\n # obs['loss'] = 0.0\n # # SGD updates\n # for neg_movie in neg_movies:\n # self.optimizer.zero_grad()\n # neg_ids = torch.LongTensor([neg_movie.matrix_id])\n # # Lookup neg item lf\n # neg_mf_item = self.model.mf_item(neg_ids)\n # neg_mlp_item = self.model.mlp_item(neg_ids)\n #\n # pos = self.model.new_user_score(mf_item_lf, mlp_item_lf)\n # neg = self.model.new_user_score(neg_mf_item, neg_mlp_item)\n #\n # loss = -torch.log(torch.sigmoid(pos - neg) + 1e-12)\n # loss.backward(retain_graph=True)\n # # Update\n # self.optimizer.step()\n # obs['loss'] += loss.item()\n #\n # if self.verbose:\n # print(f\" Loss: {loss.item():.4f}\")\n # print(\"{:<4}Pos: {}\".format(\"\", \" | \".join([m.title for m in retrieved[:10]])))\n # print(\"{:<4}Neg: {}\".format(\"\", \" | \".join([m.title for m in neg_movies[:10]])))\n\n obs['rec'] = self._recommend()\n return obs\n","sub_path":"util/latent_factor.py","file_name":"latent_factor.py","file_ext":"py","file_size_in_byte":16758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"379438759","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# eventはsetされれば一気に解放されるが、conditionはeventとロックの組み合わせのようなイメージ\nimport threading\nimport time\nimport logging\nimport queue\n\n# loggingが面倒な場合\nlogging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')\n\ndef worker1(condition :threading.Condition):\n with condition:\n condition.wait()\n logging.debug('start')\n time.sleep(3)\n logging.debug('end')\n\ndef worker2(condition :threading.Condition):\n with condition:\n condition.wait()\n logging.debug('start')\n time.sleep(3)\n logging.debug('end')\n\ndef worker3(condition :threading.Condition):\n with condition:\n logging.debug('start')\n time.sleep(5)\n logging.debug('end')\n # conditionをセットするまでwaitする\n condition.notify_all()\n\nif __name__ == '__main__':\n condition = threading.Condition()\n t1 = threading.Thread(target=worker1, args=(condition,))\n t2 = threading.Thread(target=worker2, args=(condition,))\n t3 = threading.Thread(target=worker3, args=(condition,))\n t1.start()\n t2.start()\n t3.start()\n","sub_path":"コンディション.py","file_name":"コンディション.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"49102171","text":"from Node import Node\nfrom flask import jsonify\n\nclass Lista(object):\n head = None\n tail = None\n\n\n def add(self,data):\n new_node = Node(data)\n if self.head is None:\n self.head = self.tail = new_node\n new_node.prev = self.head\n new_node.next = self.tail\n new_node.index = 0\n else:\n new_node.data = data\n new_node.prev = self.tail\n new_node.next = self.head\n new_node.index = self.tail.index + 1\n self.tail.next = new_node\n self.head.prev = new_node\n self.tail = new_node\n return new_node\n def search(self,dato):\n temp = self.head\n if self.head is not None:\n while (True):\n if(temp.data == dato):\n return temp\n temp = temp.next\n if (temp == self.head):\n break\n\n def search_user(self,dato):\n temp = self.head\n if self.head is not None:\n while (True):\n if(temp.data.username == dato):\n return temp\n temp = temp.next\n if (temp == self.head):\n break\n\n def search_year(self, dato):\n temp = self.head\n if self.head is not None:\n while (True):\n if (temp.data.year == dato):\n return temp\n temp = temp.next\n if (temp == self.head):\n return None\n\n def search_genere(self, dato):\n temp = self.head\n if self.head is not None:\n while (True):\n if (temp.data.genere == dato):\n return temp\n temp = temp.next\n if (temp == self.head):\n return None\n\n def delete(self,node):\n if node is not None:\n node.prev.next = node.next\n node.next.prev = node.prev\n node = None\n\n def add_years(self,data):\n self.add(data)\n\n def sort_by_years(self):\n temp = self.head\n if self.head is not None and self.head.next is not self.head:\n while (True):\n temp2 = self.head\n while (True):\n if temp2.next is not self.head and int(temp2.data.year) > int(temp2.next.data.year):\n bubble_data = temp2.next.data\n temp2.next.data = temp2.data\n temp2.data = bubble_data\n temp2 = temp2.next\n if (temp2 == self.head):\n break\n temp = temp.next\n if (temp == self.head):\n break\n\n def sort_by_generes(self):\n temp = self.head\n if self.head is not None and self.head.next is not self.head:\n while (True):\n temp2 = self.head\n while (True):\n if temp2.next is not self.head and temp2.data.genero.replace(\" \",\"\") > temp2.next.data.genero.replace(\" \",\"\"):\n bubble_data = temp2.next.data\n temp2.next.data = temp2.data\n temp2.data = bubble_data\n temp2 = temp2.next\n if (temp2 == self.head):\n break\n temp = temp.next\n if (temp == self.head):\n break\n\n def show(self):\n print(\"Show list data:\")\n temp = self.head\n if self.head is not None:\n while (True):\n print(temp.data.__dict__)\n temp = temp.next\n if (temp == self.head):\n break\n def structure_string(self):\n nodes = \"\"\n\n temp = self.head\n if self.head is not None:\n nodes += \"subgraph col\"+str(temp.index)+\"{ \\n rank=UD; \\n\"\n while (True):\n nodes += \"user{0}[label={1}] \\n\".format(temp.index, temp.data.username)\n nodes += \"user{0}->user{1} \\n\".format(temp.index,temp.next.index)\n nodes += \"user{1}->user{0} \\n\".format(temp.prev.index, temp.index)\n temp = temp.next\n if (temp == self.head):\n break\n nodes += \" } \"\n\n output = \"digraph dibujo{node[shape=box width=1];rank=LR; \"+nodes+\" }\"\n print(output)\n return output\n\n def __init__(self):\n pass","sub_path":"WebApp/PlayerServer/Lista.py","file_name":"Lista.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"653945866","text":"# -*- coding: utf-8 -*-\n\n# (c) Copyright IBM Corp. 2020,2021\n# Apache License, Version 2.0 (see https://opensource.org/licenses/Apache-2.0)\nfrom __future__ import absolute_import, division, print_function\nfrom collections import OrderedDict\n\n__metaclass__ = type\n\nfrom ansible_collections.ibm.ibm_zos_cics.plugins.modules import cmci_create\nfrom ansible_collections.ibm.ibm_zos_cics.tests.unit.helpers.cmci_helper import (\n HOST, PORT, CONTEXT, od, body_matcher, cmci_module, CMCITestHelper\n)\n\n\ndef test_csd_create(cmci_module): # type: (CMCITestHelper) -> None\n record = OrderedDict({})\n record['csdgroup'] = 'bat'\n record['name'] = 'bar'\n record['bundledir'] = '/u/bundles/bloop'\n\n cmci_module.stub_records(\n 'POST',\n 'cicsdefinitionbundle',\n [record],\n scope='IYCWEMW2',\n additional_matcher=body_matcher(od(\n ('request', od(\n ('create', od(\n ('parameter', od(\n ('@name', 'CSD')\n )),\n ('attributes', od(\n ('@csdgroup', 'bat'),\n ('@name', 'bar'),\n ('@bundledir', '/u/bundles/bloop')\n ))\n ))\n ))\n ))\n )\n\n cmci_module.expect(\n result(\n 'https://winmvs2c.hursley.ibm.com:26040/CICSSystemManagement/'\n 'cicsdefinitionbundle/CICSEX56/IYCWEMW2',\n record,\n '<request><create>'\n '<parameter name=\"CSD\"></parameter>'\n '<attributes csdgroup=\"bat\" name=\"bar\" bundledir=\"/u/bundles/bloop\"></attributes>'\n '</create></request>'\n )\n )\n\n cmci_module.run(cmci_create, dict(\n cmci_host=HOST,\n cmci_port=PORT,\n context=CONTEXT,\n scope='IYCWEMW2',\n type='cicsdefinitionbundle',\n create_parameters=[dict(\n name='CSD'\n )],\n attributes=record\n ))\n\n\ndef test_bas_create(cmci_module): # type: (CMCITestHelper) -> None\n record = OrderedDict({})\n record['AUTOINST'] = 'NO'\n record['RGSCOPE'] = 'BAS1'\n record['RESDESC'] = 'BASICB11'\n\n cmci_module.stub_records(\n 'POST',\n 'cicsdefinitionbundle',\n [record],\n scope='IYCWEMW2',\n additional_matcher=body_matcher(od(\n ('request', od(\n ('create', od(\n ('parameter', od(\n ('@name', 'BAS')\n )),\n ('attributes', od(\n ('@AUTOINST', 'NO'),\n ('@RGSCOPE', 'BAS1'),\n ('@RESDESC', 'BASICB11')\n ))\n ))\n ))\n ))\n )\n\n cmci_module.expect(\n result(\n 'https://winmvs2c.hursley.ibm.com:26040/CICSSystemManagement/'\n 'cicsdefinitionbundle/CICSEX56/IYCWEMW2',\n record,\n '<request><create>'\n '<parameter name=\"BAS\"></parameter>'\n '<attributes AUTOINST=\"NO\" RGSCOPE=\"BAS1\" RESDESC=\"BASICB11\"></attributes>'\n '</create></request>'\n )\n )\n\n cmci_module.run(cmci_create, dict(\n cmci_host=HOST,\n cmci_port=PORT,\n context=CONTEXT,\n scope='IYCWEMW2',\n type='cicsdefinitionbundle',\n create_parameters=[dict(\n name='BAS'\n )],\n attributes=record\n ))\n\n\ndef result(url, record, body):\n return {\n 'changed': True,\n 'connect_version': '0560',\n 'cpsm_reason': '',\n 'cpsm_reason_code': 0,\n 'cpsm_response': 'OK',\n 'cpsm_response_code': 1024,\n 'http_status': 'OK',\n 'http_status_code': 200,\n 'record_count': 1,\n 'records': [record],\n 'request': {\n 'url': url,\n 'method': 'POST',\n 'body': body\n },\n }\n","sub_path":"tests/unit/modules/test_cmci_create.py","file_name":"test_cmci_create.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"565515762","text":"\"\"\"Tests for neurodocker.interfaces.Convert3D\"\"\"\n\nfrom neurodocker.interfaces.tests import utils\n\n\nclass TestConvert3D(object):\n\n def test_docker(self):\n specs = {\n 'pkg_manager': 'apt',\n 'instructions': [\n ('base', 'ubuntu:18.04'),\n ('convert3d', {'version': '1.0.0'}),\n ('user', 'neuro'),\n ]\n }\n\n bash_test_file = \"test_convert3d.sh\"\n utils.test_docker_container_from_specs(\n specs=specs, bash_test_file=bash_test_file)\n\n def test_singularity(self):\n specs = {\n 'pkg_manager': 'apt',\n 'instructions': [\n ('base', 'docker://ubuntu:16.04'),\n ('convert3d', {'version': '1.0.0'}),\n ('user', 'neuro'),\n ]\n }\n\n bash_test_file = \"test_convert3d.sh\"\n utils.test_singularity_container_from_specs(\n specs=specs, bash_test_file=bash_test_file)\n","sub_path":"neurodocker/interfaces/tests/test_convert3d.py","file_name":"test_convert3d.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"500013788","text":"import twstock\n\ndef get_price(stockid): # 取得股票名稱和及時股價\n rt = twstock.realtime.get(stockid) # 取得台積電的及時交易資訊\n if rt['success']: # 如果讀取成功\n return (rt['info']['name'], #←傳回 (股票名稱, 及時價格)\n float(rt['realtime']['latest_trade_price']))\n else:\n return (False, False)\n\ndef get_best(stockid): # 檢查是否符合四大買賣點\n stock = twstock.Stock(stockid)\n bp = twstock.BestFourPoint(stock).best_four_point()\n if(bp):\n return ('買進' if bp[0] else '賣出', bp[1]) #←傳回買進或賣出的建議\n else:\n return (False, False) #←都不符合\n\nname, price = get_price('2330') #←用 name 及 price 來承接傳回的 tuple\nact, why = get_best('2330') #←用 act 及 why 來承接傳回的四大買賣點 tuple\nprint(name, price, act, why, sep=' | ')\n","sub_path":"ML from Courses/FT700/ch06/6-6.py","file_name":"6-6.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"437127724","text":"import os\nimport argparse\nimport matplotlib.pyplot as plt\nimport mxnet as mx\nfrom mxnet import image, nd\nfrom tools.tools import try_gpu, import_module\n\n\n# 读取单张测试图片\ndef single_image_data_loader(filename, test_image_size=300):\n \"\"\"\n 加载测试用的图片,测试数据没有groundtruth标签\n \"\"\"\n\n def reader():\n img_size = test_image_size\n file_path = os.path.join(filename)\n img = image.imread(file_path)\n img = image.imresize(img, img_size, img_size, 3).astype('float32')\n\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n mean = nd.array(mean).reshape((1, 1, -1))\n std = nd.array(std).reshape((1, 1, -1))\n out_img = (img / 255.0 - mean) / std\n out_img = out_img.transpose((2, 0, 1)).expand_dims(axis=0) # 通道 h w c->c h w\n\n yield out_img\n return reader\n\n\n# 预测目标\ndef predict(test_image, net, img, labels, threshold=0.3):\n anchors,bbox_preds,cls_preds= net(test_image)\n cls_probs = nd.SoftmaxActivation(cls_preds.transpose((0, 2, 1)), mode='channel')\n output = nd.contrib.MultiBoxDetection(cls_probs, bbox_preds, anchors,\n force_suppress=True, clip=True,\n threshold=0.5, nms_threshold=.45)\n\n idx = [i for i, row in enumerate(output[0]) if row[0].asscalar() != -1]\n if idx:\n output = output[0, idx]\n display(img, labels, output, threshold=threshold)\n return True\n else:\n return False\n\n\n# 显示多个边界框\ndef show_bboxes(axes, bboxes, labels=None):\n for i, bbox in enumerate(bboxes, 0):\n bbox = bbox.asnumpy()\n rect = plt.Rectangle(\n xy=(bbox[0], bbox[1]), width=bbox[2]-bbox[0], height=bbox[3]-bbox[1],\n fill=False, linewidth=2, color='w')\n axes.add_patch(rect)\n if labels:\n axes.text(rect.xy[0], rect.xy[1], labels,\n horizontalalignment='center', verticalalignment='center', fontsize=8,\n color='k', bbox=dict(facecolor='w', alpha=1))\n\n\ndef display(img, labels, output, threshold):\n fig = plt.imshow(img.asnumpy())\n for row in output:\n score = row[1].asscalar()\n if score < threshold:\n continue\n h, w = img.shape[0:2]\n bbox = [row[2:6] * nd.array((w, h, w, h), ctx=row.context)]\n label = labels[int(row[0].asscalar())]\n show_bboxes(fig.axes, bbox, '%s-%.2f' % (label, score))\n plt.show()\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='predict the single image')\n parser.add_argument('--image-path', dest='img_path', help='image path',\n default=None, type=str)\n parser.add_argument('--model', dest='model', help='choice model to use',\n default='resnet_ssd', type=str)\n parser.add_argument('--model-params', dest='model_params', help='choice model params to use',\n default='mask_resnet18_SSD_model.params', type=str)\n parser.add_argument('--class-names', dest='class_names', help='choice class to use',\n default='without_mask,with_mask,mask_weared_incorrect', type=str)\n parser.add_argument('--image-shape', dest='image_shape', help='image shape',\n default=512, type=int)\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n # ctx = try_gpu()\n ctx = mx.cpu()\n\n img = image.imread(args.img_path).as_in_context(ctx)\n reader = single_image_data_loader(args.img_path, args.image_shape)\n labels = args.class_names.strip().split(',')\n class_nums = len(labels)\n\n model_path = os.path.join('model', args.model_params)\n net = import_module('model.'+args.model).get_model(class_nums, pretrained_model=model_path, pretrained=True, ctx=ctx)\n\n for x in reader():\n output = predict(x, net, img, labels)\n if not output:\n print('not found!')\n\n\n# img_path = 'D:/mxnet_projects/mxnet_ssd/data/facemask/images/maksssksksss5.png'","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"622353963","text":"# coding=utf-8\nfrom mininet.net import Containernet\nfrom mininet.node import Controller, Docker, OVSSwitch\nfrom mininet.cli import CLI\nfrom mininet.topo import Topo\n\nclass TopoTrabalhoFinal( Topo ):\n\tdef build(self):\n\t\th1 = self.addHost( 'h1' );#cliente de vídeo\n\t\th2 = self.addHost( 'h2' ) #Servidor de video\n\t\th3 = self.addHost( 'h3',cls=Docker, dimage='gmiotto/click') #Point of Presence\n\t\t#h3 = self.addHost( 'h3' ) #Servidor de video\n\t\th4 = self.addHost( 'h4' ) #End point do malicioso\n\t\th5 = self.addHost( 'h5' ) #Malicioso\n\n\t\ts1 = self.addSwitch( 's1')\n\t\ts2 = self.addSwitch( 's2')\n\t\ts3 = self.addSwitch( 's3')\n\t\ts4 = self.addSwitch( 's4')\n\t\ts5 = self.addSwitch( 's5')\n\n\t\t# Duas interfaces para o PoP\n\t\tself.addLink( h3,s3)\n\t\tself.addLink( h3,s3)\n\t\t\n\t\t# Conexões entre switches\n\t\tself.addLink( s1,s2)\n\n\t\tself.addLink( s2,s3)\n\n\t\tself.addLink( s3,s4)\n\n\t\tself.addLink( s4,s5)\n\n\t\t# Conexões para hosts\n\t\tself.addLink( h1,s1)\n\t\tself.addLink( h2,s2)\n\t\tself.addLink( h4,s4)\n\t\tself.addLink( h5,s5)\n\n\n\ntopos = { 'TFTopo': TopoTrabalhoFinal }\n","sub_path":"Mininet/sfcTest.py","file_name":"sfcTest.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"110975301","text":"import os\n\nPROJECT_APPS = ('django_geoip', 'tests')\nROOT_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\n\ntry:\n import django_jenkins\n JENKINS_APP = ('django_jenkins',)\nexcept ImportError:\n JENKINS_APP = None\n\nDEBUG = True\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'mydatabase'\n }\n}\nINSTALLED_APPS = ('django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.admin',) + PROJECT_APPS + JENKINS_APP + ('south',)\nPROJECT_APPS = PROJECT_APPS\nJENKINS_TASKS = (\n 'django_jenkins.tasks.with_coverage',\n 'django_jenkins.tasks.django_tests',\n 'django_jenkins.tasks.run_pep8',\n 'django_jenkins.tasks.run_pylint',\n)\nPYLINT_RCFILE = os.path.join(ROOT_PATH, 'tests', 'pylint.rc')\nROOT_URLCONF = 'tests.urls'","sub_path":"tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"431952572","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport math\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import nn_ops\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\nimport tensorflow as tf\nimport random\nimport numpy as np\nimport time\nimport sparse_tools as sp\nimport os\nfrom sparse_module import sparse_nn_ops as sc_module\n\npid = os.getpid()\nprint(pid)\n\n#print(dir(sc_module))\n\nraw_input(\"Press Enter to continue...\")\n\n\nfilter_in_sizes=[3, 3, 3, 1, 1] #[depth, height, width, in_channels, out_channels] \nstride=1\ndim = 3\nrho_filter=1\npadding='SAME'\n\nnum_resolutions = 64\nres_step_size = 4\nnum_trials = 4\n\nall_t_s = [None] * num_resolutions\nall_t_as = [None] * num_resolutions\nall_t_d = [None] * num_resolutions\nall_res = [None] * num_resolutions\nall_bp1 = [None] * num_resolutions\nall_bp2 = [None] * num_resolutions\nall_bp3 = [None] * num_resolutions\nall_bp4 = [None] * num_resolutions\nall_bp5 = [None] * num_resolutions\n\nif isinstance(stride, collections.Iterable):\n strides = [1] + list(stride) + [1]\nelse:\n strides = [1, stride, stride, stride, 1]\n\nfor res_step in range(1, num_resolutions + 1):\n res = res_step * res_step_size\n\n tensor_in_sizes=[1, res, res, res, 1] #[batch, depth, height, width, in_channels]\n rho_data = 1. / res\n\n [t1ind, t1val, t1sh] = sp.createRandomSparseTensor(rho_data, tensor_in_sizes)\n s1 = tf.SparseTensor(indices=t1ind, values=t1val, dense_shape=t1sh)\n d1 = sp.sparse_to_dense(t1ind, t1val, t1sh)\n\n [t2ind, t2val, t2sh] = sp.createRandomSparseTensor(rho_filter, filter_in_sizes)\n s2 = tf.SparseTensor(indices=t2ind, values=t2val, dense_shape=t2sh)\n d2 = sp.sparse_to_dense(t2ind, t2val, t2sh)\n\n config = tf.ConfigProto(\n device_count = {'GPU': 0},\n# inter_op_parallelism_threads=2,\n# intra_op_parallelism_threads=1\n )\n\n print(\"input shape\", tensor_in_sizes)\n print(\"filter shape\", filter_in_sizes)\n t_dense = 0\n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n conv = nn_ops.conv3d(d1, d2, strides, padding)\n t1 = time.time()\n expected = sess.run(conv)\n t2 = time.time()\n t_dense = t_dense + t2 - t1\n t_dense = t_dense / float(num_trials)\n\n print(\"time dense: \", t_dense)\n\n t_sparse = 0\n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n scskconv = sc_module.sparse_tensor_sparse_kernel_dense_conv_kd(t1ind, t1val, t1sh, t2ind, t2val, t2sh, strides, padding, dim, False);\n t1 = time.time()\n sv2 = sess.run(scskconv)\n t2 = time.time()\n t_sparse = t_sparse + t2 - t1\n t_sparse = t_sparse / float(num_trials)\n print(\"time sparse: \", t_sparse)\n\n t_asparse = 0\n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n scskconv = sc_module.sparse_tensor_sparse_kernel_dense_conv_kd(t1ind, t1val, t1sh, t2ind, t2val, t2sh, strides, padding, dim, True);\n t1 = time.time()\n sv2 = sess.run(scskconv)\n t2 = time.time()\n t_asparse = t_asparse + t2 - t1\n t_asparse = t_asparse / float(num_trials)\n print(\"time approx. sparse: \", t_asparse)\n \n t_bp1 = 0\n t_bp2 = 0\n t_bp3 = 0\n t_bp4 = 0\n t_bp5 = 0\n \n out_backprop_shape = conv.get_shape().as_list()\n [t3ind, t3val, t3sh] = sp.createRandomSparseTensor(rho_data + 0.01, out_backprop_shape, 1, 9)\n \n \n if res < 136: #dummy line\n d3_ = sp.sparse_to_dense(t3ind, t3val, t3sh)\n d3 = constant_op.constant(d3_)\n out_backprop_val = d3\n \n \n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n fbp = nn_ops.conv3d_backprop_filter_v2(d1, filter_in_sizes, out_backprop_val, strides, padding)\n t1 = time.time()\n sess.run(fbp)\n t2 = time.time()\n t_bp1 = t_bp1 + t2 - t1\n t_bp1 = t_bp1 / float(num_trials)\n print(\"time bp1: \", t_bp1)\n \n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n fbp = nn_ops.conv3d_backprop_input_v2(tensor_in_sizes, d2, out_backprop_val, strides, padding)\n t1 = time.time()\n sess.run(fbp)\n t2 = time.time()\n t_bp2 = t_bp2 + t2 - t1\n t_bp2 = t_bp2 / float(num_trials)\n print(\"time bp2: \", t_bp2)\n \n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n fbp = sc_module.sparse_tensor_sparse_kernel_dense_conv_kd_filter_grad(t1ind, t1val, t1sh, t2ind, t2val, t2sh, t3ind, t3val, t3sh, strides, padding)\n t1 = time.time()\n sess.run(fbp)\n t2 = time.time()\n t_bp3 = t_bp3 + t2 - t1\n t_bp3 = t_bp3 / float(num_trials)\n print(\"time bp3: \", t_bp3)\n \n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n fbp = sc_module.sparse_tensor_sparse_kernel_dense_conv_kd_input_grad(t1ind, t1val, t1sh, t2ind, t2val, t2sh, t3ind, t3val, t3sh, strides, padding)\n t1 = time.time()\n sess.run(fbp)\n t2 = time.time()\n t_bp4 = t_bp4 + t2 - t1\n t_bp4 = t_bp4 / float(num_trials)\n print(\"time bp4: \", t_bp4)\n\n time.sleep(1)\n with tf.Session(config=config) as sess:\n for i in range(num_trials):\n fbp = sc_module.sparse_tensor_sparse_kernel_dense_conv_kd_grad_v2(t1ind, t1val, t1sh, t2ind, t2val, t2sh, t3ind, t3val, t3sh, strides, padding)\n t1 = time.time()\n sess.run(fbp)\n t2 = time.time()\n t_bp5 = t_bp5 + t2 - t1\n t_bp5 = t_bp5 / float(num_trials)\n \n tf.reset_default_graph()\n\n print(\"time bp5: \", t_bp5)\n all_res[res_step - 1] = res\n all_t_s[res_step - 1] = t_sparse\n all_t_as[res_step - 1] = t_asparse\n all_t_d[res_step - 1] = t_dense\n all_bp1[res_step - 1] = t_bp1\n all_bp2[res_step - 1] = t_bp2\n all_bp3[res_step - 1] = t_bp3\n all_bp4[res_step - 1] = t_bp4\n all_bp5[res_step - 1] = t_bp5\n\nresult_file = open('eval_time_conv.txt', 'w')\nfor i in range(len(all_t_s)):\n result_file.write(\"%s %s %s %s %s %s %s %s %s\\n\" % (all_res[i], all_t_d[i], all_t_s[i], all_t_as[i], all_bp1[i], all_bp2[i], all_bp3[i], all_bp4[i], all_bp5[i]))\n\n","sub_path":"tensorflow/core/user_ops/cpu_tests/test_conv_layer.py","file_name":"test_conv_layer.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"554277387","text":"import argparse\nimport logging\nimport os\nimport six\n\ntry:\n from gevent import subprocess\nexcept ImportError:\n import subprocess\n\ntry:\n from logging import NullHandler\nexcept ImportError:\n # NullHandler doesn't exist in Python 2.6\n from logging import Handler\n\n\n class NullHandler(Handler):\n def emit(self, record):\n pass\n\nLETSENCRYPT_SAN_LIMIT = 100\n\nlogger = logging.getLogger(__name__)\n\n\nclass ACMEException(BaseException):\n pass\n\n\nclass DomainsMissing(ACMEException):\n pass\n\n\nclass MisconfiguredCommands(ACMEException):\n pass\n\n\ndef _generate_certificate(domains, **options):\n subprocess_args = [\n 'sudo',\n ]\n\n # split the python location (if any) from the certbot path\n subprocess_args += [six.moves.shlex_quote(part) for part in options.get('certbot_command', '').split()]\n\n subprocess_args += [\n 'certonly',\n '--noninteractive',\n '--preferred-challenges=http-01',\n '--manual',\n '--manual-public-ip-logging-ok',\n '--manual-auth-hook={0}'.format(six.moves.shlex_quote(options.get('auth_script', ''))),\n '--domains={0}'.format(six.moves.shlex_quote(domains))\n ]\n\n account = options.get('account', None)\n if account is not None:\n subprocess_args.append('--account={0}'.format(account))\n\n rsa_key_size = options.get('rsa_key_size', None)\n if rsa_key_size:\n subprocess_args.append('--rsa-key-size={0}'.format(six.moves.shlex_quote(str(rsa_key_size))))\n\n if options.get('allow_domain_subset', False):\n subprocess_args.append('--allow-subset-of-names')\n\n # default to maintaining certbot(-auto) version to minimize breakage\n if not options.get('allow_self_upgrade', False):\n subprocess_args.append('--no-self-upgrade')\n\n if not options.get('production', False):\n subprocess_args.append('--staging')\n\n if options.get('redirect', False):\n subprocess_args.append('--redirect')\n\n if options.get('hsts', False):\n subprocess_args.append('--hsts')\n\n if options.get('must_staple', False):\n subprocess_args.append('--must-staple')\n\n if options.get('staple_ocsp', False):\n subprocess_args.append('--staple-ocsp')\n\n if options.get('uir', False):\n subprocess_args.append('--uir')\n\n logger.debug('certbot subprocess arguments: %s', subprocess_args)\n\n proc = subprocess.Popen(subprocess_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = proc.communicate()\n\n logger.debug('certbot subprocess result code: %s', proc.returncode)\n if proc.returncode:\n logger.debug('certbot subprocess stdout:\\n%s', out)\n logger.debug('certbot subprocess stderr:\\n%s', err)\n\n return {\n 'success': not bool(proc.returncode),\n 'stdout': out,\n 'stderr': err\n }\n\n\n# NOTE: keyword-based arguments instead of parameters to allow for future adjustment\n# related to `certbot` changes - less likely to break users code\ndef generate_certificate(**options):\n # Possible parameters, all map approximately to certbot options:\n # [\n # 'account', 'allow_domain_subset', 'allow_self_upgrade',\n # 'auth_script', 'certbot_command', 'domains', 'hsts',\n # 'must_staple', 'production', 'redirect', 'rsa_key_size',\n # 'san_ucc', 'staple_ocsp', 'uir'\n # ]\n # Generate this list using --generate_function_params\n\n domains = options.pop('domains', [])\n if not domains:\n raise DomainsMissing\n\n if isinstance(domains, six.string_types):\n domains = [domains]\n\n if not options.get('certbot_command') or not options.get('auth_script'):\n raise MisconfiguredCommands\n\n if options.get('san_ucc', False):\n # TODO: split domains into chunks of 100 (or 99?)\n # NOTE: the first item in each chunk of 100 will be\n # set as the CN for the cert\n logger.debug('Generating SAN certificate for %s', domains)\n _result = _generate_certificate(','.join(domains), **options)\n results = dict([(d, _result) for d in domains])\n else:\n results = {}\n for domain in domains:\n logger.debug('Generating one certificate for %s', domain)\n results[domain] = _generate_certificate(domain, **options)\n\n return results\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", default=False, help=\"Verbose output\")\n parser.add_argument(\"--generate_function_params\", action=\"store_true\", default=False,\n help=\"Display all `generate_certificate` parameters (for developers integrating this library)\")\n parser.add_argument('-d', '--domains', type=str, default=None,\n help=\"Comma-separated list of domains for which to create a certificate(s)\")\n parser.add_argument('-a', '--auth-script', default=None,\n help=\"Full path to auth hook script; no spaces allowed\")\n parser.add_argument('-c', '--certbot-command', default=None,\n help=\"Full path to `certbot`/`certbot-auto`\")\n parser.add_argument('--account', default=None,\n help=\"Account ID to use for registering domains\")\n parser.add_argument('--rsa-key-size', type=int, default=None,\n help=\"RSA key size to use for certificate generation\")\n parser.add_argument('-s', '--san-ucc', action='store_true', default=False,\n help=\"If multiple domains are specified, this indicates whether to bundle up to \"\n \"{0} domains into a single SAN/UCC certificate (default is false)\".format(\n LETSENCRYPT_SAN_LIMIT))\n parser.add_argument(\"--allow-domain-subset\", action=\"store_true\", default=False,\n help=\"Allow certificate generation to succeed even if a subset of domains fail to authorize (default is false)\")\n parser.add_argument('--must-staple', action='store_true', default=False,\n help=\"Adds the OCSP Must Staple extension to the certificate (default is false)\")\n parser.add_argument('--staple-ocsp', action='store_true', default=False,\n help=\"Enables OCSP Stapling (default is false)\")\n parser.add_argument('--hsts', action='store_true', default=False,\n help=\"Add the Strict-Transport-Security header to every HTTP response (default is false)\")\n parser.add_argument('--uir', action='store_true', default=False,\n help=\"Add the \\\"Content-Security-Policy: upgrade-insecure-requests\\\" header to every HTTP response (default is false)\")\n parser.add_argument('--redirect', action='store_true', default=False,\n help=\"Automatically redirect all HTTP traffic to HTTPS for the newly authenticated vhost (default is false)\")\n parser.add_argument('--allow-self-upgrade', action='store_true', default=False,\n help=\"Permit automatic certbot upgrades (only applies when using certbot-auto; default is false)\")\n parser.add_argument('--production', action='store_true', default=False,\n help=\"Use production Let's Encrypt servers. (default is false)\")\n\n args = parser.parse_args()\n\n if args.verbose:\n logger_level = logging.DEBUG\n else:\n logger_level = logging.INFO\n\n logging.basicConfig(format='%(asctime)-15s %(levelname)-8s %(name)-5s %(message)s')\n logger.setLevel(logger_level)\n\n options = vars(args)\n if args.generate_function_params:\n parser.exit(status=0, message=\"keyword arguments only (order unimportant):\\ngenerate_certificate({0})\\n\".format(\", \".join(sorted([p for p in options.keys() if p not in ['verbose', 'generate_function_params']]))))\n\n if not args.domains:\n parser.error('argument -d/--domains is required')\n if not args.certbot_command:\n parser.error('argument -c/--certbot-command is required')\n if not args.auth_script:\n parser.error('argument -c/--auth-script is required')\n\n # do some quick overrides of arguments\n options['domains'] = args.domains.split(',') if args.domains else []\n options['certbot_command'] = args.certbot_command or os.getenv('LETSENCRYPT_CERTBOT_COMMAND', '')\n options['auth_script'] = args.auth_script or os.getenv('LETSENCRYPT_AUTH_HOOK_SCRIPT', '')\n options['account'] = args.account or os.getenv('LETSENCRYPT_ACCOUNT', None)\n\n results = generate_certificate(**options)\n\n for domain, result in six.iteritems(results):\n if result.get('success', False):\n logger.info('SSL certificate successfully generated for %s', domain)\n else:\n logger.info('Could not generate SSL certificate for %s', domain)\n\n\nif __name__ == \"__main__\":\n main()\nelse:\n logger.addHandler(NullHandler())\n logger.setLevel(logging.INFO)\n\n# LETSENCRYPT_CERTBOT_COMMAND=\"/vagrant/certbot/venv/local/bin/python /vagrant/certbot/venv/local/bin/certbot\" LETSENCRYPT_AUTH_HOOK_SCRIPT=\"/vagrant/certbot/test-auth-hook.sh\"\n","sub_path":"certbot_py/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"222729735","text":"\n\"\"\"\n Verify if yaota8266.bin flashed on the device\n and check if the same RSA key was used\n\n Just call this file on your ESP8266.\n Insert your RSA modulus, first!\n\"\"\"\nimport esp\nfrom micropython import const\n\nYAOTA8266_MAGIC = b'yaotaota' # for: machine.RTC().memory('yaotaota') to trigger OTA\n\n# copy&paste your RSA modulus from your config.h:\nYAOTA8266_RSA_MODULUS = b'\\xce\\x4a\\xaf\\x65\\x0d\\x4a\\x74\\xda\\xc1\\x30\\x59\\x80\\xcf\\xdd\\xe8\\x2a\\x2e\\x1d\\xf7\\xa8\\xc9\\x6c\\xa9\\x4a\\x2c\\xb7\\x8a\\x5a\\x2a\\x25\\xc0\\x2b\\x7b\\x2f\\x58\\x4c\\xa8\\xcb\\x82\\x07\\x06\\x08\\x7e\\xff\\x1f\\xce\\x47\\x13\\x67\\x94\\x5f\\x9a\\xac\\x5e\\x7d\\xcf\\x63\\xf0\\x08\\xe9\\x51\\x98\\x95\\x01'\n\nCHUNK_SIZE = const(128)\nBUFFER = bytearray(CHUNK_SIZE)\n\n\ndef search(offset, text, max_address=None):\n offset_step = CHUNK_SIZE - len(text)\n\n if offset_step <= 0:\n raise AssertionError('Search text too large: increase CHUNK_SIZE!')\n\n if max_address is None:\n max_address = esp.flash_size()\n\n end_researched = False\n while True:\n if offset + CHUNK_SIZE > max_address:\n # Search to esp.max_address(), but don't go beyond.\n offset = max_address - CHUNK_SIZE\n end_researched = True\n\n try:\n esp.flash_read(offset, BUFFER)\n except OSError as e:\n print('Read flash error: %s at 0x%x - 0x%x' % (e, offset, offset + CHUNK_SIZE))\n return -1\n\n if text in BUFFER:\n # bytearray has no .find() method\n return offset + bytes(BUFFER).find(text)\n\n if end_researched:\n print('End researched, searched up to 0x%x' % (offset + CHUNK_SIZE))\n return -1\n\n offset += offset_step\n\n\ndef verfiy_yaota8266():\n pos = search(offset=0, text=YAOTA8266_MAGIC, max_address=0x100)\n if pos == -1:\n print('yaota8266 magic word not found!')\n else:\n print('yaota8266 magic word found at 0x%x, ok.' % pos)\n\n pos = search(offset=0, text=YAOTA8266_RSA_MODULUS, max_address=0x3c000)\n if pos == -1:\n print('yaota8266 RSA modulus not found! Maybe compiles with other RSA key?!?')\n else:\n print('yaota8266 RSA modulus found at 0x%x, ok.' % pos)\n\n\nif __name__ == '__main__':\n verfiy_yaota8266()\n","sub_path":"helpers/verify_device.py","file_name":"verify_device.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"516807105","text":"class SqlQuery():\n def __init__(self, extract_query_file, source_db, target_table):\n self.extract_query_file = 'queries/' + extract_query_file\n self.source_db = source_db\n self.target_table = target_table\n\nIndividualWorkloads = SqlQuery(\n extract_query_file = 'individual_workloads.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_indworkloads'\n)\n\nIncompleteProcessesBL = SqlQuery(\n extract_query_file = 'incomplete_processes_bl.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_incompleteprocesses_bl'\n)\n\nIncompleteProcessesTL = SqlQuery(\n extract_query_file = 'incomplete_processes_tl.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_incompleteprocesses_tl'\n)\n\nMan001ActiveJobsBLInd = SqlQuery(\n extract_query_file = 'Man001ActiveJobsBL_ind_records.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activejobs_bl_ind'\n)\n\nMan001ActiveJobsBLCount = SqlQuery(\n extract_query_file = 'Man001ActiveJobsBL_counts.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activejobs_bl_counts'\n)\n\nMan001ActiveJobsTLInd = SqlQuery(\n extract_query_file = 'Man001ActiveJobsTL_ind_records.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activejobs_tl_ind'\n)\n\nMan001ActiveJobsTLCount = SqlQuery(\n extract_query_file = 'Man001ActiveJobsTL_counts.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activejobs_tl_counts'\n)\n\nMan002ActiveProcessesBLInd = SqlQuery(\n extract_query_file = 'Man002ActiveProcessesBL_ind_records.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activeproc_bl_ind'\n)\n\nMan002ActiveProcessesBLCount = SqlQuery(\n extract_query_file = 'Man002ActiveProcessesBL_counts.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activeproc_bl_counts'\n)\n\nMan002ActiveProcessesTLInd = SqlQuery(\n extract_query_file = 'Man002ActiveProcessesTL_ind_records.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activeproc_tl_ind'\n)\n\nMan002ActiveProcessesTLCount = SqlQuery(\n extract_query_file = 'Man002ActiveProcessesTL_counts.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_activeproc_tl_counts'\n)\n\nMan004BLJobVolumesBySubmissionTypes = SqlQuery(\n extract_query_file = 'Man004BLJobVolumesBySubmissionType.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_jobvolsbysubtype_bl'\n)\n\nMan004TLJobVolumesBySubmissionTypes = SqlQuery(\n extract_query_file = 'Man004TLJobVolumesBySubmissionType.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_jobvolsbysubtype_tl'\n)\n\nMan005BLExpirationDates = SqlQuery(\n extract_query_file = 'Man005BLExpirationDates.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_expirationdates_bl'\n)\n\nMan005TLExpirationDates = SqlQuery(\n extract_query_file = 'Man005TLExpirationDates.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_expirationdates_tl'\n)\n\nMan006OverdueBLInspections = SqlQuery(\n extract_query_file = 'Man006OverdueBLInspections.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_overdueinsp_bl'\n)\n\nSLA_BL = SqlQuery(\n extract_query_file = 'SLA_BL.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_sla_bl'\n)\n\nSLA_TL = SqlQuery(\n extract_query_file = 'SLA_TL.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_sla_tl'\n)\n\nUninspectedBLsWithCompCheck = SqlQuery(\n extract_query_file = 'UninspectedBLsWithCompChecks.sql',\n source_db = 'ECLIPSE_PROD',\n target_table = 'li_dash_uninsp_bl_comp_check'\n)\n\nqueries1 = [\n IndividualWorkloads,\n IncompleteProcessesBL,\n IncompleteProcessesTL,\n UninspectedBLsWithCompCheck,\n Man001ActiveJobsBLInd,\n Man001ActiveJobsBLCount,\n Man001ActiveJobsTLInd, \n Man001ActiveJobsTLCount,\n Man002ActiveProcessesBLInd,\n Man002ActiveProcessesBLCount, \n Man002ActiveProcessesTLInd,\n Man002ActiveProcessesTLCount,\n Man004BLJobVolumesBySubmissionTypes,\n Man004TLJobVolumesBySubmissionTypes,\n Man005BLExpirationDates,\n Man005TLExpirationDates,\n Man006OverdueBLInspections,\n SLA_BL,\n SLA_TL\n]\n\nSLA_BL_BUS_DAYS = SqlQuery(\n extract_query_file = 'SLA_BL_BUS_DAYS.sql',\n source_db = 'GISLICLD',\n target_table = 'sla_bl_bus_days'\n)\n\nSLA_TL_BUS_DAYS = SqlQuery(\n extract_query_file = 'SLA_TL_BUS_DAYS.sql',\n source_db = 'GISLICLD',\n target_table = 'sla_tl_bus_days'\n)\n\nqueries2 = [\n SLA_BL_BUS_DAYS,\n SLA_TL_BUS_DAYS\n]\n\nqueries_lists = (queries1, queries2)","sub_path":"etl/sql_queries.py","file_name":"sql_queries.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"643417586","text":"import helper\nfrom random_junctions import get_max_possible_genomic_regions, get_5utr_boundaries\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ntifs = helper.read_all_tifs(positive_strand_only=False, return_dict=True)\ngenome = helper.organize_genome_by_chrom(helper.read_bedfile())\nbamfile = helper.read_bamfile()\n\n#gene_start, gene_end = get_5utr_boundaries()\ngene_start, gene_end = get_max_possible_genomic_regions()\n\nfor chrom in helper.kYeastChroms:\n density, _ = helper.generate_read_density_chrom(chrom, bamfile)\n del _\n for gn, gene in genome[chrom].items():\n if gene.strand == \"+\" and gn in tifs[chrom] and gn in gene_start[\n chrom] and gn in gene_end[chrom]:\n print(gn)\n plt.plot(range(gene_start[chrom][gn], gene_end[chrom][gn]),\n density[gene_start[chrom][gn]:gene_end[chrom][gn]])\n junctions = np.unique(sorted(tifs[chrom][gn]['t5'].tolist()))\n for j in junctions:\n plt.axvline(j, color='k', alpha=0.5)\n\n plt.xlabel(\"Genomic position (nt)\")\n plt.ylabel(\"Read density\")\n\n plt.title(\"Read density across 5'UTR of gene \" + gn)\n\n plt.savefig(\"bulk/gene_\" + gn + \".png\")\n plt.close()\n","sub_path":"code/in_bulk_plots.py","file_name":"in_bulk_plots.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"62416594","text":"import json, pika\n\nfrom optparse import OptionParser\n\n#usage: alert_producer -r critical.rate_limit -m rate_out_of_limitation\nopt_parser = OptionParser()\n\nopt_parser.add_option(\"-r\", \"--routing_key\", dest=\"routing_key\", help=\"Routing key for message \" +\\\n \" (e.g. myalert.im)\")\n\nopt_parser.add_option(\"-m\", \"--message\", dest=\"message\", help=\"Message text for alert\")\n\nargs = opt_parser.parse_args()[0]\n\ncreds_broker = pika.PlainCredentials(\"alert_user\", \"alertme\")\nconn_params = pika.ConnectionParameters(\"localhost\", virtual_host=\"/\", credentials = creds_broker)\nconn_broker = pika.BlockingConnection(conn_params)\n\nchannel = conn_broker.channel()\n\nmsg = json.dumps(args.message)\nmsg_props = pika.BasicProperties()\nmsg_props.content_type = \"application/json\"\nmsg_props.durable = False\n\n\nchannel.publish(body=msg, exchange=\"alerts\", properties=msg_props, routing_key=args.routing_key)\nprint(\"Sent message %s tagged with routing key '%s' to \" % (args.message, args.routing_key))\n\n\n","sub_path":"php/chapter-4/alert_producer.py","file_name":"alert_producer.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"327853836","text":"from django.shortcuts import render\nimport requests\nfrom datetime import datetime\nfrom django.http import JsonResponse\n\n\n# Create your views here.\n\n\n\ndef home_weather(request):\n #ovdje spremamo url od meteobaze\n url = 'http://meteo.pointjupiter.co/'\n response = requests.get(url.format()).json()\n # ovdje imamo spremljenu sad cijelu listu objekata gradova\n cities = response['cities']\n context = {\n 'cities':cities\n }\n #forEach(citiy in cities){\n # take url > make get reque\n # store response in cities\n # e.g\n # Rijeka{\n # name: \"Rijeka\";\n # url: \"http......\",\n # data: response.data\n # }\n # }\n #\n return JsonResponse(context)\n\n\ndef home_weather_prediction(request, city_name):\n now = datetime.now()\n curr_date = now.strftime(\"%Y-%m-%d\")\n print(curr_date)\n url = 'http://meteo.pointjupiter.co/'\n response = requests.get(url.format()).json()\n cities = response['cities']\n t_arr1 = []\n pertcp_arr1 = []\n t_arr2 = []\n pertcp_arr2 = []\n t_arr3 = []\n pertcp_arr3 = []\n t_arr4 = []\n pertcp_arr4 = []\n weather_json = {\n 'day_1':'',\n 'day_2':'',\n 'day_3':'',\n 'day_4':'',\n 'day_5':''\n }\n for city in cities:\n if city['name'] == city_name:\n city_url = city['url']\n responsee = requests.get(city_url.format()).json()\n resp = responsee['data'][1]['forecast']\n resp2 = responsee['data'][2]['forecast']\n resp3 = responsee['data'][3]['forecast']\n resp4 = responsee['data'][4]['forecast']\n i = 0\n for data in resp:\n t_arr1.append(resp[i]['temperature'])\n i+=1\n i = 0\n for data in resp2:\n t_arr2.append(resp2[i]['temperature'])\n i+=1\n i = 0\n for data in resp3:\n t_arr3.append(resp3[i]['temperature'])\n i+= 1\n i=0\n for data in resp4:\n t_arr4.append(resp4[i]['temperature'])\n i+=1\n x = 0\n for data in resp:\n pertcp_arr1.append(resp[x]['prec'])\n x+=1\n x = 0\n for data in resp2:\n pertcp_arr2.append(resp2[x]['prec'])\n x+=1\n x = 0\n for data in resp3:\n pertcp_arr3.append(resp3[x]['prec'])\n x+=1\n x = 0\n for data in resp4:\n pertcp_arr4.append(resp4[x]['prec'])\n x+=1\n arr_temp_final = t_arr1 + t_arr2 + t_arr3 + t_arr4\n arr_prec_final = pertcp_arr1 + pertcp_arr2 + pertcp_arr3 + pertcp_arr4\n curr_day = {\n 'date':responsee['data'][0]['date'],\n 'weekday':responsee['data'][0]['weekday'],\n 'forecast':responsee['data'][0]['forecast']\n }\n day_1 = {\n 'date': responsee['data'][1]['date'],\n 'weekday': responsee['data'][1]['weekday'],\n 'forecast': responsee['data'][1]['forecast'],\n }\n day_2 = {\n 'date': responsee['data'][2]['date'],\n 'weekday': responsee['data'][2]['weekday'],\n 'forecast': responsee['data'][2]['forecast'],\n }\n day_3 = {\n 'date': responsee['data'][3]['date'],\n 'weekday': responsee['data'][3]['weekday'],\n 'forecast': responsee['data'][3]['forecast'],\n\n }\n day_4 = {\n 'date': responsee['data'][4]['date'],\n 'weekday': responsee['data'][4]['weekday'],\n 'forecast': responsee['data'][4]['forecast'],\n 'temp_arr':arr_temp_final,\n 'perctp_arr' :arr_prec_final\n }\n weather_json = {\n 'curr_day':curr_day,\n 'day_1':day_1,\n 'day_2':day_2,\n 'day_3':day_3,\n 'day_4':day_4\n }\n return JsonResponse(weather_json)\n\n\n","sub_path":"weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"256831949","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 10 11:01:23 2019\r\n\r\n@author: Matheus\r\n\"\"\"\r\n\r\n#from selenium import webdriver\r\n\r\n#chrome = webdriver.Chrome(executable_path='C:/webdrivers/chromedriver')\r\n\r\n#chrome.get('http://google.com.br')\r\n\r\nfrom geopy.geocoders import Nominatim\r\ngeolocator = Nominatim()\r\nlocation = geolocator.geocode(\"bonsucesso, rio de janeiro\") #entrar com os dados aqui\r\n#print(location.address)\r\n#print((location.latitude, location.longitude))\r\n\r\nfrom selenium import webdriver\r\n\r\nfirefox = webdriver.Firefox(executable_path='C:/webdrivers/geckodriver')\r\n\r\nfirefox.get('http://www.cresesb.cepel.br/index.php?section=sundata')\r\nfirefox.find_element_by_name('latitude_dec').send_keys('{}'.format(location.latitude))\r\nfirefox.find_element_by_name('longitude_dec').send_keys('{}'.format(location.longitude))\r\nfirefox.find_element_by_id('submit_btn').click()\r\n\r\n\r\n\r\n\r\n#firefox.quit()\r\n\r\n","sub_path":"webpython.py","file_name":"webpython.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"417197932","text":"'''\nAuthor: mukangt\nDate: 2020-12-07 17:50:07\nLastEditors: mukangt\nLastEditTime: 2020-12-15 14:41:51\nDescription: \n'''\nimport logging\nimport logging.handlers\nimport time\n\nfrom conf.config import Config\n\nstart_time = time.localtime()\n\nexec_day = time.strftime('%Y-%m-%d', start_time) # Execution date\nexec_hour = time.strftime('%H', start_time)\nexec_minute = time.strftime('%M', start_time)\n\nfmt_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\nlogging.basicConfig(level=logging.INFO, format=fmt_str)\nlog_file_handler = logging.handlers.TimedRotatingFileHandler(Config.LOG_PREFIX,\n when='D',\n interval=1,\n backupCount=3)\nlog_file_handler.suffix = \"%Y%m%d_%H%M%S.log\"\nlog_file_handler.setLevel(logging.INFO)\nformatter = logging.Formatter(fmt_str)\nlog_file_handler.setFormatter(formatter)\nlogging.getLogger('').addHandler(log_file_handler)\nlogging.info('exec_day :{}, exec_hour :{}, exec_minute :{}'.format(\n exec_day, exec_hour, exec_minute))\n","sub_path":"model_serving/app/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"216677663","text":"from ua.univer.prof.lesson_13_14_inheritance.doctor import Doctor\nfrom ua.univer.prof.lesson_13_14_inheritance.fighter import Fighter\nfrom ua.univer.prof.lesson_13_14_inheritance.human_factory import Human_factory\nfrom ua.univer.prof.lesson_13_14_inheritance.student import Student\n\n\ndef cafe(human):\n human.eat()\n\n\ndef print_list_of_human_type(humans, human_type):\n count_h = 0\n list_h = []\n for h in humans:\n if isinstance(h, human_type):\n count_h += 1\n list_h.append(h)\n print(human_type.__name__, \"count find =\", count_h)\n for h in list_h:\n print(h)\n\n\ndef print_10_human_from_factory():\n humans = []\n for i in range(10):\n humans.append(humans_factory.get_human_by_key(i % 3))\n for h in humans:\n print(h.list_of_fields())\n\n\nif __name__ == '__main__':\n\n humans_factory = Human_factory()\n humans = humans_factory.read_from_csv(\"humans.csv\")\n\n print(\"What kind of human find?\")\n human_str = input(\"Input : \")\n\n human_type = humans_factory.get_human_type_by_str(human_str)\n if human_type != None:\n print_list_of_human_type(humans, human_type)\n else:\n print(\"No such people\")","sub_path":"ua/univer/prof/lesson_13_14_inheritance/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"327525492","text":"# Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.\n#\n# Note:\n#\n# All numbers will be positive integers.\n# The solution set must not contain duplicate combinations.\n# Example 1:\n#\n# Input: k = 3, n = 7\n# Output: [[1,2,4]]\n# Example 2:\n#\n# Input: k = 3, n = 9\n# Output: [[1,2,6], [1,3,5], [2,3,4]]\n\nclass Solution:\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n\n def dfs(k, n, index, curr):\n if k < 0 or n < 0: return\n if k == 0 and n == 0:\n result.append(curr[:])\n return\n for i in range(index + 1, 10):\n curr.append(i)\n dfs(k - 1, n - i, i, curr)\n curr.pop()\n\n result = []\n dfs(k, n, 0, [])\n return result","sub_path":"src/216_Combination_Sum_III.py","file_name":"216_Combination_Sum_III.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"339776645","text":"\nimport log\nimport command\nimport utils\nimport os\n\nfrom commands.utils import select_services\nfrom commands.cmd_action_base import CommandActionBase\n\n\nclass InstallDockerServiceAction(CommandActionBase):\n def __installOneService(self, service, config):\n fullSrcImage = config.dockerContext.srcRegistryBase + service.srcImage\n serviceDocker = service.docker\n\n cmd = ['docker', 'run', '-d']\n cmd.append('--name={}'.format(serviceDocker.containerName))\n if serviceDocker.restart == 'always':\n cmd.append('--restart=always')\n\n if serviceDocker.dockerRunOptions is not None and len(serviceDocker.dockerRunOptions) > 0:\n cmd.extend(serviceDocker.dockerRunOptions)\n\n if serviceDocker.useHostNetwork:\n cmd.append('--net=host')\n else:\n for onePort in serviceDocker.ports:\n cmd.append('-p')\n cmd.append(onePort)\n\n if serviceDocker.privileged is not None and serviceDocker.privileged:\n cmd.append('--privileged=true')\n\n for oneEnv in serviceDocker.envs:\n cmd.append('-e')\n cmd.append(oneEnv)\n\n dataPathRoot = os.path.abspath(config.context.dataPathRoot)\n for oneVolume in serviceDocker.volumes:\n cmd.append('-v')\n cmd.append(dataPathRoot + oneVolume)\n\n cmd.append(fullSrcImage)\n if len(serviceDocker.command) > 0:\n cmd.append(serviceDocker.command)\n\n isSuccessful = command.executeWithOSSystem(cmd)\n if isSuccessful:\n log.highlight('install {0}:{1} service successfully'.format(\n service.namespace, service.name))\n else:\n log.error('install {0}:{1} service failed'.format(\n service.namespace, service.name))\n\n return\n\n def execute(self):\n services = select_services(self.config.services)\n if len(services) == 0:\n print(f'You do not select any service')\n return\n else:\n selected_service_set = set(services)\n for oneService in self.config.services:\n service_key = f'{oneService.namespace}:{oneService.name}'\n if service_key in selected_service_set:\n utils.printSectionLine('', 80, '*')\n self.__installOneService(oneService, self.config)\n return\n","sub_path":"deploy-script/commands/docker/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"347954908","text":"# import urllib.request\n# import urllib.parse\nimport requests\nimport copy\nimport time\nimport hashlib\nimport math\nimport json\nimport csv \t\t# necessary for parsing excel / csv file\nimport sys \nimport pprint\nimport string\nimport random\nfrom base64 import b64encode\nimport argparse\nimport logging\nimport http.client\nimport argparse\nimport datetime\nimport pdb\n\n__author__=\"kincy\"\n__date__ =\"$Jan 11, 2011 10:18:04 AM$\"\n\ndevelopers = json.load(open('developers.json'))['resat']\n\n\nnewKeySuffixSize = 16\nkeyInputFile = \"./wpmKeyList.txt\"\nkeyOutputFile = \"./newWpmKeyList.json\"\nkeyErrorsFile = \"./wpmErrors.txt\"\nareaID = 777\t\t# training area 1\n# areaID = 306\t\t# neustarbiz\n\ncount = 0\nendpoint = \"https://api.mashery.com\"\npath = \"/v2/json-rpc/\" + str(areaID)\n\n# initialize logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\ndef buildAuthParams():\n \"\"\"This function takes our API key and shared secret and uses it to create the signature that mashery wants \"\"\"\n authHash = hashlib.md5();\n #time.time() gets the current time since the epoch (1970) with decimals seconds\n temp = str.encode(developers['apikey'] + developers['secret'] + repr(int(time.time())))\n authHash.update(temp)\n return authHash.hexdigest()\n\ndef generateNewKeyString():\n\n\tprefix = str(int(hashlib.md5(str(count).encode('utf-8')).hexdigest(), 16) % (10 ** 8))\n\treturn prefix + stringGenerator(newKeySuffixSize - len(prefix))\n\ndef stringGenerator(size=8, chars=string.ascii_lowercase + string.digits):\n\t\n\t# this function generates a random list of 16 characters\n\tkey = ''.join(random.choice(chars) for _ in range(size))\n\treturn key\n\ndef OLDgenerateNewKeyString(oldApiKey, prefix):\n\t# this gives us the location of the last dot in the oldApiKey\n\tdot = oldApiKey.rfind(\".\")\n\t\n\t# we keep everything before the last dot in the old key\n\tkeeper = oldApiKey[:dot]\n\tlogging.debug(\"OLDKEY: \" + oldApiKey)\n\tlogging.debug(\"KEEPER: \" + keeper)\n\t\n\t# we generate a key by prefixing the provided string and filling the remainder with \n\t# random characters \n\tsuffix = prefix + stringGenerator(newKeySuffixSize - len(prefix))\n\treturn keeper + \".\" + suffix\n\t\n\ndef fetchKey(key):\n\tdata = {}\n\tdata[\"method\"] = \"object.query\"\n\tdata[\"id\"] = 1\n\tdata[\"params\"] = [\"SELECT * FROM keys WHERE apikey = '\" + key +\"'\"]\t\n\tresult = callAPI(\"fetchKey\", data)\n\tif not result:\n\t\treturn False\n\t\n\tif len(result['result']['items']) == 0:\n\t\twriteMasheryError(\"fetchKey\", key, \"Key not found in Mashery database\")\n\t\treturn False \n\t\n\tlogging.debug(\"Successfully fetched key: \" + key)\n\tlogging.debug(result['result']['items'][0])\n\treturn result['result']['items'][0]\n\ndef createNewKeyObject(oldKeyObject):\n\n\t# we clone the the key so we can make changes to the newKeyObject and still \n\t# retain the oldKeyObject for reference\n\tnewKeyObject = copy.copy(oldKeyObject)\t\t\t\n\t\t\n\t# the we generate a new key\n\tnewKeyObject['apikey'] = oldKeyObject['apikey'] + \".\" + generateNewKeyString()\n\t\n\t# generate a new secret for the new key\n\tnewKeyObject['secret'] = stringGenerator(8)\n\t\n\t# remove these structures from the creation object \n\tdel newKeyObject['username'], newKeyObject['service_key']\n\tnewKeyObject['member'] = {'username' : oldKeyObject['username']}\n\tnewKeyObject['service'] = { 'service_key' : oldKeyObject['service_key']}\n\n\t# these fields need to be removed since they are generated by the creation of a new key\n\tdel newKeyObject['created'], newKeyObject['id'], newKeyObject['object_type'], newKeyObject['updated']\n\tlogging.info(\"Successfully created newKeyObject\")\n\tlogging.debug(newKeyObject)\n\treturn newKeyObject\n\ndef createKey(keyObject):\n\tdata = {}\n\tdata[\"method\"] = \"key.create\"\n\tdata[\"id\"] = 1\n\tdata[\"params\"] = [keyObject]\n\tlogging.debug(\"DATA FOR KEY CREATE\")\n\tlogging.debug(data)\n\t\n\tresult = callAPI(\"createKey\", data)\n\tif not result:\n\t\treturn False\n\t\t\n\t# result = json.loads(result.decode(\"utf-8\"))\t\n\t\n\tlogging.debug(\"sucessfully created key: \" + keyObject[\"apikey\"])\n\tlogging.debug(result)\n\treturn result\n\ndef callAPI(operation, data):\n\t# convert the dict to a JSON payload\n\tdata = json.dumps(data, ensure_ascii=True).encode('utf-8') # , sort_keys = True, indent=4)\n\t# generate the URL to call the Mashery API\n\turl = endpoint + path + \"?apikey=\" + developers['apikey'] + \"&sig=\" + buildAuthParams()\n\n\ttry:\n\t\tresponse = requests.post(url, data, timeout=30)\n\t\n\texcept requests.exceptions.RequestException as e:\n\t\t# we have to decode the json object for pretty printing\n\t\t# Otherwise, just outputs a byte object that isn't pretty printable\n\t\terrorOutput = {}\n\t\terrorOutput['operation'] = operation\n\t\terrorOutput[\"message\"] = str(e)\n\t\terrorOutput[\"oldapikey\"] = oldApiKey.rstrip()\n\t\terrorOutput[\"time\"] = str(datetime.datetime.now().time())\n\t\tlogging.warn(errorOutput)\n\t\twith open(keyErrorsFile, \"a\") as errorFile:\n\t\t\terrorFile.write(str(errorOutput) + \"\\n\")\n\t\ttime.sleep(5)\n\t\treturn False\n\n\tlogging.debug(\"RESPONSE HEADERS\")\n\tlogging.debug(response.headers)\n\t\n\tif response.headers['Content-Length'] == 0:\n\t\tlogging.warn(\"Zero-byte Content Returned\")\n\t\twriteMasheryError(\"fetchKey\", key, \"Key not found in Mashery database\")\n\t\ttime.sleep(2)\n\t\treturn False\n\n\ttry:\n\t\treturn response.json()\n\texcept (ValueError, TypeError):\n\t\terrorOutput = {}\n\t\terrorOutput['operation'] = operation\n\t\terrorOutput[\"message\"] = \"No JSON Response\" + str(response.headers)\n\t\terrorOutput[\"oldapikey\"] = oldApiKey.rstrip()\n\t\terrorOutput[\"time\"] = str(datetime.datetime.now().time())\n\t\tlogging.warn(errorOutput)\n\t\twith open(keyErrorsFile, \"a\") as errorFile:\n\t\t\terrorFile.write(str(errorOutput) + \"\\n\")\n\t\ttime.sleep(2)\n\t\treturn False\n\t\t\n\treturn response.json()\n\t\ndef writeMasheryError(operation, apikey, reason):\n\t\terrorOutput = {}\n\t\terrorOutput['message'] = reason\n\t\terrorOutput['oldapikey'] = oldApiKey.rstrip()\n\t\terrorOutput[\"time\"] = str(datetime.datetime.now().time())\n\t\terrorOutput['operation'] = operation\n\t\tlogging.warn(errorOutput)\n\t\twith open(keyErrorsFile, \"a\") as errorFile:\n\t\t\terrorFile.write(str(errorOutput) + \"\\n\")\n\nif __name__ == \"__main__\":\n\n\t# initialize the errors file\n\topen(keyErrorsFile, 'w').close()\n\n\twith open(keyInputFile) as keyfile, open(keyOutputFile, \"w\") as newKeyFile:\n\t\tfor oldApiKey in keyfile:\n\n\t\t\t# maintain a count of each key \n\t\t\tcount += 1\n\t\t\tlogging.info(str(datetime.datetime.now().time()) + \" counter: \" + str(count))\n\t\t\t# first we get the key from the list and retrieve it from the Mashery\n\t\t\t# rstrip is like perl chomp\n\t\t\tresult = fetchKey((oldApiKey.rstrip()))\n\t\t\t# pdb.set_trace()\n\t\t\t\n\t\t\tif result == False:\n\t\t\t\tcontinue\n\n\t\t\tnewKeyObject = createNewKeyObject(result)\n\t\t\t\n\t\t\t# here we call the create key function from the Mashery\n\t\t\tresult = createKey(newKeyObject)\n\t\t\tif result == False:\n\t\t\t\tcontinue\n\t\t\t\t\t\t\n\t\t\t# now we build the output JSON file\n\t\t\t\n\t\t\toutputDict = {}\n\t\t\toutputDict['oldkey'] = oldApiKey.rstrip()\n\t\t\toutputDict['newkey'] = newKeyObject['apikey']\n\t\t\toutputDict['newsecret'] = newKeyObject['secret']\n\t\t\t\n\t\t\t# this is being done for testing purposes \n\t\t\t# newKeyOutput['oldsecret'] = oldKeyObject['secret']\n\n\t\t\tnewKeyFile.write(str(outputDict) + \"\\n\")\t\t\t\n\t\t\tlogging.info(\"updated object:\" + outputDict['newkey'])\n\t\t\tlogging.debug(newKeyObject)","sub_path":"updateNeustarKeys.v0.1.py","file_name":"updateNeustarKeys.v0.1.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"624924571","text":"import urllib.request\nfrom pyquery import PyQuery\n\n\ndef get_url_title(url):\n html = urllib.request.urlopen(url)\n content = html.read()\n pq = PyQuery(content)\n tag = pq(\"title\")\n print(tag.text())\n\n\ndef main():\n while True:\n input_url = input(\"Enter url: \\n\")\n get_url_title(input_url.strip())\n\n\nif __name__ == '__main__':\n main()","sub_path":"websites_title.py","file_name":"websites_title.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"189524890","text":"class Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n res = 0\n boxTypes.sort(key=lambda x: x[1])\n for item in reversed(boxTypes):\n if item[0] <= truckSize:\n truckSize -= item[0]\n res += item[0] * item[1]\n else:\n res += truckSize * item[1]\n break\n return res\n","sub_path":"array/1710_maximum_units_on_a_truck.py","file_name":"1710_maximum_units_on_a_truck.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"274344412","text":"\"\"\"empty message\n\nRevision ID: 38e6cecd3849\nRevises: e0a00045f6c7\nCreate Date: 2019-07-21 09:22:24.303125\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '38e6cecd3849'\ndown_revision = 'e0a00045f6c7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('set_anon',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('exercise', sa.String(length=128), nullable=True),\n sa.Column('pounds', sa.Integer(), nullable=True),\n sa.Column('reps', sa.Integer(), nullable=True),\n sa.Column('rpe', sa.Integer(), nullable=True),\n sa.Column('notes', sa.String(length=140), nullable=True),\n sa.Column('bodyweight', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_set_anon_timestamp'), 'set_anon', ['timestamp'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_set_anon_timestamp'), table_name='set_anon')\n op.drop_table('set_anon')\n # ### end Alembic commands ###\n","sub_path":"backend/migrations/versions/38e6cecd3849_.py","file_name":"38e6cecd3849_.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"224912346","text":"# coding: utf-8\nimport sys\nimport os\nimport re\nimport json\nimport uuid\nimport binascii\nimport subprocess\nimport webbrowser\n\nimport sublime_plugin\nimport sublime\n\nPY2 = sys.version_info < (3, 0)\n\ntry:\n from .floo import editor\n from .floo.sublime_connection import SublimeConnection\n from .floo.common import api, reactor, msg, shared as G, utils\n from .floo.common.exc_fmt import str_e\n from .floo.common.handlers.account import CreateAccountHandler\n from .floo.common.handlers.credentials import RequestCredentialsHandler\n assert api and G and msg and utils\nexcept (ImportError, ValueError):\n from floo import editor\n from floo.common import api, reactor, msg, shared as G, utils\n from floo.common.exc_fmt import str_e\n from floo.common.handlers.account import CreateAccountHandler\n from floo.common.handlers.credentials import RequestCredentialsHandler\n from floo.sublime_connection import SublimeConnection\n\nreactor = reactor.reactor\n\n\ndef disconnect_dialog():\n if G.AGENT and G.AGENT.joined_workspace:\n disconnect = sublime.ok_cancel_dialog('You can only be in one workspace at a time.', 'Leave %s/%s' % (G.AGENT.owner, G.AGENT.workspace))\n if disconnect:\n msg.debug('Stopping agent.')\n reactor.stop()\n G.AGENT = None\n return disconnect\n return True\n\n\ndef link_account(host, cb):\n account = sublime.ok_cancel_dialog('No credentials found in ~/.floorc.json for %s.\\n\\n'\n 'Click \"Link Account\" to open a web browser and add credentials.' % host,\n 'Link Account')\n if not account:\n return\n token = binascii.b2a_hex(uuid.uuid4().bytes).decode('utf-8')\n agent = RequestCredentialsHandler(token)\n if not agent:\n sublime.error_message('''A configuration error occured earlier. Please go to %s and sign up to use this plugin.\\n\nWe're really sorry. This should never happen.''' % host)\n return\n\n agent.once('end', cb)\n\n try:\n reactor.connect(agent, host, G.DEFAULT_PORT, True)\n except Exception as e:\n print(str_e(e))\n\n\ndef create_or_link_account(force=False):\n disable_account_creation = utils.get_persistent_data().get('disable_account_creation')\n if disable_account_creation and not force:\n print('We could not automatically create or link your floobits account. Please go to floobits.com and sign up to use this plugin.')\n return\n\n opts = [\n ['Use existing Floobits account.', '(opens web page)'],\n ['Create a new Floobits account.', ''],\n ['Cancel', ''],\n ]\n\n def cb(index):\n if index == 0:\n token = binascii.b2a_hex(uuid.uuid4().bytes).decode('utf-8')\n agent = RequestCredentialsHandler(token)\n elif index == 1:\n agent = CreateAccountHandler()\n else:\n d = utils.get_persistent_data()\n if d.get('disable_account_creation'):\n return\n d['disable_account_creation'] = True\n utils.update_persistent_data(d)\n sublime.message_dialog('''You can set up a Floobits account at any time under\\n\\nTools -> Floobits -> Setup''')\n try:\n reactor.connect(agent, G.DEFAULT_HOST, G.DEFAULT_PORT, True)\n except Exception as e:\n print(str_e(e))\n\n def get_workspace_window():\n w = sublime.active_window()\n if w is None:\n return utils.set_timeout(get_workspace_window, 50)\n sublime.message_dialog('Thank you for installing the Floobits plugin!\\n\\nLet\\'s set up your editor to work with Floobits.')\n w.show_quick_panel(opts, cb)\n get_workspace_window()\n\n\nclass FloobitsBaseCommand(sublime_plugin.WindowCommand):\n def is_visible(self):\n return True\n\n def is_enabled(self):\n return bool(G.AGENT and G.AGENT.is_ready())\n\n\nclass FloobitsOpenSettingsCommand(sublime_plugin.WindowCommand):\n def run(self):\n window = sublime.active_window()\n if window:\n window.open_file(G.FLOORC_PATH)\n\n\nclass FloobitsShareDirCommand(FloobitsBaseCommand):\n def is_enabled(self):\n return not super(FloobitsShareDirCommand, self).is_enabled()\n\n def run(self, dir_to_share=None, paths=None, current_file=False, api_args=None):\n self.api_args = api_args\n utils.reload_settings()\n if not utils.can_auth():\n return create_or_link_account()\n if paths:\n if len(paths) != 1:\n return sublime.error_message('Only one folder at a time, please. :(')\n return self.on_input(paths[0])\n if dir_to_share is None:\n folders = self.window.folders()\n if folders:\n dir_to_share = folders[0]\n else:\n dir_to_share = os.path.expanduser(os.path.join('~', 'share_me'))\n self.window.show_input_panel('Directory to share:', dir_to_share, self.on_input, None, None)\n\n @utils.inlined_callbacks\n def on_input(self, dir_to_share):\n file_to_share = None\n dir_to_share = os.path.expanduser(dir_to_share)\n dir_to_share = os.path.realpath(utils.unfuck_path(dir_to_share))\n workspace_name = os.path.basename(dir_to_share)\n workspace_url = None\n\n # TODO: use prejoin_workspace instead\n def find_workspace(workspace_url):\n r = api.get_workspace_by_url(workspace_url)\n if r.code < 400:\n return r\n try:\n result = utils.parse_url(workspace_url)\n d = utils.get_persistent_data()\n del d['workspaces'][result['owner']][result['name']]\n utils.update_persistent_data(d)\n except Exception as e:\n msg.debug(str_e(e))\n\n def join_workspace(workspace_url):\n try:\n w = find_workspace(workspace_url)\n except Exception as e:\n sublime.error_message('Error: %s' % str_e(e))\n return False\n if not w:\n return False\n msg.debug('workspace: %s', json.dumps(w.body))\n # if self.api_args:\n anon_perms = w.body.get('perms', {}).get('AnonymousUser', [])\n new_anon_perms = self.api_args.get('perms').get('AnonymousUser', [])\n # TODO: warn user about making a private workspace public\n if set(anon_perms) != set(new_anon_perms):\n msg.debug(str(anon_perms), str(new_anon_perms))\n w.body['perms']['AnonymousUser'] = new_anon_perms\n response = api.update_workspace(workspace_url, w.body)\n msg.debug(str(response.body))\n utils.add_workspace_to_persistent_json(w.body['owner'], w.body['name'], workspace_url, dir_to_share)\n self.window.run_command('floobits_join_workspace', {'workspace_url': workspace_url})\n return True\n\n if os.path.isfile(dir_to_share):\n file_to_share = dir_to_share\n dir_to_share = os.path.dirname(dir_to_share)\n\n try:\n utils.mkdir(dir_to_share)\n except Exception:\n sublime.error_message('The directory %s doesn\\'t exist and I can\\'t create it.' % dir_to_share)\n return\n\n floo_file = os.path.join(dir_to_share, '.floo')\n\n info = {}\n try:\n floo_info = open(floo_file, 'r').read()\n info = json.loads(floo_info)\n except (IOError, OSError):\n pass\n except Exception:\n msg.error('Couldn\\'t read the floo_info file: %s' % floo_file)\n\n workspace_url = info.get('url')\n try:\n utils.parse_url(workspace_url)\n except Exception:\n workspace_url = None\n\n if workspace_url and join_workspace(workspace_url):\n return\n\n for owner, workspaces in utils.get_persistent_data()['workspaces'].items():\n for name, workspace in workspaces.items():\n if workspace['path'] == dir_to_share:\n workspace_url = workspace['url']\n if join_workspace(workspace_url):\n return\n\n auth = yield editor.select_auth, self.window, G.AUTH\n if not auth:\n return\n\n username = auth.get('username')\n host = auth['host']\n\n def on_done(owner):\n msg.log('Colab dir: %s, Username: %s, Workspace: %s/%s' % (G.COLAB_DIR, username, owner[0], workspace_name))\n self.window.run_command('floobits_create_workspace', {\n 'workspace_name': workspace_name,\n 'dir_to_share': dir_to_share,\n 'upload': file_to_share or dir_to_share,\n 'api_args': self.api_args,\n 'owner': owner[0],\n 'host': host,\n })\n\n try:\n r = api.get_orgs_can_admin(host)\n except IOError as e:\n sublime.error_message('Error getting org list: %s' % str_e(e))\n return\n\n if r.code >= 400 or len(r.body) == 0:\n on_done([username])\n return\n\n orgs = [[org['name'], 'Create workspace owned by %s' % org['name']] for org in r.body]\n orgs.insert(0, [username, 'Create workspace owned by %s' % username])\n self.window.show_quick_panel(orgs, lambda index: index < 0 or on_done(orgs[index]))\n\n\nclass FloobitsCreateWorkspaceCommand(sublime_plugin.WindowCommand):\n def is_visible(self):\n return False\n\n def is_enabled(self):\n return True\n\n # TODO: throw workspace_name in api_args\n def run(self, workspace_name=None, dir_to_share=None, prompt='Workspace name:', api_args=None, owner=None, upload=None, host=None):\n if not disconnect_dialog():\n return\n self.owner = owner\n self.dir_to_share = dir_to_share\n self.workspace_name = workspace_name\n self.api_args = api_args or {}\n self.upload = upload\n self.host = host\n if workspace_name and dir_to_share and prompt == 'Workspace name:':\n return self.on_input(workspace_name, dir_to_share)\n self.window.show_input_panel(prompt, workspace_name, self.on_input, None, None)\n\n def on_input(self, workspace_name, dir_to_share=None):\n if dir_to_share:\n self.dir_to_share = dir_to_share\n if workspace_name == '':\n return self.run(dir_to_share=self.dir_to_share)\n try:\n self.api_args['name'] = workspace_name\n self.api_args['owner'] = self.owner\n msg.debug(str(self.api_args))\n r = api.create_workspace(self.host, self.api_args)\n except Exception as e:\n msg.error('Unable to create workspace: %s' % str_e(e))\n return sublime.error_message('Unable to create workspace: %s' % str_e(e))\n\n workspace_url = 'https://%s/%s/%s' % (self.host, self.owner, workspace_name)\n msg.log('Created workspace %s' % workspace_url)\n\n if r.code < 400:\n utils.add_workspace_to_persistent_json(self.owner, workspace_name, workspace_url, self.dir_to_share)\n return self.window.run_command('floobits_join_workspace', {\n 'workspace_url': workspace_url,\n 'upload': dir_to_share\n })\n\n msg.error('Unable to create workspace: %s' % r.body)\n if r.code not in [400, 402, 409]:\n try:\n r.body = r.body['detail']\n except Exception:\n pass\n return sublime.error_message('Unable to create workspace: %s' % r.body)\n\n kwargs = {\n 'dir_to_share': self.dir_to_share,\n 'workspace_name': workspace_name,\n 'api_args': self.api_args,\n 'owner': self.owner,\n 'upload': self.upload,\n 'host': self.host,\n }\n if r.code == 400:\n kwargs['workspace_name'] = re.sub('[^A-Za-z0-9_\\-\\.]', '-', workspace_name)\n kwargs['prompt'] = 'Invalid name. Workspace names must match the regex [A-Za-z0-9_\\-\\.]. Choose another name:'\n elif r.code == 402:\n try:\n r.body = r.body['detail']\n except Exception:\n pass\n if sublime.ok_cancel_dialog('%s' % r.body, 'Open billing settings'):\n webbrowser.open('https://%s/%s/settings#billing' % (self.host, self.owner))\n return\n else:\n kwargs['prompt'] = 'Workspace %s/%s already exists. Choose another name:' % (self.owner, workspace_name)\n\n return self.window.run_command('floobits_create_workspace', kwargs)\n\n\nclass FloobitsPromptJoinWorkspaceCommand(sublime_plugin.WindowCommand):\n\n def run(self, workspace=None):\n if workspace is None:\n workspace = 'https://%s/' % G.DEFAULT_HOST\n for d in self.window.folders():\n floo_file = os.path.join(d, '.floo')\n try:\n floo_info = open(floo_file, 'r').read()\n wurl = json.loads(floo_info).get('url')\n utils.parse_url(wurl)\n # TODO: check if workspace actually exists\n workspace = wurl\n break\n except Exception:\n pass\n self.window.show_input_panel('Workspace URL:', workspace, self.on_input, None, None)\n\n def on_input(self, workspace_url):\n if disconnect_dialog():\n self.window.run_command('floobits_join_workspace', {\n 'workspace_url': workspace_url,\n })\n\n\nclass FloobitsJoinWorkspaceCommand(sublime_plugin.WindowCommand):\n\n def run(self, workspace_url, agent_conn_kwargs=None, upload=None):\n agent_conn_kwargs = agent_conn_kwargs or {}\n self.upload = upload\n\n def get_workspace_window():\n workspace_window = None\n for w in sublime.windows():\n for f in w.folders():\n if utils.unfuck_path(f) == utils.unfuck_path(G.PROJECT_PATH):\n workspace_window = w\n break\n return workspace_window\n\n def set_workspace_window(cb):\n workspace_window = get_workspace_window()\n if workspace_window is None:\n return utils.set_timeout(set_workspace_window, 50, cb)\n G.WORKSPACE_WINDOW = workspace_window\n cb()\n\n def open_workspace_window(cb):\n if PY2:\n open_workspace_window2(cb)\n else:\n open_workspace_window3(cb)\n\n def open_workspace_window2(cb):\n if sublime.platform() == 'linux':\n subl = open('/proc/self/cmdline').read().split(chr(0))[0]\n elif sublime.platform() == 'osx':\n floorc = utils.load_floorc_json()\n subl = floorc.get('SUBLIME_EXECUTABLE')\n if not subl:\n settings = sublime.load_settings('Floobits.sublime-settings')\n subl = settings.get('sublime_executable', '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl')\n if not os.path.exists(subl):\n return sublime.error_message('''Can't find your Sublime Text executable at %s.\nPlease add \"sublime_executable\": \"/path/to/subl\" to your ~/.floorc.json and restart Sublime Text''' % subl)\n elif sublime.platform() == 'windows':\n subl = sys.executable\n else:\n raise Exception('WHAT PLATFORM ARE WE ON?!?!?')\n\n command = [subl]\n if get_workspace_window() is None:\n command.append('--new-window')\n command.append('--add')\n command.append(G.PROJECT_PATH)\n\n msg.debug('command:', command)\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n poll_result = p.poll()\n msg.debug('poll:', poll_result)\n\n set_workspace_window(cb)\n\n def open_workspace_window3(cb):\n def finish(w):\n G.WORKSPACE_WINDOW = w\n msg.debug('Setting project data. Path: %s' % G.PROJECT_PATH)\n G.WORKSPACE_WINDOW.set_project_data({'folders': [{'path': G.PROJECT_PATH}]})\n cb()\n\n def get_empty_window():\n for w in sublime.windows():\n project_data = w.project_data()\n try:\n folders = project_data.get('folders', [])\n if len(folders) == 0 or not folders[0].get('path'):\n # no project data. co-opt this window\n return w\n except Exception as e:\n print(str_e(e))\n\n def wait_empty_window(i):\n if i > 10:\n print('Too many failures trying to find an empty window. Using active window.')\n return finish(sublime.active_window())\n w = get_empty_window()\n if w:\n return finish(w)\n return utils.set_timeout(wait_empty_window, 50, i + 1)\n\n w = get_workspace_window() or get_empty_window()\n if w:\n return finish(w)\n\n sublime.run_command('new_window')\n wait_empty_window(0)\n\n def make_dir(d):\n d = os.path.realpath(os.path.expanduser(d))\n\n if not os.path.isdir(d):\n make_dir = sublime.ok_cancel_dialog('%s is not a directory. Create it?' % d)\n if not make_dir:\n return self.window.show_input_panel('%s is not a directory. Enter an existing path:' % d, d, None, None, None)\n try:\n utils.mkdir(d)\n except Exception as e:\n return sublime.error_message('Could not create directory %s: %s' % (d, str_e(e)))\n G.PROJECT_PATH = d\n\n if self.upload:\n result['upload'] = d\n else:\n result['upload'] = \"\"\n\n utils.add_workspace_to_persistent_json(result['owner'], result['workspace'], workspace_url, d)\n open_workspace_window(lambda: run_agent(**result))\n\n @utils.inlined_callbacks\n def run_agent(owner, workspace, host, port, secure, upload):\n if G.AGENT:\n msg.debug('Stopping agent.')\n reactor.stop()\n G.AGENT = None\n try:\n auth = G.AUTH.get(host)\n if not auth:\n success = yield link_account, host\n if not success:\n return\n auth = G.AUTH.get(host)\n conn = SublimeConnection(owner, workspace, auth, upload)\n reactor.connect(conn, host, port, secure)\n except Exception as e:\n msg.error(str_e(e))\n\n try:\n result = utils.parse_url(workspace_url)\n except Exception as e:\n return sublime.error_message(str_e(e))\n\n utils.reload_settings()\n if not utils.can_auth():\n return create_or_link_account()\n\n d = utils.get_persistent_data()\n try:\n G.PROJECT_PATH = d['workspaces'][result['owner']][result['workspace']]['path']\n except Exception:\n msg.log('%s/%s not in persistent.json' % (result['owner'], result['workspace']))\n G.PROJECT_PATH = ''\n\n msg.log('Project path is %s' % G.PROJECT_PATH)\n\n if not os.path.isdir(G.PROJECT_PATH):\n default_dir = None\n for w in sublime.windows():\n if default_dir:\n break\n for d in self.window.folders():\n floo_file = os.path.join(d, '.floo')\n try:\n floo_info = open(floo_file, 'r').read()\n wurl = json.loads(floo_info).get('url')\n if wurl == workspace_url:\n # TODO: check if workspace actually exists\n default_dir = d\n break\n except Exception:\n pass\n\n default_dir = default_dir or os.path.realpath(os.path.join(G.COLAB_DIR, result['owner'], result['workspace']))\n\n return self.window.show_input_panel('Save workspace in directory:', default_dir, make_dir, None, None)\n\n open_workspace_window(lambda: run_agent(upload=upload, **result))\n\n\nclass FloobitsPinocchioCommand(sublime_plugin.WindowCommand):\n def is_visible(self):\n return self.is_enabled()\n\n def is_enabled(self):\n return G.AUTO_GENERATED_ACCOUNT\n\n def run(self):\n floorc = utils.load_floorc_json()\n auth = floorc.get('AUTH', {}).get(G.DEFAULT_HOST, {})\n username = auth.get('username')\n secret = auth.get('secret')\n print(username, secret)\n if not (username and secret):\n return sublime.error_message('You don\\'t seem to have a Floobits account of any sort')\n webbrowser.open('https://%s/%s/pinocchio/%s' % (G.DEFAULT_HOST, username, secret))\n\n\nclass FloobitsLeaveWorkspaceCommand(FloobitsBaseCommand):\n\n def run(self):\n if G.AGENT:\n message = 'You have left the workspace.'\n G.AGENT.update_status_msg(message)\n reactor.stop()\n G.AGENT = None\n # TODO: Mention the name of the thing we left\n if not G.EXPERT_MODE:\n sublime.error_message(message)\n else:\n sublime.error_message('You are not joined to any workspace.')\n\n def is_enabled(self):\n return bool(G.AGENT)\n\n\nclass FloobitsClearHighlightsCommand(FloobitsBaseCommand):\n def run(self):\n G.AGENT.clear_highlights(self.window.active_view())\n\n\nclass FloobitsSummonCommand(FloobitsBaseCommand):\n # TODO: ghost this option if user doesn't have permissions\n def run(self):\n G.AGENT.summon(self.window.active_view())\n\n\nclass FloobitsJoinRecentWorkspaceCommand(sublime_plugin.WindowCommand):\n def _get_recent_workspaces(self):\n self.recent_workspaces = utils.get_persistent_data()['recent_workspaces']\n\n try:\n recent_workspaces = [x.get('url') for x in self.recent_workspaces if x.get('url') is not None]\n except Exception:\n pass\n return recent_workspaces\n\n def run(self, *args):\n workspaces = self._get_recent_workspaces()\n self.window.show_quick_panel(workspaces, self.on_done)\n\n def on_done(self, item):\n if item == -1:\n return\n workspace = self.recent_workspaces[item]\n if disconnect_dialog():\n self.window.run_command('floobits_join_workspace', {'workspace_url': workspace['url']})\n\n def is_enabled(self):\n return bool(len(self._get_recent_workspaces()) > 0)\n\n\nclass FloobitsAddToWorkspaceCommand(FloobitsBaseCommand):\n def run(self, paths, current_file=False):\n if not self.is_enabled():\n return\n\n if paths is None and current_file:\n paths = [self.window.active_view().file_name()]\n\n notshared = []\n for path in paths:\n if utils.is_shared(path):\n G.AGENT.upload(path)\n else:\n notshared.append(path)\n\n if notshared:\n limit = 5\n sublime.error_message(\"The following paths are not a child of\\n\\n%s\\n\\nand will not be shared for security reasons:\\n\\n%s%s.\" %\n (G.PROJECT_PATH, \",\\n\".join(notshared[:limit]), len(notshared) > limit and \",\\n...\" or \"\"))\n\n def description(self):\n return 'Add file or directory to currently-joined Floobits workspace.'\n\n\nclass FloobitsRemoveFromWorkspaceCommand(FloobitsBaseCommand):\n def run(self, paths, current_file=False):\n if not self.is_enabled():\n return\n\n unlink = bool(sublime.ok_cancel_dialog('Delete? Hit cancel to remove from the workspace without deleting.', 'Delete'))\n\n if paths is None and current_file:\n paths = [self.window.active_view().file_name()]\n\n for path in paths:\n G.AGENT.delete_buf(path, unlink)\n\n def description(self):\n return 'Add file or directory to currently-joined Floobits workspace.'\n\n\nclass FloobitsCreateHangoutCommand(FloobitsBaseCommand):\n def run(self):\n owner = G.AGENT.owner\n workspace = G.AGENT.workspace\n host = G.AGENT.proto.host\n webbrowser.open('https://plus.google.com/hangouts/_?gid=770015849706&gd=%s/%s/%s' % (host, owner, workspace))\n\n def is_enabled(self):\n return bool(super(FloobitsCreateHangoutCommand, self).is_enabled() and G.AGENT.owner and G.AGENT.workspace)\n\n\nclass FloobitsPromptHangoutCommand(FloobitsBaseCommand):\n def run(self, hangout_url):\n confirm = bool(sublime.ok_cancel_dialog('This workspace is being edited in a Google+ Hangout? Do you want to join the hangout?'))\n if not confirm:\n return\n webbrowser.open(hangout_url)\n\n def is_visible(self):\n return False\n\n def is_enabled(self):\n return bool(super(FloobitsPromptHangoutCommand, self).is_enabled() and G.AGENT.owner and G.AGENT.workspace)\n\n\nclass FloobitsOpenWebEditorCommand(FloobitsBaseCommand):\n def run(self):\n try:\n agent = G.AGENT\n url = utils.to_workspace_url({\n 'port': agent.proto.port,\n 'secure': agent.proto.secure,\n 'owner': agent.owner,\n 'workspace': agent.workspace,\n 'host': agent.proto.host,\n })\n webbrowser.open(url)\n except Exception as e:\n sublime.error_message('Unable to open workspace in web editor: %s' % str_e(e))\n\n\nclass FloobitsHelpCommand(FloobitsBaseCommand):\n def run(self):\n webbrowser.open('https://floobits.com/help/plugins/sublime', new=2, autoraise=True)\n\n def is_visible(self):\n return True\n\n def is_enabled(self):\n return True\n\n\nclass FloobitsToggleFollowModeCommand(FloobitsBaseCommand):\n def run(self):\n if G.FOLLOW_MODE:\n self.window.run_command('floobits_disable_follow_mode')\n else:\n self.window.run_command('floobits_enable_follow_mode')\n\n\nclass FloobitsEnableFollowModeCommand(FloobitsBaseCommand):\n def run(self):\n G.FOLLOW_MODE = True\n msg.log('Follow mode enabled')\n G.AGENT.update_status_msg()\n G.AGENT.highlight()\n\n def is_visible(self):\n if G.AGENT:\n return self.is_enabled()\n return True\n\n def is_enabled(self):\n return bool(super(FloobitsEnableFollowModeCommand, self).is_enabled() and not G.FOLLOW_MODE)\n\n\nclass FloobitsDisableFollowModeCommand(FloobitsBaseCommand):\n def run(self):\n G.FOLLOW_MODE = False\n G.SPLIT_MODE = False\n msg.log('Follow mode disabled')\n G.AGENT.update_status_msg('Stopped following changes. ')\n\n def is_visible(self):\n return self.is_enabled()\n\n def is_enabled(self):\n return bool(super(FloobitsDisableFollowModeCommand, self).is_enabled() and G.FOLLOW_MODE)\n\n\nclass FloobitsOpenWorkspaceSettingsCommand(FloobitsBaseCommand):\n def run(self):\n url = G.AGENT.workspace_url + '/settings'\n webbrowser.open(url, new=2, autoraise=True)\n\n def is_enabled(self):\n return bool(super(FloobitsOpenWorkspaceSettingsCommand, self).is_enabled() and G.PERMS and 'kick' in G.PERMS)\n\n\nclass RequestPermissionCommand(FloobitsBaseCommand):\n def run(self, perms, *args, **kwargs):\n G.AGENT.send({\n 'name': 'request_perms',\n 'perms': perms\n })\n\n def is_enabled(self):\n if not super(RequestPermissionCommand, self).is_enabled():\n return False\n if 'patch' in G.PERMS:\n return False\n return True\n\n\nclass FloobitsFollowSplit(FloobitsBaseCommand):\n def run(self):\n G.SPLIT_MODE = True\n G.FOLLOW_MODE = True\n if self.window.num_groups() == 1:\n self.window.set_layout({\n 'cols': [0.0, 1.0],\n 'rows': [0.0, 0.5, 1.0],\n 'cells': [[0, 0, 1, 1], [0, 1, 1, 2]]\n })\n\n\nclass FloobitsSetup(FloobitsBaseCommand):\n def is_visible(self):\n return True\n\n def is_enabled(self):\n return not utils.can_auth()\n\n def run(self):\n create_or_link_account(True)\n\n\nclass FloobitsNotACommand(sublime_plugin.WindowCommand):\n def run(self, *args, **kwargs):\n pass\n\n def is_visible(self):\n return True\n\n def is_enabled(self):\n return False\n\n def description(self):\n return\n","sub_path":"window_commands.py","file_name":"window_commands.py","file_ext":"py","file_size_in_byte":28807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"501314314","text":"\"\"\"Script to transform and upload IRENA's capacity data to Resource Watch.\n\nIRENA information is available through a Tableau applet.\nThis data must be downloaded manually, it is not possible to acquire\nthrough an HTTP GET as we can tell.\n\nOnce downloaded, only minor transformation is needed to prepare it for upload.\nThe core issue is that the information does not fall into a data cube without\naggregating some rows to fit with expectations around data dimensionality.\n\nIt seems the data should be keyed on the dimensions:\n - country\n - year\n - most granular technology (e.g. \"offshore wind\" not \"wind\")\n - on-grid/off-grid\n\nWhen keyed in this way there are still many compound keys\nthat have multiple rows and need to be summed to produce the\nvalues expressed in Tableau visualization.\n\n\"\"\"\n\nimport os\nimport pandas as pd\nfrom zipfile import ZipFile\nimport shutil\nutils_path = os.path.join(os.path.abspath(os.getenv('PROCESSING_DIR')),'utils')\nif utils_path not in sys.path:\n sys.path.append(utils_path)\nimport util_files\nimport util_cloud\nimport util_carto\nimport logging\n\n# Set up logging\n# Get the top-level logger object\nlogger = logging.getLogger()\nfor handler in logger.handlers: logger.removeHandler(handler)\nlogger.setLevel(logging.INFO)\n# make it print to the console.\nconsole = logging.StreamHandler()\nlogger.addHandler(console)\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# name of table on Carto where you want to upload data\n# this should be a table name that is not currently in use\ndataset_name = 'ene_010_renewable_capacity_annually'\n\nlogger.info('Executing script for dataset: ' + dataset_name)\n# create a new sub-directory within your specified dir called 'data'\n# within this directory, create files to store raw and processed data\ndata_dir = util_files.prep_dirs(dataset_name)\n\n'''\nDownload data and save to your data directory\n'''\n# data can be downloaded by following the steps in the 'Data Acquisition' section of the README file\n# generate path to downloaded data file\ndownload = os.path.join(os.path.expanduser(\"~\"), 'Downloads', 'Export_Full_Data_data.csv')\n\n# Move this file into your data directory\nraw_data_file = os.path.join(data_dir, os.path.basename(download))\nshutil.move(download,raw_data_file)\n\n'''\nProcess data\n'''\n\n# read in csv file as Dataframe\ndf = pd.read_csv(raw_data_file, dtype=str)\n\n# filter pumped storage plants just like IRENA default\ndf = df[df['Sub-technology'] != 'Pumped Storage']\n\n# convert values from string to float because summing later\ndf['Values_asfloat'] = df['Values'].astype(float)\n\n# subset into capacity\ncapacity_data = df[df['DataType'] == 'Installed Capacity']\n\n# assuming MW everywhere, check that; yes the field name has a space at the end\nassert (capacity_data['Unit '] == 'MW').all()\n\n# group by the key dimensions\ngrouped = capacity_data.groupby(['ISO', 'Years', 'Sub-technology', 'Type'])\n# ensure Technology is mapped 1:1 with Sub-technology\nassert grouped.agg({'Technology': lambda x: len(set(x)) == 1}).Technology.all()\n\n# create the data frame, renaming values and organizing the column order\ndata = grouped.agg({\n 'Values_asfloat': 'sum', # sum the numeric capacity value\n 'IRENA Label': 'first', # take a long name for the country\n 'Technology': 'first', # take the technology (superclass) \n }).reset_index().rename(columns={\n 'ISO': 'iso_a3',\n 'Years': 'year',\n 'Sub-technology': 'subtechnology',\n 'Technology': 'technology',\n 'Type': 'grid_connection',\n 'IRENA Label': 'country_name',\n 'Values_asfloat': 'capacity_MW',\n })[[ # set a new column order\n 'iso_a3', # key\n 'country_name', # 1:1 with iso_a3\n 'year', # key\n 'subtechnology', # key\n 'technology', # 1:n with subtechnology\n 'grid_connection', # key\n 'capacity_MW' # the numeric value in megawatts\n ]]\n\n#save processed dataset to csv\nprocessed_data_file = os.path.join(data_dir, dataset_name+'_edit.csv')\ndata.to_csv(processed_data_file, index=False)\n\n'''\nUpload processed data to Carto\n'''\nlogger.info('Uploading processed data to Carto.')\nutil_carto.upload_to_carto(processed_data_file, 'LINK')\n\n'''\nUpload original data and processed data to Amazon S3 storage\n'''\n# initialize AWS variables\naws_bucket = 'wri-public-data'\ns3_prefix = 'resourcewatch/'\n\nlogger.info('Uploading original data to S3.')\n# Upload raw data file to S3\n\n# Copy the raw data into a zipped file to upload to S3\nraw_data_dir = os.path.join(data_dir, dataset_name+'.zip')\nwith ZipFile(raw_data_dir,'w') as zip:\n zip.write(raw_data_file, os.path.basename(raw_data_file))\n# Upload raw data file to S3\nuploaded = util_cloud.aws_upload(raw_data_dir, aws_bucket, s3_prefix+os.path.basename(raw_data_dir))\n\nlogger.info('Uploading processed data to S3.')\n# Copy the processed data into a zipped file to upload to S3\nprocessed_data_dir = os.path.join(data_dir, dataset_name+'_edit.zip')\nwith ZipFile(processed_data_dir,'w') as zip:\n zip.write(processed_data_file, os.path.basename(processed_data_file))\n# Upload processed data file to S3\nuploaded = util_cloud.aws_upload(processed_data_dir, aws_bucket, s3_prefix+os.path.basename(processed_data_dir))","sub_path":"ene_010_renewable_capacity_annually/ene_010_renewable_capacity_annually_processing.py","file_name":"ene_010_renewable_capacity_annually_processing.py","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"425745417","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[197]:\n\n\nimport pandas\nimport numpy as np\n\n# Get age information from demographic information\ndem = pandas.read_csv(\"demographics.txt\",\" \").to_numpy()\nnames_full = [dem[i,0] for i in range(0,dem.shape[0])]\nages_full = [int('18' in dem[i,2]) for i in range(0,dem.shape[0])]\n\n# Create dictionary of names and ages\nfull_D = dict(zip(names_full, ages_full))\nprint(full_D)\n\n\n# In[198]:\n\n\n# Create average typing speed dictionary - not really used\ndata = pandas.read_csv(\"DSL-StrongPasswordData.csv\").to_numpy()\nspeeds = [(data[i,1:].sum()) for i in range(0,data.shape[0])]\nnum_trials = 400\navgs = [np.mean(speeds[400*i:400*(i+1)-1]) for i in range(int(len(speeds)/num_trials))]\nnames = [data[400*i,0] for i in range(int(len(speeds)/num_trials))]\nD = dict(zip(names, avgs))\n\n\n# In[199]:\n\n\n# Show difference exists between younger and older ppl in terms of typing speed\ny = []\no = []\nfor n in names: \n avg = D[n]\n if(full_D[n] == 0): o = o + [avg]\n else: y = y + [avg]\n \nprint(np.mean(y))\nprint(np.mean(o))\n\n\n# In[200]:\n\n\n#Try to create a graph\nfrom scipy.stats.stats import pearsonr\nimport math\nimport matplotlib.pyplot as plt\nimport networkx as nx # importing networkx package\n\ndata = pandas.read_csv(\"DSL-StrongPasswordData.csv\").to_numpy()\n#avgs = np.array(data[0*400:(0+1)*400,1:].mean(axis=0))\n# Use 8th trial as it is the most stable\navgs = np.array(data[8,1:])\nfor i in range(1,int(data.shape[0]/400)): \n #avgdata = data[i*400:(i+1)*400,1:].mean(axis=0)\n avgdata = data[i*400 + 8, 1:]\n avgs = np.vstack((avgs,np.array(avgdata)))\n\n\n# In[201]:\n\n\n# Graph based on pearson scores pairwise between typists\n# typist 42 is removed because they are an extreme outlier\ncorrs = np.zeros((51,51))\nfor i in range(51):\n for j in range(51):\n corrs[i,j] = pearsonr(avgs[i],avgs[j])[0]\nmint = np.min(corrs)\ncorrs = corrs - np.diag([1]*51)\nmaxt = np.max(corrs)\n\ncorrs = (corrs - mint)/(maxt-mint)\nfor i in range(51):\n corrs[i,i] = 0\nprint(corrs)\nprint(np.mean(corrs))\ncorr2 = (corrs>np.mean(corrs))\nderp = False\nfor i in range(51):\n for j in range(51):\n corr2[i,j] = int(corr2[i,j])\n if(corr2[i,j] == 1 ): derp = True\n if(derp == False): print(i)\n derp = False\n#plt.matshow(corr2)\n\n\nA = corr2\nA2 = np.array(A)\nA2 = np.delete(A2, 42,0)\nA2 = np.delete(A2,42,1)\n\nG = nx.from_numpy_matrix(A2)\nnx.draw(G)\n\n\n# In[204]:\n\n\n# Graph based on euclidean distance between feature vectors of pairwise users\ncorrs = np.zeros((51,51))\nfor i in range(51):\n for j in range(51):\n corrs[i,j] = np.sum((np.array(avgs[i]) - np.array(avgs[j]))**2)\n\nmint = np.min(corrs)\ncorrs = corrs - np.diag([1]*51)\nmaxt = np.max(corrs)\n\ncorrs = (corrs - mint)/(maxt-mint)\nfor i in range(51):\n corrs[i,i] = 0\n\ncorr2 = (corrs>np.mean(corrs))\n\n\nG = nx.from_numpy_matrix(corr2)\nnx.draw(G)\n\n\n# In[205]:\n\n\n# graph based on differences between average typing speed\ncorrs = np.zeros((51,51))\nfor i in range(51):\n for j in range(51):\n corrs[i,j] = np.abs(np.sum(np.array(avgs[i]))/len(avgs[i]) - np.sum(np.array(avgs[j]))/len(avgs[i]))\n\nmint = np.min(corrs)\ncorrs = corrs - np.diag([1]*51)\nmaxt = np.max(corrs)\n\ncorrs = (corrs - mint)/(maxt-mint)\nfor i in range(51):\n corrs[i,i] = 0\n\ncorr2 = (corrs>np.mean(corrs))\nA = corr2\n\nG = nx.from_numpy_matrix(A)\nnx.draw(G)\n\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"439413915","text":"#tkinter : GUI관련 제공해주는 표준 윈도우 라이브러리\n# 윈도우 창 생성시 사용\nfrom tkinter import *\n\n#Tk() : 윈도우 반환\nwindow = Tk();\n\n #window 창 구현부\nwindow.title(\"Window.title\"); #윈도우 창 제목\nwindow.geometry(\"500x600\"); #윈도우 창 크기 지정\nwindow.resizable(width=False, height=False) #윈도우 창 크기 고정\n #The end of Window\n\n #Lable 구현부\nlable1 = Label(window, text=\" 1\");\nlable2 = Label(window, text=\" 2\", font=(\"D2Coding\",30)); #bg : background, 배경색\nlable3 = Label(window, text=\" 3\", font=(\"D2Coding\",30), bg='blue'); #fg : foreground 약자, 글자색\nlable4 = Label(window, text=\" 4\", font=(\"D2Coding\",30), bg='red', fg='black'); #anchor : 위젯의 위치,\nlable5 = Label(window, text=\" 5\", font=(\"D2Coding\",30), bg='green', fg='black', width=20); #SE : South East,\nlable6 = Label(window, text=\" 6\", font=(\"D2Coding\",30), bg='yellow', fg='black', width=20, height=5);\nlable7 = Label(window, text=\" 7\", font=(\"D2Coding\",30), bg='magenta', fg='black', width=20, height=5, anchor=SE);\n\n #이미지 삽입 구현부 349Page\nphoto = PhotoImage(file=\"C:/Users/kccistc/Desktop/김민서/images/GIF/froyo.gif\");\nlable8 = Label(window, image=photo);\n\nlable1.pack();\nlable2.pack();\nlable3.pack();\nlable4.pack();\nlable5.pack();\nlable6.pack();\nlable7.pack();\nlable8.pack();\n #The end of Lable\n\n#윈도우창에 이벤트 처리\nwindow.mainloop();","sub_path":"[6] 빅데이터 분석 플랫폼 시스템 개발/pythonProject Ver10.27/SOURCE CODE/CHAPTER 12.py","file_name":"CHAPTER 12.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"179874681","text":"\"\"\" Convert Numpy or image files to tfrecords\n\nauthor: sagunkayastha\n\n\"\"\"\n\n\nimport numpy as np\nimport tensorflow as tf \nimport os\nimport matplotlib.pyplot as plt\nimport time\nfrom tqdm import tqdm\n# FILEPATH = 'tf_data.tfrecords'\n\n\nclass TF_NPY:\n \"\"\" Convert Numpy or image files to tfrecords\n filename = filename for tfrecords file, default = demo\n \"\"\"\n\n def __init__(self, filename= 'demo.tfrecords'):\n self.FILENAME = filename\n \n def _int64_feature(self,value):\n \"\"\" Helper function\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n def _bytes_feature(self,value):\n \"\"\" Helper function\"\"\"\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n def numpy_to_tflearn(self, images, labels):\n\n \"\"\" Convert Numpy files to tfrecords\"\"\"\n\n with tf.python_io.TFRecordWriter(self.FILENAME) as writer:\n i=0\n for image, label in zip(images, labels):\n if i*10%len(images)==0:\n perc = np.ceil((i+1)/len(images)*100 -1)\n print(f'{int(perc)} %')\n feature = {'image': self._bytes_feature(tf.compat.as_bytes(image.tostring())),\n 'label': self._int64_feature(int(label))}\n\n example = tf.train.Example(features=tf.train.Features(feature=feature))\n writer.write(example.SerializeToString())\n i+=1\n\n def folder_to_tfrecords(self,folder_path,label):\n\n \"\"\" Convert images files in folder tfrecords\"\"\"\n\n TRAIN_PATH = folder_path\n train_ids = next(os.walk(TRAIN_PATH))[2]\n\n with tf.python_io.TFRecordWriter(self.FILENAME) as writer:\n for i, (image, label) in enumerate(zip(train_ids, labels)):\n \n if i*10%len(train_ids)==0:\n perc = np.ceil((i+1)/len(train_ids)*100-1 )\n print(f'{int(perc)} %')\n image = plt.imread(TRAIN_PATH+image)\n feature = {'image': self._bytes_feature(tf.compat.as_bytes(image.tostring())),\n 'label': self._int64_feature(int(label))}\n\n example = tf.train.Example(features=tf.train.Features(feature=feature))\n writer.write(example.SerializeToString())\n \nobj = TF_NPY() # Filename\nobj.FILENAME = \"test.tfrecords\"\n\n\nimage = np.load('train_img.npy')\nlabel = np.load('train_mask.npy')\n \n# Numpy to tfrecords\nobj.numpy_to_tflearn(image,label)\n\n# Folder to tfrecords\nlabels = np.repeat(label,2) # only for this example\nobj.folder_to_tfrecords('images/',labels)\n","sub_path":"tf_convert.py","file_name":"tf_convert.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"579202707","text":"import stamp_network\nimport os\nfrom sacred.observers import FileStorageObserver\nfrom sacred import Experiment\n\ncur_file_name = os.path.basename(__file__)[:-3]\n\nsteps_per_epoch = 128\nimg_rows = 84\nstamp_size = 28\n\nconfig_file = {\n \"run_parameters\" : {\n \"epochs\": 1000,\n \"steps_per_epoch\": 128,\n \"validation_steps\": 100,\n \"shuffle\": False,\n # These parameters depend on the image type.\n \"img_type\": \"t_mnist\",\n \"img_type_parameters\": {\n \"nr_img_per_canvas\": 2,\n \"overlap\": True\n }\n },\n\n \"layer_parameters\" : {\n \"input_parameters\": {\n \"batch_size\": 64,\n \"img_rows\": img_rows,\n \"img_cols\": img_rows,\n \"img_channels\": 1,\n },\n \"encoder_parameters\": {\n \"encoder_dropout_rate\": 0.2,\n \"conv_layer_sizes\": [16, 32, 64, 128, 128],\n \"conv_kernel_size\": (3, 3),\n \"final_conv_size\": 256,\n \"final_conv_kernel\": (3, 3)\n },\n \"decoder_parameters\": {\n \"decoder_enc_size\": 128,\n \"stamp_size\": stamp_size,\n \"nr_of_stamps\": 40,\n \"stamps_per_canvas\": 2,\n \"gumbel_parameters\": {\n \"tau_init\": 7,\n \"anneal_rate\": 0.005,\n \"min_temperature\": 0.2,\n \"steps_per_epoch\": steps_per_epoch\n },\n \"coord_tensor_size\": img_rows - stamp_size + 1\n },\n \"loss\": \"mse\"\n }\n}\n\nstamp_network.ex.add_config(config_file)\nstamp_network.ex.observers[0] = FileStorageObserver.create(\n basedir=os.path.join('runs', cur_file_name))\nstamp_network.ex.run(options={'--name': cur_file_name})","sub_path":"t_mnist_2.py","file_name":"t_mnist_2.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"17426338","text":"#!/usr/bin/env python3\r\n\"\"\"\r\nVery simple HTTP server in python for logging requests\r\nUsage::\r\n ./server.py [<port>]\r\n\"\"\"\r\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\r\nfrom requests import Request, Session\r\nfrom datetime import datetime\r\nfrom os import listdir, remove\r\nimport pandas as pd\r\nimport numpy as np\r\nimport jsonpickle\r\nimport requests\r\nimport logging\r\nimport json\r\nimport cgi\r\nimport os\r\nimport io\r\n\r\nimport process_request\r\nimport pipeline\r\n\r\narray_data = []\r\n \r\n\r\nclass S(BaseHTTPRequestHandler):\r\n def _set_response(self):\r\n self.send_response(200) \r\n self.send_header('Content-type', 'text/html')\r\n self.send_header('Access-Control-Allow-Origin', '*') \r\n self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')\r\n self.send_header(\"Access-Control-Allow-Headers\", \"X-Requested-With\")\r\n self.end_headers()\r\n\r\n def do_GET(self):\r\n #logging.info(\"GET request,\\nPath: %s\\nHeaders:\\n%s\\n\", str(self.path), str(self.headers))\r\n content_length = int(self.headers['Content-Length']) # <--- Gets the size of data\r\n post_data = self.rfile.read(content_length) # <--- Gets the data itself \r\n\r\n self._set_response()\r\n self.wfile.write(\"GET request for {}\".format(self.path).encode('utf-8'))\r\n\r\n def crear_objeto_json(self, datos_entrada):\r\n objetos = []\r\n bloque = ''\r\n cantidad = 0\r\n while cantidad < len(datos_entrada):\r\n if not datos_entrada[cantidad] == '}':\r\n bloque += datos_entrada[cantidad]\r\n else:\r\n bloque += '}'\r\n objetos.append(bloque)\r\n bloque = ''\r\n cantidad += 1\r\n\r\n cantidad += 1\r\n \r\n return np.asarray(objetos)\r\n\r\n\r\n def do_POST(self):\r\n content_length = int(self.headers['Content-Length']) # <--- Gets the size of data\r\n post_data = self.rfile.read(content_length) # <--- Gets the data itself \r\n #Una vez finalizado debemos enviar estos datos a una funcion para crear el JSON y crear la pipeline\r\n #En este punto el servidor debe pocesar los datos en formato JSON que recibe\r\n \r\n string_datos = post_data.decode(\"utf-8\")\r\n\r\n print(string_datos)\r\n\r\n objeto_json = self.crear_objeto_json(string_datos)\r\n print(objeto_json)\r\n pipe1 = pipeline.pipeline(objeto_json)\r\n json_final = pipe1.execute()\r\n\r\n #proces1 = process_request.process_request(string_datos)\r\n #resultado = proces1.process_block()\r\n \r\n #data = resultado.encode('utf-8')\r\n \r\n print('********************')\r\n self.stream_data(json_final) #Enviamos los resultados al front-end\r\n self._set_response()\r\n self.wfile.write(\"POST request for {}\".format(self.path).encode('utf-8'))\r\n \r\n\r\n def do_OPTIONS(self): \r\n #En cada opcion se debe elegir las funciones a realizar, hacer el servidor es complicado\r\n #El servidor debe gestionar las peticiones que le llegan, y lo que le llega es conjunto de datos\r\n #que son los ficheros en EEG y los ficheros evento y un JSON con la pipeline que se debe ejecutar\r\n \r\n self._set_response()\r\n self.wfile.write(\"OPTIONS request for {}\".format(self.path).encode('utf-8')) \r\n '''self.send_header('Access-Control-Allow-Origin', '*') \r\n self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')\r\n self.send_header(\"Access-Control-Allow-Headers\", \"X-Requested-With\") '''\r\n\r\n\r\n def stream_data(self, stream):\r\n #Consumes a stream in chunks to produce the response's output\r\n print('[+]- Streaming started...') \r\n jsonData = stream\r\n #jsonData = (stream.to_json(orient='split')) \r\n data = jsonData.encode('utf-8')\r\n\r\n self.send_response(200)\r\n \r\n\r\n\t\t#Luego, enviamos las cabezeras, yo enviare solo el tipo del contenido\r\n\t\t#Usamos el metodo send_header, pasandole como argumento la informacion deseada\r\n \r\n self.send_header('Content-type', 'application/json; charset=utf-8')\r\n self.send_header('Access-Control-Allow-Origin', '*') \r\n self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')\r\n self.send_header(\"Access-Control-Allow-Headers\", \"X-Requested-With, Content-Type, Accept\")\r\n self.send_header(\"Content-Length\", str(len(data)))\r\n \r\n\t\t#Con el metodo end_headers, terminamos de colocar las cabezeras del servidor\r\n self.end_headers()\r\n self.wfile.write(data)\r\n #Creamos una variable que contendra nuestro mensaje.\r\n #Fijense que estoy usando etiquetas HTML, ya que lo defini el los headers\r\n \r\n\r\n #Ahora, escribimos la respuesta en el cuerpo de la pagina\r\n \r\n \r\n\r\n print('[+]- Streaming end...')\r\n \r\n\r\ndef run(server_class=HTTPServer, handler_class=S, port=8080):\r\n #logging.basicConfig(level=logging.INFO)\r\n server_address = ('', port)\r\n httpd = server_class(server_address, handler_class)\r\n print('[+]- Start httpd ... \\n')\r\n #logging.info('Starting httpd...\\n')\r\n try:\r\n httpd.serve_forever()\r\n except KeyboardInterrupt:\r\n print('Error en el servidor !!!')\r\n\r\n httpd.server_close()\r\n print('[+]- Stopping httpd... \\n')\r\n #logging.info('Stopping httpd...\\n')\r\n\r\nif __name__ == '__main__':\r\n from sys import argv\r\n\r\n if len(argv) == 2:\r\n try:\r\n run(port=int(argv[1]))\r\n except:\r\n print('Error en el servidor !!!')\r\n\r\n else:\r\n run()","sub_path":"python_code/cgiserver.py","file_name":"cgiserver.py","file_ext":"py","file_size_in_byte":5714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"511062596","text":"import os\n\nclass mergeData:\n def __init__(self):\n self.train_dir_path = \"./data/mscoco/splited/train\"\n self.dev_dir_path = \"./data/mscoco/splited/dev\"\n self.test_dir_path = \"./data/mscoco/splited/test\"\n\n self.train_caps = \"./data/mscoco/ori_train_caps.txt\"\n self.train_lines = sum(1 for line in open(self.train_caps))\n print(\"self.train_lines: {}\".format(self.train_lines))\n\n def merge_train_by_lang(self, lang):\n outpath = '{}/ori_train_caps.txt'.format(self.train_dir_path)\n if os.path.exists(outpath):\n print(\"======flag1=====\")\n os.remove(outpath)\n if lang == \"fr\":\n splited_files = list(filter(lambda x: x[-6:-4] == lang,os.listdir(self.train_dir_path)))\n print(splited_files)\n splited_files = sorted(splited_files, key = lambda x: int(x.split('_')[-2]))\n for filename in splited_files:\n print(filename, end = \" \")\n\n\n\n\n\nif __name__ == \"__main__\":\n mergeData().merge_train_by_lang(\"fr\")","sub_path":"srcMutiLang/additional/mergeData.py","file_name":"mergeData.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"313453481","text":"#!/usr/bin/env python\n\nimport os\nfrom os import path\nfrom subprocess import check_call\n\nimport arg_parser\nimport context\n\n\ndef main():\n args = arg_parser.receiver_first()\n\n cc_repo = path.join(context.third_party_dir, 'copt')\n recv_src = path.join(cc_repo, 'server.py')\n send_src = path.join(cc_repo, 'client.py')\n\n if args.option == 'deps':\n print ('deps for copt')\n return\n\n if args.option == 'setup':\n check_call(['make'])\n check_call(['sudo','insmod','tcp_pcc.ko'])\n return\n\n if args.option == 'receiver':\n cmd = [recv_src, args.port]\n check_call(cmd)\n return\n\n if args.option == 'sender':\n cmd = [send_src, args.port]\n check_call(cmd)\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/wrappers/copt.py","file_name":"copt.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"185955471","text":"import urllib.parse\nfrom asyncio import get_event_loop\nfrom random import choice, randint\nfrom re import search\nfrom typing import Any, Tuple, Union\n\nfrom aiohttp import ClientSession\n\nfrom .classes import Colour, Icon, Image\nfrom .errors import BadRequest, HTTPException, InternalServerError, NotFound\n\n\ndef _replace_characters(text: str) -> str:\n return urllib.parse.quote(text)\n\n\nversion = \"1.6.2\"\n\n_hex_regex = r'^(?:[0-9a-fA-F]{3}){1,2}$'\n_hex_regex_failed = \"Invalid HEX value. You're only allowed to enter HEX (0-9 & A-F)\"\n\n\nclass Client:\n\n def __init__(self, session: ClientSession = None) -> None:\n self.session = ClientSession(loop = get_event_loop()) or session\n self._api_url = \"https://api.alexflipnote.dev\"\n\n async def _check_url(self, url: str):\n url = str(url)\n headers = {\"User-Agent\": f\"AlexFlipnote.py by Soheab_#6240 | Version: {version}\"}\n response = await self.session.get(url = url, headers = headers)\n if response.status == 200:\n return url\n elif response.status == 400:\n raise BadRequest((await response.json()).get(\"description\"))\n elif response.status == 404:\n raise NotFound((await response.json()).get(\"description\"))\n elif response.status == 500:\n raise InternalServerError((await response.json()).get(\"description\"))\n else:\n raise HTTPException(response, (await response.json()).get(\"description\"))\n\n # can anyone improve this? PRs are more than welcome.\n\n # remove next version.\n async def steam(self, profile: str) -> str:\n return \"This endpoint is removed from the API, sorry.\"\n\n # Json/URL\n\n async def support_server(self, creator: bool = False) -> Tuple[Any, str]:\n api = await self.session.get(self._api_url)\n support_server = (await api.json()).get(\"support_server\")\n if creator:\n return support_server, \"https://discord.gg/yCzcfju\"\n\n return support_server\n\n async def birb(self) -> str:\n response = await self.session.get(f\"{self._api_url}/birb\")\n\n return (await response.json()).get('file')\n\n async def cats(self) -> str:\n response = await self.session.get(f\"{self._api_url}/cats\")\n return (await response.json()).get('file')\n\n async def sadcat(self) -> str:\n response = await self.session.get(f\"{self._api_url}/sadcat\")\n return (await response.json()).get('file')\n\n async def fml(self) -> str:\n response = await self.session.get(f\"{self._api_url}/fml\")\n return (await response.json()).get('text')\n\n async def dogs(self) -> str:\n response = await self.session.get(f\"{self._api_url}/dogs\")\n return (await response.json()).get('file')\n\n # Colour\n\n async def colour(self, colour=None) -> Colour:\n if colour is None:\n colour = \"%06x\" % randint(0, 0xFFFFFF)\n\n if not search(_hex_regex, colour):\n raise BadRequest(_hex_regex_failed)\n\n response = await self.session.get(f\"{self._api_url}/colour/{colour}\")\n color = await response.json()\n\n return Colour(color)\n\n # Dict\n\n async def github_colours(self) -> dict:\n response = await self.session.get(f\"{self._api_url}/color/github\")\n colors = await response.json()\n\n return dict(colors)\n\n # Image\n\n async def achievement(self, text: str, icon: Union[int, str, Icon] = None) -> Image:\n text = _replace_characters(str(text))\n actual_icon = \"\"\n if icon is not None:\n if isinstance(icon, int):\n try:\n actual_icon = Icon(int(icon)).value\n except ValueError:\n icon = None\n elif isinstance(icon, str):\n try:\n actual_icon = Icon[str(icon)].value\n except KeyError:\n icon = None\n elif isinstance(icon, Icon):\n actual_icon = icon.value\n else:\n actual_icon = \"\"\n\n if icon is not None and actual_icon != \"\":\n actual_icon = f\"&icon={actual_icon}\"\n\n url = f\"{self._api_url}/achievement?text={text}{actual_icon}\"\n\n return Image(url, self.session)\n\n async def amiajoke(self, image: str) -> Image:\n url = await self._check_url(\n f\"{self._api_url}/amiajoke?image={image}\"\n )\n\n return Image(url, self.session)\n\n async def bad(self, image: str) -> Image:\n url = await self._check_url(\n f\"{self._api_url}/bad?image={image}\"\n )\n\n return Image(url, self.session)\n\n async def calling(self, text: str) -> Image:\n text = _replace_characters(text)\n url = f\"{self._api_url}/calling?text={text}\"\n\n return Image(url, self.session)\n\n async def captcha(self, text: str) -> Image:\n text = _replace_characters(text)\n url = f\"{self._api_url}/captcha?text={text}\"\n\n return Image(url, self.session)\n\n async def challenge(self, text: str, icon: Union[int, str, Icon] = None) -> Image:\n text = _replace_characters(text)\n actual_icon = \"\"\n if icon is not None:\n if isinstance(icon, int):\n try:\n actual_icon = Icon(int(icon)).value\n except ValueError:\n icon = None\n elif isinstance(icon, str):\n try:\n actual_icon = Icon[str(icon)].value\n except KeyError:\n icon = None\n elif isinstance(icon, Icon):\n actual_icon = icon.value\n else:\n actual_icon = \"\"\n\n if icon is not None and actual_icon != \"\":\n actual_icon = f\"&icon={actual_icon}\"\n\n url = f\"{self._api_url}/challenge?text={text}{actual_icon}\"\n\n return Image(url, self.session)\n\n async def colour_image(self, colour=None) -> Image:\n if colour is None:\n colour = \"%06x\" % randint(0, 0xFFFFFF)\n\n if not search(_hex_regex, colour):\n raise BadRequest(_hex_regex_failed)\n\n url = f\"{self._api_url}/colour/image/{colour}\"\n\n return Image(url, self.session)\n\n async def colour_image_gradient(self, colour=None) -> Image:\n if colour is None:\n colour = \"%06x\" % randint(0, 0xFFFFFF)\n\n if not search(_hex_regex, colour):\n raise BadRequest(_hex_regex_failed)\n\n url = f\"{self._api_url}/colour/image/gradient/{colour}\"\n\n return Image(url, self.session)\n\n async def colourify(self, image: str, colour=None, background=None) -> Image:\n url = f\"{self._api_url}/colourify?image={image}\"\n if colour is not None:\n if not search(r'^(?:[0-9a-fA-F]{3}){1,2}$', colour):\n raise BadRequest(\"Invalid HEX value for colour. You're only allowed to enter HEX (0-9 & A-F)\")\n\n url += f\"&c={colour}\"\n\n if background is not None:\n if not search(_hex_regex, background):\n raise BadRequest(\"Invalid HEX value for background. You're only allowed to enter HEX (0-9 & A-F)\")\n\n url += f\"&b={background}\"\n\n return Image(url, self.session)\n\n async def didyoumean(self, top: str, bottom: str) -> Image:\n top = _replace_characters(top)\n bottom = _replace_characters(bottom)\n url = f\"{self._api_url}/didyoumean?top={top}&bottom={bottom}\"\n\n return Image(url, self.session)\n\n async def drake(self, top: str, bottom: str) -> Image:\n top = _replace_characters(top)\n bottom = _replace_characters(bottom)\n url = f\"{self._api_url}/drake?top={top}&bottom={bottom}\"\n\n return Image(url, self.session)\n\n async def facts(self, text: str) -> Image:\n text = _replace_characters(text)\n url = f\"{self._api_url}/facts?text={text}\"\n\n return Image(url, self.session)\n\n async def filter(self, name: str, image: str) -> Image:\n options = ['blur', 'invert', 'b&w', 'deepfry', 'sepia', 'pixelate',\n 'magik', 'jpegify', 'wide', 'snow', 'gay', 'communist',\n 'random']\n\n if name.lower() not in options:\n raise NotFound(\"Filter not found. Valid options: \" + \", \".join(options))\n if name.lower() == \"random\":\n name = choice(options)\n\n url = await self._check_url(f\"{self._api_url}/filter/{name.lower()}?image={image}\")\n return Image(url, self.session)\n\n async def floor(self, text: str, image: str = None) -> Image:\n text = _replace_characters(text)\n url = f\"{self._api_url}/floor?text={text}\"\n if image is not None:\n url += f\"&image={image}\"\n\n return Image(url, self.session)\n\n async def jokeoverhead(self, image: str) -> Image:\n url = await self._check_url(\n f\"{self._api_url}/jokeoverhead?image={image}\"\n )\n\n return Image(url, self.session)\n\n async def pornhub(self, text: str, text2: str) -> Image:\n text = _replace_characters(text)\n text2 = _replace_characters(text2)\n url = f\"{self._api_url}/pornhub?text={text}&text2={text2}\"\n\n return Image(url, self.session)\n\n async def salty(self, image: str) -> Image:\n url = await self._check_url(\n f\"{self._api_url}/salty?image={image}\"\n )\n\n return Image(url, self.session)\n\n async def scroll(self, text: str) -> Image:\n text = _replace_characters(text)\n url = f\"{self._api_url}/scroll?text={text}\"\n\n return Image(url, self.session)\n\n async def ship(self, user: str, user2: str) -> Image:\n url = await self._check_url(\n f\"{self._api_url}/ship?user={user}&user2={user2}\"\n )\n\n return Image(url, self.session)\n\n async def supreme(self, text: str, dark: bool = False, light: bool = False) -> Image:\n text = _replace_characters(text)\n darkorlight = \"\"\n if dark:\n darkorlight = \"&dark=true\"\n if light:\n darkorlight = \"&light=true\"\n if dark and light:\n raise BadRequest(\"You can only choose either light or dark, not both.\")\n\n url = f\"{self._api_url}/supreme?text={text}{darkorlight}\"\n\n return Image(url, self.session)\n\n async def trash(self, face: str, trash: str) -> Image:\n url = await self._check_url(\n f\"{self._api_url}/trash?face={face}&trash={trash}\"\n )\n\n return Image(url, self.session)\n\n # aliases\n\n color = colour\n github_colors = github_colours\n color_image = colour_image\n\n async def close(self) -> None:\n if not self.session.closed:\n await self.session.close()\n","sub_path":"alexflipnote/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":10697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"595622319","text":"# coding= utf-8\nimport numpy as np\nimport matplotlib as mpl\n\nlatex_output = False\n\nif latex_output:\n mpl.use('PDF')\n mpl.rc('font',**{'family':'serif','serif':['Computer Modern Roman']})\n mpl.rc('text', usetex=True)\n\nmpl.rcParams.update({'font.size': 15})\n \nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatch\nimport matplotlib.lines as mlines\n\ndef sort_for_violin_plot(data_set, key='coercions', value=\"time\"):\n data = {c : [] for c in data_set[key]}\n for datum in data_set:\n data[datum[key]].append(datum[value])\n data = data.items()\n data.sort(key=(lambda x: x[0]))\n return tuple([list(t) for t in zip(*data)])\n\ndef set_violin_color_label(vplot, color, label):\n for p in vplot['bodies']:\n p.set_color(color)\n return mpatch.Patch(color=color, label=label)\n\n# Function cast analysis\nplt.figure(1)\nloop_data = np.genfromtxt('loop-fn-app.txt',\n dtype=(int, float, float),\n names=\"apps, t_time, c_time\",\n usecols=(\"apps, t_time, c_time\"))\n\ndef violin_plot_data(data, x_key, y_key, color, name\n , violin_widths=.35\n , violin_showextrema=False\n , violin_showmedians=False\n , violin_showmeans=False\n , reg_poly=0\n , reg_color=\"red\"\n , reg_linstyle=\"-\"):\n x_vals, y_vals = sort_for_violin_plot(data , key=x_key , value=y_key)\n vplt = plt.violinplot(tdata_times\n , positions=x_vals\n , widths=violin_widths\n , showextrema=violin_showextrema\n , showmedians=violin_showmedians\n , showmeans=violin_showmeans)\n vplt_fake = set_violin_color_label(vplt, color, name)\n if 0 == reg_poly:\n return vplt_fake\n else:\n reg = np.polyfit(data[x_key], data[y_key], reg_poly)\n rplt = plt.plot(data[x_key]\n , np.polyval(reg, loop_data[x_key])\n , linestyle=reg_linestyle\n , color=reg_color)\n if reg[-1] < 0 :\n eq = \"%.2f$A$ - %.2f\\t\" % (reg[0], (-1.0 * reg[1]))\n else:\n eq = \"%.2f$A$ + %.2f\\t\" % (reg[0], reg[1])\n reg_fake = mlines.Line2D([],[],color=reg_color, label=reg_label)\n if reg_text:\n reg_eq_txt = plt.text(reg_label, 8 , cdata_lplt_eq, color=cdata_lplt_fake.get_color())\n return vplt_fake, reg_fake\n\n# Twosomes cast introduction analysis\ntdata_pos, tdata_times = sort_for_violin_plot(loop_data\n , key='apps'\n , value='t_time')\ntdata_vplt = plt.violinplot(tdata_times\n , positions=tdata_pos\n , widths=.35\n , showextrema=False\n , showmedians=False\n , showmeans=False)\ntdata_vplt_fake = set_violin_color_label(tdata_vplt, \"blue\", \"Type-Based Casts\")\n\n# tdata_lreg = np.polyfit(twosomes_cast_data[\"apps\"]\n# ,twosomes_cast_data[\"t_time\"]\n# ,1)\n\n# Coercions cast introduction analysis\ncdata_pos, cdata_times = sort_for_violin_plot(loop_data\n , key='apps'\n , value='t_time')\ncdata_vplt = plt.violinplot(cdata_times\n , positions=cdata_pos\n , widths=.35\n , showextrema=False\n , showmedians=False\n , showmeans=False)\ncdata_vplt_fake = set_violin_color_label(cdata_vplt, \"green\", \"Coercions\")\n\n\ncdata_lreg = np.polyfit(loop_data[\"apps\"], loop_data[\"c_time\"], 1)\ncdata_lplt = plt.plot(loop_data[\"apps\"]\n , np.polyval(cdata_lreg, loop_data[\"apps\"])\n , linestyle=\"-\"\n , color=\"red\")\n\nif cdata_lreg[1] < 0 :\n cdata_lplt_eq = \"%.2f$A$ - %.2f\" % \\\n (cdata_lreg[0], (-1.0 * cdata_lreg[1]))\nelse:\n cdata_lplt_eq = \"%.2f$A$ + %.2f\" % (cdata_lreg[0], cdata_lreg[1])\ncdata_lplt_fake = mlines.Line2D([],[],color=\"red\", label='Linear model of Coercions')\ncdata_lplt_txt = plt.text(5, 8 , cdata_lplt_eq, color=cdata_lplt_fake.get_color())\n\nplt.axis([0, 16, 0, 50])\nplt.xlabel('Number of Applications of Function w/o Proxy (A)')\nplt.ylabel('Time in $ns$ per iteration')\n#plt.title('Timing Results for Function Casts Resulting in Higher-Order Casts')\n\nlegend = plt.legend(handles=[ tdata_vplt_fake\n ,cdata_vplt_fake\n #,cdata_lplt_fake\n]\n , loc=\"upper left\"\n , shadow=True)\n\nif latex_output:\n plt.savefig('loop-fn-app', bbox_inches='tight')\nelse:\n plt.savefig('loop-fn-app.png', bbox_inches='tight')\n plt.show() \n\n\n","sub_path":"benchmark/suite/icfp/timing-loop.py","file_name":"timing-loop.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"354860388","text":"# -*- coding: utf-8 -*-\np=int(input('Digite p:' ))\nq=int(input('Digite q:' ))\ncont=0\ncont2=0\natual=q\nwhile atual>0:\n atual=atual//10\n cont=cont+1\nwhile q>0:\n valor=q%(10**cont)\n if valor==p:\n cont2=cont2+1 \n valor=q//10\nif cont2!=0:\n print('S')\nelse:\n print('N')","sub_path":"moodledata/vpl_data/81/usersdata/224/46993/submittedfiles/dec2bin.py","file_name":"dec2bin.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"572275199","text":"import re\nimport sqlite3\n\nconn = sqlite3.connect('../../db.sqlite')\nc = conn.cursor()\n\nc.execute('SELECT id, json FROM fractals')\nfor i, json in c.fetchall():\n new_json = re.sub(\n r'\\[0\\.0,0\\.0,0\\.0\\]',\n r'null',\n json\n )\n c.execute(\"UPDATE fractals SET json = ? WHERE id = ?\", (new_json, i))\n print(i)\n\nconn.commit()\nconn.close()\n","sub_path":"migrations/2018-03-21-142455_color_is_option/repair_json.py","file_name":"repair_json.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"438161634","text":"import textract\nimport random\n\nfrom docx import Document;\n\ntext = textract.process('To The Light House.epub')\ndocumentName = \"To The Light House.docx\"\n\ntext = text.split(\"\\n\")\n\ncounter = 1\nchapters = []\nchapter = \"\"\ngotToChapter1 = False\n\nfor line in text:\n chapterCounter = \"Chapter \" + str(counter)\n if line == chapterCounter: \n gotToChapter1 = True\n counter += 1\n if gotToChapter1:\n chapters.append(chapter)\n chapter = \"\"\n if len(line) > 0:\n chapter += line\n\ncounter = 1\ndocument = Document()\n\nfailCounter = 0;\ndef randomNote(lines):\n\n global failCounter\n\n if failCounter > 5:\n failCounter = 0\n return None;\n \n randomNoteLine = random.choice(lines)\n\n if len(randomNoteLine.split(\" \")) <= 5:\n failCounter += 1\n return randomNote(lines)\n else:\n failCounter = 0\n return randomNoteLine + \".\"\n\ndef slicePer(source, step):\n return [source[i::step] for i in range(step)]\n\nfor chapter in chapters:\n\n chapterLine = document.add_paragraph('', style='ListBullet')\n chapterLine.add_run(\"Chapter \" + str(counter)).bold=True\n lines = chapter.split(\".\")\n\n linesSplit = slicePer(lines, 10)\n\n for lineSplit in linesSplit:\n try:\n randomLine = randomNote(lineSplit)\n if randomLine is None:\n break;\n\n randomLine = randomLine.encode('ascii', 'ignore')\n noteLine = document.add_paragraph('', style='ListBullet')\n print(randomLine)\n noteLine.add_run(randomLine).bold = False;\n except (Exception):\n print(\"ERROR: \" + randomLine)\n\n counter += 1\n\ndocument.save(documentName)\nprint(\"Notes created\")\n\n","sub_path":"Python/NoteTaker/NoteTakerEpub.py","file_name":"NoteTakerEpub.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"384477881","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n\treturn np.cos( x / 2 ) + np.sin( 5 / ( np.abs(x) + 0.2 ) ) - 0.1 * x\n\t\nx = np.linspace(-10, 10, 1001)\n\ndef g(x, a0=1/2, a1=-1/4, a2=1/8, a3=-1/16, a4=1/32, a5=-1/64, a6=-1/128, a7=-1/256):\n\treturn a0 + a1 * x + a2 * x ** 2 + a3 * x ** 3 + a4 * x ** 4 + a5 * x ** 5 + a6 * x ** 6 + a7 * x ** 7\n\t\n\nfx = np.vectorize(f)(x)\ngx = np.vectorize(g)(x)\t\n\n# Durchschnittlicher absoluter Fehler\ndef calculate_error(fx, gx):\n\terror = 0\n\tfor i in range(len(fx)):\n\t\terror += np.abs( fx[i] - gx[i] )\n\terror /= len(fx)\n\treturn error\n# 7.2\n\nerror = calculate_error(fx,gx)\nprint( 'Durchschnittlicher absoluter Fehler: ' + str(error) )\n'''\nplt.figure()\nplt.plot(x, fx)\nplt.plot(x, gx)\nplt.show()\n'''\n\n# 7.3\nmin_error = 999999\nmin_parameters = None\nmin_gx = None\nfor i in range(1000):\n\n\tparameters = np.random.uniform(-5,5,8)\n\t\n\tnew_gx = np.vectorize(g)(x, parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7] )\n\t\n\terror = calculate_error( fx, new_gx )\n\t\n\tif error < min_error:\n\t\tmin_parameters = parameters\n\t\tmin_error = error\n\t\tmin_gx = new_gx\n\nif min_parameters is not None:\n\tprint( 'Minimaler Fehler: ' + str(min_error) ) \n\tprint( 'Gefundene Parameter: ' + str(min_parameters) )\n\t\n\tplt.figure()\n\tplt.plot(x, fx)\n\tplt.plot(x, min_gx)\n\tplt.show()\nelse:\n\tprint( 'Funktion konnte nicht minimiert werden' )\n\n\t\n# 7.4\nmin_error = 999999\nmin_parameters = None\nmin_gx = None\nfor i in range(10):\n\n\tparameters = np.random.uniform(-5,5,8)\n\t\n\tcurrent_gx = np.vectorize(g)(x, parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7] )\n\tcurrent_error = calculate_error( fx, current_gx )\n\t\n\tfor j in range(100):\n\n\t\tinkrement = np.random.uniform(-0.1,0.1,8)\n\t\t\n\t\tnew_parameters = parameters + inkrement\n\t\tnew_gx = np.vectorize(g)(x, new_parameters[0], new_parameters[1], new_parameters[2], new_parameters[3], new_parameters[4], new_parameters[5], new_parameters[6], new_parameters[7] )\n\t\tnew_error = calculate_error( fx, new_gx )\n\t\n\t\tif new_error < current_error:\n\t\t\tcurrent_error = new_error\n\t\t\tcurrent_gx = new_gx\n\t\t\tparameters = new_parameters\n\t\nfinal_gx = np.vectorize(g)(x, parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7] )\nfinal_error = calculate_error( fx, final_gx )\n\t\nprint( 'Minimaler Fehler: ' + str(final_error) ) \nprint( 'Gefundene Parameter: ' + str(parameters) )\n\nplt.figure()\nplt.plot(x, fx)\nplt.plot(x, final_gx)\nplt.show()\n\n\n'''\n\nDurchschnittlicher absoluter Fehler: 5195.255019747363\n\n7.3\nMinimaler Fehler: 105167.09250309649\nGefundene Parameter: [ 2.45846605 1.40560459 -2.94196272 -4.33455524 0.18040104 2.07176139 -0.73362339 0.01411922]\n\n7.4:\nMinimaler Fehler: 12325.526218340863\nGefundene Parameter: [ 1.27137875 -3.54205779 3.062015 -1.61141771 4.5323086 3.40049512 -0.04311234 -0.04566663]\n\n'''","sub_path":"Blatt 7/Dienstag/Kleemann/Blatt7.py","file_name":"Blatt7.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"199339285","text":"\n\nfrom math import pi\nfrom Useful import *\n\n\n# trend will be multiply by pi\n\nnodesPerLayer = 2\n# generating test samples\nnumSamples = 1\n# test_samples = [[random.random() for j in range(nodesPerLayer)] for i in range(numSamples)]\ntest_samples = [[1, 2] for j in range(0, numSamples)]\nM = [[1, 2],[3, 4]]\n\ntest_labels = [MVM(M, test_samples[i]) for i in range(numSamples)]\n# test_labels = [[test_samples[i][j] * pi for j in range(0, nodesPerLayer)] for i in range(numSamples)]\n\n# print(test_samples)\n# print(test_labels)\n\n\n# trend will be multiply by pi\nif __name__ == \"__main__\":\n\n\t# w = [[random.random() for z in range(nodesPerLayer)] for i in range(nodesPerLayer)]\n\t# w = [[pi for z in range(nodesPerLayer)] for i in range(nodesPerLayer)]\n\tw = [[0, 2], [3, 4]]\n\n\txVals = []\n\toutput_Vals = [[] for i in range(nodesPerLayer)]\n\tyVals = [[] for i in range(nodesPerLayer)]\n\tcostVals = []\n\twVals = []\n\tfor i in range(numSamples):\n\n\t\ta = [[0] for v in range(nodesPerLayer+1)]\n\t\td = [[0 for l in range(0, nodesPerLayer)] for v in range(0, nodesPerLayer)]\n\n\t\ta[0] = test_samples[i]\n\t\ty = test_labels[i]\n\t\ta[1] = MVM(w, a[0])\n\n\t\tprint (\"a[1] is {}\".format(a[1]))\n\t\tprint(\"y is {}\".format(y))\n\t\t# print(\"output vector is {} label is {}\".format(a[1], y))\n\n\t\ttotal_cost = 0\n\t\tfor o in range(nodesPerLayer):\n\t\t\ttotal_cost += pow((a[1][o] - y[o]), 2)\n\n\n\t\tfor r in range(0, nodesPerLayer):\n\t\t\tfor v in range(0, nodesPerLayer):\n\t\t\t\ttotal_change = 0\n\t\t\t\t# for t in range(0, nodesPerLayer):\n\t\t\t\ttotal_change += a[0][r] * 2 * (a[1][v] - y[v])\n\t\t\t\td[r][v] = total_change\n\n\t\tmatrixPrinter(d)\n\t\tmatrixPrinter(w)\n\n\n\t\t# print(d[1])\n\t\t# print(w[1])\n\t\tc = -1/100\n\t\tw = MMA([w] , SMM(c, [d]))[0]\n\t\t# w[0] = VVA(w[0], SVM(c, d[0]))\n\t\t# w[1] = VVA(w[1], SVM(c, d[1]))\n\n\t\txVals.append(i)\n\t\tcostVals.append(total_cost)\n\t\tfor q in range(0, nodesPerLayer):\n\t\t\toutput_Vals[q].append(a[1][q])\n\t\tfor q in range(0, nodesPerLayer):\n\t\t\tyVals[q].append(y[q])\n\t\t# for q in range(0, nodesPerLayer):\n\t\twVals.append(w[0][0])\n\n\n\tfor i in range(0, nodesPerLayer):\n\t\tpylab.subplot((nodesPerLayer+1) * 100 + 11+i)\n\t\tpylab.plot(xVals, wVals, 'b--')\n\t\tpylab.plot(xVals, output_Vals[i], 'b--')\n\t\tpylab.plot(xVals, yVals[i], 'r--')\n\n\n\tpylab.subplot((nodesPerLayer+1) * 100 + 11 + nodesPerLayer)\n\tpylab.plot(xVals, costVals, 'g--')\n\t# print(w)\n\t# print(MVM(w, [1,1]))\n\t# matrixPrinter(w)\n\tpylab.show()\n\t# t = 1\n\t# for j in range(numLayers):\n\t# \tt *= w[j]\n\t# print(t)\n\n\n\n\n\n\n","sub_path":"layerOfNodes.py","file_name":"layerOfNodes.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"172167977","text":"import string\nimport random\nimport time\ndef rules():\n print(' RULES ::==>')\n print(' 1.There Will Be Two user_chs')\n print(' 1.Player')\n print(' 2.Computer')\n print(' 2.User Can Play Any Number of Time')\ndef random_name(size=6,chars=string.ascii_uppercase + string.digits):\n name=input('Enter Your Name : ')\n print(f'\\nWelcome --> {name}')\n com_name=''.join(random.choice(chars) for _ in range(size))\n print('The Computer Will play as --> ',com_name)\n\ndef choices():\n choices=['Rock','Paper','Scissors']\n print(choices)\n user_ch=input('Select Your Choices ?(Case Sensitive) ')\n x=random.choice(choices)\n time.sleep(1)\n print('Computer\\'s Choice --> ',x)\n time.sleep(1)\n if user_ch=='':\n print('Blank Choice...')\n print('Please Select a Choice....') \n else:\n if user_ch == x:\n print('Tie!')\n elif user_ch == 'Rock':\n if x == 'Paper':\n print('You lose!', x, 'covers', user_ch)\n else:\n print('You win!', user_ch, 'smashes', x)\n elif user_ch == 'Paper':\n if x == 'Scissors':\n print('You lose!', x, 'cut', user_ch)\n else:\n print('You win!', user_ch, 'covers', x)\n elif user_ch == 'Scissors':\n if x == 'Rock':\n print('You lose...', x, 'smashes', user_ch)\n\n\ndef play():\n rules()\n random_name()\n choices()\nopt='yes'\nwhile opt=='yes' or opt=='y':\n play()\n opt=input('\\nDo You want To play Again ? ')\n\n ","sub_path":"rockpaper.py","file_name":"rockpaper.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"456703217","text":"import json\nimport numpy as np\nimport random\n\nfrom os.path import isfile, isdir\nfrom os.path import join as pjoin\n\nimport torch\nfrom torch.utils.data import Dataset\n\n#########\n# Node typing: checking the type of a specific sub-tree (dict value)\n#########\ndef is_span(val):\n try:\n a, (b, c) = val\n return all([type(v) == int for v in [a, b, c]])\n except (ValueError, TypeError):\n return False\n\n\ndef is_span_list(val):\n res = type(val) == list and len(val) > 0 and all([is_span(v) for v in val])\n return res\n\n\ndef is_cat(val):\n return type(val) == str or val is True or val is False\n\n\ndef is_cat_list(val):\n res = (type(val) == list) and len(val) > 0 and all([is_cat(v) for v in val])\n return res\n\n\ndef is_int(val):\n return type(val) == dict\n\n\ndef is_int_list(val):\n res = (type(val) == list) and len(val) > 0 and all([is_int(v) for v in val])\n return res\n\n\n#########\n# Make grammar from dataset. Starts with empty full_tree\n# then add all nodes found in the dataset\n#########\n# if new_tree is outside of what the grammar can handle, modifies grammar\n# also counts number of occurence of each node\ndef add_tree(full_tree, new_tree, vocounts, nw=1):\n for k, v in new_tree.items():\n if k not in full_tree:\n full_tree[k] = {\"name\": k, \"children\": {}, \"values\": {}, \"count\": 0}\n full_tree[k][\"count\"] += nw\n if is_cat(v):\n full_tree[k][\"values\"][v] = full_tree[k][\"values\"].get(v, 0) + nw\n w = \"C:\" + k + \"|\" + str(v)\n vocounts[w] = vocounts.get(w, 0) + nw\n elif is_int(v):\n ws = \"IB:\" + k\n we = \"IE:\" + k\n vocounts[ws] = vocounts.get(ws, 0) + nw\n vocounts[we] = vocounts.get(we, 0) + nw\n add_tree(full_tree[k][\"children\"], v, vocounts, nw)\n elif is_int_list(v):\n ws = \"ILB:\" + k\n wi = \"IL&:\" + k\n we = \"ILE:\" + k\n vocounts[ws] = vocounts.get(ws, 0) + nw\n vocounts[wi] = vocounts.get(wi, 0) + nw\n vocounts[we] = vocounts.get(we, 0) + nw\n for c in v:\n add_tree(full_tree[k][\"children\"], c, vocounts, nw)\n elif is_span(v) or is_span_list(v):\n w = \"S:\" + k\n ws = \"BE:\" + k\n vocounts[w] = vocounts.get(w, 0) + nw\n vocounts[ws] = vocounts.get(ws, 0) + nw\n\n\n# starts with an empty grammar and adds trees from the dataset\ndef make_full_tree(trees_weight_ls):\n res = {}\n vocounts = {}\n for trees, weight in trees_weight_ls:\n for dlg, tr in trees:\n add_tree(res, tr, vocounts, weight)\n tree_i2w = [k for k, v in sorted(vocounts.items(), key=lambda x: x[1], reverse=True)] + [\n \"BE:span\"\n ]\n return res, tree_i2w\n\n\n#########\n# Linearize and de-linearize trees\n#########\n# transforms tree into sequence of (token, start_span, end_span)\n# idx_map maps the span ids before and after tokenization\ndef tree_to_seq(full_tree, tree, idx_map=None):\n res = []\n sorted_keys = sorted(\n [k for k in tree.keys() if k in full_tree],\n key=lambda x: full_tree[x][\"count\"],\n reverse=True,\n ) + sorted([k for k, v in tree.items() if k not in full_tree])\n for k in sorted_keys:\n if is_cat(tree[k]):\n res += [(\"C:\" + k + \"|\" + str(tree[k]), -1, -1)]\n elif is_span(tree[k]):\n a, (b, c) = tree[k]\n # res += [('S:' + k, idx_map[a][b][0], idx_map[a][c][1])]\n res += [(\"S:\" + k, -1, -1)]\n res += [(\"BE:\" + k, idx_map[a][b][0], idx_map[a][c][1])]\n elif is_int(tree[k]):\n res += (\n [(\"IB:\" + k, -1, -1)]\n + tree_to_seq(full_tree.get(k, {\"children\": {}})[\"children\"], tree[k], idx_map)\n + [(\"IE:\" + k, -1, -1)]\n )\n elif is_int_list(tree[k]):\n res += [(\"ILB:\" + k, -1, -1)]\n for c in tree[k]:\n res += tree_to_seq(full_tree.get(k, {\"children\": {}})[\"children\"], c, idx_map) + [\n (\"IL&:\" + k, -1, -1)\n ]\n res = res[:-1] + [(\"ILE:\" + k, -1, -1)]\n else:\n raise NotImplementedError\n return res\n\n\n# selects sub-tree in (span in the output sequence) so we can apply recursively seq_to_tree\ndef select_spans(seq):\n spans = [-1 for _ in seq]\n active = {}\n unopened = False\n for i, (w, b_id, e_id) in enumerate(seq):\n if w.startswith(\"IB:\") or w.startswith(\"ILB:\"):\n active[w] = active.get(w, {})\n active[w][i] = 0\n for s_idx in active[w]:\n active[w][s_idx] += 1\n elif w.startswith(\"IE:\") or w.startswith(\"ILE:\"):\n ws = w.replace(\"E:\", \"B:\")\n if ws not in active:\n # closing an unopened bracket\n unopened = True\n else:\n closed = []\n for s_idx in active[ws]:\n active[ws][s_idx] -= 1\n if active[ws][s_idx] <= 0:\n closed += [s_idx]\n spans[s_idx] = i\n for s_idx in closed:\n del active[ws][s_idx]\n # check whether all brackets have been closed\n well_formed = (sum([len(ctr_dict) for ws, ctr_dict in active.items()]) == 0) and not unopened\n for ws in active:\n for s_idx in active[ws]:\n spans[s_idx] = len(seq)\n # create a dictionary of left bracket > right bracket\n span_dict = {}\n for s_idx, e_idx in enumerate(spans):\n if e_idx > 0:\n span_dict[s_idx] = e_idx\n return (span_dict, well_formed)\n\n\n# transforms sequence back into tree of nested dictionaries\n# span_dict identifies the sub-sequences corresponding to sub-trees\ndef seq_to_tree(full_tree, seq, idx_rev_map=None, span_dct=None, start_id=0):\n res = {}\n if span_dct is None:\n span_dict, well_formed = select_spans(seq)\n else:\n span_dict = span_dct\n well_formed = True\n idx = 0\n while idx < len(seq):\n if \":\" not in seq[idx][0]:\n idx += 1\n continue\n t, w = seq[idx][0].split(\":\")\n # categorical node\n if t == \"C\":\n cat, val = w.split(\"|\")\n res[cat] = val\n idx += 1\n # span node\n elif t == \"S\":\n if idx + 1 < len(seq):\n b_pre = seq[idx + 1][1]\n e_pre = seq[idx + 1][2]\n l_idx, b_idx = idx_rev_map[b_pre]\n _, e_idx = idx_rev_map[e_pre]\n res[w] = [l_idx, [b_idx, e_idx]]\n else:\n res[w] = [-1, [-1, -1]]\n # idx += 1\n idx += 2\n # internal node\n elif t == \"IB\":\n sub_full_tree = full_tree.get(w, {\"children\": {}})[\"children\"]\n sub_span = (idx + 1, span_dict[start_id + idx] - start_id)\n sub_seq = seq[sub_span[0] : sub_span[1]]\n res[w] = seq_to_tree(\n sub_full_tree, sub_seq, idx_rev_map, span_dict, start_id=start_id + sub_span[0]\n )[0]\n idx = sub_span[1]\n # internal node list\n elif t == \"ILB\":\n sub_full_tree = full_tree.get(w, {\"children\": {}})[\"children\"]\n sub_span = (idx + 1, span_dict[start_id + idx] - start_id)\n pre_sub_seq = seq[sub_span[0] : sub_span[1]]\n # split sub-sequence by list items\n sub_seq_ls_idx = (\n [-1]\n + [i for i, sw in enumerate(pre_sub_seq) if sw[0] == \"IL&:\" + w]\n + [len(pre_sub_seq)]\n )\n sub_span_ls = [\n (sub_span[0] + sub_seq_ls_idx[i] + 1, sub_span[0] + sub_seq_ls_idx[i + 1])\n for i in range(len(sub_seq_ls_idx) - 1)\n ]\n # read sub-trees\n res[w] = []\n for s_sub_span in sub_span_ls:\n sub_seq = seq[s_sub_span[0] : s_sub_span[1]]\n res[w] += [\n seq_to_tree(\n sub_full_tree,\n sub_seq,\n idx_rev_map,\n span_dict,\n start_id=start_id + s_sub_span[0],\n )[0]\n ]\n idx = sub_span[1]\n # failure case??? TODO: raise error\n else:\n idx += 1\n return (res, well_formed)\n\n\n# returns empty tree if ta and tb are the same tree\ndef compare_tree(ta, tb):\n res = {}\n # internal node\n if is_int(ta) or is_int_list(ta):\n if is_int_list(ta):\n ta = ta[0]\n tb = tb[0]\n for a in ta:\n if a in tb:\n comp = compare_tree(ta[a], tb[a])\n if len(comp) > 0:\n res[a] = comp\n else:\n res[a] = (ta[a], \"\")\n for b in tb:\n if b not in ta:\n res[b] = (\"\", tb[b])\n elif ta != tb:\n res = (ta, tb)\n return res\n\n\n##################\n# torch Dataset\n##################\n# helper function to align word indices before and after applying BPE\ndef align_post_tok(pre_tok, post_tok, seen_toks=0):\n i, j, ci, cj = [0] * 4\n idx_map = [[seen_toks, seen_toks] for _ in range(len(pre_tok.split()))]\n while ci < len(pre_tok) and cj < len(post_tok):\n if pre_tok[ci] == post_tok[cj]:\n if pre_tok[ci] == \" \":\n i += 1\n j += 1\n if i > 0:\n idx_map[i - 1][1] = j - 1 + seen_toks\n idx_map[i][0] = j + seen_toks\n ci += 1\n cj += 1\n elif post_tok[cj] == \" \":\n j += 1\n cj += 1\n elif pre_tok[ci] == \" \":\n i += 1\n if i > 0:\n idx_map[i - 1][0] = j - 1 + seen_toks\n idx_map[i][1] = j + seen_toks\n ci += 1\n else:\n cj += 1\n idx_map[i][-1] = j + seen_toks\n return idx_map\n\n\n# applies BPE to input and creates mapping of span indices before and after BPE\ndef tokenize_mapidx(text, tokenizer):\n # re-order lines: last chat in multi-chat is first in the list\n # rev_lines = [line.strip() for line in text.split('<SEP>')]\n # text_lines = [rev_lines[i - 1] for i in range(len(rev_lines), 0, -1)]\n text_lines = [line.strip() for line in text.split(\"<SEP>\")]\n # tokenize text and linearize tree\n seen_toks = 1\n idx_maps = [[] for _ in text_lines]\n res_toks = [\"[CLS]\"]\n for lid, line in enumerate(text_lines):\n tok_line = tokenizer.tokenize(line)\n tok_join = \" \".join(tok_line)\n idx_maps[-1 - lid] = align_post_tok(line, tok_join, seen_toks)\n res_toks += tok_line[:] + [\"[SEP]\"]\n seen_toks += len(tok_line) + 1\n return (\" \".join(res_toks), idx_maps)\n\n\n# takes raw text and tree, returns BPE-ed text and linearized tree\ndef tokenize_linearize(text, tree, tokenizer, full_tree, word_noise=0.0):\n tok_text, idx_maps = tokenize_mapidx(text, tokenizer)\n tokenized = \" \".join(\n [\n \"[UNK]\" if w not in [\"[CLS]\", \"[SEP]\"] and random.random() < word_noise else w\n for w in tok_text.split()\n ]\n )\n lin_tree = tree_to_seq(full_tree, tree, idx_maps)\n return (tokenized, lin_tree)\n\n\n# torch Dataset for the CAIP format, applies BPE and linearizes trees on-the-fly\nclass CAIPDataset(Dataset):\n \"\"\"\n CAIP: CraftAssist Instruction Parsing\n \"\"\"\n\n def __init__(\n self,\n tokenizer,\n args,\n prefix=\"train\",\n dtype=\"templated\",\n sampling=False,\n word_noise=0.0,\n full_tree_voc=None,\n ):\n assert isdir(args.data_dir)\n self.tokenizer = tokenizer\n\n # We load the (input, tree) pairs for all data types and\n # initialize the hard examples buffer\n self.data = {}\n self.sampling = sampling\n self.word_noise = word_noise\n dtype_samples = json.loads(args.dtype_samples)\n self.dtype = dtype\n self.dtypes = [t for t, p in dtype_samples]\n self.sample_probas = np.array([p for t, p in dtype_samples])\n self.sample_probas /= self.sample_probas.sum()\n if prefix == \"train\":\n for k in self.dtypes:\n fname = pjoin(args.data_dir, prefix, k + \".json\")\n if isfile(fname):\n print(\"loading\", fname)\n self.data[k] = json.load(open(fname))\n else:\n self.data[k] = []\n self.hard_buffer_size = 1024\n self.hard_buffer_counter = 0\n else:\n fname = pjoin(args.data_dir, prefix, dtype + \".json\")\n if isfile(fname):\n print(\"loading\", fname)\n self.data[dtype] = json.load(open(fname))\n else:\n self.data[dtype] = []\n\n # load meta-tree and tree vocabulary\n if full_tree_voc is None:\n print(\"making tree\")\n ftr, tr_i2w = make_full_tree(\n [\n (self.data[\"humanbot\"], 3e5),\n (self.data[\"prompts\"], 1e5),\n (self.data[\"templated\"][:100000], 1),\n ]\n )\n self.full_tree = ftr\n else:\n full_tree, tr_i2w = full_tree_voc\n self.full_tree = full_tree\n spec_tokens = [\"[PAD]\", \"unused\", \"[UNK]\", \"[CLS]\", \"[SEP]\", \"[MASK]\", \"<S>\", \"</S>\"]\n self.tree_voc = spec_tokens[:] + tr_i2w\n self.tree_idxs = dict([(w, i) for i, w in enumerate(self.tree_voc)])\n\n self.dataset_length = max([len(v) for v in self.data.values()])\n if args.examples_per_epoch > 0:\n self.dataset_length = min(self.dataset_length, args.examples_per_epoch)\n\n def __len__(self):\n return self.dataset_length\n\n def __getitem__(self, idx):\n # sample data type and get example\n if self.sampling:\n dtype = np.random.choice(self.dtypes, p=self.sample_probas)\n if len(self.data[dtype]) == 0:\n dtype = self.dtype\n else:\n dtype = self.dtype\n p_text, p_tree = self.data[dtype][idx % len(self.data[dtype])]\n text, tree = tokenize_linearize(\n p_text, p_tree, self.tokenizer, self.full_tree, self.word_noise\n )\n text_idx_ls = [self.tokenizer._convert_token_to_id(w) for w in text.split()]\n tree_idx_ls = [\n [self.tree_idxs[w], bi, ei]\n for w, bi, ei in [(\"<S>\", -1, -1)] + tree + [(\"</S>\", -1, -1)]\n ]\n return (text_idx_ls, tree_idx_ls, (text, p_text, p_tree))\n\n def add_hard_example(self, exple):\n if self.hard_buffer_counter < self.hard_buffer_size:\n self.data[\"hard\"] += [exple]\n else:\n self.data[\"hard\"][self.hard_buffer_counter % self.hard_buffer_size] = exple\n self.hard_buffer_counter += 1\n\n\n# applies padding and makes batch tensors\ndef caip_collate(batch, tokenizer):\n # keep track of examples\n pre_examples = [(p_text, p_tree) for x, y, (_, p_text, p_tree) in batch]\n # input: text\n batch_x_ls = [x for x, y, _ in batch]\n x_len = max([len(x) for x in batch_x_ls])\n x_mask_ls = [[1] * len(x) + [0] * (x_len - len(x)) for x in batch_x_ls]\n batch_x_pad_ls = [x + [tokenizer.pad_token_id] * (x_len - len(x)) for x in batch_x_ls]\n # output: linearized trees\n batch_y_ls = [y for x, y, _ in batch]\n y_len = max([len(y) for y in batch_y_ls])\n y_mask_ls = [[1] * len(y) + [0] * (y_len - len(y)) for y in batch_y_ls]\n batch_y_pad_ls = [y + [[0, -1, -1]] * (y_len - len(y)) for y in batch_y_ls] # 0 as padding idx\n # tensorize\n x = torch.tensor(batch_x_pad_ls)\n x_mask = torch.tensor(x_mask_ls)\n y = torch.tensor(batch_y_pad_ls)\n y_mask = torch.tensor(y_mask_ls)\n return (x, x_mask, y, y_mask, pre_examples)\n","sub_path":"python/craftassist/ttad/ttad_transformer_model/utils_caip.py","file_name":"utils_caip.py","file_ext":"py","file_size_in_byte":15857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"291188612","text":"from scrapy import cmdline\n\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.utils.project import get_project_settings\nfrom twisted.internet import task\n\n\ndef v1cmds():\n cmdline.execute('scrapy crawl v1spider'.split())\n\n\ndef looping_call_spider(crawler_process):\n spider_loader = crawler_process.spider_loader\n spider_names = spider_loader.list()\n print(spider_names)\n for spider_name in spider_names:\n crawler_process.crawl(spider_name)\n\n\ndef v2crawler():\n settings = get_project_settings()\n\n crawler_process = CrawlerProcess(settings)\n\n _looping = task.LoopingCall(looping_call_spider, crawler_process)\n _looping.start(5) # call every second\n\n crawler_process.start(stop_after_crawl=False)\n\n\nif __name__ == \"__main__\":\n v1cmds()\n # v2crawler()\n","sub_path":"_/cmds.py","file_name":"cmds.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"512257015","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 8 14:00:01 2017\n\n@author: bgris\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 8 11:57:30 2017\n\n@author: bgris\n\nStategy : define ourselves the adapted vector field for shepp logan by :\n - restricting the rotation to a reasonnable support\n - projecting it on the rkhs (sum of translations)\n\nAnd then we use the corresponding vector field\n\n\n\n\"\"\"\n\n\n\nimport odl\nimport numpy as np\n\n##%% Create data from lddmm registration\nimport matplotlib.pyplot as plt\n\nfrom DeformationModulesODL.deform import Kernel\nfrom DeformationModulesODL.deform import DeformationModuleAbstract\nfrom DeformationModulesODL.deform import SumTranslations\nfrom DeformationModulesODL.deform import UnconstrainedAffine\nfrom DeformationModulesODL.deform import LocalScaling\nfrom DeformationModulesODL.deform import LocalRotation\nfrom DeformationModulesODL.deform import EllipseMvt\nfrom DeformationModulesODL.deform import FromFile\nfrom DeformationModulesODL.deform import FromFileV5\nfrom DeformationModulesODL.deform import TemporalAttachmentModulesGeom\nfrom DeformationModulesODL.deform import Kernel\nimport scipy\n\n#%% load data\n\n\nspace_init = odl.uniform_discr(\n min_pt=[-16, -16], max_pt=[16, 16], shape=[512, 512],\n dtype='float32', interp='linear')\npath = '/home/barbara/data/SheppLoganRotationSmallDef/Images/'\n#\n#space = odl.uniform_discr(\n# min_pt=[-16, -16], max_pt=[16, 16], shape=[128, 128],\n# dtype='float32', interp='linear')\n\n\nspace =space_init\n\n\ntemplate_init=space_init.element(np.loadtxt(path + 'source_0'))\nsource_displaced_init=space_init.element(np.loadtxt(path + 'target_0'))\ntarget_init=space_init.element(np.loadtxt(path + 'source_5'))\n\ntemplate =space.element(template_init.interpolation(space.points().T))\nsource_displaced =space.element(source_displaced_init.interpolation(space.points().T))\ntarget =space.element(target_init.interpolation(space.points().T))\n\nforward_op=odl.IdentityOperator(space)\nground_truth=[template]\ndata = [forward_op(target)]\n\n#%% Define the vector field : useful functions\n\n\npoints=space.points()\n\ndef Rtheta(theta,points):\n # theta is the angle, in rad\n # input = list of points, for ex given by space.points() or\n # np.array(vect_field).T\n #output = list of points of same size, rotated of an angle theta\n\n points_rot=np.empty_like(points).T\n points_rot[0]=np.cos(theta)*points.T[0].copy() - np.sin(theta)*points.T[1].copy()\n points_rot[1]=np.sin(theta)*points.T[0].copy() + np.cos(theta)*points.T[1].copy()\n\n return points_rot.T.copy()\n points.T[0]\n\ndef Rinfi(theta,points):\n # theta is the angle, in rad\n # input = list of points, for ex given by space.points() or\n # np.array(vect_field).T\n #output = list of points of same size, rotated of an angle theta\n\n points_rot=np.empty_like(points).T\n points_rot[0]=np.cos(theta)*points.T[0].copy() - np.sin(theta)*points.T[1].copy()\n points_rot[1]=np.sin(theta)*points.T[0].copy() + np.cos(theta)*points.T[1].copy()\n\n return points_rot.T.copy()\n points.T[0]\n#\n##%%\n\ndef Rot_image_cache(minx,maxx,miny,maxy,theta,centre,template):\n I1=space.element()\n for i in range(len(points)):\n pt=points[i]\n if(pt[0]>minx and pt[0] < maxx and pt[1]>miny and pt[1]<maxy):\n pt_rot_inv=Rtheta(-theta,pt-centre).copy()\n I1[i]=template.interpolation([[pt_rot_inv[0]+centre[0]],[pt_rot_inv[1]+centre[1]]])\n else:\n I1[i]=template[i]\n\n return I1\n#\n\n#%% Define the vector field : Find good cache\ntheta=(0.05)*np.pi\ncentre=np.array([0,-9.6])\n\nmaxx=2.5\nminx = -2.5\nminy=-12.0\nmaxy=-7.1\n#miny=-10.6\n#maxy=-8.2\n\n#\n#maxyrot=2.5\n#minyrot = -2.5\n#minxrot=-10.6\n#maxxrot=-8.2\n\nI1=Rot_image_cache(minx,maxx,miny,maxy,theta,centre,template)\n#I1=Rot_image_cache(minxrot,maxxrot,minyrot,maxyrot,theta,centre,template)\n\nI1.show('computed')\n(I1 - source_displaced).show('difference')\n\n#%% Define the vector field : restrict and project vector field\npoints_dec = points - centre\n#rotation_field = space.tangent_bundle.element((centre + Rtheta(theta, points_dec) - points).T)\ntranslation_field = space.tangent_bundle.element([space.zero(), space.one()])\n#rotation_field.show(clim = [-5,5])\n\nimpt0 = space.element(points.T[0]).asarray()\nimpt1 = space.element(points.T[1]).asarray()\n\ncache = space.element( (impt0 < maxx) * (impt0 > minx) * (impt1 < maxy) * (impt1 > miny))\n#cache.show()\n\n#rotation_field_restricted = rotation_field * cache\ntranslation_field_restricted = translation_field * cache\n\ndef get_points(structured_field):\n dim_double, nb_points = structured_field.shape\n dim = int(dim_double/2)\n\n return structured_field[0:dim].copy()\n\n\ndef get_vectors(structured_field):\n dim_double, nb_points = structured_field.shape\n dim = int(dim_double/2)\n\n return structured_field[dim:2*dim].copy()\n\ndef create_structured(points, vectors):\n return np.vstack([points, vectors])\n\n\ndef get_from_structured_to_unstructured(space, kernel):\n mg = space.meshgrid\n\n def from_structured_to_unstructured(structured_field):\n dim_double, nb_points = structured_field.shape\n points = get_points(structured_field)\n vectors = get_vectors(structured_field)\n unstructured = space.tangent_bundle.zero()\n\n for k in range(nb_points):\n def kern_app_point(x):\n return kernel(x, points[:, k])\n\n kern_discr = kern_app_point(mg)\n\n unstructured += space.tangent_bundle.element([kern_discr * vect for vect in vectors[:, k]]).copy()\n\n return unstructured\n\n return from_structured_to_unstructured\n\ndef get_structured_vectors_from_concatenated(vectors, nb_points, dim):\n return vectors.reshape(nb_points, dim).T\n\n\ndef make_covariance_matrix(points, kernel):\n \"\"\" creates the covariance matrix of the kernel for the given points\"\"\"\n\n dim = len(points)\n p1 = np.reshape(points, (dim, 1, -1))\n p2 = np.reshape(points, (dim, -1, 1))\n\n return kernel(p1, p2)\n\n\nsigma_kernel = 0.3\nfac=0.5\nxmin=miny\nxmax=maxx\ndx=round((xmax-xmin)/(fac*sigma_kernel))\nymin=miny\nymax=maxy\ndy=round((ymax-ymin)/(fac*sigma_kernel))\n\npoints_reg=[]\nfor i in range(dx+1):\n for j in range(dy+1):\n points_reg.append([xmin +fac*sigma_kernel* i*1.0, ymin + fac*sigma_kernel*j*1.0])\npoints_reg = np.array(points_reg).T\n\n\ndef kernel(x, y):\n return np.exp(- sum([ (xi - yi) ** 2 for xi, yi in zip(x, y)]) / (sigma_kernel ** 2))\n\neval_kernel = make_covariance_matrix(points_reg, kernel)\n\ndim, nb_points=points_reg.shape\n\n#field = rotation_field_restricted.copy()\nfield = translation_field_restricted.copy()\n\nvector_syst = np.zeros(dim*nb_points)\nbasis = np.identity(dim)\n\neval_field = np.array([field[u].interpolation(\n points_reg) for u in range(dim)])\n\nfor k0 in range(nb_points):\n for l0 in range(dim):\n vector_syst[dim*k0 + l0] += np.dot(eval_field.T[k0],\n basis[:, l0])\n\nmatrix_syst = np.kron(eval_kernel, basis)\n\nalpha_concatenated = np.linalg.solve(matrix_syst, vector_syst)\nalpha = get_structured_vectors_from_concatenated(alpha_concatenated, nb_points, dim)\n\nget_unstructured_op = get_from_structured_to_unstructured(space, kernel)\n\nvect_field_estimated = get_unstructured_op(create_structured(points_reg, alpha))\n\nfield.show('restricted')\nvect_field_estimated.show('projected')\n(vect_field_estimated - field).show('difference')\n\n#%% save vector field\n\nName = '/home/bgris/DeformationModulesODL/deform/vect_field_rotation_SheppLogan_restrictedrotation_sigma_0_3__nbtrans_560'\nName = '/home/bgris/DeformationModulesODL/deform/vect_field_rotation_SheppLogan_restrictedinfinitesimalrotation'\nName = '/home/barbara/DeformationModulesODL/deform/vect_field_translation_SheppLogan_restrictedprojected_symtranslation_sigma_0_3__nbtrans_1496'\n\nif False:\n np.savetxt(Name, vect_field_estimated)\n\n\n\n\n\n#%% Define Module\nNEllipse=1\n\nkernelelli=Kernel.GaussianKernel(0.3)\n\nupdate=[1,1]\nelli=FromFileV5.FromFileV5(space, Name, kernelelli,update)\n\nModule=DeformationModuleAbstract.Compound([elli])\n\n##%%test elli\nGD=[[0.0,0.0], -0.5*np.pi, [0.0,0.0], [1.0,0.0]]\nCont=1\n\n#ope_der=elli.ComputeFieldDer(GD,Cont)\nvect_field=elli.ComputeField(GD,Cont)\n\n#%% functionals\ndim = 2\nlam=0.0001\nnb_time_point_int=10\n\nlamb0=1e-5\nlamb1=1e-5\n\ndata_time_points=np.array([1])\ndata_space=odl.ProductSpace(forward_op.range,data_time_points.size)\ndata=data_space.element(data)\nforward_operators=[forward_op]\n\nNorm=odl.solvers.L2NormSquared(forward_op.range)\n\nfunctional_mod = TemporalAttachmentModulesGeom.FunctionalModulesGeom(lamb0, nb_time_point_int, template, data, data_time_points, forward_operators,Norm, Module)\n\n\n\n# The parameter for kernel function\nsigma = 0.3\n\n# Give kernel function\ndef kernel_lddmm(x):\n scaled = [xi ** 2 / ( sigma ** 2) for xi in x]\n return np.exp(-sum(scaled))\n\n\n# Define energy operator\nenergy_op_lddmm=odl.deform.TemporalAttachmentLDDMMGeom(nb_time_point_int, template ,data,\n data_time_points, forward_operators,Norm, kernel_lddmm,\n domain=None)\n\n\nReg=odl.deform.RegularityLDDMM(kernel_lddmm,energy_op_lddmm.domain)\n\nfunctional_lddmm=energy_op_lddmm + lamb1*Reg\n\n\n#%% Useful functional\n\ndef Mix_vect_field(vect_field_list,GD_init,Cont):\n space_pts=template.space.points()\n GD=GD_init.copy()\n vect_field_list_tot=vect_field_list.copy()\n for i in range(nb_time_point_int):\n vect_field_list_mod=functional_mod.Module.ComputeField(GD,Cont[i]).copy()\n vect_field_list_mod_interp=template.space.tangent_bundle.element([vect_field_list_mod[u].interpolation(space_pts.T) for u in range(dim)]).copy()\n vect_field_list_tot[i]+=vect_field_list_mod_interp.copy()\n GD+=(1/nb_time_point_int)*functional_mod.Module.ApplyVectorField(GD,vect_field_list_tot[i]).copy()\n\n return vect_field_list_tot\n\n\ndef vect_field_list(GD_init,Cont):\n space_pts=template.space.points()\n GD=GD_init.copy()\n vect_field_list_tot=[]\n for i in range(nb_time_point_int+1):\n vect_field_mod=functional_mod.Module.ComputeField(GD,Cont[i]).copy()\n vect_field_list_interp=template.space.tangent_bundle.element([vect_field_mod[u].interpolation(space_pts.T) for u in range(dim)]).copy()\n GD+=(1/nb_time_point_int)*functional_mod.Module.ApplyVectorField(GD,vect_field_list_interp).copy()\n vect_field_list_tot.append(vect_field_list_interp)\n\n return odl.ProductSpace(template.space.tangent_bundle,nb_time_point_int+1).element(vect_field_list_tot)\n\n\n\ndef Shoot_mixt(vect_field_list,GD,Cont):\n vect_field_list_mod=Mix_vect_field(vect_field_list,GD,Cont).copy()\n I=TemporalAttachmentModulesGeom.ShootTemplateFromVectorFields(vect_field_list_mod, template)\n return I\n\ndef attach_tot(vect_field_list,GD,Cont):\n I=Shoot_mixt(vect_field_list,GD,Cont)\n return Norm(forward_operators[0](I[nb_time_point_int])-data[0])\n\ndef attach_mod(GD,Cont):\n vect_field_list_mod=vect_field_list(GD,Cont)\n I=TemporalAttachmentModulesGeom.ShootTemplateFromVectorFields(vect_field_list_mod, template)\n return Norm(forward_operators[0](I[nb_time_point_int])-data[0])\n\n\n\n\ndef grad_attach_vector_field(GD,Cont):\n vect_field_list_tot=vect_field_list(GD,Cont)\n grad=energy_op_lddmm.gradient(vect_field_list_tot).copy()\n return grad\n#\n\ndef grad_attach_vector_fieldL2(GD,Cont):\n vect_field_list_tot=vect_field_list(GD,Cont)\n grad=energy_op_lddmm.gradientL2(vect_field_list_tot).copy()\n return grad\n#\n\ndef ComputeGD_list(GD,Cont):\n GD_list=[]\n GD_list.append(GD.copy())\n for i in range(nb_time_point_int):\n GD_temp=GD_list[i].copy()\n vect_field=functional_mod.Module.ComputeField(GD_temp,Cont[i]).copy()\n GD_temp+=(1/nb_time_point_int)*functional_mod.Module.ApplyVectorField(GD_temp,vect_field)\n GD_list.append(GD_temp.copy())\n\n return GD_list.copy()\n#\n\nmini=0\nmaxi=1\nrec_space=template.space\ntime_itvs=nb_time_point_int\n\n\ndef compute_grid_deformation(vector_fields_list, time_step, initial_grid):\n vector_fields_list = vector_fields_list\n nb_time_points = vector_fields_list.size\n\n grid_points = initial_grid\n\n for t in range(nb_time_points):\n velocity = np.empty_like(grid_points)\n for i, vi in enumerate(vector_fields_list[t]):\n velocity[i, ...] = vi.interpolation(grid_points)\n grid_points += time_step*velocity\n\n return grid_points\n\n\ndef compute_grid_deformation_list(vector_fields_list, time_step, initial_grid):\n vector_fields_list = vector_fields_list\n nb_time_points = vector_fields_list.size\n grid_list=[]\n grid_points=initial_grid.copy()\n grid_list.append(initial_grid)\n\n for t in range(nb_time_points):\n velocity = np.empty_like(grid_points)\n for i, vi in enumerate(vector_fields_list[t]):\n velocity[i, ...] = vi.interpolation(grid_points)\n grid_points += time_step*velocity\n grid_list.append(grid_points.copy())\n\n return grid_list\n\n\n# As previously but check if points of the grids are in the\n# Domain and if they are not the velocity is equal to zero\ndef compute_grid_deformation_list_bis(vector_fields_list, time_step, initial_grid):\n vector_fields_list = vector_fields_list\n nb_time_points = vector_fields_list.size\n grid_list=[]\n grid_points=initial_grid.T.copy()\n grid_list.append(initial_grid.T)\n mini=vector_fields_list[0].space[0].min_pt\n maxi=vector_fields_list[0].space[0].max_pt\n for t in range(nb_time_points):\n print(t)\n velocity = np.zeros_like(grid_points)\n for i, vi in enumerate(vector_fields_list[t]):\n for k in range(len(initial_grid.T)):\n isindomain=1\n point=grid_points[k]\n for u in range(len(mini)):\n if (point[u]<mini[u] or point[u]>maxi[u] ):\n isindomain=0\n if (isindomain==1):\n velocity[k][i] = vi.interpolation(point)\n\n grid_points += time_step*velocity\n grid_list.append(grid_points.copy().T)\n\n return grid_list\n\n\ndef plot_grid(grid, skip):\n for i in range(0, grid.shape[1], skip):\n plt.plot(grid[0, i, :], grid[1, i, :], 'r', linewidth=0.5)\n\n for i in range(0, grid.shape[2], skip):\n plt.plot(grid[0, :, i], grid[1, :, i], 'r', linewidth=0.5)\n#\n\n\ndef plot_result(name,image_N0):\n plt.figure()\n rec_result_1 = rec_space.element(image_N0[time_itvs // 4])\n rec_result_2 = rec_space.element(image_N0[time_itvs // 4 * 2])\n rec_result_3 = rec_space.element(image_N0[time_itvs // 4 * 3])\n rec_result = rec_space.element(image_N0[time_itvs])\n ##%%\n # Plot the results of interest\n plt.figure(2, figsize=(24, 24))\n #plt.clf()\n\n plt.subplot(3, 3, 1)\n plt.imshow(np.rot90(template), cmap='bone',\n vmin=mini,\n vmax=maxi)\n plt.axis('off')\n #plt.savefig(\"/home/chchen/SwedenWork_Chong/NumericalResults_S/LDDMM_results/J_V/template_J.png\", bbox_inches='tight')\n plt.colorbar()\n #plt.title('Trajectory from EllipseMvt with DeformationModulesODL/deform/vect_field_ellipse')\n\n plt.subplot(3, 3, 2)\n plt.imshow(np.rot90(rec_result_1), cmap='bone',\n vmin=mini,\n vmax=maxi)\n\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs // 4))\n\n plt.subplot(3, 3, 3)\n plt.imshow(np.rot90(rec_result_2), cmap='bone',\n vmin=mini,\n vmax=maxi)\n #grid=grid_points[time_itvs // 4].reshape(2, rec_space.shape[0], rec_space.shape[1]).copy()\n #plot_grid(grid, 2)\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs // 4 * 2))\n\n plt.subplot(3, 3, 4)\n plt.imshow(np.rot90(rec_result_3), cmap='bone',\n vmin=mini,\n vmax=maxi)\n #grid=grid_points[time_itvs // 4*2].reshape(2, rec_space.shape[0], rec_space.shape[1]).copy()\n #plot_grid(grid, 2)\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs // 4 * 3))\n\n plt.subplot(3, 3, 5)\n plt.imshow(np.rot90(rec_result), cmap='bone',\n vmin=mini,\n vmax=maxi)\n\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs ))\n\n plt.subplot(3, 3, 6)\n plt.imshow(np.rot90(target), cmap='bone',\n vmin=mini,\n vmax=maxi)\n plt.axis('off')\n plt.colorbar()\n plt.title('Ground truth')\n\n\n\n plt.savefig(name, bbox_inches='tight')\n\n\ndef plot_result_grid(name,image_N0, grid_points):\n plt.figure()\n rec_result_1 = rec_space.element(image_N0[time_itvs // 4])\n rec_result_2 = rec_space.element(image_N0[time_itvs // 4 * 2])\n rec_result_3 = rec_space.element(image_N0[time_itvs // 4 * 3])\n rec_result = rec_space.element(image_N0[time_itvs])\n ##%%\n # Plot the results of interest\n plt.figure(2, figsize=(24, 24))\n #plt.clf()\n\n plt.subplot(3, 3, 1)\n plt.imshow(np.rot90(template), cmap='bone',\n vmin=mini,\n vmax=maxi)\n plt.axis('off')\n #plt.savefig(\"/home/chchen/SwedenWork_Chong/NumericalResults_S/LDDMM_results/J_V/template_J.png\", bbox_inches='tight')\n plt.colorbar()\n #plt.title('Trajectory from EllipseMvt with DeformationModulesODL/deform/vect_field_ellipse')\n\n plt.subplot(3, 3, 2)\n plt.imshow(np.rot90(rec_result_1), cmap='bone',\n vmin=mini,\n vmax=maxi)\n grid=grid_points[time_itvs // 4].reshape(2, space.shape[0], space.shape[1]).copy()\n plot_grid(grid, 5)\n\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs // 4))\n\n plt.subplot(3, 3, 3)\n plt.imshow(np.rot90(rec_result_2), cmap='bone',\n vmin=mini,\n vmax=maxi)\n grid=grid_points[time_itvs // 4].reshape(2, rec_space.shape[0], rec_space.shape[1]).copy()\n plot_grid(grid, 2)\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs // 4 * 2))\n\n plt.subplot(3, 3, 4)\n plt.imshow(np.rot90(rec_result_3), cmap='bone',\n vmin=mini,\n vmax=maxi)\n grid=grid_points[time_itvs // 4*2].reshape(2, rec_space.shape[0], rec_space.shape[1]).copy()\n plot_grid(grid, 2)\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs // 4 * 3))\n\n plt.subplot(3, 3, 5)\n plt.imshow(np.rot90(rec_result), cmap='bone',\n vmin=mini,\n vmax=maxi)\n grid=grid_points[time_itvs].reshape(2, space.shape[0], space.shape[1]).copy()\n plot_grid(grid, 5)\n\n plt.axis('off')\n plt.colorbar()\n plt.title('time_pts = {!r}'.format(time_itvs ))\n\n plt.subplot(3, 3, 6)\n plt.imshow(np.rot90(target), cmap='bone',\n vmin=mini,\n vmax=maxi)\n plt.axis('off')\n plt.colorbar()\n plt.title('Ground truth')\n\n\n\n plt.savefig(name, bbox_inches='tight')\n\n\n#\n#%% Gradient descent : initialisation and test\n\n\n#GD_init=Module.GDspace.element([[[-0.77478469, -9.85281818], -0.0*np.pi, [0.0,0.0], [1.0,0.0]]])\nGD_init=Module.GDspace.element([[[-1,0], -0.0*np.pi, [-1.77478469,-9.85281818], [1.2521,-9.85281818]]])\n\na_init = np.array([-1.77478469,-9.85281818])\nb_init = np.array([1.2521,-9.85281818])\n\nc_init = 0.5* (b_init + a_init)\n\nGD_init=Module.GDspace.element([[c_init, -0.0*np.pi, a_init, b_init]])\nCont_init=odl.ProductSpace(Module.Contspace,nb_time_point_int+1).zero()\n\n\nvect_field=Module.ComputeField(GD_init,Module.Contspace.one())\nvect_field.show('bis2')\n\n\nniter=500\neps = 0.01\n\nX=functional_mod.domain.element([GD_init,Cont_init].copy())\n\nvector_fields_list_init=energy_op_lddmm.domain.zero()\nvector_fields_list=vector_fields_list_init.copy()\n#%% Gradient descent : parameters\ndim=2\nattachment_term=attach_mod(X[0],X[1])\nenergy=attachment_term\nReg_mod=functional_mod.ComputeReg(X)\nprint(\" Initial , attachment term : {}, reg_mod = {}\".format(attachment_term,Reg_mod))\ngradGD=functional_mod.Module.GDspace.element()\ngradCont=odl.ProductSpace(functional_mod.Module.Contspace,nb_time_point_int+1).element()\n\nd_GD=functional_mod.Module.GDspace.zero()\nd_Cont=odl.ProductSpace(functional_mod.Module.Contspace,nb_time_point_int+1).zero()\nModulesList=Module.ModulesList\nNbMod=len(ModulesList)\ndelta=0.1\nepsmax=0.5\ndeltamin=0.1\ndeltaCont=0.1\ndeltaGD=space.cell_sides[0]\n# 0=SumTranslations, 1=affine, 2=scaling, 3=rotation, 4 = ellipsemvt\nTypes=[4]\n#energy=functional(X)+1\ninv_N=1/nb_time_point_int\nepsContmax=1\nepsGDmax=1\nepsCont=1\nepsGD_Pts=0.1\nepsGD_theta=0.1\nepsGD_c=0.1\nepsGD_ab=0.1\neps_vect_field=0.1\ncont=1\nspace_pts=template.space.points()\n\n\nenergy=attach_mod(X[0],X[1])\nReg_mod=functional_mod.ComputeReg(X)\nenergy_mod=Reg_mod+energy\n\n#%% Gradient descent : descent\nprint('Initial energy = {} '.format(energy_mod))\nfor k in range(niter):\n gradGD=functional_mod.Module.GDspace.zero()\n gradCont=odl.ProductSpace(functional_mod.Module.Contspace,nb_time_point_int+1).zero()\n\n\n #energy=attach_tot(vector_fields_list,X[0],X[1])\n #Reg_mod=functional_mod.ComputeReg(X)\n #energy_mod=Reg_mod+energy\n GD=ComputeGD_list(X[0],X[1]).copy()\n #print('k={} before vect field attachment term = {}, reg_mod={}'.format(k,energy,Reg_mod))\n # gradient with respect to vector field\n #grad_vect_field=grad_attach_vector_field(X[0],X[1])\n grad_vect_field=grad_attach_vector_fieldL2(X[0],X[1])\n # (1-lamb1) because of the gradient of the regularity term\n\n #GD=ComputeGD_mixt(vector_fields_list,X[0],X[1]).copy()\n\n #energy=attach_tot(vector_fields_list,X[0],X[1])\n #Reg_mod=functional_mod.ComputeReg(X)\n #energy_mod=Reg_mod+energy\n #print(' k={} after vect field attachment term = {}, reg_mod={}'.format(k,energy,Reg_mod))\n\n for i in range(NbMod):\n\n basisCont=ModulesList[i].basisCont.copy()\n dimCont=len(basisCont)\n #print('i = {}'.format(i))\n for iter_cont in range(dimCont):\n for t in range(nb_time_point_int):\n X_temp=X.copy()\n X_temp[1][t][i]+=deltaCont*basisCont[iter_cont]\n GD_diff=ComputeGD_list(X[0],X_temp[1]).copy()\n temp=0\n #print('t = {}'.format(t))\n for s in range(nb_time_point_int):\n # vec_temp is the derivative of the generated vector field at s with respect to h[t][iter_cont]\n vec_temp=( Module.ComputeField(GD_diff[s], X_temp[1][s]).copy()-Module.ComputeField(GD[s], X[1][s]).copy() )/deltaCont\n\n # It is necessary to interpolate in order to do the inner product\n vec_temp_interp=space.tangent_bundle.element(vec_temp).copy()\n\n temp+=inv_N*grad_vect_field[s].inner(vec_temp_interp)\n #print('s = {}'.format(s))\n\n #ATTENTION : WE SUPPOSE THAT THE DERIVATIVE OF THE COST\n # WITH RESPECT TO GD IS NULL\n temp+=lamb0*Module.CostGradCont(GD[t], X[1][t])[iter_cont]\n gradCont[t][i][iter_cont]+=temp\n\n\n\n\n\n ########### Case optimizing everything\n for i in range(NbMod):\n basisGD=ModulesList[i].basisGD.copy()\n dimGD=len(basisGD)\n\n for iter_gd in range(dimGD):\n X_temp=X.copy()\n X_temp[0][i]+=deltaGD*basisGD[iter_gd]\n GD_diff=ComputeGD_list(X_temp[0],X_temp[1]).copy()\n temp=0\n for s in range(nb_time_point_int):\n # vec_temp is the derivative of the generated vector field at s with respect to GD[iter_cont]\n vec_temp=( Module.ComputeField(GD_diff[s], X_temp[1][s]).copy()-Module.ComputeField(GD[s], X[1][s]).copy() )/deltaGD\n\n # It is necessary to interpolate in order to do the inner product\n vec_temp_interp=space.tangent_bundle.element(vec_temp).copy()\n #[vec_temp[u].interpolation(space_pts.T) for u in range(dim)]).copy()\n\n temp+=inv_N*grad_vect_field[s].inner(vec_temp_interp)\n gradGD[i]+=temp*basisGD[iter_gd]\n\n for ite in range(20):\n\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy=attach_mod(X_temp[0],X_temp[1])\n Reg_mod=functional_mod.ComputeReg(X_temp)\n energy_mod0=Reg_mod+energy\n\n X_temp=X.copy()\n X_temp[1]-=0.8*epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy=attach_tot(vector_fields_list,X_temp[0],X_temp[1])\n Reg_mod=functional_mod.ComputeReg(X_temp)\n energy_mod1=Reg_mod+energy\n\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=0.8*epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy=attach_tot(vector_fields_list,X_temp[0],X_temp[1])\n Reg_mod=functional_mod.ComputeReg(X_temp)\n energy_mod2=Reg_mod+energy\n\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=0.8*epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy=attach_mod(X_temp[0],X_temp[1])\n Reg_mod=functional_mod.ComputeReg(X_temp)\n energy_mod3=Reg_mod+energy\n\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=0.8*epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=0.8*epsGD_ab*gradGD[0][3]\n energy=attach_mod(X_temp[0],X_temp[1])\n Reg_mod=functional_mod.ComputeReg(X_temp)\n energy_mod4=Reg_mod+energy\n\n\n\n print('energy0 = {}, energy1 = {}, energy2 = {}, energy3 = {} '.format(energy_mod0,energy_mod1,energy_mod2,energy_mod3) )\n if (energy_mod0 <= energy_mod1 and energy_mod0 <= energy_mod2 and energy_mod0 <= energy_mod3 and energy_mod0 <= energy_mod4):\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy_mod_temp=energy_mod0\n elif (energy_mod1 <= energy_mod0 and energy_mod1 <= energy_mod2 and energy_mod1 <= energy_mod3 and energy_mod1 <= energy_mod4):\n X_temp=X.copy()\n X_temp[1]-=0.8*epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy_mod_temp=energy_mod1\n epsCont*=0.8\n elif (energy_mod2 <= energy_mod0 and energy_mod2 <= energy_mod1 and energy_mod2 <= energy_mod3 and energy_mod2 <= energy_mod4):\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=0.8*epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy_mod_temp=energy_mod2\n epsGD_c*=0.8\n elif (energy_mod3 <= energy_mod0 and energy_mod3 <= energy_mod1 and energy_mod3 <= energy_mod3 and energy_mod3 <= energy_mod4):\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=0.8*epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy_mod_temp=energy_mod3\n epsGD_theta*=0.8\n else:\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=0.8*epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=0.8*epsGD_ab*gradGD[0][3]\n energy_mod_temp=energy_mod4\n epsGD_ab*=0.8\n\n\n\n if (energy_mod_temp < energy_mod):\n X=X_temp.copy()\n energy_mod=energy_mod_temp\n print('k={} , energy = {} '.format(k,energy_mod_temp))\n print('GD = {}'.format(X[0]))\n epsCont*=1.2\n epsGD_c*=1.2\n epsGD_theta*=1.2\n epsGD_ab*=1.2\n break\n else:\n epsCont*=0.8\n epsGD_c*=0.8\n epsGD_theta*=0.8\n epsGD_ab*=0.8\n\n if (ite==19):\n print('No possible to descent')\n break\n\n if epsGD_Pts>epsmax:\n epsGD_Pts=epsmax\n\n if epsGD_theta>epsmax:\n epsGD_theta=epsmax\n\n print('epsGDc= {} ,epsGDtheta= {}, epsGD_ab ={}, epsCont = {}'.format(epsGD_c,epsGD_theta,epsGD_ab,epsCont))\n #vector_fields_list=((1-eps_vect_field*lamb1)*vector_fields_list-eps_vect_field*grad_vect_field ).copy()\n#\n\n\n#%%\n\n ########### Case optimizing only control\n for ite in range(20):\n X_temp=X.copy()\n X_temp[1]-=epsCont*gradCont.copy()\n X_temp[0][0][0]-=epsGD_c*gradGD[0][0]\n X_temp[0][0][1]-=epsGD_theta*gradGD[0][1]\n X_temp[0][0][2]-=epsGD_ab*gradGD[0][2]\n X_temp[0][0][3]-=epsGD_ab*gradGD[0][3]\n energy=attach_mod(X_temp[0],X_temp[1])\n Reg_mod=functional_mod.ComputeReg(X_temp)\n energy_mod0=Reg_mod+energy\n\n\n\n\n energy_mod_temp=energy_mod0\n\n\n print('energy0 = {}'.format(energy_mod0) )\n\n\n if (energy_mod_temp < energy_mod):\n X=X_temp.copy()\n energy_mod=energy_mod_temp\n print('k={} , energy = {} '.format(k,energy_mod_temp))\n print('GD = {}'.format(X[0]))\n epsCont*=1.2\n epsGD_c*=1.2\n epsGD_theta*=1.2\n epsGD_ab*=1.2\n break\n else:\n epsCont*=0.8\n epsGD_c*=0.8\n epsGD_theta*=0.8\n epsGD_ab*=0.8\n\n if (ite==19):\n print('No possible to descent')\n break\n#\n\n#%% See result\n\nvect_field_list_mod=vect_field_list(X[0],X[1])\nI_t=TemporalAttachmentModulesGeom.ShootTemplateFromVectorFields(vect_field_list_mod, template)\n\nname='/home/bgris/Results/DeformationModules/testEstimation/Rotation/EstimatedTrajectory_restrictedrotation'\nname += 'GD_optimized'\n#name+= '_sigma_2_INDIRECT_num_angle_10_initial_epsCont_0_01_fixed_GD'\n#name+= 'sigma_0_3__nbtrans_560_nbint_10'\nimage_N0=I_t\nplot_result(name,image_N0)\n\n#%% Save X for only one module !\nname_Cont = name + '_Controls'\nnp.savetxt(name_Cont, np.array(X[1]))\n\nname_GD_c = name + '_GD_c'\nnp.savetxt(name_GD_c, np.array(X[0][0][0]))\n\nname_GD_theta = name + '_GD_theta'\nnp.savetxt(name_GD_theta, np.array(X[0][0][1]))\n\nname_GD_a = name + '_GD_a'\nnp.savetxt(name_GD_a, np.array(X[0][0][2]))\n\nname_GD_b = name + '_GD_b'\nnp.savetxt(name_GD_b, np.array(X[0][0][3]))\n\n\n#%% Load X\nCont = np.loadtxt(name + '_Controls')\nc= np.loadtxt(name + '_GD_c')\ntheta= np.loadtxt(name + '_GD_theta')\na= np.loadtxt(name + '_GD_a')\nb= np.loadtxt(name + '_GD_b')\nGD_load = functional_mod.Module.GDspace.element([[c, theta, a, b]])\nCont_list = [[Cont[i]] for i in range(len(Cont))]\nCont_load = odl.ProductSpace(functional_mod.Module.Contspace,nb_time_point_int+1).element(Cont_list)\nX_load = [GD_load, Cont_load]\n#%% See result with grid\n\ngrid_points=compute_grid_deformation_list(vect_field_list_mod, 1/nb_time_point_int, template.space.points().T)\n\nfor t in range(nb_time_point_int + 1):\n plt.figure()\n #t = nb_time_point_int\n I_t_Y[t].show('First')\n grid=grid_points[t].reshape(2, space.shape[0], space.shape[1]).copy()\n plot_grid(grid, 5)\n\n#\nplt.savefig(name + 'finalgrid')\n\n#%%\nimport copy\nY = copy.deepcopy(X)\nY[1] *= 1.2\n#Y[0] = GD_init.copy()\nY[0][0][2][0] = -Y[0][0][3][0]\nY[0][0][0][0] = 0.0\n\nvect_field_list_mod=vect_field_list(Y[0],Y[1])\nI_t_Y=TemporalAttachmentModulesGeom.ShootTemplateFromVectorFields(vect_field_list_mod, template)\n\nname='/home/bgris/Results/DeformationModules/testEstimation/Rotation/EstimatedTrajectory_restrictedrotation'\n#name+= '_sigma_2_INDIRECT_num_angle_10_initial_epsCont_0_01_fixed_GD'\nname+= 'sigma_0_3__nbtrans_560_nbint_10_test'\nimage_N0=I_t\nplot_result(name,image_N0)\n\n\n\n\nfor t in range(nb_time_point_int+1):\n #t=nb_time_point_int\n vect_field_list_mod[t].show('Y vect field time {}'.format(t+1))\n #I_t[t].show(' time {}'.format(t+1))\n#\n\npas = 40\npoints = space.points()\nGD_list = ComputeGD_list(Y[0], Y[1])\nfor t in range(nb_time_point_int+1):\n #t=nb_time_point_int\n #vect_field_list_mod[t].show('Y vect field time {}'.format(t+1))\n I_t_Y[t].show('Y time {}'.format(t+1))\n #plt.quiver(points.T[0][::pas],points.T[1][::pas],vect_field_list_mod[t][0][::pas],vect_field_list_mod[t][1][::pas],color='r')\n plt.plot(GD_list[t][0][2][0], GD_list[t][0][2][1], 'xb')\n plt.plot(GD_list[t][0][3][0], GD_list[t][0][3][1], 'xb')\n\n#\n\nt=9\nvect_field_list_mod[t].show('Y vect field time {}'.format(t+1))\n\n\nt=0\nI_t[t].show('Y time {}'.format(t+1))\nplt.plot(GD_init[0][2][0], GD_init[0][2][1], 'xr')\nplt.plot(GD_init[0][3][0], GD_init[0][3][1], 'xb')\n\n\ncentre_gen = np.array([-0.86492676, -9.77465868])\n\ndec_ab = np.array([0, 0.1])\ndec_a = np.array([0.5, 0.0])\ndec_b = np.array([-0.5, 0.0])\na_init = np.array([-1.77478469,-9.85281818]) #+ dec_ab + dec_a\na_init = np.array([-1, centre_gen[1]])\nb_init = np.array([-a_init[0], a_init[1]])\n#b_init = np.array([1.2521,-9.85281818]) + dec_ab + dec_b\n\nc_init = np.array([-centre_gen[0], 0.0]) + dec_ab\n#c_init = 0.5* (b_init + a_init)\n\nGD_init=Module.GDspace.element([[c_init, -0.0*np.pi, a_init, b_init]])\n\n\nY[0] = GD_init\nY[1] = 10*odl.ProductSpace(functional_mod.Module.Contspace,nb_time_point_int+1).one()\nvect_field_list_mod=vect_field_list(Y[0],Y[1])\nI_t_Y=TemporalAttachmentModulesGeom.ShootTemplateFromVectorFields(vect_field_list_mod, template)\n\n\n","sub_path":"example/MatchingGivenModule.py","file_name":"MatchingGivenModule.py","file_ext":"py","file_size_in_byte":34272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"270264756","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 6 11:15:26 2018\n\n@author: Imaris\n\"\"\"\n\nfrom brian2 import *\nimport numpy\nimport random \nimport itertools\n\ndefaultclock.dt = 0.01*ms\n\nCm = 1*uF # /cm**2\nIapp = 0*uA\ngL = 0.1*msiemens\nEL = -65*mV\nENa = 55*mV\nEK = -90*mV\ngNa = 35*msiemens\ngK = 52*msiemens\ntausyn = 2*ms\ntaugsyn = 10*ms\n\neqs = '''\ndv/dt = (-gNa*m**3*h*(v-ENa)-gK*n**4*(v-EK)-gL*(v-EL)+Iapp - Isyn - gIsyn)/Cm : volt\nIsyn = gsyn*(v - ENa) : amp\ndgsyn/dt = -gsyn/tausyn: siemens\ngIsyn = esyn*(v - EK) : amp\ndesyn/dt = -esyn/taugsyn : siemens\nm = alpha_m/(alpha_m+beta_m) : 1\nalpha_m = -0.1/mV*(v+35*mV)/(exp(-0.1/mV*(v+35*mV))-1)/ms : Hz\nbeta_m = 4*exp(-(v+60*mV)/(18*mV))/ms : Hz\ndh/dt = 5*(alpha_h*(1-h)-beta_h*h) : 1\nalpha_h = 0.07*exp(-(v+58*mV)/(20*mV))/ms : Hz\nbeta_h = 1./(exp(-0.1/mV*(v+28*mV))+1)/ms : Hz\ndn/dt = 5*(alpha_n*(1-n)-beta_n*n) : 1\nalpha_n = -0.01/mV*(v+34*mV)/(exp(-0.1/mV*(v+34*mV))-1)/ms : Hz\nbeta_n = 0.125*exp(-(v+44*mV)/(80*mV))/ms : Hz\n'''\n#choose a multiple of 3 please.\nrt = 300\ngap = 10 #2 gaps\nskip = 100\ntotal_rt = rt + (gap*2) + skip\n#Experiment: all in one run: A1 - 1000, choose 300, every 5/50? ms diff group of 50 fire.\n# A2 - same 300 \" \"\n# B1 - diff 300 \" \"\n#neuron groups-----------------------------------------------------------------\nn1 = NeuronGroup(300, eqs, threshold = 'v > -40*mV', refractory = 'v >= -40*mV', method='exponential_euler')\nn1.v = -80*mV\nn1.h = 1\n\nn2 = NeuronGroup(300, eqs, threshold = 'v > -40*mV', refractory = 'v >= -40*mV', method='exponential_euler')\nn2.v = -80*mV\nn2.h = 1\n\nn3 = NeuronGroup(300, eqs, threshold = 'v > -40*mV', refractory = 'v >= -40*mV', method='exponential_euler')\nn3.v = -80*mV\nn3.h = 1\n\n#inhibitory group--------------------------------------------------------------\nI = NeuronGroup(100, eqs, threshold = 'v > -40*mV', refractory = 'v >= -40*mV',method='exponential_euler')\nwa = (2000)#inhibitory\nwe = (2400)#excitatory\n#firing------------------------------------------------------------------------\n#next time: change this to spike generator group. 1000, choose 300, each time, randomly choose 50 of 300 to fire every 5 ms.\n#PG = PoissonGroup(1000, 1*Hz)\n\n#==============================================================================\ntime_break1 = int((rt)/3)\ntime_break2 = time_break1 * 2\n#------------------------------A1----------------------------------------------\nind = list(random.sample(range(0, 1000), 100))\n\n\nt = []\ntemp = []\nfor idx in range(skip, time_break1 + skip, 5):\n temp = [idx] * 50\n for idx2 in temp:\n t.append(idx2)\n\nind2 = []\nfor idx in range(skip, time_break1 + skip, 5):\n temp = random.sample(ind, 50)\n for idx2 in temp:\n ind2.append(idx2)\n \n#print('ind1: %s' %len(ind2))\n#------------------------------A2----------------------------------------------\n \nfor idx in range(time_break1 + gap + skip, time_break2 + gap + skip, 5):\n temp = [idx + gap] * 50\n for idx2 in temp:\n t.append(idx2)\n\nfor idx in range(time_break1 + gap + skip, time_break2 + gap + skip, 5):\n temp = random.sample(ind, 50)\n for idx2 in temp:\n ind2.append(idx2)\n \n#print('ind2: %s' %len(ind2))\n#------------------------------B1----------------------------------------------\nind_B1 = list(random.sample(range(0, 1000), 100))\n\n\n\nfor idx in range(time_break2 + (gap*2) + skip, total_rt, 5):\n temp = [idx + (gap*2)] * 50\n for idx2 in temp:\n t.append(idx2)\n\nfor idx in range(time_break2 + (gap*2) + skip, total_rt, 5):\n temp = random.sample(ind_B1, 50)\n for idx2 in temp:\n ind2.append(idx2)\n\n#print('ind3: %s' %len(ind2))\n#print('time3: %s' %len(t))\n#print('ind: %s' %ind2)\n#print('time: %s' %t)\n\nindicies = numpy.array(ind2)\ntimes = numpy.array(t) * ms\nPG = SpikeGeneratorGroup(1000, indicies, times) \n#==============================================================================\n\n#firing + neuron group---------------------------------------------------------\nS1 = Synapses(PG, n1, on_pre='gsyn += we*nsiemens')\nS1.connect(p = .15)\n\nS2 = Synapses(PG, n2, on_pre='gsyn += we*nsiemens')\nS2.connect(p = .15)\n\nS3 = Synapses(PG, n3, on_pre='gsyn += we*nsiemens')\nS3.connect(p = .15)\n\n#neuron group + inhibitory-----------------------------------------------------\nS4 = Synapses(n1, I, on_pre='gsyn += we*nsiemens')\nS4.connect(p = .21)\n\nS5 = Synapses(n2, I, on_pre='gsyn += we*nsiemens')\nS5.connect(p = .11)\n\n#S6 = Synapses(n3, I, on_pre='gsyn += wa*nsiemens')\n#S6.connect(p = .1)\n\n#inhibitoty + neuron group-----------------------------------------------------\nS7 = Synapses(I, n1, on_pre='esyn += wa*nsiemens')\nS7.connect(p = .21)\n\nS8 = Synapses(I, n2, on_pre='esyn += wa*nsiemens')\nS8.connect(p = .11)\n\n#S9 = Synapses(I, n3, on_pre='esyn += wa*nsiemens')\n#S9.connect(p = .1)\n\n#spikemonitor------------------------------------------------------------------\nM1 = SpikeMonitor(n1)\nM2 = SpikeMonitor(n2)\nM3 = SpikeMonitor(n3)\n\n#stateMonitor------------------------------------------------------------------\nM4 = StateMonitor(n1, True, record = True)\n\n#------------------------------------------------------------------------------\nrun(total_rt*ms)\n\n#==============================================================================\n#also next time ignore first few ms because many fire for some weird reason....\nplt.figure(0)\nplt.plot(M1.t/ms, M1.i, '.k')\nplt.show\nxlabel('Time (ms)')\nylabel('Neuron index')\n\nplt.figure(1)\nplt.plot(M2.t/ms, M2.i, '.k')\nplt.show\nxlabel('Time (ms)')\nylabel('Neuron index')\n\nplt.figure(2)\nplt.plot(M3.t/ms, M3.i, '.k')\nplt.show\nxlabel('Time (ms)')\nylabel('Neuron index')\n#==============================================================================\n#prints out the total neurons fired in a group, average firing rate of each neuron in the group, and standard deviation.\ndef neuro_spike_info(M, n):\n n_idx = {}\n \n for i in range(0, 300):\n n_idx[i] = 0\n \n for j in M.i:\n n_idx[j] += 1\n \n list1 = []\n \n for k in n_idx:\n list1.append(n_idx[k])\n \n average = numpy.mean(list1)\n std = numpy.std(list1)\n \n total = 0\n for l in n_idx:\n if n_idx[l] > 0:\n total += n_idx[l]\n print('total neurons fired in group %s: %d' %(n, total))\n print('average firing rate: %d' %average)\n print('std: %d' %std)\n\nneuro_spike_info(M1, 1)\nneuro_spike_info(M2, 2)\nneuro_spike_info(M3, 3)\n#==============================================================================\ndef sort_spikes(M, n):\n\n list_A1 = []\n list_A2 = []\n list_B1 = []\n\n for i in range(0, 300):\n list_A1.append(0.0)\n list_A2.append(0.0)\n list_B1.append(0.0)\n \n\n for i, t in itertools.zip_longest(M.i, M.t):\n if t < (time_break1 + gap + skip)*ms:\n list_A1[i] += 1.0\n elif t >= (time_break2 + (gap*2) + skip)*ms:\n list_B1[i] += 1.0\n else:\n list_A2[i] += 1.0\n \n \n total_A1 = sum(list_A1)\n\n percent_A1 = []\n\n for a1 in list_A1:\n percent_A1.append(a1/total_A1)\n\n occur_A2 = []\n occur_B1 = []\n\n for l_a2, l_b1, p_a1 in zip(list_A2, list_B1, percent_A1):\n occur_A2.append(l_a2 * p_a1)\n occur_B1.append(l_b1 * p_a1) \n \n print('--------For Neuron Group: %d--------' %n)\n print('A1-A2: %.2f' %sum(occur_A2))\n print('A1-B1: %.2f' %sum(occur_B1))\n print('List_A1 total: %d' %sum(list_A1))\n print('List_A2 total: %d' %sum(list_A2))\n print('List_B1 total: %d' %sum(list_B1))\n \n\nsort_spikes(M1, 1)\nsort_spikes(M2, 2)\nsort_spikes(M3, 3)\n\n#SSE===========================================================================\ndef sum_square_err(M, n):\n list_A1 = []\n list_A2 = []\n list_B1 = []\n\n for i in range(0, 300):\n list_A1.append(0.0)\n list_A2.append(0.0)\n list_B1.append(0.0)\n \n for i, t in itertools.zip_longest(M.i, M.t):\n if t < (time_break1 + gap + skip)*ms:\n list_A1[i] += 1.0\n elif t >= (time_break2 + (gap*2) + skip)*ms:\n list_B1[i] += 1.0\n else:\n list_A2[i] += 1.0\n \n total_A1 = sum(list_A1)\n total_A2 = sum(list_A2)\n total_B1 = sum(list_B1)\n\n percent_A1 = []\n percent_A2 = []\n percent_B1 = []\n\n for a1, a2, b1 in zip(list_A1, list_A2, list_B1):\n percent_A1.append(a1/total_A1)\n percent_A2.append(a2/total_A2)\n percent_B1.append(b1/total_B1)\n \n SSE_A2 = []\n SSE_B1 = []\n \n for p_a1, p_a2, p_b1 in zip(percent_A1, percent_A2, percent_B1):\n SSE_A2.append((p_a1 - p_a2)**2)\n SSE_B1.append((p_a1 - p_b1)**2)\n \n print('--------For Neuron Group: %d--------' %n)\n print('SSE A1-A2: %.2f' %sum(SSE_A2))\n print('SSE A1-B1: %.2f' %sum(SSE_B1))\n \nsum_square_err(M1, 1) \nsum_square_err(M2, 2) \nsum_square_err(M3, 3) \n\nshow()","sub_path":"dg.py","file_name":"dg.py","file_ext":"py","file_size_in_byte":8971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"325923873","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass CloudServiceConfiguration(Model):\n \"\"\"The configuration for nodes in a pool based on the Azure Cloud Services\n platform.\n\n :param os_family: The Azure Guest OS family to be installed on the\n virtual machines in the pool.\n :type os_family: str\n :param target_os_version: The Azure Guest OS version to be installed on\n the virtual machines in the pool. The default value is * which specifies\n the latest operating system version for the specified OS family.\n :type target_os_version: str\n :param current_os_version: The Azure Guest OS Version currently installed\n on the virtual machines in the pool. This may differ from\n targetOSVersion if the pool state is Upgrading.\n :type current_os_version: str\n \"\"\" \n\n _validation = {\n 'os_family': {'required': True},\n }\n\n _attribute_map = {\n 'os_family': {'key': 'osFamily', 'type': 'str'},\n 'target_os_version': {'key': 'targetOSVersion', 'type': 'str'},\n 'current_os_version': {'key': 'currentOSVersion', 'type': 'str'},\n }\n\n def __init__(self, os_family, target_os_version=None, current_os_version=None):\n self.os_family = os_family\n self.target_os_version = target_os_version\n self.current_os_version = current_os_version\n","sub_path":"azure-batch/azure/batch/models/cloud_service_configuration.py","file_name":"cloud_service_configuration.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"327950940","text":"import pandas as pd\nimport tensorflow as tf\nimport numpy as np\nimport itertools as it\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import SGDRegressor\nfrom sklearn.preprocessing import normalize\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n# concatenate the separate files\ndir = './data2/'\ndf1 = pd.read_csv(dir+'DNNRNN_testing_medusa_Media.csv')\ndf2 = pd.read_csv(dir+'DNNRNN_testing_medusa_webSearch.csv')\ndf3 = pd.read_csv(dir+'DNNRNN_testing_medusa.csv')\n\ndf = pd.concat([df1, df2, df3], axis=0, ignore_index=True)\ndf = df.dropna()\n\n# these are relatively uninformative, as seen in linear regression\nlabels_to_drop = [\n 'timeStamp',\n 'systemTime1Sec',\n 'ioWaitTime1Sec',\n 'percentVirtualMemory',\n 'networkBytesSent',\n 'networkBytesReceived',\n 'networkConnections',\n 'systemCalls',\n 'cacheMemoryUsedBytes',\n 'swapMemoryUsedBytes',\n 'swapMemoryOutBytes',\n 'swapMemoryInBytes',\n 'ioReadBytes',\n 'ioWriteBytes',\n 'predictedPower'\n]\ndf = df.drop(columns=labels_to_drop, axis=1)\n\n# shuffle dataframe\ndf = df.sample(frac = 1)\n\n# split into training and testing data\ntraining_data = df.iloc[:int(0.85*len(df)), :]\ntesting_data = df.iloc[int(0.85*len(df)):, :]\n\n# training target and features\ntrn_target = training_data.pop('whatsupPower')\ntrn_features = training_data.values\n\n# normalized training features\ntrn_norm_features = MinMaxScaler().fit_transform(trn_features)\n\n# ? is just using trn_target the same as trn_target.values in this case\n\n# training dataset\ntrn = tf.data.Dataset.from_tensor_slices((trn_norm_features, trn_target))\n\n# create validation dataset and edit size of training dataset\ntrn_ds_size = int(len(training_data)*0.7)\nsample_tst_ds_size = int(len(training_data)*0.15)\n\ntrn_ds = trn.take(trn_ds_size)\nsample_tst_ds = trn.skip(trn_ds_size)\nval_ds = sample_tst_ds.skip(sample_tst_ds_size)\nsample_tst_ds = sample_tst_ds.take(sample_tst_ds_size)\n\n# build the model\n# model = keras.Sequential(\n# [\n# # layers.Dense(units=64, input_dim=9, activation='relu', name='layer1'),\n# # layers.Dense(units=64, activation='relu', name='layer2'),\n# # layers.Dense(units=1, name='end'),\n#\n# layers.Dense(units=32, activation='relu'),\n# layers.Dense(units=16, activation='relu'),\n# layers.Dense(units=32, activation='relu'),\n# layers.Dense(units=8,activation='relu'),\n# layers.Dense(1)\n# ]\n# )\n\n# model.compile(\n# optimizer=tf.keras.optimizers.Adam(learning_rate=0.00001),\n# loss='mean_absolute_error',\n# metrics=['mean_absolute_error'],\n# )\n\n# ALTERNATE METHOD\n# model.compile(\n# optimizer='adam',\n# loss=tf.keras.losses.MeanSquaredError(reduction=\"auto\", name=\"mean_squared_error\"),\n# metrics=['mse']\n# )\n\n# model.fit(\n# x=trn_ds,\n# epochs=200,\n# validation_data=val_ds,\n# verbose=1,\n# callbacks=[tf.keras.callbacks.EarlyStopping(patience=10)],\n# shuffle=False,\n# )\n\n# evaluate the model\n# model.evaluate(\n# x=sample_tst_ds,\n# verbose=1,\n# callbacks=[tf.keras.callbacks.EarlyStopping(patience=10)],\n# )\n\n# testing target and features\ntst_target = testing_data.pop('whatsupPower')\ntst_features = testing_data.values\n\n# testing normalized features\ntst_norm_features = MinMaxScaler().fit_transform(tst_features)\n\n# testing dataset\ntst_ds = tf.data.Dataset.from_tensor_slices((tst_norm_features, tst_target))\n\n# save the current model and delete it, reinstantiating later with the saved weights\n# model.save(\n# filepath='/tmp/DNNRNN_testing_medusa01',\n# )\n# del model\n\n# reinstantiate saved weights\nmodel = keras.models.load_model('/tmp/DNNRNN_testing_medusa01')\n\n# make predictions on test values\npredictions = model.predict(\n x=tst_ds,\n verbose=1,\n)\n\nactual_values = tst_target.values.tolist()\npredicted_values = list(it.chain.from_iterable(predictions.tolist()))\n\ntotal = []\ntotal.extend(actual_values)\ntotal.extend(predicted_values)\nmax_val = max(total)\n\nax = plt.axes()\nax.set_xlim([0, max_val+10])\nax.set_ylim([0, max_val+10])\n\nfor index, a in enumerate(actual_values):\n offset = abs(a - predicted_values[index])\n plt.scatter(a, predicted_values[index], c='red')\n\nplt.title('Predicted and Actual Energy Consumption in Watts')\nplt.xlabel('ACTUAL VALUE')\nplt.ylabel('PREDICTED VALUE')\nplt.legend()\nplt.show()\n\n\n# # REGRESSION TESTING\ntarget = data.pop('Wattage') #y\nfeatures =data.values #X\n#\n#\n# #features = data[['CPU_Freq']]\n#\n# # alt\n#target = data['Wattage']\n# features = data[['CPU_Freq','CPU_Util','Num_Proc','Num_Apps']]\n#\n#linear_regression = LinearRegression()\n# linear_regression.fit(features, target)\n# y_pred = linear_regression.predict(features)\n# LR_ERROR = mean_squared_error(target, y_pred)\n# print(f'LINEAR REGRESSION ERROR IS {LR_ERROR}')\n# plt.title('Wattage Predictions')\n# plt.plot(target, color='black', linewidth=2.0, label='Actual Wattage')\n# plt.plot(y_pred, color='red', alpha=0.85, label='Predicted Wattage Li')\n#\n# # Normalizing Does Nothing\n# #linear_regression = LinearRegression(normalize=True)\n# #linear_regression.fit(features, target)\n# #y_pred = linear_regression.predict(features)\n# #plt.plot(y_pred, color='blue', alpha=0.75, label='Normalized Predicted Wattage')\n#\n# elastic_regression = ElasticNet()\n# elastic_regression.fit(features, target)\n# y_pred = elastic_regression.predict(features)\n# plt.plot(y_pred, color='blue', alpha=0.85, label='Predicted Wattage E')\n#\n# lasso_regression = Lasso(tol=1e-2)\n# lasso_regression.fit(features, target)\n# y_pred = lasso_regression.predict(features)\n# plt.plot(y_pred, color='green', alpha=0.85, label='Predicted Wattage La')\n#\n# features = normalize(features)\n# sgd_regression = SGDRegressor(penalty='l1', max_iter=3000, learning_rate='adaptive', alpha=0.00001, verbose=1, shuffle=False)\n# sgd_regression.fit(features, target)\n# y_pred = sgd_regression.predict(features)\n# plt.plot(y_pred, color='cyan', alpha=0.85, label='Predicted Wattage SGD')\n#\n# plt.legend()\n# plt.show()\n#\n# #ERROR = mean_squared_error(targets, y_pred)\n\n\n# NN TESTING\n#file_path = 'data/cleaned_1+2.npy'\nfile_path = 'data/cleaned_02.npy'\narr = np.load(file=file_path)\n\ndata = pd.DataFrame(data=arr, columns=['CPU_Freq','CPU_Util','Num_Proc','Num_Apps','Wattage'])\n\n\n\n\n# #target = data.pop('Wattage')\n# #normed_data = pd.DataFrame(MinMaxScaler().fit_transform(data), columns=['CPU_Freq','CPU_Util','Num_Proc','Num_Apps','Wattage'])\n# #print(normed_data.shape)\n#\n# #target = data.pop('Wattage')\n# #print(data.values)\n# data = MinMaxScaler().fit_transform(data.values).reshape(len(data),5)\n# print(data[:,:4].shape)\n# print(data[:, -1].reshape(-1,1).shape)\n# dataset = tf.data.Dataset.from_tensor_slices((data[:,:4], data[:,-1].reshape(-1,1)))\n# #dataset = dataset.shuffle(buffer_size=int(len(data)*0.7), seed=1234, reshuffle_each_iteration=True)\n#\n# train_size = int(len(data)*0.7)\n# test_size = int(len(data)*0.15)\n# train_dataset = dataset.take(train_size)\n# test_dataset = dataset.skip(train_size)\n# val_dataset = test_dataset.skip(test_size)\n# test_dataset = test_dataset.take(test_size)\n#\n# model = keras.Sequential(\n# [\n# layers.Dense(units=32, activation='relu', name='layer1'),\n# layers.Dense(units=64, activation='relu', name='layer2'),\n# layers.Dense(units=1, name='end'),\n# ]\n# )\n#\n# model.compile(\n# optimizer='adam',\n# loss='mse',#tf.keras.losses.MeanSquaredError(reduction=\"auto\", name=\"mean_squared_error\"),\n# metrics=['mse']\n# )\n#\n#\n# model.fit(\n# x=train_dataset,\n# epochs=20,\n# validation_data=val_dataset,\n# verbose=1,\n# callbacks=[tf.keras.callbacks.EarlyStopping(patience=5)],\n# shuffle=False,\n# )\n#\n# model.evaluate(\n# x=test_dataset,\n# verbose=1,\n# callbacks=[tf.keras.callbacks.EarlyStopping(patience=5)],\n# )\n#\n# model.save(\n# filepath='/tmp/trained_on_cleaned_02',\n# )\n# del model\n#\n# model = keras.models.load_model('/tmp/trained_on_cleaned_02')\n#\n# file_path = 'data/cleaned_1+2.npy'\n# arr = np.load(file=file_path)\n# data = pd.DataFrame(data=arr, columns=['CPU_Freq','CPU_Util','Num_Proc','Num_Apps','Wattage'])\n# x = data.pop('Wattage')\n# y = data.values\n#\n# #actual = data['Wattage']\n# #print(f'UNSCALED ACTUAL: {actual}')\n# #data = MinMaxScaler().fit_transform(data.values).reshape(len(data),5)\n# dataset = tf.data.Dataset.from_tensor_slices((y, x))\n#\n# predictions = model.predict(\n# x=dataset,\n# verbose=1,\n# )\n#\n# #actual_vals = data[:,-1].reshape(-1,1)\n# #print(f'RESCALED ACTUAL: {actual_vals}')\n#\n# plt.plot(x, color='red', label='Scaled Actual')\n# plt.plot(predictions, color='blue', label='Scaled Predictions')\n# plt.legend()\n# plt.show()\n","sub_path":"energy_usage/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":8880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"265988277","text":"# author:2632158294@qq.com\n# github:https://github.com/PyCN/algorithm/tree/master/leetcode/38\n\nclass Solution:\n def countAndSay(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n res = ['1']\n for i in range(n - 1): res = self.build(res)\n return ''.join(res)\n\n def build(self, s):\n count, res = 1, []\n for i in range(1, len(s)):\n if s[i] != s[i - 1]:\n res.extend([str(count), s[i - 1]])\n count = 1\n else:\n count += 1\n res.extend([str(count), s[len(s) - 1]])\n return res\n","sub_path":"leetcode/38/hduyyg.py","file_name":"hduyyg.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"466022972","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 30 11:57:51 2017\n\n@author: suny2\n\"\"\"\nimport os\nimport time\n\nimport numpy as np\nimport scipy.io as sio\nimport scipy.sparse.linalg as ssl\n\nfrom util_shared import set_base_indent_level, iprint, get_time_diff\n\n\n# ----------------------------------------------------------------------------\n\n\ndef get_word_idx(filename, skip_header=False, sep=\"\\t\"):\n \"\"\"Load input data and build lookup word to w_id and list of frequencies.\n\n :param filename: input filename for CSV file with w_id, word, frequency\n :param skip_header: whether to skip a possible header in filename (Default value = False)\n :param sep: column separator (Default value = \"\\t\")\n :returns: tuple: lookup word2w_id and frequencies for each word\n\n \"\"\"\n vocab2id = dict()\n # id2freq = dict()\n freqlist = list()\n\n # assume ordered, w_id asc; and no duplicates\n with open(filename, \"r\", encoding=\"utf-8\") as fid:\n if skip_header:\n fid.readline()\n for line in fid:\n line = line.strip(\"\\n\").split(sep)\n\n w_id = int(line[0])\n word = line[1].strip()\n freq = int(line[2])\n\n # this can silently ignore duplicate words ... so:\n if word in vocab2id:\n iprint(\n \"! word duplicate: {}, ids: {},{}\".format(\n word, vocab2id[word], w_id\n )\n )\n continue\n\n vocab2id[word] = w_id\n\n # id2freq[w_id] = freq\n freqlist.append(freq)\n\n freqlist = np.array(freqlist)\n\n # if it fails, you have to modify manually ...\n # assert freqlist.shape[0] != len(vocab2id), \"duplicate words?\"\n\n return vocab2id, freqlist\n\n\ndef get_cum_cooccur(filename, vocab2id, skip_header=True, sep=\"\\t\"):\n \"\"\"Build cummulative cooccurrence matrix from CSV data file.\n\n :param filename: input filename of yearly cooccurrences\n :param vocab2id: lookup word to w_id\n :param skip_header: whether to skip a possible header in filename (Default value = True)\n :param sep: column separator (Default value = \"\\t\")\n :returns: matrix with cooccurrence, sparse (but dense object)\n\n \"\"\"\n num_words = len(vocab2id.keys())\n cooccur = np.zeros((num_words, num_words))\n\n with open(filename, \"r\", encoding=\"utf-8\") as fid:\n if skip_header:\n fid.readline()\n\n num_err = 0\n for ln, line in enumerate(fid, 1):\n # if ln % 100000 == 0:\n # iprint(ln / (41709765.0))\n\n word1, word2, counts = line.strip(\"\\n\").split(sep, 2)\n\n try:\n w1_id = vocab2id[word1]\n w2_id = vocab2id[word2]\n except KeyError as ex:\n num_err += 1\n if num_err < 10:\n iprint(\"! line: {} - {}\".format(ln, ex))\n\n if w1_id == w2_id:\n iprint(\"! word-pair same?: '{}', '{}'\".format(w1_id, w2_id))\n # continue\n\n for count in counts.split(\",\"):\n if not count.strip():\n continue\n cooccur[w1_id, w2_id] += int(count)\n # cooccur[w2_id, w1_id] += int(count)\n\n iprint(\"! {} errors.\".format(num_err))\n\n return cooccur\n\n\ndef build_static_embs(cooccur, freq, rank=50, debug=False):\n \"\"\"Build eigen(values/vectors) embeddings.\n See: SMOP (not so good), converted from matlab. Hopefully works ...\n\n :param cooccur: cooccurence matrix\n :param freq: vector of frequencies\n :param rank: rank/dimension for reduction? number of eigenvalues/eigenvectors (Default value = 50)\n :param debug: print some debug information (Default value = False)\n :returns: tuple: eigenvectors, eigenvalues, embeddings\n\n \"\"\"\n if debug:\n iprint(\"cooccur shape = {}\".format(cooccur.shape))\n iprint(\"freq shape = {}\".format(freq.shape))\n\n cooccur += np.diag(freq) # cooccur = cooccur + diag(freq);\n if debug:\n iprint(\"add freq diag, cooccur: {}\".format(cooccur.shape))\n cooccur *= np.sum(freq) # cooccur = cooccur*sum(freq) ./ (freq*freq');\n if debug:\n iprint(\"prod of sum freqs, cooccur: {}\".format(cooccur.shape))\n cooccur /= np.dot(freq, freq.T)\n if debug:\n iprint(\"div of freq dot product, cooccur: {}\".format(cooccur.shape))\n\n pmi = np.log(np.clip(cooccur, 0, None))\n pmi[np.isinf(pmi)] = 0\n if debug:\n iprint(\"clip + log of cooccur, pmi shape = {}\".format(pmi.shape))\n # asdf # ??\n\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html#scipy.sparse.linalg.eigsh\n # https://de.mathworks.com/help/matlab/ref/eigs.html#bu2_q3e-sigma\n # eigs(...) (square matrix) - eigsh(...) (sq.mat, real symmetric)\n eigenvalues, eigenvectors = ssl.eigs(\n pmi, rank, which=\"LA\"\n ) # sigma='la'/largestreal option in Matlab? opts=isreal/issym\n # MATLAB: [X, D] = eigs(pmi,50,'la', opts);\n # X - eigenvectors, columns are the eigenvectors of A such that A*X = X*D\n # D - eigenvalues, diagonal matrix with the eigenvalues on the main diagonal\n # SCIPY: (eigenvalues, eigenvectors)\n # eigenvalues - eigenvalues, array\n # eigenvectors - eigenvectors, column eigenvectors[:, i] is the eigenvector corresponding to the eigenvalue eigenvalues[i]\n\n if debug:\n iprint(\"eigenvalues shape = {}\".format(eigenvalues.shape))\n iprint(\"eigenvectors shape = {}\".format(eigenvectors.shape))\n\n # sqrt, above zero\n eigenvalues2 = np.sqrt(np.clip(eigenvalues, 0, None))\n if debug:\n iprint(\"clip + sqrt, eigenvalues2: {}\".format(eigenvalues2.shape))\n\n emb = np.dot(eigenvectors, np.diag(eigenvalues2))\n if debug:\n iprint(\"dot with eigenvalues, emb shape = {}\".format(emb.shape))\n\n return eigenvectors, eigenvalues, emb\n\n\n# ----------------------------------------------------------------------------\n\n\ndef main(\n word_freq_file,\n yearly_cooc_file,\n emb_static_file,\n rank,\n initial_coocfreq_file=None,\n eigs_static_file=None,\n debug=False,\n):\n \"\"\"Main workflow.\n\n :param word_freq_file: csv file with w_id,word,frequency\n :param yearly_cooc_file: csv file with word-pair and yearly value (pmi?)\n :param emb_static_file: output file with initial static embeddings\n :param rank: rank/dimension of embeddings (number of eigenvectors to compute)\n :param initial_coocfreq_file: output file for cooc matrix and frequency vector (Default value = None)\n :param eigs_static_file: output file for eigenvector/eigenvalue data (Default value = None)\n :param debug: debug output information (Default value = False)\n\n \"\"\"\n set_base_indent_level()\n\n iprint(\"* Load words and frequencies ...\", end=\"\", flush=True)\n start_time = time.time()\n vocab2id, freqlist = get_word_idx(word_freq_file)\n print(\" {}\".format(get_time_diff(start_time)))\n\n iprint(\"* Load yearly coocs and build matrix ...\", end=\"\", flush=True)\n start_time = time.time()\n cooccur = get_cum_cooccur(yearly_cooc_file, vocab2id)\n print(\" {}\".format(get_time_diff(start_time)))\n\n if initial_coocfreq_file:\n iprint(\n \"* Save cooc mat + freq vec to: {}\".format(initial_coocfreq_file), level=1\n )\n try:\n sio.savemat(initial_coocfreq_file, {\"cooccur\": cooccur, \"freq\": freqlist})\n except Exception as ex:\n print(\"! {}\".format(ex), level=2)\n\n iprint(\"* Generate static embeddings ...\")\n start_time = time.time()\n eigenvectors, eigenvalues, emb = build_static_embs(\n cooccur, freqlist, rank=rank, debug=debug\n )\n iprint(\"~ Took {}\".format(get_time_diff(start_time)))\n\n if eigs_static_file:\n iprint(\"* Save eigenvectors/-values to: {}\".format(eigs_static_file), level=1)\n sio.savemat(\n eigs_static_file, {\"X\": eigenvectors, \"D\": eigenvalues}\n ) # save -v7.3 eigs_static X D\n iprint(\"* Save static embeddings to: {}\".format(emb_static_file), level=1)\n sio.savemat(emb_static_file, {\"emb\": emb})\n\n\ndef parse_args():\n \"\"\"Parse arguments, use defaults if not set.\n\n :returns: arguments/parameters\n\n \"\"\"\n # Defaults\n\n #: directory\n data_dir = \"data\"\n\n #: inputs\n words_file = \"wordIDHash.csv\"\n yearly_coocs_file = \"wordCoOccurByYear_min200_ws5.csv\"\n\n #: results/outputs\n coocs_matrix_file = \"initial_cooccur_freq.mat\"\n eigs_static_file = \"eigs_static.mat\"\n emb_static_file = \"emb_static.mat\"\n\n rank = 50\n\n # Parse arguments\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"-d\",\n \"--data-dir\",\n default=data_dir,\n help=\"base directory for all input and output files, default: {}\".format(\n data_dir\n ),\n )\n parser.add_argument(\n \"-w\",\n \"--words-file\",\n default=words_file,\n help=\"input filename for CSV file of words, w_ids and frequencies, default: {}\".format(\n words_file\n ),\n )\n parser.add_argument(\n \"-c\",\n \"--yearly-coocs-file\",\n default=yearly_coocs_file,\n help=\"input filename for CSV file of yearly cooccurrence data, default: {}\".format(\n yearly_coocs_file\n ),\n )\n parser.add_argument(\n \"-e\",\n \"--emb-file\",\n default=emb_static_file,\n help=\"output filename for initial static embeddings, default: {}\".format(\n emb_static_file\n ),\n )\n parser.add_argument(\n \"-r\",\n \"--rank\",\n type=int,\n default=rank,\n help=\"rank/dimensions for eigenvector computation and resulting embeddings, default: {}\".format(\n rank\n ),\n )\n parser.add_argument(\n \"--coocs-matrix-file\",\n default=coocs_matrix_file,\n help=\"output filename for matrix with word cooccurence frequencies?; empty to disable, default: {}\".format(\n coocs_matrix_file\n ),\n )\n parser.add_argument(\n \"--eigs-file\",\n default=eigs_static_file,\n help=\"output filename for eigenvalue/eigenvector data; empty to disable, default: {}\".format(\n eigs_static_file\n ),\n )\n parser.add_argument(\n \"--debug\",\n action=\"store_true\",\n default=False,\n help=\"debugging information about matix shapes etc.\",\n )\n\n args = parser.parse_args()\n\n if not args.coocs_matrix_file:\n args.coocs_matrix_file = None\n if not args.eigs_file:\n args.eigs_file = None\n\n if os.path.exists(args.data_dir):\n args.words_file = os.path.join(args.data_dir, args.words_file)\n args.yearly_coocs_file = os.path.join(args.data_dir, args.yearly_coocs_file)\n\n if args.coocs_matrix_file:\n args.coocs_matrix_file = os.path.join(args.data_dir, args.coocs_matrix_file)\n if args.eigs_file:\n args.eigs_file = os.path.join(args.data_dir, args.eigs_file)\n args.emb_file = os.path.join(args.data_dir, args.emb_file)\n\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(\n args.words_file,\n args.yearly_coocs_file,\n args.emb_file,\n args.rank,\n args.coocs_matrix_file,\n args.eigs_file,\n debug=args.debug,\n )\n","sub_path":"train_model/prepare_static_embeddings.py","file_name":"prepare_static_embeddings.py","file_ext":"py","file_size_in_byte":11310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"343752999","text":"import unittest\nimport string\nimport logging\nfrom _groupsig import ffi\n\nfrom pygroupsig import groupsig\nfrom pygroupsig import grpkey\nfrom pygroupsig import mgrkey\nfrom pygroupsig import memkey\nfrom pygroupsig import identity\nfrom pygroupsig import message\nfrom pygroupsig import signature\nfrom pygroupsig import gml\nfrom pygroupsig import constants\n\n# Tests for group operations\nclass TestGroupOps(unittest.TestCase):\n\n # Non-test functions\n def addMember(self):\n msg1 = groupsig.join_mgr(0, self.isskey, self.grpkey, gml = self.gml)\n msg2 = groupsig.join_mem(1, self.grpkey, msgin = msg1)\n usk = msg2['memkey']\n msg3 = groupsig.join_mgr(2, self.isskey, self.grpkey, msg2['msgout'], gml = self.gml)\n msg4 = groupsig.join_mem(3, self.grpkey, msgin = msg3, memkey = usk)\n usk = msg4['memkey']\n self.memkeys.append(usk)\n\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n self.gml = group1['gml'] \n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n self.memkeys = []\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Creates a group\n def test_groupCreate(self):\n self.assertNotEqual(self.grpkey, ffi.NULL)\n self.assertNotEqual(self.isskey, ffi.NULL)\n self.assertNotEqual(self.opnkey, ffi.NULL)\n self.assertEqual(groupsig.get_joinseq(constants.KLAP20_CODE), 3)\n self.assertEqual(groupsig.get_joinstart(constants.KLAP20_CODE), 0) \n\n # Adds one member\n def test_addMember(self):\n n_members = len(self.memkeys)\n self.addMember()\n self.assertEqual(len(self.memkeys), n_members+1)\n self.assertNotEqual(self.memkeys[n_members], ffi.NULL)\n \n # Accepts a valid signature for a message passed as a string\n def test_acceptValidSignatureString(self):\n self.addMember()\n sig = groupsig.sign(\"Hello, World!\", self.memkeys[0], self.grpkey)\n b = groupsig.verify(sig, \"Hello, World!\", self.grpkey)\n self.assertTrue(b)\n\n # Rejects a valid signature for a different message, also passed as a string\n def test_rejectValidSignatureWrongMessageString(self):\n self.addMember()\n sig = groupsig.sign(\"Hello, World!\", self.memkeys[0], self.grpkey)\n b = groupsig.verify(sig, \"Hello, Worlds!\", self.grpkey)\n self.assertFalse(b)\n\n # Accepts a valid signature for a message passed as a byte array\n def test_acceptValidSignatureBytes(self):\n self.addMember()\n sig = groupsig.sign(b\"Hello, World!\", self.memkeys[0], self.grpkey)\n b = groupsig.verify(sig, b\"Hello, World!\", self.grpkey)\n self.assertTrue(b)\n\n # Rejects a valid signature for a different message, also passed as a byte array\n def test_rejectValidSignatureWrongMessageBytes(self):\n self.addMember()\n sig = groupsig.sign(b\"Hello, World!\", self.memkeys[0], self.grpkey)\n b = groupsig.verify(sig, b\"Hello, Worlds!\", self.grpkey)\n self.assertFalse(b)\n\n # Accepts a batch of valid signatures\n def test_acceptValidSignatureBatch(self):\n self.addMember()\n sigs = []\n msgs = []\n for i in range(10):\n msg = \"Hello, World \"+ str(i) + \"!\"\n sig = groupsig.sign(msg, self.memkeys[0], self.grpkey)\n msgs.append(msg)\n sigs.append(sig)\n b = groupsig.verify_batch(sigs, msgs, self.grpkey)\n self.assertTrue(b)\n\n # Reject a batch of signatures including a wrong signature\n def test_rejectWrongSignatureBatch(self):\n self.addMember()\n sigs = []\n msgs = []\n for i in range(10):\n msg = \"Hello, World \"+ str(i) + \"!\"\n sig = groupsig.sign(msg, self.memkeys[0], self.grpkey)\n msgs.append(msg)\n sigs.append(sig)\n msgs[0] = \"Hello, World!\"\n b = groupsig.verify_batch(sigs, msgs, self.grpkey)\n self.assertFalse(b)\n\n # Successfully opens a signature\n def test_openSignature(self):\n self.addMember()\n self.addMember()\n sig = groupsig.sign(b\"Hello, World!\", self.memkeys[1], self.grpkey)\n gsopen = groupsig.open(sig, self.opnkey, self.grpkey, gml = self.gml)\n self.assertEqual(gsopen[\"index\"], 1)\n proof = gsopen['proof']\n b = groupsig.open_verify(proof, sig, self.grpkey)\n self.assertTrue(b)\n \n# Tests for signature operations\nclass TestSignatureOps(unittest.TestCase):\n\n # Non-test functions\n def addMember(self):\n msg1 = groupsig.join_mgr(0, self.isskey, self.grpkey, gml = self.gml)\n msg2 = groupsig.join_mem(1, self.grpkey, msgin = msg1)\n usk = msg2['memkey']\n msg3 = groupsig.join_mgr(2, self.isskey, self.grpkey, msg2['msgout'], gml = self.gml)\n msg4 = groupsig.join_mem(3, self.grpkey, msgin = msg3, memkey = usk)\n usk = msg4['memkey']\n self.memkeys.append(usk)\n \n # Creates a group, adds a member and generates a signature\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n self.gml = group1['gml'] \n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n self.memkeys = []\n self.addMember()\n self.sig = groupsig.sign(\"Hello, World!\", self.memkeys[0], self.grpkey)\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Exports and reimports a signature, and it verifies correctly\n def test_sigExportImport(self):\n sig_str = signature.signature_export(self.sig)\n sig = signature.signature_import(self.code, sig_str)\n b = groupsig.verify(sig, \"Hello, World!\", self.grpkey)\n self.assertTrue(b)\n \n # Prints a string (this just checks the produced string is not empty)\n def test_sigToString(self):\n sig_str = signature.signature_to_string(self.sig)\n self.assertGreater(len(sig_str), 0)\n self.assertTrue(set(sig_str).issubset(set(string.printable)))\n\n# Tests for group key operations\nclass TestGrpkeyOps(unittest.TestCase):\n\n # Creates a group, adds a member and generates a signature\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n self.gml = group1['gml'] \n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n self.memkeys = []\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Exports and reimports a group key\n def test_grpkeyExportImport(self):\n grpkey_str = grpkey.grpkey_export(self.grpkey)\n gpk = grpkey.grpkey_import(self.code, grpkey_str)\n # This is quite useless, as import returns an exception if the FFI\n # method returns ffi.NULL. Maybe implementing a cmp function for\n # grp keys would be good for testing this (and also in general?)\n self.assertIsNot(ffi.NULL, gpk)\n\n# Tests for manager key operations\nclass TestIssuerkeyOps(unittest.TestCase):\n\n # Creates a group, adds a member and generates a signature\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n self.gml = group1['gml']\n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n self.memkeys = []\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Exports and reimports an manager key\n def test_isskeyExportImport(self):\n isskey_str = mgrkey.mgrkey_export(self.isskey)\n ikey = mgrkey.mgrkey_import(self.code, isskey_str)\n # This is quite useless, as import returns an exception if the FFI\n # method returns ffi.NULL. Maybe implementing a cmp function for\n # manager keys would be good for testing this (and also in general?)\n self.assertIsNot(ffi.NULL, ikey)\n\n# Tests for opener key operations\nclass TestOpenerkeyOps(unittest.TestCase):\n\n # Creates a group, adds a member and generates a signature\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Exports and reimports a converter key\n def test_opnkeyExportImport(self):\n opnkey_str = mgrkey.mgrkey_export(self.opnkey)\n okey = mgrkey.mgrkey_import(self.code, opnkey_str)\n # This is quite useless, as import returns an exception if the FFI\n # method returns ffi.NULL. Maybe implementing a cmp function for\n # manager keys would be good for testing this (and also in general?)\n self.assertIsNot(ffi.NULL, okey) \n\n# Tests for member key operations\nclass TestMemkeyOps(unittest.TestCase):\n\n # Non-test functions\n def addMember(self):\n msg1 = groupsig.join_mgr(0, self.isskey, self.grpkey, gml = self.gml)\n msg2 = groupsig.join_mem(1, self.grpkey, msgin = msg1)\n usk = msg2['memkey']\n msg3 = groupsig.join_mgr(2, self.isskey, self.grpkey, msg2['msgout'], gml = self.gml)\n msg4 = groupsig.join_mem(3, self.grpkey, msgin = msg3, memkey = usk)\n usk = msg4['memkey']\n self.memkey = usk\n \n # Creates a group, adds a member and generates a signature\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n self.gml = group1['gml'] \n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n self.memkeys = []\n self.addMember()\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Exports and reimports a member key\n def test_memkeyExportImport(self):\n memkey_str = memkey.memkey_export(self.memkey)\n mkey = memkey.memkey_import(self.code, memkey_str)\n # This is quite useless, as import returns an exception if the FFI\n # method returns ffi.NULL. Maybe implementing a cmp function for\n # mem keys would be good for testing this (and also in general?)\n self.assertIsNot(ffi.NULL, mkey)\n\n# Tests for GML operations\nclass TestGmlOps(unittest.TestCase):\n\n # Non-test functions\n def addMember(self):\n msg1 = groupsig.join_mgr(0, self.isskey, self.grpkey, gml = self.gml)\n msg2 = groupsig.join_mem(1, self.grpkey, msgin = msg1)\n usk = msg2['memkey']\n msg3 = groupsig.join_mgr(2, self.isskey, self.grpkey, msg2['msgout'], gml = self.gml)\n msg4 = groupsig.join_mem(3, self.grpkey, msgin = msg3, memkey = usk)\n usk = msg4['memkey']\n self.memkey = usk\n \n # Creates a group, adds a member and generates a signature\n def setUp(self):\n groupsig.init(constants.KLAP20_CODE, 0)\n group1 = groupsig.setup(constants.KLAP20_CODE)\n self.code = constants.KLAP20_CODE\n grpkey1 = group1['grpkey']\n self.isskey = group1['mgrkey']\n self.gml = group1['gml'] \n group2 = groupsig.setup(constants.KLAP20_CODE, grpkey1);\n self.opnkey = group2['mgrkey']\n self.grpkey = group2['grpkey']\n self.memkeys = []\n self.addMember()\n \n def tearDown(self):\n groupsig.clear(self.code)\n\n # Exports and reimports a member key\n def test_gmlExportImport(self):\n gml_str = gml.gml_export(self.gml)\n _gml = gml.gml_import(self.code, gml_str)\n # This is quite useless, as import returns an exception if the FFI\n # method returns ffi.NULL. Maybe implementing a cmp function for\n # GMLs would be good for testing this (and also in general?)\n self.assertIsNot(ffi.NULL, _gml)\n \n# Define test suites\ndef suiteGroupOps():\n suiteGroupOps = unittest.TestSuite() \n suiteGroupOps.addTest(WidgetTestCase('test_groupCreate'))\n suiteGroupOps.addTest(WidgetTestCase('test_addMember'))\n suiteGroupOps.addTest(WidgetTestCase('test_acceptValidSignatureString'))\n suiteGroupOps.addTest(WidgetTestCase('test_rejectValidSignatureWrongMessageString'))\n suiteGroupOps.addTest(WidgetTestCase('test_acceptValidSignatureBytes'))\n suiteGroupOps.addTest(WidgetTestCase('test_rejectValidSignatureWrongMessageBytes'))\n suiteGroupOps.addTest(WidgetTestCase('test_acceptValidSignatureBatch'))\n suiteGroupOps.addTest(WidgetTestCase('test_rejectWrongSignatureBatch'))\n suiteGroupOps.addTest(WidgetTestCase('test_openSignature'))\n return suiteGroupOps\n \ndef suiteSigOps():\n suiteSigOps = unittest.TestSuite() \n suiteSigOps.addTest(WidgetTestCase('test_sigExportImport'))\n suiteSigOps.addTest(WidgetTestCase('test_sigToString'))\n return suiteSigOps\n\ndef suiteGrpkeyOps():\n suiteGrpkeyOps = unittest.TestSuite() \n suiteGrpkeyOps.addTest(WidgetTestCase('test_grpkeyExportImport'))\n return suiteGrpkeyOps\n\ndef suiteIssuerkeyOps():\n suiteIssuerkeyOps = unittest.TestSuite() \n suiteIssuerkeyOps.addTest(WidgetTestCase('test_isskeyExportImport'))\n return suiteIssuerkeyOps\n\ndef suiteOpenerkeyOps():\n suiteOpenerkeyOps = unittest.TestSuite() \n suiteOpenerkeyOps.addTest(WidgetTestCase('test_opnkeyExportImport'))\n return suiteOpenerkeyOps\n\ndef suiteMemkeyOps():\n suiteMemkeyOps = unittest.TestSuite() \n suiteMemkeyOps.addTest(WidgetTestCase('test_memkeyExportImport'))\n return suiteMemkeyOps\n\ndef suiteGmlOps():\n suiteGmlOps = unittest.TestSuite() \n suiteGmlOps.addTest(WidgetTestCase('test_gmlExportImport'))\n return suiteGmlOps\n \nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suiteGroupOps())\n runner.run(suiteSigOps())\n runner.run(suiteGrpkeyOps())\n runner.run(suiteIssuerkeyOps())\n runner.run(suiteOpenerkeyOps()) \n runner.run(suiteMemkeyOps())\n runner.run(suiteGmlOps())\n","sub_path":"src/wrappers/python/tests/test_KLAP20.py","file_name":"test_KLAP20.py","file_ext":"py","file_size_in_byte":15108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"119647380","text":"import refnx\nimport numpy as np\nimport glob\nimport matplotlib.pyplot as plt\nimport models.two_layer as tl\nimport toolbox as tb\nimport h5py\nimport dynesty\nimport sys\n\nml_number = sys.argv[1]\n\noutput_dir = './results/'\n\ndata_dir = './data/ml_{}'.format(ml_number)\ndata_files = sorted(glob.glob('{}/*.dat'.format(data_dir)))\nsamples = len(data_files)\ndatasets = []\nfor i in range(samples):\n d = refnx.dataset.ReflectDataset(data_files[i])\n datasets.append(refnx.dataset.ReflectDataset([d.x, d.y, d.y_err]))\n\nhead = {\"C\": 10, \"H\": 18, \"O\": 8, \"N\": 1, \"P\": 1}\ntail = {\"C\": 15 * 2, \"H\": 15 * 4 + 2}\n\nb_head = tb.get_scattering_length(head, 12.5)\nb_tail = tb.get_scattering_length(tail, 12.5)\n\nlipids = []\nfor i in range(samples):\n lipids.append(\n tl.TwoLayer([b_head, b_tail], name='sample{}'.format(i+1)))\n\nair = refnx.reflect.SLD(0, \"air\")\nwater = refnx.reflect.SLD(9.45, \"h2o\")\nstructures = []\nfor i in range(samples):\n structures.append(air(0, 0) | lipids[i] | water(0, 3.3))\n\nlipids[0].thick_t.setp(18., vary=True, bounds=(14, 20))\nlipids[0].mol_vol_h.setp(319, vary=False)\nlipids[0].mol_vol_t.setp(829, vary=False)\nstructures[0][-1].rough.setp(3., vary=True, bounds=(2.9, 5))\nlipids[0].rough_h_t.constraint = structures[0][-1].rough\nlipids[0].rough_t_a.constraint = structures[0][-1].rough\nlipids[0].phi_t.setp(0., vary=True, bounds=(0., 0.25))\nlipids[0].phi_h.setp(0.5, vary=True, bounds=(0.5, 0.95))\nlipids[0].thick_h.setp(10., vary=False)\n\nlipids[0].solv_sld.constrain = structures[0][-1].sld.real\n\nfor j in range(1, samples):\n lipids[j].thick_h.constraint = lipids[0].thick_h\n lipids[j].thick_t.setp(18., vary=True, bounds=(14, 20))\n lipids[j].phi_h.setp(0.5, vary=True, bounds=(0.5, 0.95))\n structures[j][-1].rough.setp(3., vary=True, bounds=(2.9, 5))\n lipids[j].phi_t.setp(0., vary=True, bounds=(0., 0.25))\n lipids[j].rough_h_t.constraint = structures[j][-1].rough\n lipids[j].rough_t_a.constraint = structures[j][-1].rough\n lipids[j].solv_sld.constraint = structures[0][-1].sld.real\n lipids[j].mol_vol_h.constraint = lipids[0].mol_vol_h\n lipids[j].mol_vol_t.constraint = lipids[0].mol_vol_t\n\nmodels = []\n\nfor i in range(samples):\n models.append(refnx.reflect.ReflectModel(structures[i]))\n\nmodels[0].bkg.setp(datasets[0].y.min(), vary=False)\nmodels[0].scale.setp(1, vary=False)\nfor i in range(1, samples):\n models[i].scale.constraint = models[0].scale\n models[i].bkg.setp(datasets[i].y.min(), vary=False)\n\n\nobjectives = []\n\nfor i in range(samples):\n objectives.append(refnx.analysis.Objective(\n models[i], datasets[i], \n transform=refnx.analysis.Transform(\"YX4\")))\n\nglobal_objective = refnx.analysis.GlobalObjective(objectives)\n\nfitter = refnx.analysis.CurveFitter(global_objective)\nfitter.fit('differential_evolution', seed=1)\n\nfitter.sample(400, random_state=1)\nfitter.reset()\n\nres = fitter.sample(500, random_state=1)\n\nflatchain = fitter.sampler.flatchain\n\nh5_file = h5py.File('{}/ml_{}_chain.h5'.format(output_dir, ml_number), \"w\")\nh5_file.create_dataset('flatchain', data=flatchain)\nh5_file.close()\n\nfile_open = open('{}/ml_{}_output.txt'.format(output_dir, ml_number), 'w')\nfile_open.write(global_objective.__str__())\nfile_open.close()\n\n\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"612837987","text":"#! /usr/bin/env python\n\n# Project Log Analysis\n\nimport psycopg2\n# library for database we are using\n\ndbName = \"news\"\n# for psql pg = psycopg.connect(\"dbname=somedb\")\n\n\ndef three_most_popular_article():\n \"\"\"1. What are the most popular three articles of all time?\n Which articles have been accessed the most? Present this\n information as a sorted list with the most popular article\n at the top.\"\"\"\n db = psycopg2.connect(database=dbName)\n c = db.cursor()\n popular_articles = '''\n select title, count(*) as views\n from log join articles\n on log.path = concat('/article/', articles.slug)\n group by title\n order by views desc\n limit 3;\n '''\n c.execute(popular_articles)\n print(\"Most popular articles:\")\n for (title, count) in c.fetchall():\n print(\" {} - {} views\".format(title, count))\n print(\"-\" * 70)\n\n # all three of the solutions below work.\n # select title, count(log.path) as views\n # from articles join log\n # on articles.slug = substring(log.path FROM 10)\n # group by articles.title\n # order by views\n # desc limit 3;\n\n # select title, count(*) as views\n # from log join articles on\n # log.path = concat('/article/', articles.slug)\n # group by title\n # order by views\n # desc limit 3;\n\n # select title, count(log.path) as views\n # from articles, log\n # where log.path like concat('%',articles.slug,'%')\n # group by articles.title\n # order by views\n # desc limit 3;\n\n db.close()\n\n\ndef most_popular_article_authors():\n \"\"\"2. Who are the most popular article authors of all time?\n That is, when you sum up all of the articles each author has\n written, which authors get the most page views? Present this\n as a sorted list with the most popular author at the top.\"\"\"\n db = psycopg2.connect(database=dbName)\n c = db.cursor()\n mpaa = '''select authors.name, count(log.path) as views\n from authors, log, articles\n where log.path like '%'||articles.slug and articles.author = authors.id\n group by authors.name\n order by views desc;\n '''\n\n c.execute(mpaa)\n print(\"Most popular article authors:\")\n for (authors, count) in c.fetchall():\n print(\" {} - {} views\".format(authors, count))\n print(\"-\" * 70)\n db.close()\n\n\ndef day_with_most_error():\n \"\"\"3. On which days did more than 1% of requests lead to errors?\n The log table includes a column status that indicates the HTTP\n status code that the news site sent to the user's browser.\n (Refer back to this lesson if you want to review the idea of\n HTTP status codes.)\"\"\"\n db = psycopg2.connect(database=dbName)\n c = db.cursor()\n dwme = '''select date(time), trunc(100.0*\n count(case log.status\n when '200 OK'\n then null else 1 end)/count(status),2)\n as \\\"Percent Error\\\"\n from log\n group by date(time)\n having trunc(100.0*\n count(case log.status\n when '200 OK'\n then null else 1 end)/count(status),2) > 2.0\n order by \\\"Percent Error\\\" desc;\n '''\n c.execute(dwme)\n print(\"Most days with Percent Error(s):\")\n for (date, trunc) in c.fetchall():\n print(\" {} - {} Percent Error\".format(date, trunc))\n print(\"-\" * 70)\n db.close()\n\nthree_most_popular_article()\nmost_popular_article_authors()\nday_with_most_error()\n","sub_path":"Project Log Analysis/Project Log Analysis.py","file_name":"Project Log Analysis.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"510103769","text":"# coding:utf-8\nfrom datetime import datetime\nfrom flask import Blueprint, request, jsonify\nfrom .. import db\nfrom ..models import Topic\nfrom ..utils import auth, QiniuToken\n\nbp = Blueprint('topic_blueprint', __name__)\n\n\n@bp.route('/api/topics/hot', methods=['GET'])\n@auth.login_required\ndef get_hot_topics():\n # Get top 5 topics\n hot_topics = db.session.query(Topic).order_by(Topic.created.desc()).limit(5)\n return jsonify(hot_topics=[e.serialize() for e in hot_topics])\n\n\n@bp.route('/api/topics', methods=['POST'])\ndef add_topic():\n # Check callback validation\n token_client = QiniuToken()\n rv = token_client.check_callback(request)\n\n if not rv:\n return jsonify({'status': 400, 'message': 'Illegal callback'})\n\n album = request.form.get('key')\n content = request.form.get('content')\n\n topic = Topic()\n topic.content = content\n topic.album = album\n topic.created = datetime.utcnow()\n\n db.session.add(topic)\n db.session.commit()\n return jsonify({'status': 200})\n","sub_path":"application/controllers/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"25755407","text":"import numpy as np\nimport random\n\n\nclass Minimax():\n \"\"\"\n Performs minimax tree search on a game\n Arguments\n game: connect4 game instance\n heuristic: heuristic function for how good the board is for the player\n with pieces \"1\" given player \"1\" is about to move. If the board looks\n good for player \"1\" the heuristic should return a value near 1 and if\n it looks good for the other player \"-1\" the heuristic should return a\n value near -1.\n randomized: when multiple actions are tied for the same value, randomized\n determines if the move is picked randomly or just the first move in\n the list\n \"\"\"\n\n def __init__(self, game, heuristic=lambda x: 0, randomized=False):\n self.game = game\n self.heuristic = heuristic\n self.randomized = randomized\n\n\n def compute_minimax(self, canonicalBoard, remaining_depth):\n \"\"\"\n Recursively computes the minimax value of a board position with given depth\n\n Arguments\n canonicalBoard: the board state (as given by game.getCanonicalForm)\n remaining_depth: search depth remaining (if this is 2 then we will search\n down two more layers on the tree)\n Returns\n value: the negation of the maximal guaranteed value as given by minimax\n (between -1 and 1)\n action: action to take to achieve that value (-1 if no action by game end\n or evaluated by heuristic)\n \"\"\"\n\n end_value = self.game.getGameEnded(canonicalBoard, 1)\n if end_value != 0: # Game ended\n # terminal node\n return -end_value, -1\n\n if remaining_depth <= 0:\n v = self.heuristic(canonicalBoard)\n return -min(max(v, -1), 1), -1 # Constrains invalid heuristic range\n\n # Mask of valid moves\n valids = self.game.getValidMoves(canonicalBoard, 1)\n\n # Best value and action so far\n cur_best = -float('inf')\n best_actions = [-1]\n # Iterate over valid moves and recursively minimax\n for a in range(self.game.getActionSize()):\n if valids[a]:\n next_s, next_player = self.game.getNextState(canonicalBoard, 1, a)\n # Swaps board representation to next player\n next_s = self.game.getCanonicalForm(next_s, next_player)\n v = self._compute_minimax_recursive(next_s, remaining_depth - 1, a)\n if v > cur_best:\n cur_best = v\n best_actions = [a]\n elif v == cur_best:\n best_actions.append(a)\n if not self.randomized:\n return -cur_best, best_actions[0]\n return -cur_best, random.choice(best_actions)\n\n def _compute_minimax_recursive(self, canonicalBoard, remaining_depth, previous_action):\n # recursive helper which requires the previous action to reduce computation\n\n end_value = self.game.getGameEndedIncremental(canonicalBoard, 1, previous_action)\n if end_value != 0: # Game ended\n # terminal node\n return -end_value\n\n # Evaluate heuristic at leaf node\n if remaining_depth <= 0:\n v = self.heuristic(canonicalBoard)\n return -min(max(v, -1), 1) # Constrains invalid heuristic range\n\n # Mask of valid moves\n valids = self.game.getValidMoves(canonicalBoard, 1)\n\n # Best value and action so far\n cur_best = -float('inf')\n # Iterate over valid moves and recursively minimax\n for a in range(self.game.getActionSize()):\n if valids[a]:\n next_s, next_player = self.game.getNextState(canonicalBoard, 1, a)\n next_s = self.game.getCanonicalForm(next_s, next_player)\n v = self._compute_minimax_recursive(next_s, remaining_depth - 1, a)\n if v > cur_best:\n cur_best = v\n return -cur_best\n\n\nclass MinimaxPlayer():\n def __init__(self, game, depth=6, randomized=False):\n self.game = game\n self.depth = depth\n self.randomized = randomized\n\n def board_heuristic(self, board):\n \"\"\"\n Given a board state evaluates how well player \"1\" is doing.\n Arguments\n board: a numpy array (basically a list of lists) with a\n representation of the connect 4 board. For example\n [[ 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0]\n [ 0 0 0 -1 0 0 1]\n [ 0 0 0 1 0 0 -1]\n [ 0 0 0 1 -1 0 -1]\n [-1 1 -1 1 -1 1 1]]\n Returns\n value: a number between 1 and -1 representing the value of the game\n for player \"1\". Should be close to 1 if player \"1\" is winning.\n \"\"\"\n return 0\n\n def play(self, board):\n mini = Minimax(self.game, self.board_heuristic, self.randomized)\n v, a = mini.compute_minimax(self.game.getCanonicalForm(board, 1), self.depth)\n return a","sub_path":"connect4/Connect4Players/MinimaxPlayer.py","file_name":"MinimaxPlayer.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"443825320","text":"# -----------------------------------------\n# webpage: https://github.com/bpsmith/tia\n#\n# pip install tia\n# ------------------------------------------\n\nimport tia.bbg.datamgr as dm\n\n# create a DataManager for simpler api access\nmgr = dm.BbgDataManager()\n# retrieve a single security accessor from the manager\nmsft = mgr['MSFT US EQUITY']\n\n# Can now access any Bloomberg field (as long as it is upper case)\nmsft.PX_LAST, msft.PX_OPEN\n\n# Access multiple fields at the same time\nmsft['PX_LAST', 'PX_OPEN']\n\n# OR pass an array\nmsft[['PX_LAST', 'PX_OPEN']]\n\n# Have the manager default to returning a frame instead of values\nmgr.sid_result_mode = 'frame'\nmsft.PX_LAST\n\n# Retrieve historical data\nmsft.get_historical(['PX_OPEN', 'PX_HIGH', 'PX_LOW', 'PX_LAST'], '1/1/2014', '1/12/2014').head()\n\n#########################\n# Multi-security accessor\n#########################\n\nsids = mgr['MSFT US EQUITY', 'IBM US EQUITY', 'CSCO US EQUITY']\nsids.PX_LAST\n\nsids.get_historical('PX_LAST', '1/1/2014', '11/12/2014').head()\n\n# ----------------------------------------------------------------------------\n# Example of using the v3api directly\n# ----------------------------------------------------------------------------\n\nfrom tia.bbg import LocalTerminal\nimport pandas as pd\n\n# Single SID, Multiple Valid Fields\nresp = LocalTerminal.get_reference_data('MSFT US EQUITY', ['PX_LAST', 'GICS_SECTOR_NAME', 'VOLATILITY_30D'])\nresp.as_frame()\n\n# Get the response as a dict\nresp.as_map()\n\n# Single SID, Invalid Fields\n# Ability to ignore errors\nresp = LocalTerminal.get_reference_data('MSFT US EQUITY', ['PX_LAST', 'GICS_SECTOR_NAME', 'BAD FIELD'],\n ignore_field_error=1)\nresp.as_frame()\n\n# Multiple SID, Invalid Fields\n# allows for non-homogeneous security types to be batched together\nresp = LocalTerminal.get_reference_data(['ED1 COMDTY', 'MSFT US EQUITY'], ['PX_LAST', 'GICS_SECTOR_NAME'],\n ignore_field_error=1)\nresp.as_frame()\n\n# Retrieve data without override\nLocalTerminal.get_reference_data('SPX INDEX', 'CUST_TRR_RETURN_HOLDING_PER').as_frame()\n\n# Retrieve data with override (1 month total return)\ndt = pd.datetools.BDay(-21).apply(pd.datetime.now()).strftime('%Y%m%d')\nLocalTerminal.get_reference_data('SPX INDEX', 'CUST_TRR_RETURN_HOLDING_PER', CUST_TRR_START_DT=dt).as_frame()\n\n# -------------------------------------------------\n# HISTORY\n# -------------------------------------------------\n\n# Single SID, Multiple Valid Fields HISTORY\nresp = LocalTerminal.get_historical('MSFT US EQUITY', ['PX_OPEN', 'PX_LAST'], start='1/1/2014', end='3/1/2014')\nresp.as_frame().head()\n\n# Multiple SIDs, Multiple Valid Fields\nresp = LocalTerminal.get_historical(['IBM US EQUITY', 'MSFT US EQUITY'], ['PX_OPEN', 'PX_LAST'], start='1/1/2014',\n end='3/1/2014')\nresp.as_frame().head()\n\n# Weekly data\nresp = LocalTerminal.get_historical(['IBM US EQUITY', 'MSFT US EQUITY'], ['PX_OPEN', 'PX_LAST'],\n start='1/1/2014', end='3/1/2014', period='WEEKLY')\nresp.as_frame().head()\n\n# format response as panel\nresp.as_panel()\n\n# --------------------------------------------------\n# Retreiving Curves and Members\n# --------------------------------------------------\n\n# Retrieve the EURUSD Forward Curve\nresp = LocalTerminal.get_reference_data('eurusd curncy', 'fwd_curve')\n# must retrieve a frame from the first row\nresp.as_frame().ix[0, 'fwd_curve'].head()\n# OR\nresp.as_map()['eurusd curncy']['fwd_curve'].head()\n\n# Retrive the EURUSD Vol Surface\nresp = LocalTerminal.get_reference_data('eurusd curncy', 'dflt_vol_surf_bid')\nresp.as_frame().ix[0, 'dflt_vol_surf_bid'].head()\n\n# More complex example\n# Retrive all members of the S&P 500, then get price and vol data\nresp = LocalTerminal.get_reference_data('spx index', 'indx_members')\nmembers = resp.as_frame().ix[0, 'indx_members']\n# append region + yellow key = 'US EQUITY'\nmembers = members.icol(0).apply(lambda x: x.split()[0] + ' US EQUITY')\nresp = LocalTerminal.get_reference_data(members, ['PX_LAST', 'VOLATILITY_30D'])\nresp.as_frame().head()\n\npxs = LocalTerminal.get_historical(members, 'PX_LAST')\nf = pxs.as_frame()\nf.columns = f.columns.get_level_values(0)\n# Show first 5 rows for last 5 days\nf.iloc[:5, -5:]\n\n# --------------------------------------------------------------------------\n# Intraday Tick and Bar\n# --------------------------------------------------------------------------\n\nimport datetime\n\nsid = 'VOD LN EQUITY'\nevents = ['TRADE', 'AT_TRADE']\ndt = pd.datetools.BDay(-1).apply(pd.datetime.now())\nstart = pd.datetime.combine(dt, datetime.time(13, 30))\nend = pd.datetime.combine(dt, datetime.time(13, 35))\nf = LocalTerminal.get_intraday_tick(sid, events, start, end, include_condition_codes=True).as_frame()\nf.head()\n\n# Bar Request\n\n\nimport datetime\n\nsid = 'IBM US EQUITY'\nevent = 'TRADE'\ndt = pd.datetools.BDay(-1).apply(pd.datetime.now())\nstart = pd.datetime.combine(dt, datetime.time(13, 30))\nend = pd.datetime.combine(dt, datetime.time(21, 30))\nf = LocalTerminal.get_intraday_bar(sid, event, start, end, interval=60).as_frame()\nf.head()\n","sub_path":"Test Files/tia-test.py","file_name":"tia-test.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"17911964","text":"\"\"\"\nhttps://code.google.com/codejam/contest/5304486/dashboard\n\"\"\"\nfrom typing import List\n\n\ndef find_adjacent(row: int, col: int, matrix: List[List[str]]) -> List[str]:\n R = len(matrix)\n C = len(matrix[0])\n left = (row - 1, col) if row - 1 >= 0 else None\n right = (row + 1, col) if row + 1 < R else None\n up = (row, col - 1) if col - 1 >= 0 else None\n down = (row, col + 1) if col + 1 < C else None\n\n neighbors = [left, right, up, down]\n\n # print(neighbors)\n return [e for e in [matrix[n[0]][n[1]] for n in neighbors if n] if e != \"?\"]\n\n\ndef check(row: int, col: int, matrix: List[List[str]], letter: str) -> bool:\n R = len(matrix)\n C = len(matrix[0])\n top_left = (row - 1, col - 1)\n left = (row - 1, col)\n bottom_left = (row + 1, col - 1)\n\n top_right = (row - 1, col + 1)\n right = (row + 1, col)\n bottom_right = (row + 1, col + 1)\n\n up = (row, col - 1)\n down = (row, col + 1)\n\n neighbors = [\n n\n for n in [top_left, left, bottom_left, top_right, right, bottom_right, up, down]\n if 0 <= n[0] < R and 0 <= n[1] < C and matrix[n[0]][n[1]] != \"?\"\n ]\n\n for i in range(len(neighbors) - 1):\n for j in range(i + 1, len(neighbors)):\n first = neighbors[i]\n second = neighbors[j]\n if (\n matrix[first[0]][first[1]] == matrix[second[0]][second[1]]\n and first[0] != second[0]\n and first[1] != second[1]\n ):\n return False\n\n return True\n\n\ndef simulate(matrix: List[List[str]]) -> None:\n R = len(matrix)\n C = len(matrix[0])\n\n for rowIndex in range(R):\n row = matrix[rowIndex]\n for colIndex in range(C):\n cell = row[colIndex]\n\n if cell == \"?\":\n neighbors = find_adjacent(rowIndex, colIndex, matrix)\n for n in neighbors:\n if check(rowIndex, colIndex, matrix, n):\n matrix[rowIndex][colIndex]\n\n\ndef to_matrix(m: str) -> List[List[str]]:\n return [[letter for letter in row] for row in m.strip().split()]\n\n\nmatrix = to_matrix(\n \"\"\"\nG??\n?C?\n??J\n\"\"\"\n)\n\nsimulate(matrix)\n","sub_path":"jam/2017/one_a/a_alpha_cake.py","file_name":"a_alpha_cake.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"449525397","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# -------------------------------------------\n# File Name: analyse.py\n# Written by Pierre_Hao\n# Mail: hao.zhang@1000look.com\n# Created Time: Tue 07 Jun 2016 02:10:12 PM CST\n# Copyright (c) 2016 Nanjing Qingsou\n# -------------------------------------------\n\nimport os\nimport shutil\n\ndef main(txt, path):\n f = open(txt,'r')\n lines = f.readlines()\n for line in lines:\n line = line.strip()\n a,p,n,cls = line.split(' ')[:4]\n des = os.path.join(path, str(cls))\n if not os.path.exists(des):\n os.mkdir(des)\n target_a = os.path.join(des, a.split('/')[-1])\n target_p = os.path.join(des, p.split('/')[-1])\n if not os.path.exists(target_a):\n shutil.copy(a, target_a)\n if not os.path.exists(target_p):\n shutil.copy(p, target_p)\n des_n = os.path.join(path, n.split('/')[-2])\n target_n = os.path.join(des_n, n.split('/')[-1])\n if not os.path.exists(des_n):\n os.mkdir(des_n)\n if not os.path.exists(target_n):\n shutil.copy(n, target_n)\n\nif __name__ == \"__main__\":\n txt = '../image/trainset1.txt' \n path = '/media/F/train_data/guwan2/'\n main(txt, path)\n","sub_path":"python/TripletTrain_caffe/tools/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"642039894","text":"__author__ = 'hamed1soleimani'\n\nn = int(input())\nexams = list()\n\nfor i in range(n):\n temp = input().split()\n exams.append((int(temp[0]), int(temp[1])))\n\nexams = sorted(exams, key=lambda s: s[0])\nday = -1\n\nwhile len(exams) != 0:\n temp = exams.pop(0)\n if min(temp) >= day:\n day = min(temp)\n else:\n day = max(temp)\n\n\nprint(day)\n","sub_path":"Algorithms/codeForcesProblemSet/exams.py","file_name":"exams.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"519320665","text":"import sys\nfrom glob import glob\nimport subprocess\nimport os\n\ndef split_pkg(pkg):\n if not pkg.endswith(\".tar.bz2\"):\n raise RuntimeError(\"Can only process packages that end in .tar.bz2\")\n pkg = pkg[:-8]\n plat, pkg_name = pkg.split(\"/\")\n name_ver, build = pkg_name.rsplit('-', 1)\n name, ver = name_ver.rsplit('-', 1)\n return plat, name, ver, build\n\n\ndef get_files():\n return [f for f in glob(\"pkgs/*\") if f != \"pkgs/example.txt\"]\n\n\ndef check_packages():\n for file_name in get_files():\n with open(file_name, \"r\") as f:\n pkgs = f.readlines()\n pkgs = [pkg.strip() for pkg in pkgs]\n for pkg in pkgs:\n # ignore blank lines or Python-style comments\n if pkg.startswith('#') or len(pkg) == 0:\n continue\n plat, name, ver, build = split_pkg(pkg)\n subprocess.check_call(f\"CONDA_SUBDIR={plat} conda search {name}={ver}={build} -c conda-forge --override-channels\", shell=True)\n\n\ntoken_path = os.path.expanduser(\"~/.config/binstar/https%3A%2F%2Fapi.anaconda.org.token\")\n\n\ndef mark_broken_file(file_name):\n with open(file_name, \"r\") as f:\n pkgs = f.readlines()\n pkgs = [pkg.strip() for pkg in pkgs]\n for pkg in pkgs:\n # ignore blank lines or Python-style comments\n if pkg.startswith('#') or len(pkg) == 0:\n continue\n plat, name, ver, build = split_pkg(pkg)\n try:\n subprocess.check_call(f\"anaconda -t {token_path} -v move conda-forge/{name}/{ver}/{pkg} --from-label main --to-label broken\", shell=True)\n except subprocess.CalledProcessError:\n return\n subprocess.check_call(f\"git rm {file_name}\", shell=True)\n subprocess.check_call(f\"git commit -m 'Remove {file_name} after marking broken'\", shell=True)\n subprocess.check_call(\"git show\", shell=True)\n\n\ndef mark_broken():\n if not \"BINSTAR_TOKEN\" in os.environ:\n return\n\n os.makedirs(os.path.expanduser(\"~/.config/binstar\"))\n with open(token_path, \"w\") as f:\n f.write(os.environ[\"BINSTAR_TOKEN\"])\n\n try:\n for file_name in get_files():\n mark_broken_file(file_name)\n finally:\n os.remove(token_path)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n raise RuntimeError(\"Need 1 and only 1 argument\")\n if sys.argv[1] == 'check':\n check_packages()\n elif sys.argv[1] == 'mark':\n mark_broken()\n else:\n raise RuntimeError(f\"Unrecognized argument {sys.argv[1]}\")\n\n","sub_path":"mark_broken.py","file_name":"mark_broken.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"527062198","text":"import sys\nimport re\n\nsentence_lst = []\nfor line in sys.stdin: \n\tsentence_lst.append(line)\n\nhist_file = open(sys.argv[1])\ndict = {}\nfor line in hist_file: \n\tline = line.strip(\"\\n\")\n\tline = line.strip(\" \")\n\tlst_line = line.split(\" \")\n\tif len(lst_line) > 1 and lst_line[1]: \n\t\tlst_line[1] = lst_line[1].lower()\n\t\tif lst_line[1] in dict: \n\t\t\tdict[lst_line[1]] = dict[lst_line[1]] + lst_line[0]\n\t\telse: \n\t\t\tdict[lst_line[1]] = lst_line[0]\n\nfor sentence in sentence_lst: \n\tprint_string = \"\"\n\tsentence = sentence.strip(\"\\n\")\n\tlst_sentence = sentence.split(\" \")\n\tfor word in lst_sentence: \n\t\tword = word.lower()\n\t\tend_punctuation = \"\"\n\t\tif re.search(\"[!?.,]\", word[-1]): \n\t\t\tend_punctuation = word[-1]\n\t\t\tword = word[0:len(word) - 1]\n\t\tif word not in dict:\n\t\t\tprint_string += \"*\"\n\t\tprint_string += word + end_punctuation + \" \"\n\tprint(print_string)\n\n\t\n\t\n\t","sub_path":"basic _python/spellchecker.py","file_name":"spellchecker.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"192398042","text":"from pyo import *\n\ns = Server().boot()\ns.start()\n\na = SineLoop([449,450], feedback=0.05, mul=.2)\nb = SineLoop([650,651], feedback=0.05, mul=.2)\n\nc = InputFader(a).out()\n# c.__setattr__(\"fadetime\", 5) # didnt work, tyrintg to just fade a single audio signal\n\nc.setInput(b, fadetime=1) # assign a new audio input to created a crossfade\n\ns.gui(locals())\n","sub_path":"pyo_scripts/pyo_input_fader.py","file_name":"pyo_input_fader.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"21005772","text":"import re\n\nclass Tokenizer(object):\n\n def __init__(self, file):\n self.currentToken = None\n self.tokenIndex = None\n self.loadLists()\n self.loadDictionary()\n fhand = open(file)\n self.file = fhand.readlines()\n self.prepare()\n self.toEnd = len(self.file)\n\n def loadLists(self):\n self.keywords = [\n 'class',\n 'constructor',\n 'function',\n 'method',\n 'field',\n 'static',\n 'var',\n 'int',\n 'char',\n 'boolean',\n 'void',\n 'true',\n 'false',\n 'null',\n 'this',\n 'let',\n 'do',\n 'if',\n 'else',\n 'while',\n 'return'\n ]\n self.symbols = [\n '{', '}', '(', ')', '[', ']', '.',\n ',', ';', '+', '-', '*', '/', '&',\n '|', '<', '>', '=', '~'\n ]\n\n def loadDictionary(self):\n self.symbolSwitch = {\n '<':'<',\n '>': '>',\n '\"': '"',\n '&': '&'\n }\n\n def prepare(self):\n cleanedFile = []\n\n for line in self.file:\n line = line.strip()\n if line == '':\n continue\n if line[0] == '/':\n continue\n if line[0] == '*':\n continue\n if '/*' in line:\n fields = line.split('/*')\n line = fields[0]\n if '//' in line:\n fields = line.split('//')\n line = fields[0]\n #print(line)\n tokenized = re.findall(r'[\\w]+|[*\\{\\}()\\[\\].,;+\\\\\\-&/|<>=~\\?]|[\\\"\\'].+[\\\"\\']', line)\n for token in tokenized:\n cleanedFile.append(token)\n #print(token)\n\n self.file = cleanedFile\n #print(self.file)\n\n def writetoXML(self, line):\n self.output.write(line + '\\n')\n\n##### API ######\n\n\n def hasMoreTokens(self):\n if self.toEnd > 0:\n return True\n else:\n return False\n\n def advance(self):\n if self.currentToken == None:\n self.tokenIndex = 0\n else:\n self.tokenIndex = self.tokenIndex +1\n self.currentToken = self.file[self.tokenIndex]\n self.toEnd = self.toEnd - 1\n # if self.currentToken == \"\\\"\":\n # stringToken = \"\\\"\"\n # lookAheadIndex = 1\n # while(self.file[self.tokenIndex + lookAheadIndex] != \"\\\"\"):\n # stringToken += self.file[self.tokenIndex + lookAheadIndex]\n # lookAheadIndex = lookAheadIndex + 1\n # if self.file[self.tokenIndex + lookAheadIndex] != \"\\\"\":\n # stringToken += \" \"\n # self.currentToken = stringToken\n # self.tokenIndex = self.tokenIndex + lookAheadIndex\n # self.toEnd = self.toEnd - lookAheadIndex\n\n def tokenType(self):\n if self.currentToken in self.keywords:\n return('KEYWORD')\n elif self.currentToken in self.symbols:\n return('SYMBOL')\n elif str.isdigit(self.currentToken):\n if 0 <= int(self.currentToken) <= 32767:\n return('INT_CONST')\n elif self.currentToken[0] == '\"':\n return('STRING_CONST')\n match = re.fullmatch(r'[a-zA-Z_]+[0-9a-zA-Z_]*', self.currentToken)\n if match != None:\n return('IDENTIFIER')\n print('Made it through all possible token types... :(')\n\n def symbol(self):\n if self.tokenType() == 'SYMBOL':\n if any(str in self.currentToken for str in self.symbolSwitch):\n return self.symbolSwitch[self.currentToken]\n else:\n return self.currentToken\n\n def identifier(self):\n if self.tokenType() == 'IDENTIFIER':\n return self.currentToken\n\n def intVal(self):\n if self.tokenType() == 'INT_CONST':\n return int(self.currentToken)\n\n def stringVal(self):\n if self.tokenType() == \"STRING_CONST\":\n return self.currentToken[1:-1]\n","sub_path":"JackTokenizer.py","file_name":"JackTokenizer.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"594432088","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef partition_function(T,epsilon,g):\n Z_list = []\n for i in T:\n Z = 0\n for j,m in zip(epsilon,g):\n Z = Z + m * np.exp(-j/(k*i))\n Z_list.append(Z)\n return np.array(Z_list)\n\ndef fraction_population(g,T,epsilon,Z):\n frac_pop_list = []\n for j in range(len(epsilon)): \n frac_pop = (g[j] * np.exp(-epsilon[j]/(k*T)))/Z\n frac_pop_list.append(frac_pop)\n frac_pop_list = np.array(frac_pop_list)\n return frac_pop_list\n\ndef internal_energy(frac_pop,N,epsilon,T):\n N_j = N * frac_pop\n inte_energy = np.zeros([len(T)])\n for i in range(len(N_j)):\n inte_energy = inte_energy + N_j[i]*epsilon[i]\n return inte_energy\n\ndef entropy(Z,N,T,U):\n S = (N*k*np.log(Z/N)) + (U/T) + (N*k)\n return S\n\ndef free_energy(N,T,Z):\n F = -N*k*T*np.log(Z)\n return F\n\ndef graph(x1,x2,y1,y2,title,y_label,frac_pop_low,frac_pop_high,key):\n fig1,ax1 = plt.subplots(1,2)\n fig1.suptitle(title)\n if key == 0:\n ax1[0].scatter(x1,y1,label = \"Low Temperature\")\n ax1[0].set_xlabel(\"T\")\n ax1[0].set_ylabel(y_label)\n ax1[0].grid(ls = \"--\")\n ax1[0].legend()\n ax1[1].scatter(x2,y2,label = \"High Temperature\")\n ax1[1].set_xlabel(\"T\")\n ax1[1].set_ylabel(y_label)\n ax1[1].grid(ls = \"--\")\n ax1[1].legend()\n plt.show()\n elif key == 1:\n for i in range(len(frac_pop_low)):\n ax1[0].scatter(x1,frac_pop_low[i],label = \"LowTemperature\")\n ax1[1].scatter(x2,frac_pop_high[i],label = \"High Temperature\")\n ax1[0].set_xlabel(\"T\")\n ax1[0].set_ylabel(\"$\\\\dfrac{N_i}{N}$\")\n ax1[1].set_xlabel(\"T\")\n ax1[1].set_ylabel(\"$\\\\dfrac{N_i}{N}$\")\n ax1[0].grid(ls = \"--\")\n ax1[1].grid(ls = \"--\")\n ax1[0].legend()\n ax1[1].legend()\n plt.show()\n \nif __name__ == \"__main__\":\n k = 8.617 * 10**(-5)\n \n T_low = np.linspace(10**(-18),5000,50)\n T_high = np.linspace(5000,10**(5),50)\n\n g = [1,1] ; epsilon = [0,1]\n\n Z_1 = partition_function(T_low,epsilon,g)\n Z_2 = partition_function(T_high,epsilon,g)\n \n frac_pop_low = fraction_population(g,T_low,epsilon,Z_1)\n frac_pop_high = fraction_population(g,T_high,epsilon,Z_2)\n \n U_low = internal_energy(frac_pop_low,1,epsilon,T_low)\n U_high = internal_energy(frac_pop_high,1,epsilon,T_high)\n \n S_low = entropy(Z_1,1,T_low,U_low)\n S_high = entropy(Z_2,1,T_high,U_high)\n \n F_low = free_energy(1,T_low,Z_1)\n F_high = free_energy(1,T_high,Z_2)\n \n graph(T_low,T_high,Z_1,Z_2,\"Partition Function\",\"Z\",None,None,0)\n graph(T_low,T_high,None,None,\"Fraction Population\",None,frac_pop_low,frac_pop_high,1)\n graph(T_low,T_high,U_low,U_high,\"Internal Energy\",\"U\",None,None,0)\n graph(T_low,T_high,S_low,S_high,\"Entropy\",\"S\",None,None,0)\n graph(T_low,T_high,F_low,F_high,\"Helmholtz free energy\",\"F\",None,None,0)\n\n \n\n","sub_path":"exp6.py","file_name":"exp6.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"65024053","text":"import json\nimport os\n\nfrom pymongo import MongoClient\n\nif not os.getenv('IS_PROD'):\n from dotenv import load_dotenv\n load_dotenv()\n\nclient = MongoClient(\n f'mongodb+srv://{os.getenv(\"MONGODB_USER\")}:{os.getenv(\"MONGODB_PASSWORD\")}@'\n 'cluster0-gwjng.mongodb.net/admin?retryWrites=true&w=majority', connect=False\n)\ndb = client.Contractor\nitems = db.items\n\ndef add_items(path='data/items.json'):\n with open(path) as f:\n for line in f:\n items.insert_one(json.loads(line))\n\ndef drop_items():\n items.drop()\n\n\nif __name__ == '__main__':\n drop_items()\n add_items()\n","sub_path":"add_items.py","file_name":"add_items.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"276971149","text":"# -*- coding=UTF-8 -*-\n# pyright: strict, reportTypeCommentUsage=none\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from typing import Text\n\nimport codecs\nimport datetime\nimport hashlib\nimport json\nimport os\nimport shutil\nimport nuke\n\n\nfrom wulifang._compat import futures\nfrom wulifang._util import (\n TZ_CHINA,\n FileSequence,\n cast_text,\n iteritems,\n cast_str,\n cast_binary,\n)\nfrom wulifang.nuke._util import (\n iter_deep_all_nodes,\n gizmo_to_group,\n knob_of,\n Progress,\n)\n\n# spell-checker: words Changeds\n\n\nclass _Context(object):\n def __init__(self):\n self.project_dir_old = cast_text(nuke.value(cast_str(\"root.project_directory\")))\n self.script_name = cast_text(nuke.scriptName())\n self.script_dir = cast_text(os.path.dirname(self.script_name))\n self.file_dir = cast_text(self.script_name) + \".files\"\n self.file_dir_base = os.path.basename(self.file_dir)\n self.executor = futures.ThreadPoolExecutor(max_workers=32)\n try:\n os.makedirs(self.file_dir)\n except:\n pass\n self.log_file = codecs.open(\n os.path.join(self.file_dir, \"工程打包日志.txt\"),\n \"a\",\n encoding=\"utf-8\",\n )\n self._log(\"开始\")\n self._log(\"工程文件:%s\" % self.script_name)\n self._log(\"原工程目录:%s\" % self.project_dir_old)\n\n def __enter__(self):\n return self\n\n def __exit__(self, *_):\n self.executor.shutdown()\n self.log_file.close()\n\n def _log(self, msg):\n # type: (Text) -> None\n self.log_file.write(\n \"[%s] %s\\r\\n\" % (datetime.datetime.now(TZ_CHINA).isoformat(), msg)\n )\n\n def log(self, msg):\n # type: (Text) -> None\n self._log(msg)\n\n def get_src(self, k):\n # type: (nuke.File_Knob) -> Text\n input = cast_text(k.getText())\n if not input:\n return \"\"\n try:\n file_sequence = next(\n FileSequence.from_paths(\n (\n cast_text(k.evaluate(frame))\n for frame in range(\n nuke.Root().firstFrame(), nuke.Root().lastFrame() + 1\n )\n )\n )\n )\n output = file_sequence.expr\n if input != output:\n self.log(\n \"%s.%s: 计算表达式:输入='%s', 输出='%s'\"\n % (k.node().fullName(), k.name(), input, output)\n )\n return output\n except Exception as ex:\n self.log(\n \"%s.%s: 无法处理表达式:'%s': %s\" % (k.node().fullName(), k.name(), input, ex)\n )\n return input\n\n\ndef _hashed_dir(dir_path):\n # type: (Text) -> Text\n parent, p = os.path.split(dir_path)\n h = hashlib.sha256(cast_binary(os.path.normpath(parent))).hexdigest()\n return \"%s.@%s\" % (p, h[:8])\n\n\ndef _is_weak_same(a, b):\n # type: (Text, Text) -> bool\n try:\n stat_a = os.stat(a)\n stat_b = os.stat(b)\n except:\n return False\n\n return (\n stat_a.st_size == stat_b.st_size and abs(stat_a.st_mtime - stat_b.st_mtime) < 1\n )\n\n\ndef _save_by_expr(ctx, src_expr):\n # type: (_Context, Text) -> Text\n src_dir, src_base = os.path.split(src_expr)\n\n _dir_with_hash = _hashed_dir(src_dir)\n dst_dir = os.path.join(ctx.file_dir, _dir_with_hash)\n\n try:\n os.makedirs(dst_dir)\n except:\n pass\n with codecs.open(dst_dir + \".json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(\n {\"sourcePath\": src_expr},\n f,\n indent=2,\n ensure_ascii=False,\n )\n\n try:\n files = os.listdir(src_dir)\n except:\n ctx.log(\"目录无法访问: %s\" % src_dir)\n files = []\n\n seq = FileSequence(os.path.normcase(src_base))\n\n def _copy_file(i):\n # type: (Text) -> None\n src = os.path.join(src_dir, i)\n dst = os.path.join(dst_dir, i)\n if _is_weak_same(src, dst):\n return\n shutil.copy2(src, dst)\n\n for _ in ctx.executor.map(_copy_file, (i for i in files if os.path.normcase(i) in seq)): # type: ignore\n pass\n\n return \"/\".join((ctx.file_dir_base, _dir_with_hash, src_base))\n\n\ndef pack_project():\n try:\n nuke.scriptName()\n except RuntimeError:\n nuke.message(cast_str(\"请先保存工程\"))\n return\n\n with nuke.Undo(cast_str(\"打包工程\")), _Context() as ctx, Progress(\n \"打包工程\",\n estimate_secs=600,\n ) as p:\n knob_of(\n nuke.root(),\n \"project_directory\",\n nuke.File_Knob,\n ).setValue(cast_str(\"[python {nuke.script_directory()}]\"))\n\n p.set_message(\"Gizmo 转换为 Group\")\n for n in iter_deep_all_nodes():\n p.increase()\n if isinstance(n, nuke.Gizmo):\n p.set_message(\"Gizmo 转换为 Group: %s\" % (cast_text(n.fullName()),))\n name = cast_text(n.fullName())\n if n.Class() in nuke.knobChangeds:\n ctx.log(\"%s: 此类型节点有脚本回调,无法转为 Group\" % (name,))\n continue\n gizmo_to_group(n)\n ctx.log(\"将 %s 转为了 Group\" % (name,))\n\n p.set_message(\"打包素材\")\n for n in iter_deep_all_nodes():\n p.increase()\n for _, k in iteritems(n.knobs()):\n if isinstance(k, nuke.File_Knob):\n p.set_message(\"复制文件: %s\" % cast_text(k.fullyQualifiedName()))\n p.increase()\n old_src = ctx.get_src(k)\n if not old_src or old_src.startswith(ctx.file_dir_base):\n continue\n ctx.log(\"打包文件: %s.%s: %s\" % (n.fullName(), k.name(), old_src))\n new_src = _save_by_expr(\n ctx, os.path.join(ctx.project_dir_old, old_src)\n )\n k.setText(cast_str(new_src))\n if isinstance(k, nuke.FreeType_Knob):\n p.set_message(\"重置字体: %s\" % cast_text(k.fullyQualifiedName()))\n p.increase()\n old_value = k.getValue()\n if cast_text(old_value[0]) != \"Utopia\":\n k.setValue(cast_str(\"Utopia\"), cast_str(\"Regular\"))\n ctx.log(\n \"%s.%s: 设置 FreeType 字体为 Utopia(Nuke 自带):原始值=%s\"\n % (n.fullName(), k.name(), old_value)\n )\n ctx.log(\"完成\")\n nuke.message(\n cast_str(\"项目打包完毕\\n文件保存目录: %s\\n工程内的文件路径已全部替换,请检查后保存\" % (ctx.file_dir,))\n )\n","sub_path":"wulifang/nuke/_pack_project.py","file_name":"_pack_project.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"627255552","text":"from django.conf.urls import url\nfrom django.contrib.auth import views as auth_views\n\n\nfrom .import views\n\nurlpatterns = [\n url(r'^Default.html$', views.default, name='default'),\n url(r'^profiles/$', views.profiles, name='profiles'),\n url(r'^statuses/$', views.statuses, name='statuses'),\n url(r'^statuses-delete/$', views.statuses_delete, name='statuses-delete'),\n url(r'^login/$', auth_views.login,{'template_name': 'registration/login.html'}, name='login'),\n url(r'^logout/$', auth_views.logout, name='logout'),\n]\n","sub_path":"profiles_view/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"397455419","text":"import sqlite3\nimport hashlib\nimport datetime\nimport string\nimport random\nimport datetime\n\n\"\"\" cria 200 usuarios e 10000 horarios para verificar o tamanho do banco de dados\"\"\"\ndef main():\n with sqlite3.connect(\"scar.db\") as con:\n for i in range(200):\n print(\"creating usuario \",i)\n createUser(con,\n randomString(128),\n randomString(16,string.digits),\n randomString(8,string.digits),\n i\n )\n print(\"usuarios criados\")\n con.commit()\n\n users = con.cursor().execute(\"SELECT * FROM usuario\").fetchmany(100)\n\n for i in range(10000):\n print(\"creating horario \",i)\n createHorario(con,\n datetime.datetime.now(),\n datetime.datetime.now()+datetime.timedelta(days = 10),\n users[random.randint(0,99)][1]\n )\n print(\"horarios criados\")\n con.commit()\n\ndef randomString(stringLength,string_type=string.ascii_letters):\n \"\"\"Generate a random string with the combination of lowercase and uppercase letters \"\"\"\n letters = string_type\n return ''.join(random.choice(letters) for i in range(stringLength))\n\ndef createUser(con, nome, id, senha, impressao_digital = None):\n senha = hashlib.md5(senha.encode('utf8')).hexdigest()\n con.cursor().execute(\"\"\"\n INSERT INTO usuario\n (nome, id, senha, impressao_digital)\n VALUES (?,?,?,?)\"\"\",\n (nome, id, senha, impressao_digital)\n )\n return True\n\ndef createHorario(con, horario_entrada,horario_saida,index):\n con.cursor().execute(\n \"\"\"INSERT INTO horario\n (horario_entrada,horario_saida, usuario_id)\n VALUES (?,?,?)\"\"\"\n , (horario_entrada,horario_saida, index)\n )\n #print(horario_entrada,horario_saida,index)\n return True\n\nclass Dao:\n \"\"\"db_nome: caminho do banco de dados a ser aberto\"\"\"\n def __init__(self, db_name):\n self.db_name = db_name\n\n def deleteUser(self, id):\n with sqlite3.connect(self.db_name) as con:\n con.cursor().execute(\"DELETE FROM usuario WHERE id = ?\",(id,))\n con.commit()\n\n def readUser(self, id):\n with sqlite3.connect(self.db_name) as con:\n return con.cursor().execute(\"SELECT * FROM usuario WHERE id = ?\", (id,)).fetchone()\n\n def updateUser(self, id, novo_id, nome, senha, impressao_digital=-1):\n with sqlite3.connect(self.db_name) as con:\n con.cursor().execute(\"UPDATE usuario SET impressao_digital = ? WHERE id = ? LIMIT 1\", (impressao_digital, id))\n if(nome):\n con.cursor().execute(\"UPDATE usuario SET nome = ? WHERE id = ? LIMIT 1\", (nome, id))\n if(senha):\n senha = hashlib.md5(senha.encode('utf8')).hexdigest()\n con.cursor().execute(\"UPDATE usuario SET senha = ? WHERE id = ? LIMIT 1\", (senha, id))\n if(novo_id):\n con.cursor().execute(\"UPDATE usuario SET id = ? WHERE id = ? LIMIT 1\", (novo_id, id))\n con.commit()\n return True\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"exemplos/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"161811019","text":"# -*- coding:utf-8 -*-\nfrom random import randint\n\n\ndef selection_sort(items: list) -> list:\n length = len(items)\n if length < 1:\n return items\n for i in range(length - 1):\n min_index = i + 1\n for j in range(i + 2, length):\n if items[j] < items[min_index]:\n min_index = j\n if items[min_index] < items[i]:\n items[i], items[min_index] = items[min_index], items[i]\n return items\n\n\ndef test():\n for _ in range(20):\n items = [randint(1, 20) for _ in range(50)]\n result1 = list(sorted(items))\n result2 = selection_sort(items)\n assert result2 == result1\n\n for _ in range(20):\n items = [randint(1, 10 ** 6) for _ in range(50)]\n result1 = list(sorted(items))\n result2 = selection_sort(items)\n assert result2 == result1\n","sub_path":"algorithm/sort/selection_sort/selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"486609910","text":"# For python 3 portability\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\nfrom builtins import (super)\n\nfrom pyWAT.collections.wrfNetcdfFileCollection import wrfNetcdfFileCollection\nfrom pyWAT.io.wrfRestart import wrfRestart\n\n\nclass wrfRestartCollection(wrfNetcdfFileCollection):\n '''\n Class to handle the a collection of WRF restart files. \n \n Multiple Domains not supported yet!\n \n '''\n\n def __init__(self , inputFilesOrDirectory=None, exactDates=False):\n \"\"\"\n Constructor\n \n Parameters\n ----------\n \n inputFilesOrDirectory : str, list or tuple.\n List or tuple of Directory or file paths\n \n See :py:meth:`add` for more information.\n \n \n exactDates : bool, optional\n Flag to indicate if exact dates (True) or nearest (False) dates are\n used when retrieving elements from the collection.\n \"\"\"\n \n super().__init__(inputFilesOrDirectory=inputFilesOrDirectory,\n exactDates=exactDates,\n dataClass=wrfRestart)\n \n\n \n def add(self, inputFilesOrDirectory, mode='r'):\n \"\"\" \n \n Add all the information of a single wrfRestart file or directory. It supports as input argument \n a list or a tuple with directories or file path.\n \n All the times available in the files are added\n \n See \n :py:meth: `pyWAT.collections.wrfNetcdfFileCollection.wrfNetcdfFileCollection.add`\n for more details.\n \n \"\"\" \n \n super().add(inputFilesOrDirectory,\n mode=mode,\n pattern=\"wrfrst_d01*\",\n dataClass=wrfRestart)\n \n \n \n \n","sub_path":"pyWAT/collections/wrfRestartCollection.py","file_name":"wrfRestartCollection.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"562085153","text":"\"\"\"\nСчетчик гласных\nВводится строка, и программа считает количество гласных в тексте.\nДля усложнения задачи можно генерировать отчет о том, сколько раз какая\nгласная была найдена.\n\"\"\"\n\n\ndef vowel_counter(words): # Счетчик всех гласных\n count = 0\n for i in words:\n if i in 'aeiou':\n count += 1\n return count\n\n\ndef sum_different_vowel(words): # Подсчет гласных поштучно\n for i in 'aeiou':\n print('букв ', i, ' в строке', words.count(i), 'штук')\n\n\ndef main():\n words = str(input('Введите вашу строку: ')).lower()\n print(vowel_counter(words))\n sum_different_vowel(words)\n input('нажмите ентр чтоб выйти')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2018-2019/learning/schetchik_glasnyih.py","file_name":"schetchik_glasnyih.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"427461831","text":"\"\"\"\n\n.. moduleauthor:: Jordi Fernández <jordi.fernandez@whads.com>\n\"\"\"\nfrom createsend import CreateSend, Subscriber, BadRequest\nfrom cocktail.translations import translations\nfrom cocktail import schema\nfrom cocktail.pkgutils import import_object\nfrom cocktail.controllers import (\n Controller,\n FormProcessor,\n Form,\n request_property,\n redirect\n)\nfrom woost.models import Configuration\nfrom .campaignmonitorlist import CampaignMonitorList\n\ntranslations.load_bundle(\"woost.extensions.campaign3.subscriptioncontroller\")\n\n\nclass SubscriptionController(FormProcessor, Controller):\n\n class SubscriptionForm(Form):\n\n is_new = None\n\n @request_property\n def model(self):\n return import_object(self.controller.block.subscriber_model)\n\n @request_property\n def schema(self):\n adapted_schema = Form.schema(self)\n\n if len(self.controller.block.lists) > 1:\n lists = schema.Collection(\n name = \"lists\",\n items = schema.Reference(type = CampaignMonitorList),\n min = 1,\n edit_control = \"cocktail.html.CheckList\",\n )\n adapted_schema.add_member(lists)\n self.adapter.exclude(lists.name)\n\n return adapted_schema\n\n @request_property\n def subscribed_lists(self):\n return self.data.get(\"lists\") or self.controller.block.lists\n\n @request_property\n def email(self):\n return self.data[\"subscriber_email\"]\n\n @request_property\n def name(self):\n return self.data[\"subscriber_name\"]\n\n @request_property\n def custom_fields(self):\n return []\n\n def submit(self):\n Form.submit(self)\n for list in self.subscribed_lists:\n self.add_subscriber(list)\n\n def add_subscriber(self, list):\n\n subscriber = Subscriber(\n {\"api_key\": Configuration.instance.get_setting(\"x_campaign3_api_key\")}\n )\n\n # Check if the user is new to any list\n try:\n response = subscriber.get(list.list_id, self.email)\n except BadRequest:\n self.is_new = True\n else:\n if response.State != \"Active\":\n self.is_new = True\n\n response = subscriber.add(\n list.list_id,\n self.email,\n self.name,\n self.custom_fields,\n True\n )\n\n def after_submit(self):\n # Redirect the user to the confirmation success page of the first\n # list if the subscriber is already subscribed to all lists\n if not self.is_new:\n for list in self.subscribed_lists:\n if (\n list.confirmation_success_page\n and list.confirmation_success_page.is_accessible()\n ):\n redirect(list.confirmation_success_page.get_uri())\n\n # Redirect the user to the confirmation page\n for list in self.subscribed_lists:\n if (\n list.confirmation_page\n and list.confirmation_page.is_accessible()\n ):\n redirect(list.confirmation_page.get_uri())\n\n","sub_path":"woost/extensions/campaign3/subscriptioncontroller.py","file_name":"subscriptioncontroller.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"358333064","text":"import re\n\nfrom typing import List, Dict\n\nUNNECESSARY_FILES = {\n \"base-files\",\n \"ca-certificates\",\n \"cloud-guest-utils\",\n \"cloud-init\",\n \"cloud-initramfs-copymods\",\n \"command-not-found\",\n \"command-not-found-data\",\n \"debianutils\",\n \"debconf\",\n \"debconf-i18n\",\n \"distro-info-data\",\n \"dpkg\",\n \"e2fslibs\",\n \"e2fsprogs\",\n \"ed\",\n \"eject\",\n \"file\",\n \"fonts-ubuntu-font-family-console\",\n \"geoip-database\",\n \"hostname\",\n \"init-system-helpers\",\n \"install-info\",\n \"keyboard-configuration\",\n \"language-selector-common\",\n \"linux-base\",\n \"locales\",\n \"man-db\",\n \"manpages\",\n \"mime-support\",\n \"mlocate\",\n \"readline-common\",\n \"rename\",\n \"sed\",\n \"grep\",\n \"ed\",\n \"awk\",\n \"gawk\",\n \"software-properties-common\",\n \"sosreport\",\n \"ubuntu-minimal\",\n \"ubuntu-release-upgrader-core\",\n \"ubuntu-standard\",\n \"unattended-upgrades\",\n \"update-manager-core\",\n \"update-notifier-common\",\n \"uuid-runtime\",\n \"vim-common\",\n \"at\"\n}\n\nRELEASE_REGEX = re.compile(r'''([\\d\\.]+)(-)([\\d]+)''')\nOPTIMUM_LIMIT_FOR_ADD_RELEASE = 80\n\n\ndef dpkg_builder(package: List[Dict[str, str]],\n max_packages_to_analyze: int = 300) -> str:\n \"\"\"Return the full text query\"\"\"\n query = set()\n packages_to_analyze = 0\n total_packages = len(package)\n for lib in package:\n library = lib.get(\"library\", None)\n version = lib.get(\"version\", None)\n\n if not library or not version or library in UNNECESSARY_FILES:\n continue\n\n # --------------------------------------------------------------------------\n # Usually this query is very heavy. We'll try to do thinker removing\n # unnecessary libraries\n # --------------------------------------------------------------------------\n\n # lib* -> *\n if library.startswith(\"lib\"):\n library = library[len(\"lib\"):]\n\n # python3-* -> *\n if library.startswith((\"python3-\", \"python2-\")):\n library = library[len(\"python3-\"):]\n\n # *-examples\n if any(library.endswith(x) for x in (\n \"-examples\", \"-doc\", \"-src\", \"-dbg\"\n )) or any(x in library for x in (\n \"-dev\", \"-core\", \"-data\", \"-extra\", \"-utils\", \"-runtime\",\n \"-common\"\n )):\n continue\n library_full_text = f'{library.lower()}:D'\n\n # --------------------------------------------------------------------------\n # Filter for versions\n # --------------------------------------------------------------------------\n has_two_points = version.find(\":\")\n if has_two_points:\n version = version[has_two_points + 1:]\n\n # Case to parse:\n # 5.22.1-9ubuntu0.2\n # Valid result:\n # 5.22.1:rc9\n # TODO: Improve that: if we uncomment bellow code query to database is\n # TODO: really slow\n release = None\n has_sep = version.find(\"-\")\n if has_sep:\n _re = RELEASE_REGEX.search(version)\n if _re:\n version, _, release = _re.groups()\n\n if release:\n # With more than 100 elements, PostgresSQL Query is very slow\n if total_packages < OPTIMUM_LIMIT_FOR_ADD_RELEASE:\n version_full_text = f\"({version}:D | {release}:*)\"\n else:\n version_full_text = f\"{version}:D\"\n else:\n version_full_text = f\"{version}:D\"\n\n # Case to parse:\n # 1.3.dfsg2-1build1\n # Valid result\n # 1.3:rc2\n\n if packages_to_analyze > max_packages_to_analyze:\n break\n\n # --------------------------------------------------------------------------\n # Build queries\n # --------------------------------------------------------------------------\n full_text_query = f\"{library_full_text} & {version_full_text}\"\n\n if library == \"at\":\n print(library)\n\n q_select = f\"(Select '{library.lower()}:{version.lower()}', \" \\\n f\"v.cve, \" \\\n f\"v.cpe, v.cvss, \" \\\n f\"v.summary \" \\\n f\"from prodvuln_view as v \" \\\n f\"where to_tsvector('english', v.cpe) @@ to_tsquery(\" \\\n f\"'{library_full_text}') AND \" \\\n f\"to_tsvector('english', v.cpe) @@ to_tsquery(\" \\\n f\"'{version_full_text}') \" \\\n f\"order by v.cpe desc, v.cvss desc limit 10) \"\n\n query.add(q_select)\n\n packages_to_analyze += 1\n\n q = \" UNION ALL \".join(query)\n return q\n","sub_path":"server/patton_server/service/input_sources/dpkg.py","file_name":"dpkg.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"19555862","text":"class Vehicle:\r\n count=0\r\n\r\n def __init__(self,veh_id, veh_type, user, checkin, checkout=None):\r\n self.veh_type=veh_type\r\n self.veh_id=veh_id\r\n self.user = user\r\n self.checkin = checkin\r\n self.checkout = checkout\r\n \r\n def show_info(self):\r\n print(\"Vehicle Registration No : \", self.veh_id)\r\n print(\"Vehicle Type : \", self.veh_type)\r\n\r\nclass ParkingLot:\r\n\r\n def __init__(self,parking_capacity, valid_vehicles):\r\n import copy\r\n self.levels = len(parking_capacity)\r\n self.valid_vehicle = valid_vehicles\r\n self.parking_capacity = parking_capacity\r\n self.parking_status = copy.deepcopy(parking_capacity)\r\n for level in self.parking_status:\r\n for veh in list(level):\r\n level[veh]=0\r\n\r\n def check_space(self, veh_type):\r\n for level in range(0,self.levels):\r\n if self.parking_capacity[level][veh_type] > self.parking_status[level][veh_type]:\r\n return 1\r\n return -1\r\n\r\n def add_vehicle(self,vr,vt):\r\n v1=Vehicle(vr,vt)\r\n if v1.veh_type not in self.valid_vehicle:\r\n print('Vehicle Type Not Valid')\r\n else:\r\n for level in range(0,len(self.parking_status)):\r\n if self.parking_status[level][v1.veh_type] <= self.parking_capacity[level][v1.veh_type]:\r\n self.parking_status[level][v1.veh_type] += 1\r\n self.parked_vehicles.append(v1)\r\n return\r\n else:\r\n print('No Parking Space')\r\n \r\n def check_valid_vehicle(self, veh_type):\r\n if veh_type not in self.valid_vehicle:\r\n return -1\r\n else:\r\n return 1\r\n\r\n def show_parking_capacity(self):\r\n print(self.parking_capacity)\r\n \r\n def show_parking_status(self):\r\n print(self.parking_status)\r\n \r\n def list_parked_vehicles(self):\r\n for vehicle in self.parked_vehicles:\r\n print(vehicle.show_info)\r\n","sub_path":"parkinglot.py","file_name":"parkinglot.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"533662459","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/dataclay/DataClayObject.py\n# Compiled at: 2020-01-30 08:10:55\n# Size of source mod 2**32: 37790 bytes\n\"\"\"Management of Python Classes.\n\nThis module is responsible of management of the Class Objects. A central Python\nMetaclass is responsible of Class (not object) instantiation.\n\nNote that this managers also includes most serialization/deserialization code\nrelated to classes and function call parameters.\n\"\"\"\nimport inspect, traceback, logging, copy, re\nfrom operator import attrgetter\nfrom uuid import UUID\nimport six\nif six.PY2:\n from cPickle import Pickler, Unpickler\nelse:\n if six.PY3:\n from _pickle import Pickler, Unpickler\nimport uuid\nfrom dataclay.DataClayObjMethods import dclayMethod\nfrom dataclay.DataClayObjProperties import DCLAY_PROPERTY_PREFIX, PreprocessedProperty, DynamicProperty, ReplicatedDynamicProperty\nfrom dataclay.DataClayObjectExtraData import DataClayInstanceExtraData, DataClayClassExtraData\nfrom dataclay.commonruntime.ExecutionGateway import ExecutionGateway, class_extradata_cache_client, class_extradata_cache_exec_env\nfrom dataclay.commonruntime.Runtime import getRuntime\nimport dataclay.commonruntime.RuntimeType as RuntimeType\nfrom dataclay.serialization.lib.DeserializationLibUtils import DeserializationLibUtilsSingleton, PersistentLoadPicklerHelper\nfrom dataclay.serialization.lib.SerializationLibUtils import SerializationLibUtilsSingleton, PersistentIdPicklerHelper\nimport dataclay.serialization.python.lang.BooleanWrapper as BooleanWrapper\nimport dataclay.serialization.python.lang.StringWrapper as StringWrapper\nimport dataclay.serialization.python.lang.IntegerWrapper as IntegerWrapper\nimport dataclay.serialization.python.lang.DCIDWrapper as DCIDWrapper\nfrom dataclay.util.StubUtils import load_babel_data\nfrom dataclay.util.classloaders.ClassLoader import load_metaclass\nimport dataclay.util.management.classmgr.Type as Type\nimport dataclay.util.management.classmgr.UserType as UserType\nfrom dataclay.exceptions.exceptions import DataClayException, ImproperlyConfigured\nimport six\n__author__ = 'Alex Barcelo <alex.barcelo@bsc.es>'\n__copyright__ = '2016 Barcelona Supercomputing Center (BSC-CNS)'\nlogger = logging.getLogger(__name__)\nre_property = re.compile(\"(?:^\\\\s*@dclayReplication\\\\s*\\\\(\\\\s*(before|after)Update\\\\s*=\\\\s*'([^']+)'(?:,\\\\s(before|after)Update='([^']+)')?(?:,\\\\sinMaster='(True|False)')?\\\\s*\\\\)\\\\n)?^\\\\s*@ClassField\\\\s+([\\\\w.]+)[ \\\\t]+([\\\\w.\\\\[\\\\]<> ,]+)\", re.MULTILINE)\nre_import = re.compile('^\\\\s*@d[cC]layImport(?P<from_mode>From)?\\\\s+(?P<import>.+)$', re.MULTILINE)\n\ndef _get_object_by_id_helper(object_id, class_id, hint):\n \"\"\"Helper method which can be pickled and used by DataClayObject.__reduce__\"\"\"\n return getRuntime().get_object_by_id(object_id, class_id, hint)\n\n\n@six.add_metaclass(ExecutionGateway)\nclass DataClayObject(object):\n __doc__ = 'Main class for Persistent Objects.\\n\\n Objects that has to be made persistent should derive this class (either\\n directly, through the StorageObject alias, or through a derived class).\\n '\n _DataClayObject__dclay_instance_extradata = None\n\n def initialize_object(self, new_object_id=None):\n \"\"\" \n @postcondition: Initialize the object \n @param new_object_id: Object Id of the object\n \"\"\"\n if new_object_id is not None:\n self.set_object_id(new_object_id)\n getRuntime().add_to_heap(self)\n\n def initialize_object_as_persistent(self):\n \"\"\"\n @postcondition: object is initialized as a persistent object.\n Flags for \"persistent\" state might be different in EE and client.\n \"\"\"\n if getRuntime().is_exec_env():\n self.set_persistent(True)\n self.set_loaded(False)\n self.set_pending_to_register(False)\n else:\n self.set_persistent(True)\n\n def initialize_object_as_volatile(self):\n \"\"\"\n @postcondition: Initialize object with state 'volatile' with proper flags. Usually, volatile state is created by a stub, app, exec\n class,.. See same function in DataClayExecutionObject for a different initialization. This design is intended to be\n clear with object state.\n \"\"\"\n if getRuntime().is_exec_env():\n self.set_persistent(True)\n self.set_loaded(True)\n self.set_pending_to_register(True)\n self.set_hint(getRuntime().get_hint())\n self.set_owner_session_id(getRuntime().get_session_id())\n\n @classmethod\n def get_class_extradata(cls):\n classname = cls.__name__\n module_name = cls.__module__\n full_name = '%s.%s' % (module_name, classname)\n if getRuntime().current_type == RuntimeType.client:\n dc_ced = class_extradata_cache_client.get(full_name)\n else:\n dc_ced = class_extradata_cache_exec_env.get(full_name)\n if dc_ced is not None:\n return dc_ced\n else:\n logger.verbose('Proceeding to prepare the class `%s` from the ExecutionGateway', full_name)\n logger.debug('The RuntimeType is: %s', 'client' if getRuntime().current_type == RuntimeType.client else 'not client')\n dc_ced = DataClayClassExtraData(full_name=full_name,\n classname=classname,\n namespace=(module_name.split('.', 1)[0]),\n properties=(dict()),\n imports=(list()))\n if getRuntime().current_type == RuntimeType.client:\n class_stubinfo = None\n try:\n all_classes = load_babel_data()\n for c in all_classes:\n if '%s.%s' % (c.namespace, c.className) == full_name:\n class_stubinfo = c\n break\n\n except ImproperlyConfigured:\n pass\n\n if class_stubinfo is None:\n for current_cls in inspect.getmro(cls):\n if current_cls in [object, DataClayObject]:\n continue\n doc = current_cls.__doc__\n if doc is None:\n doc = ''\n property_pos = 0\n for m in re_property.finditer(doc):\n declaration = m.groups()\n prop_name = declaration[(-2)]\n prop_type = declaration[(-1)]\n beforeUpdate = declaration[1] if declaration[0] == 'before' else declaration[3] if declaration[2] == 'before' else None\n afterUpdate = declaration[1] if declaration[0] == 'after' else declaration[3] if declaration[2] == 'after' else None\n inMaster = declaration[4] == 'True'\n current_type = Type.build_from_docstring(prop_type)\n logger.trace('Property `%s` (with type signature `%s`) ready to go', prop_name, current_type.signature)\n dc_ced.properties[prop_name] = PreprocessedProperty(name=prop_name,\n position=property_pos,\n type=current_type,\n beforeUpdate=beforeUpdate,\n afterUpdate=afterUpdate,\n inMaster=inMaster)\n property_pos += 1\n setattr(cls, prop_name, DynamicProperty(prop_name))\n\n for m in re_import.finditer(doc):\n gd = m.groupdict()\n if gd['from_mode']:\n import_str = 'from %s\\n' % gd['import']\n else:\n import_str = 'import %s\\n' % gd['import']\n dc_ced.imports.append(import_str)\n\n else:\n logger.debug('Loading a class with babel_data information')\n dc_ced.class_id = class_stubinfo.classID\n dc_ced.stub_info = class_stubinfo\n for i, prop_name in enumerate(dc_ced.stub_info.propertyListWithNulls):\n if prop_name is None:\n continue\n else:\n prop_info = class_stubinfo.properties[prop_name]\n if prop_info.beforeUpdate is not None or prop_info.afterUpdate is not None:\n setattr(cls, prop_name, ReplicatedDynamicProperty(prop_name, prop_info.beforeUpdate, prop_info.afterUpdate, prop_info.inMaster))\n else:\n setattr(cls, prop_name, DynamicProperty(prop_name))\n dc_ced.properties[prop_name] = PreprocessedProperty(name=prop_name, position=i, type=(prop_info.propertyType),\n beforeUpdate=(prop_info.beforeUpdate),\n afterUpdate=(prop_info.afterUpdate),\n inMaster=(prop_info.inMaster))\n\n else:\n if getRuntime().current_type == RuntimeType.exe_env:\n logger.verbose('Seems that we are a DataService, proceeding to load class %s', dc_ced.full_name)\n namespace_in_classname, dclay_classname = dc_ced.full_name.split('.', 1)\n if namespace_in_classname != dc_ced.namespace:\n raise DataClayException('Namespace in ClassName: %s is different from one in ClassExtraData: %s', namespace_in_classname, dc_ced.namespace)\n mc = load_metaclass(dc_ced.namespace, dclay_classname)\n dc_ced.metaclass_container = mc\n dc_ced.class_id = mc.dataClayID\n for prop_info in dc_ced.metaclass_container.properties:\n if prop_info.beforeUpdate is not None or prop_info.afterUpdate is not None:\n setattr(cls, prop_info.name, ReplicatedDynamicProperty(prop_info.name, prop_info.beforeUpdate, prop_info.afterUpdate, prop_info.inMaster))\n else:\n setattr(cls, prop_info.name, DynamicProperty(prop_info.name))\n dc_ced.properties[prop_info.name] = PreprocessedProperty(name=(prop_info.name),\n position=(prop_info.position),\n type=(prop_info.type),\n beforeUpdate=(prop_info.beforeUpdate),\n afterUpdate=(prop_info.afterUpdate),\n inMaster=(prop_info.inMaster))\n\n else:\n raise RuntimeError('Could not recognize RuntimeType %s', getRuntime().current_type)\n if getRuntime().current_type == RuntimeType.client:\n class_extradata_cache_client[full_name] = dc_ced\n else:\n class_extradata_cache_exec_env[full_name] = dc_ced\n return dc_ced\n\n def _populate_internal_fields(self, deserializing=False, **kwargs):\n logger.debug('Populating internal fields for the class. Provided kwargs: %s deserializing=%s', kwargs, str(deserializing))\n fields = {'persistent_flag':False, \n 'object_id':uuid.uuid4(), \n 'dataset_id':None, \n 'loaded_flag':True, \n 'pending_to_register_flag':False, \n 'dirty_flag':False, \n 'memory_pinned':False}\n fields.update(kwargs)\n instance_dict = object.__getattribute__(self, '__dict__')\n instance_dict['_DataClayObject__dclay_instance_extradata'] = DataClayInstanceExtraData(**fields)\n instance_dict['_dclay_class_extradata'] = self.get_class_extradata()\n self.initialize_object()\n if not deserializing:\n self.initialize_object_as_volatile()\n\n def get_location(self):\n \"\"\"Return a single (random) location of this object.\"\"\"\n return getRuntime().get_location(self._DataClayObject__dclay_instance_extradata.object_id)\n\n def get_master_location(self):\n \"\"\"Return the uuid relative to the master location of this object.\"\"\"\n return self._DataClayObject__dclay_instance_extradata.master_location\n\n def set_master_location(self, eeid):\n \"\"\"Set the master location of this object.\"\"\"\n if not isinstance(eeid, UUID):\n raise AttributeError('The master location should be the ExecutionEnvironmentID, instead we received: %s' % eeid)\n self._DataClayObject__dclay_instance_extradata.master_location = eeid\n\n def get_all_locations(self):\n \"\"\"Return all the locations of this object.\"\"\"\n return getRuntime().get_all_locations(self._DataClayObject__dclay_instance_extradata.object_id)\n\n def new_replica(self, backend_id=None, recursive=True):\n getRuntime().new_replica(self.get_object_id(), self.get_class_extradata().class_id, self.get_hint(), backend_id, recursive)\n\n def new_version(self, backend_id):\n return getRuntime().new_version(self.get_object_id(), self.get_class_extradata().class_id, self.get_hint(), backend_id)\n\n def consolidate_version(self, version_info):\n getRuntime().consolidate_version(version_info)\n\n def make_persistent(self, alias=None, backend_id=None, recursive=True):\n if alias is '':\n raise AttributeError('Alias cannot be empty')\n getRuntime().make_persistent(self, alias=alias, backend_id=backend_id, recursive=recursive)\n\n def get_execution_environments_info(self):\n return getRuntime().get_execution_environments_info()\n\n @classmethod\n def dc_clone_by_alias(cls, alias, recursive=False):\n o = cls.get_by_alias(alias)\n return o.dc_clone(recursive)\n\n def dc_clone(self, recursive=False):\n \"\"\"\n @postcondition: Returns a non-persistent object as a copy of the current object\n @return: DataClayObject non-persistent instance\n \"\"\"\n return getRuntime().get_copy_of_object(self, recursive)\n\n @classmethod\n def dc_update_by_alias(cls, alias, from_object):\n o = cls.get_by_alias(alias)\n return o.dc_update(from_object)\n\n def dc_update(self, from_object):\n \"\"\"\n @postcondition: Updates all fields of this object with the values of the specified object\n @param from_object: instance from which values must be retrieved to set fields of current object\n \"\"\"\n if from_object is None:\n return\n getRuntime().update_object(self, from_object)\n\n def dc_put(self, alias, backend_id=None, recursive=True):\n if alias is None or alias is '':\n raise AttributeError('Alias cannot be null or empty')\n getRuntime().make_persistent(self, alias=alias, backend_id=backend_id, recursive=recursive)\n\n def set_all(self, from_object):\n properties = sorted((self.get_class_extradata().properties.values()), key=(attrgetter('position')))\n logger.verbose('Set all properties from object %s', from_object.get_object_id())\n for p in properties:\n value = getattr(from_object, p.name)\n setattr(self, p.name, value)\n\n def get_object_id(self):\n \"\"\"\n @postcondition: Return object id of the object\n @return Object id\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.object_id\n\n def set_object_id(self, new_object_id):\n \"\"\"\n @postcondition: Set object id of the object\n @param new_object_id: object id\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.object_id = new_object_id\n\n def _update_object_id(self, new_object_id):\n \"\"\"\n @postcondition: Set a new object id for the object and\n calls an update of its heap references\n @param new_object_id: object id\n \"\"\"\n if self.is_persistent():\n raise DataClayException('Cannot change the id of a persistent object')\n old_object_id = self.get_object_id()\n self._DataClayObject__dclay_instance_extradata.object_id = new_object_id\n getRuntime().update_object_id(old_object_id, new_object_id)\n\n def get_memory_pinned(self):\n \"\"\"\n @postcondition: Return the memory pinned flag of the object\n @return Object id\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.memory_pinned\n\n def set_memory_pinned(self, new_memory_pinned):\n \"\"\"\n @postcondition: Set memory pinned flag of the object\n @param new_memory_pinned: memory pinned flag\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.memory_pinned = new_memory_pinned\n\n def get_dataset_id(self):\n \"\"\"\n @postcondition: Return dataset id of the object \n @return Data set id\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.dataset_id\n\n def set_dataset_id(self, new_dataset_id):\n \"\"\"\n @postcondition: Set dataset id of the object\n @param new_dataset_id: dataset id\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.dataset_id = new_dataset_id\n\n def getID(self):\n \"\"\"Return the string representation of the persistent object for COMPSs.\n\n dataClay specific implementation: The objects are internally represented\n through ObjectID, which are UUID. In addition to that, some extra fields\n are added to the representation. Currently, a \"COMPSs ID\" will be:\n\n <objectID>:<backendID|empty>:<classID>\n\n In which all ID are UUID and the \"hint\" (backendID) can be empty.\n\n If the object is NOT persistent, then this method returns None.\n \"\"\"\n if self.is_persistent():\n hint = self._DataClayObject__dclay_instance_extradata.execenv_id or ''\n return '%s:%s:%s' % (\n self._DataClayObject__dclay_instance_extradata.object_id,\n hint,\n self.get_class_extradata().class_id)\n return\n\n @classmethod\n def get_object_by_id(cls, object_id, *args, **kwargs):\n return (getRuntime().get_object_by_id)(object_id, *args, **kwargs)\n\n @classmethod\n def get_by_alias(cls, alias, safe=True):\n return getRuntime().get_by_alias(alias, cls.get_class_extradata().class_id, safe)\n\n @classmethod\n def delete_alias(cls, alias):\n return getRuntime().delete_alias(alias)\n\n def set_persistent(self, ispersistent):\n \"\"\"\n @postcondition: Set value of persistent flag in the object\n @param ispersistent: value to set\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.persistent_flag = ispersistent\n\n def set_loaded(self, isloaded):\n \"\"\"\n @postcondition: Set value of loaded flag in the object\n @param isloaded: value to set\n \"\"\"\n logger.verbose('Setting loaded to `%s` for object %s', isloaded, self.get_object_id())\n self._DataClayObject__dclay_instance_extradata.loaded_flag = isloaded\n\n def is_persistent(self):\n \"\"\"\n @postcondition: Return TRUE if object is persistent. FALSE otherwise. \n @return is persistent flag\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.persistent_flag\n\n def is_loaded(self):\n \"\"\"\n @postcondition: Return TRUE if object is loaded. FALSE otherwise. \n @return is loaded flag\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.loaded_flag\n\n def get_owner_session_id(self):\n \"\"\"\n @postcondition: Get owner session id\n @return Owner session id\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.owner_session_id\n\n def set_owner_session_id(self, the_owner_session_id):\n \"\"\"\n @postcondition: Set ID of session of the owner of the object. \n @param the_owner_session_id: owner session id \n \"\"\"\n self._DataClayObject__dclay_instance_extradata.owner_session_id = the_owner_session_id\n\n def is_pending_to_register(self):\n \"\"\"\n @postcondition: Return TRUE if object is pending to register. FALSE otherwise. \n @return is pending to register flag\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.pending_to_register_flag\n\n def set_pending_to_register(self, pending_to_register):\n \"\"\"\n @postcondition: Set pending to register flag. \n @param pending_to_register: The flag to set\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.pending_to_register_flag = pending_to_register\n\n def is_dirty(self):\n \"\"\"\n @postcondition: Return TRUE if object is dirty (it was modified). FALSE otherwise. \n @return dirty flag\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.dirty_flag\n\n def set_dirty(self, dirty_value):\n \"\"\"\n @postcondition: Set dirty flag. \n @param dirty_value: The flag to set\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.dirty_flag = dirty_value\n\n def get_hint(self):\n \"\"\"\n @postcondition: Get hint\n @return Hint\n \"\"\"\n return self._DataClayObject__dclay_instance_extradata.execenv_id\n\n def set_hint(self, new_hint):\n \"\"\"\n @postcondition: Set hint\n @param new_hint: value to set\n \"\"\"\n self._DataClayObject__dclay_instance_extradata.execenv_id = new_hint\n\n def federate(self, ext_dataclay_id, recursive=True):\n \"\"\"\n @postcondition: Federates this object with an external dataClay instance\n @param ext_dataclay_id: id of the external dataClay instance\n @param recursive: Indicates if all sub-objects must be federated as well.\n \"\"\"\n getRuntime().federate_object(self.get_object_id(), ext_dataclay_id, recursive, self.get_class_extradata().class_id, self.get_hint())\n\n def unfederate(self, ext_dataclay_id=None, recursive=True):\n \"\"\"\n @postcondition: Unfederate this object with an external dataClay instance\n @param ext_dataclay_id: id of the external dataClay instance (none means to unfederate with all dcs)\n @param recursive: Indicates if all sub-objects must be unfederated as well.\n \"\"\"\n if ext_dataclay_id is not None:\n getRuntime().unfederate_object(self.get_object_id(), ext_dataclay_id, recursive)\n else:\n getRuntime().unfederate_object_with_all_dcs(self.get_object_id(), recursive)\n\n def get_external_dataclay_id(self, dcHost, dcPort):\n return getRuntime().ready_clients['@LM'].get_external_dataclay_id(dcHost, dcPort)\n\n def set_in_backend(self, backend_id, field_name, value):\n from dataclay.DataClayObjProperties import DCLAY_SETTER_PREFIX\n return getRuntime().run_remote(self.get_object_id(), backend_id, DCLAY_SETTER_PREFIX + field_name, value)\n\n def get_external_dataclay_info(self, dataclay_id):\n \"\"\" Get external dataClay information\n :param dataclay_id: external dataClay ID\n :return: DataClayInstance information\n :type dataclay_id: UUID\n :rtype: DataClayInstance\n \"\"\"\n return getRuntime().get_external_dataclay_info(dataclay_id)\n\n def get_federation_source(self):\n \"\"\" Retrieve dataClay instance id where the object comes from or NULL\n :return: dataClay instance ids where this object is federated\n :rtype: UUID\n \"\"\"\n return getRuntime().get_external_source_of_dataclay_object(self.get_object_id())\n\n def get_federation_targets(self):\n \"\"\" Retrieve dataClay instances ids where the object is federated\n :return: dataClay instances ids where this object is federated\n :rtype: set of UUID\n \"\"\"\n return getRuntime().get_dataclays_object_is_federated_with(self.get_object_id())\n\n def set_in_dataclay_instance(self, dc_info, field_name, params):\n from dataclay.DataClayObjProperties import DCLAY_SETTER_PREFIX\n getRuntime().synchronize_federated(self, params, DCLAY_SETTER_PREFIX + field_name, dc_info)\n\n def serialize(self, io_file, ignore_user_types, iface_bitmaps, cur_serialized_objs, pending_objs, reference_counting):\n IntegerWrapper().write(io_file, 0)\n cur_master_loc = self.get_master_location()\n if cur_master_loc is not None:\n StringWrapper().write(io_file, str(cur_master_loc))\n else:\n StringWrapper().write(io_file, str('x'))\n if hasattr(self, '__getstate__'):\n dco_extradata = self._DataClayObject__dclay_instance_extradata\n last_loaded_flag = dco_extradata.loaded_flag\n last_persistent_flag = dco_extradata.persistent_flag\n dco_extradata.loaded_flag = True\n dco_extradata.persistent_flag = False\n if six.PY2:\n import cPickle as pickle\n else:\n if six.PY3:\n import _pickle as pickle\n state = pickle.dumps((self.__getstate__()), protocol=(-1))\n dco_extradata.loaded_flag = last_loaded_flag\n dco_extradata.persistent_flag = last_persistent_flag\n StringWrapper(mode='binary').write(io_file, state)\n else:\n properties = sorted((self.get_class_extradata().properties.values()),\n key=(attrgetter('position')))\n logger.verbose('Serializing list of properties: %s', properties)\n for p in properties:\n try:\n value = object.__getattribute__(self, '%s%s' % (DCLAY_PROPERTY_PREFIX, p.name))\n except AttributeError:\n value = None\n\n logger.verbose('Serializing property %s with value %s ', p.name, value)\n if value is None:\n BooleanWrapper().write(io_file, False)\n elif isinstance(p.type, UserType):\n if not ignore_user_types:\n BooleanWrapper().write(io_file, True)\n SerializationLibUtilsSingleton.serialize_association(io_file, value, cur_serialized_objs, pending_objs, reference_counting)\n else:\n BooleanWrapper().write(io_file, False)\n else:\n BooleanWrapper().write(io_file, True)\n pck = Pickler(io_file, protocol=(-1))\n pck.persistent_id = PersistentIdPicklerHelper(cur_serialized_objs, pending_objs, reference_counting)\n pck.dump(value)\n\n cur_stream_pos = io_file.tell()\n io_file.seek(0)\n IntegerWrapper().write(io_file, cur_stream_pos)\n io_file.seek(cur_stream_pos)\n reference_counting.serialize_reference_counting(self.get_object_id(), io_file)\n\n def deserialize(self, io_file, iface_bitmaps, metadata, cur_deserialized_python_objs):\n \"\"\"Reciprocal to serialize.\"\"\"\n logger.verbose('Deserializing object %s', str(self.get_object_id()))\n IntegerWrapper().read(io_file)\n des_master_loc_str = StringWrapper().read(io_file)\n if des_master_loc_str == 'x':\n self._DataClayObject__dclay_instance_extradata.master_location = None\n else:\n self._DataClayObject__dclay_instance_extradata.master_location = UUID(des_master_loc_str)\n if hasattr(self, '__setstate__'):\n if six.PY2:\n import cPickle as pickle\n else:\n if six.PY3:\n import _pickle as pickle\n state = pickle.loads(StringWrapper(mode='binary').read(io_file))\n self.__setstate__(state)\n else:\n properties = sorted((self.get_class_extradata().properties.values()),\n key=(attrgetter('position')))\n logger.trace('Tell io_file before loop: %s', io_file.tell())\n logger.verbose('Deserializing list of properties: %s', properties)\n for p in properties:\n logger.trace('Tell io_file in loop: %s', io_file.tell())\n not_null = BooleanWrapper().read(io_file)\n value = None\n if not_null:\n logger.debug('Not null property %s', p.name)\n if isinstance(p.type, UserType):\n try:\n logger.debug('Property %s is an association', p.name)\n value = DeserializationLibUtilsSingleton.deserialize_association(io_file, iface_bitmaps, metadata, cur_deserialized_python_objs, getRuntime())\n except KeyError as e:\n try:\n logger.error('Failed to deserialize association', exc_info=True)\n finally:\n e = None\n del e\n\n else:\n try:\n upck = Unpickler(io_file)\n upck.persistent_load = PersistentLoadPicklerHelper(metadata, cur_deserialized_python_objs, getRuntime())\n value = upck.load()\n except:\n traceback.print_exc()\n\n logger.debug('Setting value %s for property %s', value, p.name)\n object.__setattr__(self, '%s%s' % (DCLAY_PROPERTY_PREFIX, p.name), value)\n\n def __reduce__(self):\n \"\"\"Support for pickle protocol.\n\n Take into account that internal Pickle usage should be used with help\n of PersistentIdPicklerHelper and PersistentLoadPicklerHelper --for\n further information on the inner working look at the modules\n [Des|S]erializationLibUtils and both the serialize and deserialize\n methods of this class.\n\n This method is left here as a courtesy to end users that may need or\n want to Pickle DataClayObjects manually or through other extensions.\n \"\"\"\n logger.verbose('Proceeding to `__reduce__` (Pickle-related) on a DataClayObject')\n dco_extradata = self._DataClayObject__dclay_instance_extradata\n if not dco_extradata.persistent_flag:\n logger.verbose('Pickling of object %r is causing a make_persistent', self)\n self.make_persistent()\n return (_get_object_by_id_helper,\n (self.get_object_id(),\n self.get_class_extradata().class_id,\n self.get_hint()))\n\n def __repr__(self):\n dco_extradata = self._DataClayObject__dclay_instance_extradata\n dcc_extradata = self.get_class_extradata()\n if dco_extradata.persistent_flag:\n return '<%s (ClassID=%s) instance with ObjectID=%s>' % (\n dcc_extradata.classname, dcc_extradata.class_id, dco_extradata.object_id)\n return '<%s (ClassID=%s) volatile instance with ObjectID=%s>' % (\n dcc_extradata.classname, dcc_extradata.class_id, dco_extradata.object_id)\n\n def __eq__(self, other):\n if not isinstance(other, DataClayObject):\n return False\n else:\n self_extradata = self._DataClayObject__dclay_instance_extradata\n other_extradata = other._DataClayObject__dclay_instance_extradata\n return self_extradata.persistent_flag and other_extradata.persistent_flag or False\n return self_extradata.object_id and other_extradata.object_id and self_extradata.object_id == other_extradata.object_id\n\n def __hash__(self):\n self_extradata = self._DataClayObject__dclay_instance_extradata\n return hash(self_extradata.object_id)\n\n @dclayMethod(obj='anything', property_name='str', value='anything', beforeUpdate='str', afterUpdate='str')\n def __setUpdate__(self, obj, property_name, value, beforeUpdate, afterUpdate):\n if beforeUpdate is not None:\n getattr(self, beforeUpdate)(property_name, value)\n object.__setattr__(obj, '%s%s' % ('_dataclay_property_', property_name), value)\n if afterUpdate is not None:\n getattr(self, afterUpdate)(property_name, value)","sub_path":"pycfiles/dataClay-2.1-py3.7/DataClayObject.cpython-37.py","file_name":"DataClayObject.cpython-37.py","file_ext":"py","file_size_in_byte":32218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"459252045","text":"\nimport pandas as pd\nimport FinanceDataReader as fdr\nfrom datetime import date, timedelta\nfrom dateutil.relativedelta import relativedelta\nimport requests\n\nkrx_df = fdr.StockListing(\"KRX\")\n\n\ndef MakeAlarmData(stock_code):\n \n url = 'https://finance.daum.net/api/trader/histories?page=1&perPage=30&symbolCode=A{}&pagination=true'\n real_url = url.format(stock_code)\n\n headers = {\n 'Referer': 'http://finance.daum.net',\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.127'\n }\n response = requests.get(real_url, headers=headers)\n jsonObjs = response.json()\n dataList = jsonObjs['data']\n\n foreignTrader = dataList[0][\"foreignTrader\"][\"netSales\"]\n domesticTrader = dataList[0][\"domesticTrader\"][\"netSales\"] \n \n return foreignTrader, domesticTrader\n \n\n\n\nAPI_TOKEN = '1139815049:AAHZTGRbViIkADeagV-KTvX7wX91T2O4zf4'\n\nNameList_df = pd.read_excel(r\"C:\\Users\\송준호\\Desktop\\SendTradeAlarm\\NameList.xlsx\", sheet_name = 'Sheet1')\n\nname_list = list(NameList_df[\"Name\"])\nid_list = list(NameList_df[\"ChatId\"])\n\ntoday_date = date.today()\n\nfor num in range(0, len(NameList_df)):\n \n name = name_list[num]\n chat_id = id_list[num]\n print(name)\n print(chat_id)\n\n stock_list = []\n make_df = pd.DataFrame(index = [0], columns = [\"StockCode\", \"ForeignTrader\", \"DomesticTrader\", \"AlarmDate\"])\n \n file_name = \"StockList_\" + name + \".xlsx\"\n stock_list_df = pd.read_excel(r\"C:\\Users\\송준호\\Desktop\\SendTradeAlarm\\\\\" + file_name, sheet_name = 'Sheet1') \n \n for stock_code in stock_list_df[\"StockCode\"]:\n stock_list.append(stock_code[1:])\n \n print(stock_list)\n \n for n in range(0, len(stock_list)):\n stock_code = stock_list[n]\n foreignTrader, domesticTrader = MakeAlarmData(stock_code)\n make_df.loc[n] = [stock_code, foreignTrader, domesticTrader, 0]\n \n ##비교(알람)\n file_name = \"StockPrice_\" + name + \".xlsx\"\n stock_price_df = pd.read_excel(r\"C:\\Users\\송준호\\Desktop\\SendTradeAlarm\\\\\" + file_name, sheet_name = 'Sheet1') \n\n \n for i in range(0 , len(stock_price_df)):\n \n StockName = krx_df[krx_df[\"Symbol\"] == make_df[\"StockCode\"][i]][\"Name\"].values[0]\n send_text = StockName + \", 외국인 순매수량: \" + \" \" + str(make_df[\"ForeignTrader\"][i]) + \", 기관 순매수량: \" + str(make_df[\"DomesticTrader\"][i])\n send_text = \"%s\" % send_text\n\n url_tmpl = \"https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={send_text}\"\n url = url_tmpl.format(token=API_TOKEN, chat_id=chat_id, send_text=send_text)\n r = requests.get(url)\n\n print(send_text)\n\n make_df[\"AlarmDate\"][i] = today_date\n \n make_df.to_excel(r\"C:\\Users\\송준호\\Desktop\\SendTradeAlarm\\\\\" + file_name)\n\n\nmake_df\n","sub_path":"send_dart_alarm.py","file_name":"send_dart_alarm.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"171055960","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport re\n\n#requires http://pypi.python.org/pypi/termcolor\n#but the colors make it worth it :-)\nfrom termcolor import colored, cprint\n\nfrom devstack import settings\nfrom devstack import utils\n\nfrom devstack.components import db\nfrom devstack.components import glance\nfrom devstack.components import horizon\nfrom devstack.components import keystone\nfrom devstack.components import keystone_client\nfrom devstack.components import nova\nfrom devstack.components import nova_client\nfrom devstack.components import novnc\nfrom devstack.components import openstack_x\nfrom devstack.components import quantum\nfrom devstack.components import quantum_client\nfrom devstack.components import rabbit\nfrom devstack.components import swift\n\nPROG_NAME = \"MISC\"\n\n#this determines how descriptions for components are found\n_DESCR_MAP = {\n settings.DB: db.describe,\n settings.GLANCE: glance.describe,\n settings.HORIZON: horizon.describe,\n settings.KEYSTONE: keystone.describe,\n settings.KEYSTONE_CLIENT: keystone_client.describe,\n settings.NOVA: nova.describe,\n settings.NOVA_CLIENT: nova_client.describe,\n settings.OPENSTACK_X: openstack_x.describe,\n settings.QUANTUM: quantum.describe,\n settings.RABBIT: rabbit.describe,\n settings.SWIFT: swift.describe,\n settings.NOVNC: novnc.describe,\n settings.QUANTUM_CLIENT: quantum_client.describe,\n}\n\n\ndef log_deps(components):\n shown = set()\n left_show = list(components)\n while left_show:\n c = left_show.pop()\n deps = settings.get_dependencies(c)\n dep_str = \"depends on:\"\n print(colored(c, \"green\", attrs=['bold']) + \" depends on \" + dep_str)\n for d in deps:\n print(\" \" + colored(d, \"blue\", attrs=['bold']))\n shown.add(c)\n for d in deps:\n if d not in shown and d not in left_show:\n left_show.append(d)\n\n\ndef _run_list_deps(args):\n components = settings.parse_components(args.get(\"components\"), True).keys()\n components = sorted(components)\n components.reverse()\n return log_deps(components)\n\n\ndef _run_describe_comps(args):\n components = settings.parse_components(args.get(\"components\"), True)\n c_keys = sorted(components.keys())\n for c in c_keys:\n print(\"Name: \" + colored(c, \"green\", attrs=['bold']) + \"\")\n describer = _DESCR_MAP.get(c)\n print(describer(components.get(c)))\n\n\ndef run(args):\n (rep, maxlen) = utils.welcome(PROG_NAME)\n if args.get('list_deps'):\n header = utils.center_text(\"Dependencies\", rep, maxlen)\n print(header)\n _run_list_deps(args)\n if args.get('describe_comp'):\n header = utils.center_text(\"Descriptions\", rep, maxlen)\n print(header)\n _run_describe_comps(args)\n return True\n","sub_path":"devstack/progs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"82986351","text":"import random\n\nf = open(\"TSP data Qatar.txt\", \"r\")\nlocations = {}\n# locations = {1: (0,0), 2: (2,0), 3: (0,2), 4: (2,2), 5: (0,0), 6: (0,0), 7: (0,0)}\n\nfor x in f.readlines():\n temp = x.split()\n locations[int(temp[0])] = (float(temp[1]), float(temp[2]))\nf.close()\n\nclass Individual:\n def __init__(self, size: int, sequence=None):\n \"\"\"Creates a list of the given size, optionally intializing elements to value.\n\n Args:\n - size: number of items in gnome\n - sequence: a particular sequence, if it is not provided than a random sequence is initialized\n\n Returns:\n none\n \"\"\"\n if sequence == None:\n self.gnome = list(range(1, size+1))\n random.shuffle(self.gnome)\n else:\n self.gnome = sequence\n self.fitness = 0\n for x in range(len(self.gnome)-1):\n self.fitness+=((locations[self.gnome[x]][0]-locations[self.gnome[x+1]][0])**2+(locations[self.gnome[x]][1]-locations[self.gnome[x+1]][1])**2)**0.5\n self.fitness += ((locations[self.gnome[0]][0]-locations[self.gnome[-1]][0])**2+(locations[self.gnome[0]][1]-locations[self.gnome[-1]][1])**2)**0.5\n\n def getFitness(self):\n \"\"\"Returns the fitness of the gnome.\n\n Args:\n\n Returns:\n fitness of gnome\n \"\"\"\n return self.fitness\n \n @staticmethod\n def crossover(parent1, parent2, mutation: float):\n \"\"\"Returns 2 individuals produced as the result of crossover\n\n Args:\n - parent1: an individual\n - parent2: an individual\n - mutation: probability of mutation\n\n Returns:\n List containing the 2 children\n \"\"\"\n child1 = list(parent1.gnome)\n child2 = list(parent2.gnome)\n randomNumber = random.randint(0,len(parent1.gnome)-1)\n for x in range(len(parent1.gnome)//2):\n child1[(randomNumber+x)%len(parent1.gnome)] = -1\n child2[(randomNumber+x)%len(parent1.gnome)] = -1\n count = 0\n i = 0\n while count != len(parent1.gnome)//2:\n if parent2.gnome[(randomNumber+i)%len(parent1.gnome)] not in child1:\n child1[(randomNumber+count)%len(parent1.gnome)] = parent2.gnome[(randomNumber+i)%len(parent1.gnome)]\n count += 1\n i += 1\n count = 0\n i = 0\n while count != len(parent1.gnome)//2:\n if parent1.gnome[(randomNumber+i)%len(parent1.gnome)] not in child2:\n child2[(randomNumber+count)%len(parent1.gnome)] = parent1.gnome[(randomNumber+i)%len(parent1.gnome)]\n count += 1\n i += 1\n if mutation > random.uniform(0,1):\n index1 = random.randint(0,len(child1)-1)\n index2 = random.randint(0,len(child1)-1)\n child1[index1], child1[index2] = child1[index2], child1[index1]\n child2[index1], child2[index2] = child2[index2], child2[index1]\n child1 = Individual(len(child1), child1)\n child2 = Individual(len(child2), child2)\n return [child1, child2]\n \n def __str__(self):\n \"\"\"String representation of an individual\n\n Args:\n\n Returns:\n String representation of an individual\n \"\"\"\n return \"Fitness: \"+str(round(self.fitness,2))+\"\\n\"+\" \".join([str(x) for x in self.gnome])\n\nclass EA:\n def __init__(self, size: int):\n \"\"\"Initialize the population of the given size\n\n Args:\n - size: number of individuals in the population\n\n Returns:\n none\n \"\"\"\n self.population = []\n for x in range(size):\n self.population.append(Individual(len(locations.keys())))\n # for x in self.population:\n # print(x)\n \n def getAverageFitness(self):\n \"\"\"Returns the average fitness of the population\n\n Args:\n\n Returns:\n average fitness of population\n \"\"\"\n return round(sum(x.getFitness() for x in self.population)/len(self.population), 2)\n \n def getBestFitness(self):\n \"\"\"Returns the best fitness of the population\n\n Args:\n\n Returns:\n best fitness of population\n \"\"\"\n return round(min(x.getFitness() for x in self.population), 2)\n \n def selectionScheme(self, n, scheme):\n \"\"\"Selects the parents for crossover\n\n Args:\n - n: number of selected parents\n - scheme: selection scheme for selecting parents\n - 1: Fitness Proportional Selection\n - 2: Rank Based Selection\n - 3: Binary Tournament\n - 4: Truncation\n - 5: Random\n \n Returns:\n returns n individuals of the population\n \"\"\"\n selected = []\n if scheme == 1 or scheme == 3:\n totalFitness = 0\n maxFitness = -1\n minFitness = -1\n for x in self.population:\n totalFitness += x.getFitness()\n if x.getFitness() > maxFitness:\n maxFitness = x.getFitness()\n if x.getFitness() < minFitness or minFitness == -1:\n minFitness = x.getFitness()\n totalFitness = (maxFitness + minFitness)*len(self.population) - totalFitness\n # temp = []\n # for x in self.population:\n # temp.append(maxFitness+minFitness-x.getFitness())\n # totalFitness = sum(temp)\n # print(\"Total Fitness:\", totalFitness)\n if scheme == 3:\n n *= 2\n for x in range(n):\n randomNumber = random.uniform(0,1)\n # randomNumber = 0.96\n currentSum = 0\n i = 0\n while currentSum < randomNumber:\n currentSum += (maxFitness + minFitness - self.population[i].getFitness())/totalFitness\n i += 1\n # print(i)\n selected.append(self.population[i-1])\n if scheme == 3:\n selected = sorted(selected, key=lambda x: x.getFitness())[:n//2]\n elif scheme == 2:\n totalRank = len(self.population)*(len(self.population)+1)/2\n temp = sorted(self.population, key=lambda x: x.getFitness())\n for x in range(n):\n randomNumber = random.uniform(0,1)\n # randomNumber = 0.946\n currentSum = 0\n i = 0\n while currentSum < randomNumber:\n currentSum += (len(self.population)-i)/totalRank\n i += 1\n # print(i-1)\n selected.append(temp[i-1])\n elif scheme == 4:\n selected = sorted(self.population, key=lambda x: x.getFitness())[:n]\n elif scheme == 5:\n for x in range(n):\n selected.append(self.population[random.randint(0,len(self.population)-1)])\n return selected\n \n def train(self, parentScheme, survivorScheme, mutation, offsprings, generations):\n print(\"Generation No.: 0\",\"\\t\\tBSF:\",self.getBestFitness(),\"\\t\\t\\tASF:\",self.getAverageFitness())\n for x in range(generations):\n parents = self.selectionScheme(offsprings, parentScheme)\n for y in range(offsprings//2):\n self.population += Individual.crossover(parents[2*y], parents[2*y+1], mutation)\n self.population = self.selectionScheme(len(self.population)-offsprings, survivorScheme)\n print(\"Generation No.:\",x+1,\"\\t\\tBSF:\",self.getBestFitness(),\"\\t\\t\\tASF:\",self.getAverageFitness())\n\na=EA(30)\n# a.population[0].fitness = 10.25\n# a.population[1].fitness = 35.56\n# a.population[2].fitness = 58.16\n# a.population[3].fitness = 197.3\n# a.population[4].fitness = 138.1\n# a.population[5].fitness = 164.66\n# a.population[6].fitness = 26.52\n# a.population[7].fitness = 138.57\n# a.population[8].fitness = 205.55\n# a.population[9].fitness = 167.21\n# a.selectionScheme(1,2)\na.train(3, 4, 0.5, 10, 100)","sub_path":"Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":7979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"225002611","text":"import platform\n\nimport pytest\n\nfrom devp2p import peermanager, peer\nfrom devp2p import crypto\nfrom devp2p.app import BaseApp\nimport devp2p.muxsession\nimport rlp\nimport devp2p.p2p_protocol\nimport time\nimport gevent\nimport copy\nfrom rlp.utils import encode_hex, decode_hex\n\n\ndef get_connected_apps():\n a_config = dict(p2p=dict(listen_host='127.0.0.1', listen_port=3005),\n node=dict(privkey_hex=encode_hex(crypto.sha3(b'a'))))\n b_config = copy.deepcopy(a_config)\n b_config['p2p']['listen_port'] = 3006\n b_config['node']['privkey_hex'] = encode_hex(crypto.sha3(b'b'))\n\n a_app = BaseApp(a_config)\n peermanager.PeerManager.register_with_app(a_app)\n a_app.start()\n\n b_app = BaseApp(b_config)\n peermanager.PeerManager.register_with_app(b_app)\n b_app.start()\n\n a_peermgr = a_app.services.peermanager\n b_peermgr = b_app.services.peermanager\n\n # connect\n host = b_config['p2p']['listen_host']\n port = b_config['p2p']['listen_port']\n pubkey = crypto.privtopub(decode_hex(b_config['node']['privkey_hex']))\n a_peermgr.connect((host, port), remote_pubkey=pubkey)\n\n return a_app, b_app\n\n\ndef test_handshake():\n a_app, b_app = get_connected_apps()\n gevent.sleep(1)\n assert a_app.services.peermanager.peers\n assert b_app.services.peermanager.peers\n a_app.stop()\n b_app.stop()\n\n\ndef test_big_transfer():\n\n class transfer(devp2p.p2p_protocol.BaseProtocol.command):\n cmd_id = 4\n structure = [('raw_data', rlp.sedes.binary)]\n\n def create(self, proto, raw_data=''):\n return [raw_data]\n\n # money patches\n devp2p.p2p_protocol.P2PProtocol.transfer = transfer\n devp2p.muxsession.MultiplexedSession.max_window_size = 8 * 1024\n\n a_app, b_app = get_connected_apps()\n gevent.sleep(.1)\n\n a_protocol = a_app.services.peermanager.peers[0].protocols[devp2p.p2p_protocol.P2PProtocol]\n b_protocol = b_app.services.peermanager.peers[0].protocols[devp2p.p2p_protocol.P2PProtocol]\n\n st = time.time()\n\n def cb(proto, **data):\n print('took', time.time() - st, len(data['raw_data']))\n\n b_protocol.receive_transfer_callbacks.append(cb)\n raw_data = '0' * 1 * 1000 * 100\n a_protocol.send_transfer(raw_data=raw_data)\n\n # 0.03 secs for 0.1mb\n # 0.28 secs for 1mb\n # 2.7 secs for 10mb\n # 3.7 MB/s == 30Mbit\n\n gevent.sleep(1)\n a_app.stop()\n b_app.stop()\n gevent.sleep(0.1)\n\n\ndef test_dumb_peer():\n \"\"\" monkeypatch receive_hello to make peer not to mark that hello was received.\n no hello in defined timeframe makes peer to stop \"\"\"\n\n def mock_receive_hello(self, proto, version, client_version_string,\n capabilities, listen_port, remote_pubkey):\n pass\n\n peer.Peer.receive_hello = mock_receive_hello\n\n a_app, b_app = get_connected_apps()\n\n gevent.sleep(1.0)\n assert a_app.services.peermanager.num_peers() == 1\n assert b_app.services.peermanager.num_peers() == 1\n\n gevent.sleep(peer.Peer.dumb_remote_timeout)\n assert a_app.services.peermanager.num_peers() == 0\n assert b_app.services.peermanager.num_peers() == 0\n\n a_app.stop()\n b_app.stop()\n gevent.sleep(0.1)\n\n\ndef connect_go():\n a_config = dict(p2p=dict(listen_host='127.0.0.1', listen_port=3010),\n node=dict(privkey_hex=encode_hex(crypto.sha3(b'a'))))\n\n a_app = BaseApp(a_config)\n peermanager.PeerManager.register_with_app(a_app)\n a_app.start()\n\n a_peermgr = a_app.services.peermanager\n\n # connect\n pubkey = decode_hex(\"6ed2fecb28ff17dec8647f08aa4368b57790000e0e9b33a7b91f32c41b6ca9ba21600e9a8c44248ce63a71544388c6745fa291f88f8b81e109ba3da11f7b41b9\")\n a_peermgr.connect(('127.0.0.1', 30303), remote_pubkey=pubkey)\n gevent.sleep(50)\n a_app.stop()\n\n\nif __name__ == '__main__':\n # ethereum -loglevel 5 --bootnodes ''\n import ethereum.slogging\n ethereum.slogging.configure(config_string=':debug')\n # connect_go()\n test_big_transfer()\n test_dumb_peer()\n","sub_path":"devp2p/tests/test_peer.py","file_name":"test_peer.py","file_ext":"py","file_size_in_byte":3986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"64109564","text":"from flask import Flask\nfrom flask_restful import Api\nfrom flask_cors import CORS, cross_origin\nfrom chatbot_api.ext.db import url, db, openSession\n\nfrom datetime import timedelta \n\n# from chatbot_api.resources import user\n# from chatbot_api.resources.user import UserDto\n# from chatbot_api.resources.shop import ShopDto\n# from chatbot_api.resources.food import FoodDto\n# from chatbot_api.resources.order_review import OrderReviewDto\nimport numpy as np\nfrom numpy.lib.function_base import insert\nimport pandas as pd\nprint('========== url ==========')\nprint(url)\nimport secrets\n\napp = Flask(__name__)\n\n# 세션을 위한 키 설정\n# app.config[\"SECRET_KEY\"] = \"secretkeyforsession\"\n# SECRET_KEY = \"secretkeyforsession\"\n# SESSION_TYPE = 'filesystem'\napp.secret_key = 'super secret key'\n# app.config['SESSION_TYPE'] = 'filesystem'\nCORS(app, supports_credentials=True, resources={r'/*': {\"origins\": \"*\"}})\n# CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n\napp.config['SQLALCHEMY_DATABASE_URI'] = url\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config[\"PERMANENT_SESSION_LIFETIME\"] = timedelta(minutes=30) # 세션유지 시간을 30분으로 지정\napp.config['SESSION_COOKIE_SAMESITE'] = \"None\" # 브라우저 cors block 이슈 관련\napp.config['SESSION_COOKIE_SECURE'] = True # 브라우저 cors block 이슈 관련 \n\n\n# app.config [ 'CORS_HEADERS' ] = 'Content-Type'\ndb.init_app(app)\napi = Api(app)\n\n'''\n@app.before_first_request\ndef create_tables():\n db.create_all()\nwith app.app_context():\n db.create_all()\n'''\n\n\n# 테이블 일괄 생성\nwith app.app_context():\n from chatbot_api.ext.routes import initialize_routes # db에서 sql를 첫 로딩시 실행하기 위한 임시 방편.. 모듈 로딩 관련\n # print('테이블 일괄 생성 완료')\n db.create_all()\n\n\n# with app.app_context():\n# count = UserDao.count()\n# print(f'Users Total Count is {count}')\n# if count == 0:\n# UserDao.insert_many()\n\n\ninitialize_routes(api)\n\n\n# @app.route('/api/test')\n# def test():\n# return {'test': 'Success'}\n\n# context 생성\n# app.app_context().push()\n\n# 유저 추가 (create)\n# user = UserDto(userid='tom', password='1', name='tom', addr=\"서울시 서초구\", lat=37.1234, lng=128.1234)\n# UserDao.add(user)\n\n# 유저 조회\n# 전체 조회\n# user_list = UserDao.find_all()\n# print(user_list)\n# print(type(user_list)) # <class 'list'>\n# print(user_list[0])\n# print(type(user_list[0]))\n\n# ###################################\n# # 데이터 일괄 입력\n\n# import pdb\n# food/order_review 테이블 데이터 일괄 입력\ndef insert_at_all(fila_name, dto):\n chunksize = 10 ** 4\n for cnt, chunk in enumerate(pd.read_csv(f'./../data/db/{fila_name}.csv', sep=',', encoding='utf-8-sig', chunksize=chunksize)): # 영돈\n df = chunk.replace(np.nan, 1, regex=True)\n # print(df.head())\n\n Session = openSession()\n session = Session()\n session.bulk_insert_mappings(dto, df.to_dict(orient=\"records\"))\n session.commit()\n session.close()\n print(f'{cnt*chunksize}건 입력 완료')\n\n# ######## 테이블 데이터 입력#########\n# 최초 입력 후 주석처리 해야 함\n\n# user 테이블 입력\n# insert_at_all('user', UserDto)\n\n# # shop 테이블 입력\n# insert_at_all('shop', ShopDto)\n\n# # food 테이블 입력\n# insert_at_all('food', FoodDto) \n\n# # order_review 테이블 입력\n# insert_at_all('order_review', OrderReviewDto) \n# ##################################\n\n\n# shop_seoul = df.loc[df['shop_addr'].str.contains('서울', na=False)]\n# print(shop_seoul['shop_addr'])\n\n# shop_seoul.to_csv('./data/csv/important/shop(seoul).csv', sep=',', encoding='utf-8-sig', index=False)\n\n# pdb.set_trace()\n# ####################################\n\n# 캐스��이딩 삭제 테스트\n# with app.app_context():\n# # db.session.query(ShopDto).filter(ShopDto.shop_id==117).delete()\n# user = db.session.query(ShopDto).filter(ShopDto.shop_id==117).first()\n# db.session.delete(user)\n# db.session.commit()\n# db.session.close()\n\n\n","sub_path":"api_ec2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"371061254","text":"#пункт А\n\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nlength = len(numbers)\n\nfor i in range (length):\n numbers[i] *= 2\n\nprint(\"Пункт А\", numbers)\n\n#пункт Б\n\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nA = int(input(\"Введите число А: \"))\n\nfor i in range (length):\n numbers[i] -= A\n\nprint(\"Пункт Б\", numbers)\n\n#Пункт В\n\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nx = numbers[0]\n\nfor i in range (length):\n numbers[i] = numbers[i] // x\n\nprint(\"Пункт В\", numbers)\n","sub_path":"new/11.17.py","file_name":"11.17.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"632561524","text":"import logging\nfrom urllib import request\n\nfrom core.authentication import HashAuthentication\nfrom core.models import Position, Shtab\nfrom core.permissions import IsGrantedToEditShtab\nfrom django.db.models import BooleanField, Exists, OuterRef, Value\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework import filters, mixins, viewsets\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .serializers import ShtabSerializer\n\nlogger = logging.getLogger(__name__)\n\n\nclass ShtabViewSet(mixins.UpdateModelMixin, viewsets.ReadOnlyModelViewSet):\n \"\"\"manage shtabs in the database\"\"\"\n\n serializer_class = ShtabSerializer\n queryset = Shtab.objects.all()\n\n authentication_classes = (HashAuthentication,)\n permission_classes = (IsAuthenticated, IsGrantedToEditShtab)\n filter_backends = [filters.SearchFilter]\n search_fields = (\"^title\", \"^prefix\")\n\n def get_queryset(self):\n \"\"\"Return ordered by title objects\"\"\"\n show_only_self = self.request.query_params.get(\"self\", False)\n if self.request.user.is_staff:\n queryset = self.queryset.annotate(can_edit=Value(True, BooleanField()))\n else:\n can_edit = Position.objects.filter(\n to_date=None,\n shtab=OuterRef(\"pk\"),\n boec=self.request.user.boec,\n )\n queryset = self.queryset.annotate(can_edit=Exists(can_edit))\n\n queryset = queryset.order_by(\n \"-can_edit\",\n \"prefix\",\n \"title\",\n )\n\n if show_only_self == \"true\":\n return queryset.filter(can_edit=True)\n\n return queryset\n","sub_path":"app/shtab/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"584659619","text":"# wrangle_zillow\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom env import host, user, password\nfrom sklearn.model_selection import train_test_split\nimport sklearn.preprocessing\n\n# ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# stats tests\nimport scipy.stats as stats\n\n# data summary \n\ndef get_object_cols(df):\n '''\n This function takes in a dataframe and identifies the columns that are object types\n and returns a list of those column names. \n '''\n # create a mask of columns whether they are object type or not\n mask = np.array(df.dtypes == \"object\")\n\n \n # get a list of the column names that are objects (from the mask)\n object_cols = df.iloc[:, mask].columns.tolist()\n \n return object_cols\n\ndef get_numeric_cols(df, object_cols):\n '''\n takes in a dataframe and list of object column names\n and returns a list of all other columns names, the non-objects. \n '''\n numeric_cols = [col for col in df.columns.values if col not in object_cols]\n \n return numeric_cols\n\ndef get_single_use_prop(df):\n single_use = [261, 262, 263, 264, 266, 268, 273, 276, 279]\n df = df[df.propertylandusetypeid.isin(single_use)]\n return df\n\n\ndef handle_missing_values(df, prop_required_row = 0.5, prop_required_col = 0.5):\n ''' funtcion which takes in a dataframe, required notnull proportions of non-null rows and columns.\n drop the columns and rows columns based on theshold:'''\n \n #drop columns with nulls\n threshold = int(prop_required_col * len(df.index)) # Require that many non-NA values.\n df.dropna(axis = 1, thresh = threshold, inplace = True)\n \n #drop rows with nulls\n threshold = int(prop_required_row * len(df.columns)) # Require that many non-NA values.\n df.dropna(axis = 0, thresh = threshold, inplace = True)\n \n \n return df\n\ndef get_latitude(df):\n '''\n This function takes in a datafame with latitude formatted as a float,\n converts it to a int and utilizes lambda to return the latitude values\n in a correct format.\n '''\n df.latitude = df.latitude.astype(int)\n df['latitude'] = df['latitude'].apply(lambda x: x / 10 ** (len((str(x))) - 2))\n return df\n\ndef get_longitude(df):\n '''This function takes in a datafame with longitude formatted as a float,\n converts it to a int and utilizes lambda to return the longitude values\n in the correct format.\n '''\n df.longitude = df.longitude.astype(int)\n df['longitude'] = df['longitude'].apply(lambda x: x / 10 ** (len((str(x))) - 4))\n return df\n\ndef clean_zillow(df):\n df = get_single_use_prop(df)\n\n df = handle_missing_values(df, prop_required_row = 0.5, prop_required_col = 0.5)\n\n df.set_index('parcelid', inplace=True)\n\n df.dropna(inplace = True)\n\n get_latitude(df)\n\n get_longitude(df)\n\n return df\n\n\ndef get_counties(df):\n '''\n This function will create dummy variables out of the original fips column. \n And return a dataframe with all of the original columns except regionidcounty.\n We will keep fips column for data validation after making changes. \n New columns added will be 'LA', 'Orange', and 'Ventura' which are boolean \n The fips ids are renamed to be the name of the county each represents. \n '''\n # create dummy vars of fips id\n county_df = pd.get_dummies(df.fips)\n # rename columns by actual county name\n county_df.columns = ['LA', 'Orange', 'Ventura']\n # concatenate the dataframe with the 3 county columns to the original dataframe\n df_dummies = pd.concat([df, county_df], axis = 1)\n # drop regionidcounty and fips columns\n # df_dummies = df_dummies.drop(columns = ['regionidcounty'])\n return df_dummies\n\n\ndef create_dummies(df, object_cols):\n '''\n This function takes in a dataframe and list of object column names,\n and creates dummy variables of each of those columns. \n It then appends the dummy variables to the original dataframe. \n It returns the original df with the appended dummy variables. \n '''\n \n # run pd.get_dummies() to create dummy vars for the object columns. \n # we will drop the column representing the first unique value of each variable\n # we will opt to not create na columns for each variable with missing values \n # (all missing values have been removed.)\n dummy_df = pd.get_dummies(df[object_cols], dummy_na=False, drop_first=True)\n \n # concatenate the dataframe with dummies to our original dataframe\n # via column (axis=1)\n df = pd.concat([df, dummy_df], axis=1)\n\n return df\n\ndef create_features(df):\n df['age'] = 2017 - df.yearbuilt\n df['age_bin'] = pd.cut(df.age, \n bins = [0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140],\n labels = [0, .066, .133, .20, .266, .333, .40, .466, .533, \n .60, .666, .733, .8, .866, .933])\n\n # create taxrate variable\n df['taxrate'] = df.taxamount/df.taxvaluedollarcnt*100\n\n # create acres variable\n df['acres'] = df.lotsizesquarefeet/43560\n\n # bin acres\n df['acres_bin'] = pd.cut(df.acres, bins = [0, .10, .15, .25, .5, 1, 5, 10, 20, 50, 200], \n labels = [0, .1, .2, .3, .4, .5, .6, .7, .8, .9])\n\n # square feet bin\n df['sqft_bin'] = pd.cut(df.calculatedfinishedsquarefeet, \n bins = [0, 800, 1000, 1250, 1500, 2000, 2500, 3000, 4000, 7000, 12000],\n labels = [0, .1, .2, .3, .4, .5, .6, .7, .8, .9]\n )\n\n # dollar per square foot-structure\n df['structure_dollar_per_sqft'] = df.structuretaxvaluedollarcnt/df.calculatedfinishedsquarefeet\n\n\n df['structure_dollar_sqft_bin'] = pd.cut(df.structure_dollar_per_sqft, \n bins = [0, 25, 50, 75, 100, 150, 200, 300, 500, 1000, 1500],\n labels = [0, .1, .2, .3, .4, .5, .6, .7, .8, .9]\n )\n\n\n # dollar per square foot-land\n df['land_dollar_per_sqft'] = df.landtaxvaluedollarcnt/df.lotsizesquarefeet\n\n df['lot_dollar_sqft_bin'] = pd.cut(df.land_dollar_per_sqft, bins = [0, 1, 5, 20, 50, 100, 250, 500, 1000, 1500, 2000],\n labels = [0, .1, .2, .3, .4, .5, .6, .7, .8, .9]\n )\n\n\n # update datatypes of binned values to be float\n df = df.astype({'sqft_bin': 'float64', 'acres_bin': 'float64', 'age_bin': 'float64',\n 'structure_dollar_sqft_bin': 'float64', 'lot_dollar_sqft_bin': 'float64'})\n\n\n # ratio of bathrooms to bedrooms\n df['bath_bed_ratio'] = df.bathroomcnt/df.bedroomcnt\n\n # 12447 is the ID for city of LA. \n # I confirmed through sampling and plotting, as well as looking up a few addresses.\n df['cola'] = df['regionidcity'].apply(lambda x: 1 if x == 12447.0 else 0)\n\n return df\n\ndef remove_outliers(df):\n '''\n remove outliers in bed, bath, zip, square feet, acres & tax rate\n '''\n\n return df[((df.bathroomcnt <= 7) & (df.bedroomcnt <= 7) & \n (df.regionidzip < 100000) & \n (df.bathroomcnt > 0) & \n (df.bedroomcnt > 0) & \n (df.acres < 20) &\n (df.calculatedfinishedsquarefeet < 10000) & \n (df.taxrate < 10)\n )]\n\ndef split(df, target_var):\n '''\n This function takes in the dataframe and target variable name as arguments and then\n splits the dataframe into train (56%), validate (24%), & test (20%)\n It will return a list containing the following dataframes: train (for exploration), \n X_train, X_validate, X_test, y_train, y_validate, y_test\n '''\n # split df into train_validate (80%) and test (20%)\n train_validate, test = train_test_split(df, test_size=.20, random_state=123)\n # split train_validate into train(70% of 80% = 56%) and validate (30% of 80% = 24%)\n train, validate = train_test_split(train_validate, test_size=.3, random_state=123)\n\n # create X_train by dropping the target variable \n X_train = train.drop(columns=[target_var])\n # create y_train by keeping only the target variable.\n y_train = train[[target_var]]\n\n # create X_validate by dropping the target variable \n X_validate = validate.drop(columns=[target_var])\n # create y_validate by keeping only the target variable.\n y_validate = validate[[target_var]]\n\n # create X_test by dropping the target variable \n X_test = test.drop(columns=[target_var])\n # create y_test by keeping only the target variable.\n y_test = test[[target_var]]\n\n partitions = [train, X_train, X_validate, X_test, y_train, y_validate, y_test]\n return partitions\n\ndef scale_my_data(train, validate, test):\n\n train = train.drop('logerror', axis=1)\n validate = validate.drop('logerror', axis=1)\n test = test.drop('logerror', axis=1)\n\n # 1. Create the Scaling Object\n scaler = sklearn.preprocessing.StandardScaler()\n\n # 2. Fit to the train data only\n scaler.fit(train)\n\n # 3. use the object on the whole df\n # this returns an array, so we convert to df in the same line\n train_scaled = pd.DataFrame(scaler.transform(train))\n validate_scaled = pd.DataFrame(scaler.transform(validate))\n test_scaled = pd.DataFrame(scaler.transform(test))\n\n # the result of changing an array to a df resets the index and columns\n # for each train, validate, and test, we change the index and columns back to original values\n\n # Train\n train_scaled.index = train.index\n train_scaled.columns = train.columns\n\n # Validate\n validate_scaled.index = validate.index\n validate_scaled.columns = validate.columns\n\n # Test\n test_scaled.index = test.index\n test_scaled.columns = test.columns\n\n return train_scaled, validate_scaled, test_scaled\n\ndef prepare_zillow(df):\n df = get_counties(df)\n return df","sub_path":"wrangle_zillow.py","file_name":"wrangle_zillow.py","file_ext":"py","file_size_in_byte":9921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"514071180","text":"from twilio.rest import Client\n\ndef send_message(message,dest):\n\n account_sid = \"ACb06382cd4aa268ef0c8011cfea48224c\"\n auth_token = \"141faaf93bcc278ec3d9789ccddf4b17\"\n\n client = Client(account_sid, auth_token)\n\n message = client.messages.create(\n to=dest,\n #to=\"+16474479131\",\n from_=\"(613) 900-5909\",\n body=message)\n\n print(message.sid)\n\n\n\n","sub_path":"SMS and BITCOIN/send_sms.py","file_name":"send_sms.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"441237750","text":"from collections import deque\nclass Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n stack = []\n post = deque()\n i = 0\n while i < len(s):\n if s[i].isdigit():\n start = i\n while i < len(s)-1 and s[i+1].isdigit():\n i += 1\n post.append(int(s[start: i+1]))\n elif s[i] == '(':\n stack.append(s[i])\n elif s[i] in '+-':\n while stack and stack[-1] != '(':\n post.append(stack.pop())\n stack.append(s[i])\n elif s[i] == ')':\n while stack[-1] != '(':\n post.append(stack.pop())\n stack.pop()\n i += 1\n while stack:\n post.append(stack.pop())\n while post:\n item = post.popleft()\n if item in ['+', '-']:\n t2 = stack.pop()\n t1 = stack.pop()\n stack.append(t1+t2 if item == '+' else t1-t2)\n else:\n stack.append(item)\n return stack[0]","sub_path":"224. Basic Calculator.py","file_name":"224. Basic Calculator.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"49246672","text":"from django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response, get_object_or_404, redirect\nfrom adverts.models import Advert\nfrom messages.forms import NewMessageForm\nfrom messages.models import Conversation, Message\n\n\ndef new_message(request, pk):\n\n advert = get_object_or_404(Advert, id=pk)\n\n form = NewMessageForm(request.POST)\n\n if form.is_valid():\n text = form.cleaned_data.get(\"text\")\n\n conversation = Conversation.objects.create(advert_id=pk)\n conversation.users.add(advert.user)\n conversation.users.add(request.user)\n\n message = conversation.messages.create(\n text=text,\n sender=request.user,\n )\n\n message.seen_users.add(request.user)\n\n redirect_to = \"%(path)s?message_sent=true\" % {\n \"path\": reverse(\"detail_advert\", args=[pk])\n }\n\n return redirect(redirect_to)\n\n return HttpResponse(\"gonderilmedi\")\n","sub_path":"messages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"626777768","text":"def check(l, r):\n if not l and not r:\n return True\n if not l or not r:\n return False\n return l.val == r.val and check(l.left, r.left) and check(l.right, r.right)\n\nclass Solution:\n def isSubtree(self, s, t):\n \"\"\"\n :type s: TreeNode\n :type t: TreeNode\n :rtype: bool\n \"\"\"\n if not s:\n return False\n if s.val == t.val:\n if check(s, t):\n return True\n return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)\n ","sub_path":"Python/572isSubtree.py","file_name":"572isSubtree.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"240688172","text":"from flask import current_app, jsonify, render_template, abort, session, g, request\n\nfrom info import db\nfrom info.models import News, User, Comment, CommentLike\nfrom info.utils.commons import user_login_data\nfrom info.utils.response_code import RET\nfrom . import news_blue\n\n# 443评论点赞\n# 请求路径: /news/comment_like\n# 请求方式: POST/\n# 请求参数: news_id, comment_id, action, g.user\n# 返回值: errno , errmsg , ,\n@news_blue.route('/comment_like', methods=['POST'])\n@user_login_data\ndef comment_like():\n \"\"\"\n 1. 判断用户是否有登陆\n 2. 获取参数\n 3. 参数校验,为空校验\n 4. 操作类型进行校验\n 5. 通过评论编号查询评论对象,并判断是否存在\n 6. 根据操作类型点赞取消点赞\n 7. 返回响应\n :return:\n \"\"\"\n # 1. 判断用户是否有登陆\n if not g.user:\n return jsonify(errno=RET.NODATA, errmsg=\"用户未登录\")\n\n # 2. 获取参数\n comment_id = request.json.get(\"comment_id\")\n action = request.json.get(\"action\")\n\n # 3. 参数校验,为空校验\n if not all([comment_id, action]):\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数不全\")\n\n # 4. 操作类型进行校验\n if not action in [\"add\", \"remove\"]:\n return jsonify(errno=RET.DATAERR, errmsg=\"操作类型有误\")\n\n # 5. 通过评论编号查询评论对象,并判断是否存在\n try:\n comment = Comment.query.get(comment_id)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=\"获取评论失败\")\n\n if not comment: return jsonify(errno=RET.NODATA, errmsg=\"评论不存在\")\n\n # 6. 根据操作类型点赞取消点赞\n try:\n if action == \"add\":\n # 6.1 判断用户是否有对该评论点过赞\n comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,\n CommentLike.comment_id == comment_id).first()\n if not comment_like:\n # 创建点赞对象\n comment_like = CommentLike()\n comment_like.user_id = g.user.id\n comment_like.comment_id = comment_id\n\n # 添加到数据库中\n db.session.add(comment_like)\n\n # 将该评论的点赞数量+1\n comment.like_count += 1\n db.session.commit()\n else:\n # 6.2 判断用户是否有对该评论点过赞\n comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,\n CommentLike.comment_id == comment_id).first()\n if comment_like:\n # 删除点赞对象\n db.session.delete(comment_like)\n\n # 将该评论的点赞数量1\n if comment.like_count > 0:\n comment.like_count -= 1\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR, errmsg=\"操作失败\")\n\n # 7. 返回响应\n return jsonify(errno=RET.OK, errmsg=\"操作成功\")\n\n\n\n\n\n\n\n\n\n\n# 444 新闻评论后端\n# 请求路径: /news /news_comment\n# 请求方式: POST\n# 请求参数: news_id, comment, parent_id, g.user\n# 返回值: errno , errmsg ,\n\n@news_blue.route('/news_comment', methods=['POST'])\n@user_login_data\ndef news_comment():\n # 1.判断用户是否登陆\n if not g.user:\n return jsonify(errno=RET.NODATA,errmsg=\"用户未登陆\")\n\n # 2. 2. 获取参数\n news_id = request.json.get(\"news_id\")\n content = request.json.get(\"comment\")\n parent_id = request.json.get(\"parent_id\")\n\n # 3. 校验参数\n if not all([news_id, content]):\n return jsonify(errno=RET.PARAMERR,errmsg=\"参数不全\")\n\n # 4. 通过news_id 找到新闻对象,判断是否存在新闻\n try:\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=\"获取新闻失败\")\n if not news: return jsonify(errno=RET.NODATA,errmsg=\"新闻不存在\")\n\n # 5. 创建评论对象,设置对象属性\n comment = Comment()\n comment.user_id = g.user.id\n comment.news_id = news_id\n comment.content = content\n if parent_id:\n comment.parent_id = parent_id\n # 6. 保存评论对象到数据库\n\n try:\n db.session.add(comment)\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=\"评论失败\")\n\n # 7. 返回响应\n return jsonify(errno=RET.OK,errmsg=\"评论成功\", data = comment.to_dict())\n\n\n\n\n\n\n\n\n# 收藏功能--- 完善\n# 请求路径: /news/news_collect\n# 请求方式: POST\n# 请求参数: news_id, action, g.user\n# 返回值: errno,errmsg\n\n@news_blue.route('/news_collect', methods=['POST'])\n@user_login_data\ndef news_collect():\n # 1. 判断用户是否登陆\n if not g.user:\n return jsonify(errno=RET.NODATA,errmsg=\"用户未登陆\")\n # 2.获取参数\n news_id = request.json.get('news_id')\n action = request.json.get('action')\n # 3.校验参数\n if not all([news_id, action]):\n return jsonify(errno=RET.PARAMERR,errmsg=\"参数不全\")\n # 4.判断操作类型\n if not action in ['collect','cancel_collect']:\n return jsonify(errno=RET.DATAERR,errmsg=\"操作类型错误\")\n\n # 5.根据新闻编号取出新闻对象\n try:\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=\"新闻获取失败\")\n # 6.判断新闻}对象是否存在\n if not news:\n return jsonify(errno=RET.NODATA,errmsg=\"新闻不存在\")\n\n # 7.实现操作收藏&取消收藏\n if action == 'collect':\n # 7.1 判断用户是否对该新闻做过收藏\n if not news in g.user.collection_news:\n # 添加新闻收用户的收藏列表\n g.user.collection_news.append(news)\n else:\n # 7.2 判断用户是否对该新闻做过收藏\n if news in g.user.collection_news:\n # 从用户的收藏列表中移除这条收藏\n g.user.collection_news.remove(news)\n\n # 8.返回响应\n return jsonify(errno=RET.OK,errmsg=\"操作成功\")\n\n\n# 请求路径: /news/<int:news_id>\n# 请求方式: GET\n# 请求参数:news_id\n# 返回值: detail.html页面, 用户data字典数据\n@news_blue.route('/<int:news_id>')\n@user_login_data\ndef news_detail(news_id):\n\n #1.根据新闻编号,查询新闻 对象\n try:\n news = News.query.get(news_id)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=\"获取新闻失败\")\n\n # 2.1如果新闻不存在,直接抛出异常\n if not news:\n abort(404)\n\n\n # 3. 获取6条热门新闻展示于右侧\n try:\n click_news = News.query.order_by(News.clicks.desc()).limit(6).all()\n except Exception as e:\n current_app.logger.error(e)\n # 3.1 将热门新闻的对象列表转成字典列表\n click_news_list = []\n for item_news in click_news:\n click_news_list.append(item_news.to_dict())\n\n # 5.判断用户是否收藏过该新闻\n is_collected = False\n if g.user:\n # 用户需要登陆,并且此新闻在用户的收藏新闻列表中\n if news in g.user.collection_news:\n is_collected = True\n\n\n # 6.查询数据��中,该新闻的所有评论内容\n try:\n comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=\"获取评论失败\")\n\n # 6.1 用户点赞过的评论编号\n try:\n # 6.1.1 该用户点过赞的所有评论\n commentlikes = []\n if g.user:\n commentlikes = CommentLike.query.filter(CommentLike.user_id == g.user.id).all()\n # 6.1.2 获取用户所有点赞过的评论编号\n mylike_comment_ids = []\n for commetLike in commentlikes:\n mylike_comment_ids.append(commetLike.comment_id)\n except Exception as e:\n current_app.logger.error(e)\n return jsonify(errno=RET.DBERR,errmsg=\"获取点赞失败\")\n\n\n # 7.将评论的对象列表转成字典列表\n comment_list = []\n for comment in comments:\n comm_dict = comment.to_dict()\n # 添加is_like记录点赞\n comm_dict[\"is_like\"] = False\n # 判断用户是否有对评论点赞\n\n if g.user and comment.id in mylike_comment_ids:\n comm_dict[\"is_like\"] = True\n\n comment_list.append(comm_dict)\n\n\n\n\n #2.携带数据,渲染页面\n data = {\n \"news_info\": news.to_dict(),\n \"user_info\": g.user.to_dict() if g.user else \"\",\n \"news_list\": click_news_list,\n \"is_collected\": False,\n \"comments\": comment_list\n\n }\n return render_template(\"news/detail.html\",data=data)","sub_path":"info/modules/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"222829697","text":"#!/usr/bin/env python3\n\n# Автор: Гаврилов Дмитрий, ИУ7-26Б\n# Сортировка пузырьком с флагом\n\nimport random as r\nfrom tkinter import *\nfrom tkinter import messagebox\nimport tkinter.ttk as ttk # Модуль для создания таблиц\nimport copy, time\n\ndef description():\n messagebox.showinfo(\"Описание\", '''\nВ программе используется сортировка пузырьком с флагом\n\nСортировка: открывает окно, где на исходных данных\nпоказана корректная сортировка\n\nТаблица: открывает окно, где в виде таблицы представлены замеры\nвремени сортировки на различных массивах\n\nВсе изменения представлены в секундах\n\nВАЖНО! При нажатии на кнопку <<Таблица>> возможна задержка,\nтак как сортировка происходит не мгновенно на больших массивах\n\nАвтор: Гаврилов Дмитрий, ИУ7-26Б ''')\n\n# Класс для создания таблиц\nclass Table(Frame):\n def __init__(self, parent=None, headings=tuple(), rows = tuple()):\n super().__init__(parent)\n\n # Создаем таблицу\n table = ttk.Treeview(self, show=\"headings\", selectmode=\"none\")\n table[\"columns\"]=headings\n table[\"displaycolumns\"]=headings\n\n # Добавление заголовков\n for head in headings:\n table.heading(head, text=head, anchor=CENTER)\n table.column(head, anchor=CENTER)\n\n # Добавление строк\n for row in rows:\n table.insert('', END, values=row)\n\n table.pack(expand = True, fill = BOTH)\n\n# Пузырьковая сортировка с флагом\ndef BubbleSort(arr):\n flag = True\n for i in range(len(arr)):\n if not flag: break\n flag = False\n for j in range(len(arr) - 1):\n if arr[j+1] < arr[j]:\n arr[j+1], arr[j] = arr[j], arr[j+1]\n flag = True\n return arr\n\ndef getArr(size):\n return [i-i + r.randint(-100, 100) for i in range(size-1)]\n\ndef sort_is_corrected():\n window = Tk()\n window.title('Корректная сортировка')\n window.geometry('600x50+200+100')\n\n # Копия массива, что бы при сортировке исходный массив не изменялся\n arr = getArr(9)\n copyArr = copy.copy(arr)\n\n # Таблица с указанными заголовками и полями\n table = Table(window, headings=('Исходные данные', 'Результат'), rows=(\n (copyArr, BubbleSort(arr)), ('', '')))\n\n table.pack(expand=YES, fill=BOTH)\n window = mainloop()\n\n# Функция с измерениями\ndef showSortTable():\n def getTime(arr):\n start = time.time()\n BubbleSort(arr)\n return time.time() - start\n\n window = Tk()\n window.title('Таблица замеров времени')\n window.geometry('1000x100')\n arr1, arr2, arr3 = getArr(10), getArr(1000), getArr(3000)\n print(arr1)\n getTime(arr1)\n print(arr1)\n\n table = Table(window,\n\n # Заголовки\n headings=('','Массив из 100 значений',\n 'Массив из 1000 значений',\n 'Массив из 3000 значений'),\n # Строки\n rows=(\n\n # Первая строка\n ('Случайный массив',\n '{:.5f}'.format(getTime(arr1)),\n '{:.5f}'.format(getTime(arr2)),\n '{:.5f}'.format(getTime(arr3))\n ),\n\n # Вторая строка\n ('Упорядоченный массив',\n '{:.5f}'.format(getTime(arr1)),\n '{:.5f}'.format(getTime(arr2)),\n '{:.5f}'.format(getTime(arr3))\n ),\n\n # Третяя строка, наши массивы упорядочены\n ('Упор. в обратном порядке',\n '{:.5f}'.format(getTime(list(reversed(arr1)))),\n '{:.5f}'.format(getTime(list(reversed(arr2)))),\n '{:.5f}'.format(getTime(list(reversed(arr3))))\n )))\n\n table.pack(expand=YES, fill=BOTH)\n window = mainloop()\n\ndef main():\n # root - Главное окно\n # btnSort - кнопка, показывающая корректную сортировку\n # btnTable - кнопка, показывающая таблицу с измерениями\n # btnDescr = кнопка с описанием программы\n\n # Создание окна с кнопками\n root = Tk()\n root.geometry(\"200x130+500+200\")\n root.title('Сортировка пузырьком с флагом')\n\n btnSort = Button(text = 'Сортировка', command = sort_is_corrected)\n btnTable = Button(text = 'Таблица', command = showSortTable, width = 9)\n btnDescr = Button(text = 'Описание', command = description, width = 9)\n\n btnSort.place(x = 50, y = 10)\n btnTable.place(x = 50, y = 50)\n btnDescr.place(x = 50, y = 90)\n\n root.mainloop()\nmain()\n","sub_path":"lab_02/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"40357954","text":"from conans import ConanFile, CMake, tools\nfrom conans.tools import download, unzip\nimport os, re\n\nclass h5ppConan(ConanFile):\n name = \"h5pp\"\n version = \"1.1.0\"\n license = \"MIT\"\n url = \"https://github.com/DavidAce/h5pp\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n generators = \"cmake\"\n requires = \"eigen/3.3.7@conan/stable\", \"spdlog/1.4.2@bincrafters/stable\", \"hdf5/1.10.5\"\n build_policy = 'missing'\n options = {\n 'shared': [True, False],\n }\n default_options = (\n 'shared=False',\n )\n\n def source(self):\n\n zip_name = self.version+\".zip\"\n download(\"https://github.com/DavidAce/h5pp/archive/v\"+self.version+\".zip\", zip_name)\n unzip(zip_name)\n # git = tools.Git(folder=\"h5pp-\"+self.version)\n # git.clone(\"https://github.com/DavidAce/h5pp.git\", \"master\")\n\n def configure(self):\n tools.check_min_cppstd(self, \"17\")\n\n def _configure_cmake(self):\n cmake = CMake(self)\n cmake.definitions[\"ENABLE_TESTS:BOOL\"] = True\n cmake.definitions[\"BUILD_EXAMPLES:BOOL\"] = False\n cmake.definitions[\"H5PP_PRINT_INFO:BOOL\"] = True\n cmake.definitions[\"DOWNLOAD_METHOD:STRING\"] = \"conan\"\n if tools.os_info.is_linux:\n cmake.definitions['BUILD_SHARED_LIBS:BOOL'] = True if self.options.shared else False\n\n cmake.configure(source_folder=self.build_folder+'/h5pp-'+self.version)\n return cmake\n\n def build(self):\n cmake = self._configure_cmake()\n cmake.build()\n\n def package(self):\n cmake = self._configure_cmake()\n cmake.install()\n cmake.test()\n\n def package_id(self):\n self.info.header_only()\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"171976752","text":"from AWSHalide import *\nfrom imagehelp import *\nimport time\n\ndef query_and_run(query):\n init()\n save_images(query)\n path = \"*.png\"\n for fname in glob.glob(path):\n local('rm ' + PATH_TO_ZIP_DIR + '/images/image.png')\n local('mv ' + fname + ' ' + PATH_TO_ZIP_DIR + '/images/image.png')\n upload_zip(fname+'.zip')\n\n\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"291371490","text":"from main_project.Bus_API import fetch_busapi\nfrom main_project.Bus_API.store_bus_routes_data_in_database import StoreBusRoutesData\nfrom django.test import TestCase\nfrom unittest.mock import MagicMock\nfrom mock import patch\nimport json\nimport datetime\nfrom freezegun import freeze_time\n\n\n@freeze_time(\"2021-03-11 17\")\nclass TestFetchBusApi(TestCase):\n @classmethod\n def setUpTestData(cls):\n pass\n\n def test_busapi_locations(self):\n fetch_bus_api_class = fetch_busapi.FetchBusApi()\n\n store_bus_data_to_database = StoreBusRoutesData()\n\n mocked_result = [\n {\n \"stop_id\": \"stop_0\",\n \"stop_name\": \"test_name_1\",\n \"stop_lat\": 1,\n \"stop_lon\": 2\n },\n {\n \"stop_id\": \"stop_1\",\n \"stop_name\": \"test_name_2\",\n \"stop_lat\": 3,\n \"stop_lon\": 4\n }\n ]\n store_bus_data_to_database.fetch_busstops_location = MagicMock(\n return_value=mocked_result)\n\n expected_result = {\n \"stop_0\": {\n \"STOP_ID\": \"stop_0\",\n \"STOP_NAME\": \"test_name_1\",\n \"STOP_LAT\": 1,\n \"STOP_LON\": 2\n },\n\n \"stop_1\": {\n \"STOP_ID\": \"stop_1\",\n \"STOP_NAME\": \"test_name_2\",\n \"STOP_LAT\": 3,\n \"STOP_LON\": 4\n }\n }\n\n result = fetch_bus_api_class.bus_stand_locations(\n busRoutesObj=store_bus_data_to_database)\n self.assertDictEqual(result, expected_result)\n\n def test_busapi_timings(self):\n fetch_bus_api_class = fetch_busapi.FetchBusApi()\n store_bus_data_to_database = StoreBusRoutesData()\n mocked_result_bus_trips = [\n {\n \"trip_id\": \"315_IJ\",\n \"route_id\": \"route_0\",\n \"stops\": []\n },\n {\n \"trip_id\": \"315_IJ\",\n \"route_id\": \"route_1\",\n \"stops\": []\n }\n ]\n store_bus_data_to_database.fetch_bustrips = MagicMock(\n return_value=mocked_result_bus_trips)\n\n\n mocked_result_routes = [\n {\n \"route_name\": \"route_name_0\",\n \"route_id\": \"route_0\",\n },\n {\n \"route_name\": \"route_name_1\",\n \"route_id\": \"route_1\",\n }\n ]\n store_bus_data_to_database.fetch_busroutes = MagicMock(\n return_value=mocked_result_routes)\n\n expected_result = {\n \"trip_0\": {\n \"TRIP_ID\": \"315_IJ\",\n \"ROUTE_ID\": \"route_0\",\n \"ROUTE_NAME\": \"route_name_0\",\n \"STOP_INFO\": []\n },\n\n \"trip_1\": {\n \"TRIP_ID\": \"315_IJ\",\n \"ROUTE_ID\": \"route_1\",\n \"ROUTE_NAME\": \"route_name_1\",\n \"STOP_INFO\": []\n }\n }\n result = fetch_bus_api_class.bus_trips_timings(\n busRoutesObj=store_bus_data_to_database)\n self.assertDictEqual(result, expected_result)\n","sub_path":"sustainableCityManagement/tests/Bus_API/test_fetch_busapi.py","file_name":"test_fetch_busapi.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"14784240","text":"import requests\nimport json\nimport logging\n\nimport util\n\nclass itemInitError(LookupError):\n '''raise this when there's a bad typeID on class creation or can't be found in lookup table'''\n\nclass itemJSONTableError(LookupError):\n '''raise this when there is no global itemJSON TAble Defined'''\n\ndef initialize_item_table():\n logging.debug(\"OPENING JSON for Type IDs\")\n with open('../../res/long.json', 'r') as f:\n logging.info(\"Loading JSON into Python Data Structures for Inventory Items\")\n data = json.load(f)\n logging.info(\"Complete Loading JSON into Python Data Structures for Inventory Items\")\n\n itemTable = {}\n\n for i in data:\n try:\n itemTable[i] = data[i]\n itemTable[str(data[i]['name']['en'])] = data[i]\n itemTable[i]['typeID'] = i #Embedd the typeID in the data structure so we can use it later\n logging.debug(\"adding \" + str(data[i]['name']['en']) + \" to dictionary\" +\"\\n\")\n except:\n pass\n\n return itemTable\n\n# Load static data from tier 1 sources, files or CREST API\nitemJSONTable = initialize_item_table()\n\nclass item(object):\n \"\"\"An item in eve is anything tradable on the market. Items have the\n following properties:\n\n Attributes:\n typeID: An integer for this item type unique defined by eve\n Description: A String with a friendly definition of the item. \"\"\"\n\n def __init__(self, itemJSON):\n \"\"\"Return an item object based on the typeID specified.\n :rtype: item Instance\n \"\"\"\n try:\n self.typeID = itemJSON['typeID']\n self.name = itemJSON['name']['en']\n self.description = itemJSON['description']['en']\n except:\n raise itemInitError('Bad JSON could not parse' + str(itemJSON))\n\n @classmethod\n def from_name(cls, name):\n try:\n return cls(itemJSONTable[name])\n except itemInitError as e:\n raise itemJSONTableError(e)\n\n @classmethod\n def from_typeid(cls, typeid):\n try:\n return cls(itemJSONTable[typeid])\n except itemInitError as e:\n raise itemJSONTableError(e)\n\n def __str__(self):\n return str(self.name) +\"(\" + self.typeID + \")\"\n\n\n def getMktBuyPrice(self, region):\n \"\"\" Get the Median mkt Buy Price for this item in the region sepfified, if no region is passed then\n we will use The Forge\n :param region the market region of interest\n :rtype: Median Price\n \"\"\"\n if region is \"\":\n region = \"The Forge\" #When in doubt assume Jita\n\n # Get the market data Buy EP\n mktBuyOrdersEP = \"https://crest-tq.eveonline.com/market/\" + str(region.id) + \"/orders/buy/\"\n reqArgs = {'type': \"https://crest-tq.eveonline.com/inventory/types/\" + str(self.typeID) + \"/\"}\n\n logging.info(\"CREST: GET \" + str(mktBuyOrdersEP) + \" Param \" + str(reqArgs))\n req = requests.get(url=mktBuyOrdersEP, params=reqArgs)\n if req.status_code is not 200:\n logging.error(\"Can not retrieve CREST mkt Buy Orders for \" + argRegionObject[\"NAME\"])\n logging.error(\"Status: \" + str(req.status_code) + \" Reason : \" + req.reason)\n exit(-1)\n mktBuyOrdersData = req.json()\n\n buylist = []\n for i in mktBuyOrdersData['items']:\n buylist.append(i['price'])\n\n # Calculate Avg and Median Buy\n medBuy = util.median(buylist)\n logging.info(\"INFO: Median Buy Price is \" + str(medBuy))\n return medBuy\n\n def getMktSellPrice(self, region):\n \"\"\" Get the Median mkt Buy Price for this item in the region sepfified, if no region is passed then\n we will use The Forge\n :param region the market region of interest\n :rtype: Median Price\n \"\"\"\n if region is \"\":\n region = \"The Forge\" # When in doubt assume Jita\n\n # Get the market data Buy EP\n mktBuyOrdersEP = \"https://crest-tq.eveonline.com/market/\" + region.id + \"/orders/buy/\"\n reqArgs = {'type': \"https://crest-tq.eveonline.com/inventory/types/\" + self.typeID + \"/\"}\n\n logging.info(\"CREST: GET \" + str(mktBuyOrdersEP) + \" Param \" + str(reqArgs))\n req = requests.get(url=mktBuyOrdersEP, params=reqArgs)\n if req.status_code is not 200:\n logging.error(\"Can not retrieve CREST mkt Buy Orders for \" + argRegionObject[\"NAME\"])\n logging.error(\"Status: \" + str(req.status_code) + \" Reason : \" + req.reason)\n exit(-1)\n mktBuyOrdersData = req.json()\n\n buylist = []\n for i in mktBuyOrdersData['items']:\n buylist.append(i['price'])\n\n # Calculate Avg and Median Buy\n avgBuy = float(sum(buylist)) / len(buylist)\n logging.info(\"INFO: Average Buy Price is \" + str(avgBuy))\n medBuy = util.median(buylist)\n logging.info(\"INFO: Median Buy Price is \" + str(medBuy))\n\n # Get the market data Sell EP\n logging.info(\"CREST: GET \" + str(mktSellOrdersEP) + \" Param \" + str(reqArgs))\n req = requests.get(url=mktSellOrdersEP, params=reqArgs)\n if req.status_code is not 200:\n logging.error(\"Can not retrieve CREST mkt Sell Orders for \" + argRegionObject[\"NAME\"])\n logging.error(\"Status: \" + str(req.status_code) + \" Reason : \" + req.reason)\n exit(-1)\n mktSellOrdersData = req.json()\n\n selllist = []\n for i in mktSellOrdersData['items']:\n selllist.append(i['price'])\n\n # Calculate Avg and Median Sell\n avgSell = float(sum(selllist)) / len(selllist)\n logging.info(\"INFO: Average Sell Price is \" + str(avgSell))\n medSell = util.median(selllist)\n logging.info(\"INFO: Median Sell Price is \" + str(medSell))\n\n return {\"avgBuy\": avgBuy, \"medBuy\": medBuy, \"avgSell\": avgSell, \"medSell\": medSell}\n\n return price","sub_path":"core/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":6059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"654203205","text":"#!/usr/bin/env python3\n#coding: utf-8\nfrom ev3dev.ev3 import *\nfrom threading import *\nimport socket, time, json, math\n\nuc = UltrasonicSensor('in1')\nuc.mode = 'US-DIST-CM'\n\nuf = UltrasonicSensor('in2')\nuf.mode = 'US-DIST-CM'\n\nir = InfraredSensor('in3')\nir.mode = 'IR-PROX'\n\nut = UltrasonicSensor('in4')\nut.mode = 'US-DIST-CM'\n\nclass Communication(Thread):\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n while True:\n try:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect(('169.255.168.150', 3572))\n \n while True:\n\n Sedex = {\n \"uc\" : int(uc.value()),\n \"uf\" : int(uf.value()),\n \"ir\" : int(ir.value()),\n \"ut\" : int(ut.value())\n }\n\n s.send(json.dumps(Sedex).encode())\n #time.sleep(0.1)\n \n except Exception as e:\n print(e)\n s.close()\n time.sleep(0.5)\n\ncomm = Communication()\ncomm.daemon = True\ncomm.start()\n\nwhile True:\n pass","sub_path":"Brick_2_teste.py","file_name":"Brick_2_teste.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"226346901","text":"from .base import _ApiResourceBase\n\n\nOVERLAY_PAGE_FRIENDS = 'Friends'\nOVERLAY_PAGE_COMMUNITY = 'Community'\nOVERLAY_PAGE_PLAYERS = 'Players'\nOVERLAY_PAGE_SETTINGS = 'Settings'\nOVERLAY_PAGE_GAME_GROUP = 'OfficialGameGroup'\nOVERLAY_PAGE_STATS = 'Stats'\nOVERLAY_PAGE_ACHIEVEMENTS = 'Achievements'\n\n\nclass Overlay(_ApiResourceBase):\n \"\"\"Exposes methods to manipulate overlay.\n\n Overlay-related functions only work with OpenGL/D3D applications and only\n if Steam API is initialized before renderer device.\n\n Interface can be accessed through ``api.overlay``:\n\n .. code-block:: python\n\n api.overlay.activate()\n\n \"\"\"\n _res_name = 'ISteamFriends'\n\n def activate(self, page=None):\n \"\"\"Activates overlay with browser, optionally opened at a given page.\n\n :param str page: Overlay page alias (see OVERLAY_PAGE_*)\n or a custom URL.\n\n \"\"\"\n page = page or ''\n\n if '://' in page:\n self._call('ActivateGameOverlayToWebPage', (self._ihandle(), page))\n else:\n self._call('ActivateGameOverlay', (self._ihandle(), page))\n","sub_path":"steampak/libsteam/resources/overlay.py","file_name":"overlay.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"223457733","text":"# -*- coding: utf-8 -*-\n#\n# Nitrate is copyright 2010 Red Hat, Inc.\n#\n# Nitrate is free software: you can redistribute it and/or modify it\n# 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. This program is distributed in\n# the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n# even the implied warranties of TITLE, NON-INFRINGEMENT,\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# The GPL text is available in the file COPYING that accompanies this\n# distribution and at <http://www.gnu.org/licenses>.\n#\n# Authors:\n# Chaobin Tang <ctang@redhat.com>\n\n'''\nA serializer to import/export between model objects and file formats.\n'''\n\nimport csv\nfrom lxml import etree\n\n\nclass TCR2File(object):\n '''\n Write TestCaseRun queryset into CSV or XML.\n '''\n ROOT = 'testcaseruns'\n HEADERS = (\"Case Run ID\", \"Case ID\",\n \"Category\", \"Status\", \"Summary\",\n \"script\", \"Automated\", \"Log Link\",\n \"Bug IDs\")\n\n def __init__(self, tcrs):\n self.root = self.ROOT\n self.headers = self.HEADERS\n self.tcrs = tcrs\n self.rows = []\n\n def tcr_attrs_in_a_list(self, tcr):\n line = [\n tcr.pk, tcr.case.pk, tcr.case.category,\n tcr.case_run_status, tcr.case.summary.encode('utf-8'),\n tcr.case.script, tcr.case.is_automated,\n self.log_links(tcr), self.bug_ids(tcr)\n ]\n return line\n\n def log_links(self, tcr):\n '''\n Wrap log links into a single cell by\n joining log links.\n '''\n log_links = tcr.links.all()\n return ' '.join(\n tcr.links.values_list('url', flat=True)\n )\n\n def bug_ids(self, tcr):\n '''\n Wrap bugs into a single cell by\n joining bug IDs.\n '''\n return ' '.join((\n str(pk) for pk in\n tcr.case.case_bug.values_list('bug_id', flat=True)\n ))\n\n def tcrs_in_rows(self):\n if self.rows: return self.rows\n for tcr in self.tcrs:\n row = self.tcr_attrs_in_a_list(tcr)\n self.rows.append(row)\n return self.rows\n\n def write_to_csv(self, fileobj):\n writer = csv.writer(fileobj)\n rows = self.tcrs_in_rows()\n writer.writerow(self.headers)\n writer.writerows(rows)\n\n def write_to_xml(self, fileobj):\n root = etree.Element(self.root)\n for tcr in self.tcrs:\n sub_elem = etree.Element('testcaserun')\n sub_elem.set('case_run_id', str(tcr.pk))\n sub_elem.set('case_id', str(tcr.case.pk))\n sub_elem.set('category', tcr.case.category.name or u'')\n sub_elem.set('status', str(tcr.case_run_status))\n sub_elem.set('summary', tcr.case.summary or u'')\n sub_elem.set('scripts', tcr.case.script or u'')\n sub_elem.set('automated', str(tcr.case.is_automated))\n log_sub_elem = etree.Element('loglinks')\n for link in tcr.links.all():\n log_sub_elem.set('name', link.name)\n log_sub_elem.set('url', link.url)\n sub_elem.append(log_sub_elem)\n bug_sub_elem = etree.Element('bugs')\n for bug in tcr.case.case_bug.all():\n bug_sub_elem.set('bug', str(bug.bug_id))\n sub_elem.append(bug_sub_elem)\n root.append(sub_elem)\n fileobj.write(etree.tostring(root))\n","sub_path":"tcms/apps/testruns/helpers/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"352311262","text":"import spotipy\nimport spotipy.util as util\nimport json\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport string\nimport os\nimport sys\n\n\ndef get_spotify_token(user_name, client_id, client_secret, redirect_uri):\n scope = \"user-library-read playlist-read-private playlist-read-collaborative\"\n token = util.prompt_for_user_token(\n user_name, scope=scope, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)\n return token\n\n\ndef format_item(item):\n track = item[\"track\"]\n spotify_id = track[\"id\"]\n artists = [ai[\"name\"] for ai in track[\"artists\"]]\n name = track[\"name\"]\n return {\"spotify_id\": spotify_id,\n \"artists\": artists, \"name\": name}\n\n\ndef get_saved_tracks(spotify):\n result = []\n chunk_size = 50\n offset = 0\n results = spotify.current_user_saved_tracks(\n limit=chunk_size, offset=offset)\n while results[\"items\"]:\n result.extend([format_item(item) for item in results[\"items\"]])\n number_of_items = len(results[\"items\"])\n offset += number_of_items\n results = spotify.current_user_saved_tracks(\n limit=chunk_size, offset=offset)\n return result\n\n\ndef get_playlist_tracks(spotify, owner_id, playlist_id):\n result = []\n pl = None\n tracks = None\n\n try:\n pl = spotify.user_playlist(owner_id, playlist_id)\n tracks = pl[\"tracks\"]\n result.extend([format_item(ti) for ti in tracks[\"items\"]])\n except:\n pass\n\n while tracks and tracks[\"next\"]:\n try:\n tracks = spotify.next(tracks)\n result.extend([format_item(ti) for ti in tracks[\"items\"]])\n except:\n pass\n\n return result\n\n\ndef get_playlists(spotify):\n chunk_size = 50\n offset = 0\n pls = spotify.current_user_playlists(limit=chunk_size, offset=offset)\n while pls[\"items\"]:\n for pl in pls[\"items\"]:\n playlist_id = pl[\"id\"]\n name = pl[\"name\"]\n owner_id = pl[\"owner\"][\"id\"]\n tracks = get_playlist_tracks(spotify, owner_id, playlist_id)\n if tracks:\n playlist = {\"playlist_id\": playlist_id,\n \"name\": name,\n \"tracks\": tracks}\n yield playlist\n number_of_items = len(pls[\"items\"])\n offset += number_of_items\n pls = spotify.current_user_playlists(\n limit=chunk_size, offset=offset)\n\n\ndef format_filename(s):\n valid_chars = \"-_.() %s%s\" % (string.ascii_letters, string.digits)\n filename = \"\".join(c for c in s if c in valid_chars)\n return filename\n\n\ndef write_to_json(file_name, object):\n with open(file_name, \"wt\", encoding=\"utf-8\") as outfile:\n json.dump(object, outfile)\n\n\nif __name__ == \"__main__\":\n\n input_valid = len(sys.argv) == 6\n\n if not input_valid:\n print(\"invalid arguments!\")\n print(\n \"expected arguments: [client_id] [client_secret] [redirect_uri] [user_name] [target_folder]\")\n else:\n client_id = sys.argv[1]\n client_secret = sys.argv[2]\n redirect_uri = sys.argv[3]\n user_name = sys.argv[4]\n target_folder = sys.argv[5]\n\n print(\"using '%s' as client_id.\" % client_id)\n print(\"using '%s' as client_secret.\" % client_secret)\n print(\"using '%s' as redirect_uri.\" % redirect_uri)\n print(\"using '%s' as user_name.\" % user_name)\n print(\"using '%s' as target_folder.\" % target_folder)\n\n token = get_spotify_token(user_name, client_id,\n client_secret, redirect_uri)\n\n sp = spotipy.Spotify(auth=token)\n sp.trace = False\n\n if not os.path.exists(target_folder):\n os.makedirs(target_folder)\n\n print(\"getting saved tracks\")\n saved_tracks = get_saved_tracks(sp)\n saved_tracks_filename = os.path.join(\n target_folder, \"saved_tracks.json\")\n write_to_json(saved_tracks_filename, saved_tracks)\n print(\"wrote saved tracks to %s\" % saved_tracks_filename)\n\n print(\"getting playlists\")\n for pl in get_playlists(sp):\n playlist_filename = os.path.join(\n target_folder, \"%s.json\") % format_filename(pl[\"name\"])\n write_to_json(playlist_filename, pl)\n print(\"written playlist to %s\" % playlist_filename)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"184218619","text":"import logging\nimport os\nfrom urlparse import urlparse\n\nfrom fabric.tasks import execute, WrappedCallableTask\nfrom fabric.api import env\nfrom fabric import colors\nimport click\n\nDEFAULT_LOG_LEVEL = 'ERROR'\n\ngithub_options = [\n click.option('--owner', help='GitHub owner name', default='gisce', show_default=True),\n click.option('--repository', help='GitHub repository name', default='erp', show_default=True),\n\n]\n\ndeployment_options = [\n click.option(\"--host\", help=\"Host to apply\", required=True),\n click.option('--src', help='Remote src path', default='/home/erp/src', show_default=True),\n click.option('--sudo_user', help='Sudo user from the host', default='erp', show_default=True),\n]\n\napply_pr_options = github_options + deployment_options + [\n click.option(\"--pr\", help=\"Pull request to apply\", required=True),\n click.option(\"--from-number\", help=\"From commit number\", default=0),\n click.option(\"--from-commit\", help=\"From commit hash (included)\", default=None),\n click.option(\"--force-hostname\", help=\"Force hostname\", default=False),\n click.option(\"--force-name\", help=\"Force host repository name\", default=False),\n click.option(\"--auto-exit\", help=\"Execute git am --abort when fail\",\n type=click.BOOL, default=False),\n]\n\nstatus_options = github_options + [\n click.argument('deploy-id'),\n click.argument(\n 'status', type=click.Choice(['success', 'error', 'failure']),\n default='success'),\n]\n\ncheck_prs_options = github_options + [\n click.option('--prs', required=True,\n help='List of pull request separated by space (by default)'),\n click.option(\n '--separator', help='Character separator of list by default is space',\n default=' ', show_default=True),\n click.option('--version',\n help=\"Compare with milestone and show if included in prs\"),\n]\n\ncreate_changelog_options = github_options + [\n click.option('-m', '--milestone', required=True,\n help='Milestone to get the issues from (version)'),\n click.option('--issues/--no-issues', default=False, show_default=True,\n help='Also get the data on the issues'),\n click.option('--changelog_path', default='/tmp', show_default=True,\n help='Path to drop the changelog file in'),\n]\n\ndef add_options(options):\n def _add_options(func):\n for option in reversed(options):\n func = option(func)\n return func\n return _add_options\n\n\ndef configure_logging():\n log_level = getattr(logging, os.environ.get(\n 'LOG_LEVEL', DEFAULT_LOG_LEVEL).upper()\n )\n logging.basicConfig(level=log_level)\n\n\n@click.command('apply_pr')\n@add_options(apply_pr_options)\ndef deprecated(**kwargs):\n print(colors.red(\n \"WARNING: 'apply_pr' command has been deprecated and\\n\"\n \" it will be deleted in future versions\"\n ))\n print(colors.yellow(\"> Use 'sastre deploy' instead\"))\n return apply_pr(**kwargs)\n\n\n@click.group(name='sastre')\ndef sastre(**kwargs):\n from apply_pr.version import check_version\n check_version()\n\n\ndef apply_pr(\n pr, host, from_number=0, from_commit=None, force_hostname=False,\n owner='gisce', repository='erp', src='/home/erp/src', sudo_user='erp',\n auto_exit=False, force_name=None\n):\n \"\"\"\n Deploy a PR into a remote server via Fabric\n :param pr: Number of the PR to deploy\n :type pr: str\n :param host: Host to connect\n :type host: str\n :param from_number: Number of the commit to deploy from\n :type from_number: str\n :param from_commit: Hash of the commit to deploy from\n :type from_commit: str\n :param force_hostname: Hostname used in GitHub\n :type force_hostname: str\n :param owner: Owner of the repository of GitHub\n :type owner: str\n :param repository: Name of the repository of GitHub\n :type repository: str\n :param src: Source path to the repository directory\n :type src: str\n :param sudo_user: Remote user with sudo\n :type sudo_user str\n \"\"\"\n from apply_pr import fabfile\n if 'ssh' not in host and host[:2] != '//':\n host = '//{}'.format(host)\n url = urlparse(host, scheme='ssh')\n env.user = url.username\n env.password = url.password\n\n configure_logging()\n apply_pr_task = WrappedCallableTask(fabfile.apply_pr)\n result = execute(\n apply_pr_task, pr, from_number, from_commit, hostname=force_hostname,\n src=src, owner=owner, repository=repository, sudo_user=sudo_user,\n host='{}:{}'.format(url.hostname, (url.port or 22)), auto_exit=auto_exit,\n force_name=force_name\n )\n return result\n\n\n@sastre.command(name=\"deploy\")\n@add_options(apply_pr_options)\ndef deploy(**kwargs):\n \"\"\"Deploy a PR into a remote server via Fabric\"\"\"\n return apply_pr(**kwargs)\n\n\n@sastre.command(name='check_pr')\n@click.option('--pr', help='Pull request to check', required=True)\n@click.option('--force/--no-force', default=False,\n help='Forces the usage of this command')\n@add_options(deployment_options)\ndef check_pr(pr, force, src, owner, repository, host):\n \"\"\"DEPRECATED - Check for applied commits on PR\"\"\"\n print(colors.red(\"This option has been deprecated as it doesn't work\"))\n if not force:\n print(colors.red(\n \"Use '--force' to force the usage for this command (as is)\"))\n exit()\n from apply_pr import fabfile\n\n url = urlparse(host, scheme='ssh')\n env.user = url.username\n env.password = url.password\n\n configure_logging()\n\n check_pr_task = WrappedCallableTask(fabfile.check_pr)\n execute(\n check_pr_task, pr, src=src, owner=owner, repository=repository,\n host='{}:{}'.format(url.hostname, (url.port or 22))\n )\n\n\ndef status_pr(deploy_id, status, owner, repository):\n \"\"\"Update the status of a deploy into GitHub\"\"\"\n from apply_pr import fabfile\n\n configure_logging()\n\n mark_deploy_status = WrappedCallableTask(fabfile.mark_deploy_status)\n execute(mark_deploy_status, deploy_id, status,\n owner=owner, repository=repository)\n\n\n@sastre.command(name='status')\n@add_options(status_options)\ndef status(**kwargs):\n \"\"\"Update the status of a deploy into GitHub\"\"\"\n status_pr(**kwargs)\n\n\ndef check_prs_status(prs, separator, version, owner, repository):\n \"\"\"Check the status of the PRs for a set of PRs\"\"\"\n from apply_pr import fabfile\n\n log_level = getattr(logging, os.environ.get('LOG_LEVEL', 'INFO').upper())\n logging.basicConfig(level=log_level)\n\n check_pr_task = WrappedCallableTask(fabfile.prs_status)\n execute(check_pr_task, prs,\n owner=owner,\n repository=repository,\n separator=separator,\n version=version)\n\n\n@sastre.command(name='check_prs')\n@add_options(check_prs_options)\ndef check_prs(**kwargs):\n \"\"\"Check the status of the PRs for a set of PRs\"\"\"\n check_prs_status(**kwargs)\n\n\n@sastre.command(name='create_changelog')\n@add_options(create_changelog_options)\ndef create_changelog(milestone, issues, changelog_path, owner, repository):\n \"\"\"Create a changelog for the given milestone\"\"\"\n from apply_pr import fabfile\n\n log_level = getattr(logging, os.environ.get('LOG_LEVEL', 'INFO').upper())\n logging.basicConfig(level=log_level)\n changelog_task = WrappedCallableTask(fabfile.create_changelog)\n execute(changelog_task,\n milestone,\n issues,\n changelog_path,\n owner=owner,\n repository=repository)\n\n\ndef deploy_ids(pr, owner, repository):\n from apply_pr import fabfile\n\n configure_logging()\n\n get_deploys_task = WrappedCallableTask(fabfile.get_deploys)\n execute(get_deploys_task, pr,\n owner=owner, repository=repository)\n\n\n@sastre.command(name='get_deploys')\n@click.argument('PR')\n@add_options(github_options)\ndef get_deploys(**kwargs):\n \"\"\"Get deploy IDs and their status for a given PR number\"\"\"\n deploy_ids(**kwargs)\n\n\nif __name__ == '__main__':\n sastre()\n","sub_path":"apply_pr/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":8074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"264545701","text":"\"\"\"\nViews for the Recordlib webapp.\n\n\"\"\"\nfrom typing import Tuple, List\nimport os\nimport logging\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom rest_framework.response import Response\nfrom rest_framework.parsers import MultiPartParser, FormParser\nfrom rest_framework.views import APIView\nfrom rest_framework import permissions, status\nfrom django_q.tasks import async_task\nfrom RecordLib.crecord import CRecord\nfrom RecordLib.sourcerecords import SourceRecord as RLSourceRecord\nfrom RecordLib.analysis import Analysis\nfrom RecordLib.utilities.serializers import to_serializable\nfrom RecordLib.utilities import cleanslate_screen\nfrom RecordLib.analysis.ruledefs import (\n filter_traffic_cases,\n filter_landlordtenant_cases,\n expunge_summary_convictions,\n expunge_nonconvictions,\n expunge_deceased,\n expunge_over_70,\n seal_convictions,\n)\nfrom RecordLib.petitions import Expungement, Sealing\nfrom cleanslate.models import (\n User,\n UserProfile,\n ExpungementPetitionTemplate,\n SealingPetitionTemplate,\n OverviewTemplate,\n)\nfrom cleanslate.serializers import (\n CRecordSerializer,\n PetitionViewSerializer,\n FileUploadSerializer,\n UserProfileSerializer,\n UserSerializer,\n IntegrateSourcesSerializer,\n SourceRecordSerializer,\n DownloadDocsSerializer,\n AutoScreeningSerializer,\n TemplateSerializer,\n)\nfrom cleanslate.compressor import Compressor\nfrom cleanslate.services import download as download_service, write_overview\nfrom cleanslate.models import SourceRecord\n\nlogger = logging.getLogger(__name__)\n\n\nclass FileUploadView(APIView):\n \"\"\"\n Handle uploads of source records.\n \"\"\"\n\n parser_classes = [MultiPartParser, FormParser]\n\n # noinspection PyMethodMayBeStatic\n def post(self, request):\n \"\"\"Accept dockets and summaries locally uploaded by a user, save them to the server,\n and return SourceRecords relating to those files..\n\n\n This POST needs to be a FORM post, not a json post.\n \"\"\"\n file_serializer = FileUploadSerializer(data=request.data)\n if file_serializer.is_valid():\n files = file_serializer.validated_data.get(\"files\")\n results = []\n try:\n for upload in files:\n source_record = SourceRecord.from_unknown_file(\n upload, owner=request.user\n )\n source_record.save()\n if source_record is not None:\n results.append(source_record)\n # TODO FileUploadView should report errors in turning uploaded pdfs into SourceRecords.\n return Response(\n {\"source_records\": SourceRecordSerializer(results, many=True).data},\n status=status.HTTP_200_OK,\n )\n except Exception as err:\n return Response(\n {\"error_message\": f\"Parsing failed: {str(err)}\"},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR,\n )\n else:\n return Response(\n {\"error_message\": \"Invalid Data.\", \"errors\": file_serializer.errors},\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass SourceRecordsFetchView(APIView):\n \"\"\"\n Views for handling fetching source records that are sent as urls\n \"\"\"\n\n permission_classes = [permissions.IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n API endpoint that takes a set of cases with urls to docket or summary sheets, downloads them,\n and returns SourceRecords, which point to the documents' ids in the database.\n\n This is for accepting the UJS Search results, and creating SourceRecord objects describing each of those search results. \n \n This view does _not_ attempt download the source records, or parse them.\n\n \"\"\"\n try:\n posted_data = DownloadDocsSerializer(data=request.data)\n if posted_data.is_valid():\n records = posted_data.save(owner=request.user)\n download_service.source_records(records)\n return Response(\n DownloadDocsSerializer({\"source_records\": records}).data,\n )\n return Response({\"errors\": posted_data.errors})\n except Exception as err:\n return Response({\"errors\": [str(err)]})\n\n\ndef integrate_dockets(\n crecord: CRecord,\n docket_source_records: List[SourceRecord],\n nonfatal_errors: List[str],\n) -> Tuple[CRecord, List[str]]:\n \"\"\" Combine a set of source records representing 'dockets' with a criminal record\"\"\"\n for docket_source_record in docket_source_records:\n try:\n # get a RecordLib SourceRecord from the webapp sourcerecord model. The RecordLib SourceRecord has the machinery for\n # parsing the record to get a Person and Cases out of it.\n rlsource = RLSourceRecord(\n docket_source_record.raw_text or docket_source_record.file.path,\n parser=docket_source_record.get_parser(),\n )\n # If we reach this line, the parse succeeded.\n docket_source_record.parse_status = SourceRecord.ParseStatuses.SUCCESS\n # Integrate this docket with the full crecord.\n crecord.add_sourcerecord(\n rlsource,\n override_person=True,\n docket_number=docket_source_record.docket_num,\n )\n except Exception:\n docket_source_record.parse_status = SourceRecord.ParseStatuses.FAILURE\n nonfatal_errors.append(\n f\"Could not parse {docket_source_record.docket_num} ({docket_source_record.record_type})\"\n )\n finally:\n docket_source_record.save()\n return crecord, nonfatal_errors\n\n\ndef integrate_summaries(\n crecord: CRecord,\n summary_source_records: List[SourceRecord],\n docket_source_records: List[SourceRecord],\n nonfatal_errors: List[str],\n owner,\n) -> Tuple[CRecord, List[SourceRecord], List[str]]:\n \"\"\"\n Combine a set of source records representing summary sheets with a criminal record. In addition, \n find any cases that the summary sheets mention which are not already in the criminal record. \n \n For these extra cases, find a docket sheet for this case, and add it as a source record and integrate its information\n into the criminal record.\n \"\"\"\n dockets_in_summaries = []\n for summary_source_record in summary_source_records:\n try:\n rlsource = RLSourceRecord(\n summary_source_record.raw_text or summary_source_record.file.path,\n parser=summary_source_record.get_parser(),\n )\n summary_source_record.parse_status = SourceRecord.ParseStatuses.SUCCESS\n dockets_in_summaries.extend([c.docket_number for c in rlsource.cases])\n except Exception:\n summary_source_record.parse_status = SourceRecord.ParseStatuses.FAILURE\n finally:\n summary_source_record.save()\n\n # compare the dockets_in_summaries to dockets already collected as source records\n # to see what dockets are missing from the set of source records.\n missing_dockets = [\n dn for dn in dockets_in_summaries if dn not in docket_source_records\n ]\n new_source_dockets = download_service.dockets(missing_dockets, owner=owner)\n logger.info(\"Downloaded %d\", len(new_source_dockets))\n\n # now parse and integrate these new source dockets into the crecord.\n crecord, nonfatal_errors = integrate_dockets(\n crecord, new_source_dockets, nonfatal_errors\n )\n return crecord, new_source_dockets, nonfatal_errors\n\n\nclass IntegrateCRecordWithSources(APIView):\n \"\"\"\n View to handle combining the information about a case or cases from source records with a crecord. \n \"\"\"\n\n permission_classes = [permissions.IsAuthenticated]\n\n def put(self, request):\n \"\"\"\n Accept a CRecord and a set of SourceRecords.\n \n Parse the SourceRecords, and incorporate the information that the SourceRecords\n contain into the CRecord.\n\n Two api endpoints of the Django app interact with RecordLib. This one\n accepts a serialzed crecord and a list of sourcerecords. It attempts\n to parse each source_record, and then integrate the sourcerecords into the crecord.\n\n TODO IntegrateCRecordWithSources should communicate failures better.\n\n \"\"\"\n try:\n serializer = IntegrateSourcesSerializer(data=request.data)\n if serializer.is_valid():\n nonfatal_errors = []\n crecord = CRecord.from_dict(serializer.validated_data[\"crecord\"])\n source_records = []\n # Find the SourceRecords in the database that have been sent in this request,\n # or if these are new source records, download the files they point to.\n # TODO this probably doesn't handle a request with a new SoureRecord missing a URL.\n for source_record_data in serializer.validated_data[\"source_records\"]:\n try:\n source_records.append(\n SourceRecord.objects.get(id=source_record_data[\"id\"])\n )\n except Exception:\n # create this source record in the database, if it is new.\n source_rec = SourceRecord(\n **source_record_data, owner=request.user\n )\n source_rec.save()\n # also download it to the server.\n download_service.source_records([source_rec])\n source_records.append(source_rec)\n # Parse the uploaded source records, collecting RecordLib.SourceRecord objects.\n # These objects are parsing the records and figuring out case information in the SourceRecords.\n # For any source records that are summaries, find out if the summary describes cases that aren't also\n # docket source records. Search CPCMS for those, add the missing dockets to the list of source records.\n\n # First, parse the dockets.\n # Then we'll parse the summaries to find out if there are cases the summaries mention which the dockets do not.\n docket_source_records = [\n sr\n for sr in source_records\n if sr.record_type == SourceRecord.RecTypes.DOCKET_PDF\n ]\n crecord, nonfatal_errors = integrate_dockets(\n crecord, docket_source_records, nonfatal_errors\n )\n # Now attempt to parse summary records. Check the cases in each summary record to see if we have a docket for this case yet.\n # If we dont yet have a docket for this case, fetch it, parse it, integrate it into the CRecord.\n summary_source_records = [\n sr\n for sr in source_records\n if sr.record_type == SourceRecord.RecTypes.SUMMARY_PDF\n ]\n crecord, new_source_records, nonfatal_errors = integrate_summaries(\n crecord,\n summary_source_records,\n docket_source_records,\n nonfatal_errors,\n owner=request.user,\n )\n source_records += new_source_records\n self.request.session[\"source_records\"] = SourceRecordSerializer(\n source_records, many=True\n ).data\n return Response(\n {\n \"crecord\": CRecordSerializer(crecord).data,\n \"source_records\": SourceRecordSerializer(\n source_records, many=True\n ).data,\n \"errors\": nonfatal_errors,\n },\n status=status.HTTP_200_OK,\n )\n return Response(\n {\"errors\": serializer.errors}, status=status.HTTP_400_BAD_REQUEST\n )\n except Exception as err:\n return Response(\n {\"errors\": [str(err)]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR\n )\n\n\nclass AnalysisView(APIView):\n \"\"\"\n Views related to an analysis of a CRecord.\n \"\"\"\n\n permission_classes = [permissions.IsAuthenticated]\n # noinspection PyMethodMayBeStatic\n def post(self, request):\n \"\"\" Analyze a Criminal Record for expungeable and sealable cases and charges.\n \n POST body should be json-endoded CRecord object. \n\n Return, if not an error, will be a json-encoded Decision that explains the expungements\n and sealings that can be generated for this record.\n\n \"\"\"\n try:\n serializer = CRecordSerializer(data=request.data)\n if serializer.is_valid():\n rec = CRecord.from_dict(serializer.validated_data)\n analysis = (\n Analysis(rec)\n .rule(filter_landlordtenant_cases)\n .rule(filter_traffic_cases)\n .rule(expunge_deceased)\n .rule(expunge_over_70)\n .rule(expunge_nonconvictions)\n .rule(expunge_summary_convictions)\n .rule(seal_convictions)\n )\n self.request.session[\"analysis\"] = to_serializable(analysis)\n return Response(to_serializable(analysis))\n return Response(\n {\"validation_errors\": serializer.errors},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR,\n )\n except Exception as err:\n logger.error(err)\n return Response({\"errors\": str(err)}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UserProfileView(APIView):\n \"\"\"Information about a user's account.\n \"\"\"\n\n permission_classes = [permissions.IsAuthenticated]\n\n def get(self, request):\n \"\"\"\n Get the currently logged in user's profile information.\n \"\"\"\n user = User.objects.get(id=request.user.id)\n profile = UserProfile.objects.get(user=user)\n profile_data = UserProfileSerializer(profile).data\n profile_data[\"expungement_petition_template\"] = str(\n profile.expungement_petition_template.uuid\n )\n profile_data[\"sealing_petition_template\"] = str(\n profile.sealing_petition_template.uuid\n )\n return Response(\n {\n \"user\": UserSerializer(user).data,\n \"profile\": profile_data,\n \"expungement_petition_template_options\": {\n str(t.uuid): {\n \"id\": str(t.uuid),\n \"name\": t.name,\n \"petition_type\": \"expungement\",\n }\n for t in ExpungementPetitionTemplate.objects.all()\n },\n \"sealing_petition_template_options\": {\n str(t.uuid): {\n \"id\": str(t.uuid),\n \"name\": t.name,\n \"petition_type\": \"sealing\",\n }\n for t in SealingPetitionTemplate.objects.all()\n },\n }\n )\n\n def put(self, request):\n \"\"\"Update information about the logged in user's account.\"\"\"\n\n user = User.objects.get(id=request.user.id)\n user_serializer = UserSerializer(user, data=request.data)\n\n profile = UserProfile.objects.get(user=user)\n profile_serializer = UserProfileSerializer(profile, data=request.data)\n if user_serializer.is_valid() and profile_serializer.is_valid():\n user_serializer.save()\n\n # Replace the requests's UUID identifying a petition template\n # with the actual petition template that the .save() method needs.\n try:\n exp_petition_template = ExpungementPetitionTemplate.objects.get(\n uuid=profile_serializer.validated_data[\n \"expungement_petition_template\"\n ]\n )\n profile_serializer.validated_data[\n \"expungement_petition_template\"\n ] = exp_petition_template\n except:\n profile_serializer.validated_data.pop(\"exp_petition_template\")\n\n try:\n sealing_petition_template = SealingPetitionTemplate.objects.get(\n uuid=profile_serializer.validated_data[\"sealing_petition_template\"]\n )\n profile_serializer.validated_data[\n \"sealing_petition_template\"\n ] = sealing_petition_template\n except:\n profile_serializer.validated_data.pop(\"sealing_petition_template\")\n\n profile_serializer.save()\n # Should we return the user and profile here?\n return Response({\"message\": \"Successful update\"})\n\n return Response(\n {\n \"errors\": {\n \"user\": user_serializer.errors,\n \"profile\": profile_serializer.errors,\n }\n },\n status=status.HTTP_400_BAD_REQUEST,\n )\n\n\nclass AutoScreeningView(APIView):\n \"\"\"\n Trigger an automated screening of a person's record.\n \"\"\"\n\n # NOTE: No permission classes. This is open to the public.\n\n def post(self, request):\n \"\"\"\n Receive a name, dob, and email address, and send an automated review of a person's public record\n to the email address.\n \"\"\"\n screening_request = AutoScreeningSerializer(data=request.data)\n if screening_request.is_valid():\n async_task(cleanslate_screen.by_name, **screening_request.validated_data)\n return Response({\"status\": \"screening started.\"})\n else:\n return Response({\"status\": screening_request.errors})\n\n\nclass PetitionsView(APIView):\n \"\"\" Create petitions and an Overview document from an Analysis.\n \n POST should be a json-encoded object with an 'petitions' property that is a list of\n \"\"\"\n\n permission_classes = [permissions.IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n Accept an object describing petitions to generate, and generate them.\n \"\"\"\n errors = []\n try:\n serializer = PetitionViewSerializer(data=request.data)\n if serializer.is_valid():\n crecord = CRecord.from_dict(serializer.validated_data[\"crecord\"])\n source_records = [\n SourceRecord(**s)\n for s in serializer.validated_data[\"source_records\"]\n ]\n petitions = []\n for petition_data in serializer.validated_data[\"petitions\"]:\n if petition_data[\"petition_type\"] == \"Sealing\":\n new_petition = Sealing.from_dict(petition_data)\n # this could be done earlier, if needed, to avoid querying db over and over.\n # but we'd need to test what types of templates are actually needed.\n try:\n new_petition.set_template(\n request.user.userprofile.sealing_petition_template.file\n )\n petitions.append(new_petition)\n\n except Exception as err:\n logger.error(\n \"User has not set a sealing petition template, or \"\n )\n errors.append(\n \"User has not set a sealing petition template.\"\n )\n logger.error(str(err))\n continue\n else:\n new_petition = Expungement.from_dict(petition_data)\n try:\n new_petition.set_template(\n request.user.userprofile.expungement_petition_template.file\n )\n petitions.append(new_petition)\n except Exception as err:\n logger.error(\n \"User has not set an expungement petition template, or \"\n )\n errors.append(\n \"User has not set an expungememnt petition template\"\n )\n logger.error(str(err))\n continue\n client_last = petitions[0].client.last_name\n petitions = [(p.file_name(), p.render()) for p in petitions]\n if self.request.session.get(\"analysis\"):\n overview_template = OverviewTemplate.objects.get(default=True)\n petitions.append(\n (\n \"Overview.docx\",\n write_overview(\n serializer.validated_data[\"petitions\"],\n crecord,\n source_records,\n overview_template,\n ),\n )\n )\n package = Compressor(f\"PetitionsFor{client_last}.zip\", petitions)\n\n logger.info(\"Returning x-accel-redirect to zip file.\")\n\n resp = HttpResponse()\n resp[\"Content-Type\"] = \"application/zip\"\n resp[\"Content-Disposition\"] = f\"attachment; filename={package.name}\"\n logger.info(\n \"Redirecting to: '/%s'\",\n os.path.join(settings.MEDIA_URL, package.name),\n )\n\n # Add the x-accel-redirect header, with a path to /media/\n # This /media/ path will be internally intercepted by the\n # nginx frontend's 'internal' block, and serve a file from\n # the location configured in the nginx.conf\n\n resp[\"X-Accel-Redirect\"] = \"/\" + os.path.join(\n settings.MEDIA_URL, package.name\n )\n return resp\n else:\n return Response(\n {\"validation_errors\": serializer.errors},\n status=status.HTTP_400_BAD_REQUEST,\n content_type=\"application/json\",\n )\n except Exception as e:\n logger.error(str(e))\n return Response(\n {\"errors\": errors},\n status=status.HTTP_400_BAD_REQUEST,\n content_type=\"application/json\",\n )\n\n\nclass TemplateView(APIView):\n \"\"\"\n Download a stored document template. \n \"\"\"\n\n permission_classes = [permissions.IsAuthenticated]\n\n def get(self, request, template_type, unique_id):\n if template_type == \"sealing\":\n petition = SealingPetitionTemplate.objects.get(uuid=unique_id)\n elif template_type == \"expungement\":\n petition = ExpungementPetitionTemplate.objects.get(uuid=unique_id)\n resp = HttpResponse()\n resp[\n \"Content-Type\"\n ] = \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n resp[\"Content-Disposition\"] = f\"attachment; filename={petition.name}\"\n # send the redirect-proxy url, which will be like [media_root]/path/to/[file_uid]\n logger.info(\n \"Redirecting to: '/%s'\",\n os.path.join(settings.MEDIA_URL, petition.file.name),\n )\n resp[\"X-Accel-Redirect\"] = \"/\" + os.path.join(\n settings.MEDIA_URL, petition.file.name\n )\n return resp\n","sub_path":"cleanslate/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"493774352","text":"# function used by various programs to plot decision regions\r\n# author: from Raschka; Allee updated by sdm\r\n\r\nimport numpy as np # needed for math stuff\r\nfrom matplotlib.colors import ListedColormap # for choosing colors\r\nimport matplotlib.pyplot as plt # to create the plot\r\n\r\n################################################################################\r\n# Function to plot decision regions. #\r\n# Inputs: #\r\n# X - feature values of each sample, e.g. coordinates on cartesian plane #\r\n# y - the classification of each sample - a one-dimensional array #\r\n# classifier - the machine learning classifier to use, e.g. perceptron #\r\n# test_idx - typically the range of samples that were the test set #\r\n# the default value is none; if present, highlight them #\r\n# resolution - the resolution of the meshgrid #\r\n# Output: #\r\n# None #\r\n# #\r\n# NOTE: this will support up to 5 classes described by 2 features. #\r\n################################################################################\r\n\r\ndef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):\r\n # we will support up to 5 classes...\r\n markers = ('v', 'x', 'o', '^', 's') # markers to use\r\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') # colors to use\r\n cmap = ListedColormap(colors[:len(np.unique(y))]) # the color map\r\n \r\n # plot the decision surface\r\n # x1* will be the range +/- 1 of the first feature\r\n # x2* will be the range +/- 1 of the first feature\r\n x1_min, x1_max = X[:,0].min() - 1, X[:,0].max() + 1 # all rows, col 0\r\n x2_min, x2_max = X[:,1].min() - 1, X[:,1].max() + 1 # all rows, col 1\r\n\r\n # now create the meshgrid (see m2_p1.py for examples)\r\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\r\n np.arange(x2_min, x2_max, resolution))\r\n\r\n # ravel flattens the array. The default, used here, is to flatten by taking\r\n # all of the first row, concanentating the second row, etc., for all rows\r\n # So we will predict the classification for every point in the grid\r\n Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)\r\n\r\n # reshape will take the resulting predictions and put them into a matrix\r\n # with the same shape as the mesh\r\n Z = Z.reshape(xx1.shape)\r\n\r\n # using Z, create a contour plot so we can see the regions for each class\r\n plt.contourf(xx1,xx2,Z,alpha=0.4,cmap=cmap)\r\n plt.xlim(xx1.min(), xx1.max()) # set x-axis ranges\r\n plt.ylim(xx2.min(), xx2.max()) # set y-axis ranges\r\n\r\n # plot all samples\r\n # NOTE: X[y==c1,0] returns all the column 0 values of X where the\r\n # corresponding row of y equals c1. That is, only those rows of\r\n # X are included that have been assigned to class c1.\r\n # So, for each of the unique classifications, plot them!\r\n # (In this case, idx and c1 are always the same, however this code\r\n # will allow for non-integer classifications.)\r\n\r\n for idx, c1 in enumerate(np.unique(y)):\r\n plt.scatter(x=X[y==c1,0], y=X[y==c1,1], alpha=0.8, c=colors[idx],\r\n marker=markers[idx], label=c1)\r\n \r\n #highlight test samples with black circles\r\n if test_idx:\r\n X_test, y_test = X[test_idx, :], y[test_idx] # test set is at the end\r\n plt.scatter(X_test[:,0],X_test[:,1],c='none',edgecolor='black',alpha=1.0,\r\n linewidth=1, marker='o',s=55,label='test set')\r\n","sub_path":"m5_plotdr.py","file_name":"m5_plotdr.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"637105729","text":"\"\"\" Utility functions. \"\"\"\nfrom math import isnan\nfrom collections import OrderedDict\nfrom threading import RLock\nfrom functools import wraps\nfrom hashlib import blake2b\n\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nimport segyio\n\nfrom numba import njit, prange\nfrom ..batchflow import Sampler\n\n\n\ndef file_print(msg, path):\n \"\"\" Print to file. \"\"\"\n with open(path, 'w') as file:\n print(msg, file=file)\n\n\n\nclass SafeIO:\n \"\"\" Opens the file handler with desired `open` function, closes it at destruction.\n Can log open and close actions to the `log_file`.\n getattr, getitem and `in` operator are directed to the `handler`.\n \"\"\"\n def __init__(self, path, opener=open, log_file=None, **kwargs):\n self.path = path\n self.log_file = log_file\n self.handler = opener(path, **kwargs)\n\n if self.log_file:\n self._info(self.log_file, f'Opened {self.path}')\n\n def _info(self, log_file, msg):\n with open(log_file, 'a') as f:\n f.write('\\n' + msg)\n\n def __getattr__(self, key):\n return getattr(self.handler, key)\n\n def __getitem__(self, key):\n return self.handler[key]\n\n def __contains__(self, key):\n return key in self.handler\n\n def __del__(self):\n self.handler.close()\n\n if self.log_file:\n self._info(self.log_file, f'Closed {self.path}')\n\n\nclass IndexedDict(OrderedDict):\n \"\"\" Allows to use both indices and keys to subscript. \"\"\"\n def __getitem__(self, key):\n if isinstance(key, int):\n key = list(self.keys())[key]\n return super().__getitem__(key)\n\n\n\ndef stable_hash(key):\n \"\"\" Hash that stays the same between different runs of Python interpreter. \"\"\"\n if not isinstance(key, (str, bytes)):\n key = ''.join(sorted(str(key)))\n if not isinstance(key, bytes):\n key = key.encode('ascii')\n return str(blake2b(key).hexdigest())\n\nclass Singleton:\n \"\"\" There must be only one!\"\"\"\n instance = None\n def __init__(self):\n if not Singleton.instance:\n Singleton.instance = self\n\nclass lru_cache:\n \"\"\" Thread-safe least recent used cache. Must be applied to class methods.\n\n Parameters\n ----------\n maxsize : int\n Maximum amount of stored values.\n storage : None, OrderedDict or PickleDict\n Storage to use.\n If None, then no caching is applied.\n classwide : bool\n If True, then first argument of a method (self) is changed to class name for the purposes on hashing.\n anchor : bool\n If True, then code of the whole directory this file is located is used to create a persistent hash\n for the purposes of storing.\n attributes: None, str or sequence of str\n Attributes to get from object and use as additions to key.\n pickle_module: str\n Module to use to save/load files on disk. Used only if `storage` is :class:`.PickleDict`.\n\n Examples\n --------\n Store loaded slides::\n\n @lru_cache(maxsize=128)\n def load_slide(cube_name, slide_no):\n pass\n\n Notes\n -----\n All arguments to the decorated method must be hashable.\n \"\"\"\n #pylint: disable=invalid-name, attribute-defined-outside-init\n def __init__(self, maxsize=None, classwide=False, attributes=None):\n self.maxsize = maxsize\n self.classwide = classwide\n\n # Make `attributes` always a list\n if isinstance(attributes, str):\n self.attributes = [attributes]\n elif isinstance(attributes, (tuple, list)):\n self.attributes = attributes\n else:\n self.attributes = False\n\n self.default = Singleton()\n self.lock = RLock()\n self.reset()\n\n\n def reset(self):\n \"\"\" Clear cache and stats. \"\"\"\n self.cache = OrderedDict()\n self.is_full = False\n self.stats = {'hit': 0, 'miss': 0}\n\n def make_key(self, args, kwargs):\n \"\"\" Create a key from a combination of instance reference or class reference,\n method args, and instance attributes.\n \"\"\"\n key = list(args)\n # key[0] is `instance` if applied to a method\n if kwargs:\n for k, v in sorted(kwargs.items()):\n key.append((k, v))\n\n if self.attributes:\n for attr in self.attributes:\n attr_hash = stable_hash(getattr(key[0], attr))\n key.append(attr_hash)\n\n if self.classwide:\n key[0] = key[0].__class__\n return tuple(key)\n\n\n def __call__(self, func):\n \"\"\" Add the cache to the function. \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n key = self.make_key(args, kwargs)\n\n # If result is already in cache, just retrieve it and update its timings\n with self.lock:\n result = self.cache.get(key, self.default)\n if result is not self.default:\n del self.cache[key]\n self.cache[key] = result\n self.stats['hit'] += 1\n return result\n\n # The result was not found in cache: evaluate function\n result = func(*args, **kwargs)\n\n # Add the result to cache\n with self.lock:\n self.stats['miss'] += 1\n if key in self.cache:\n pass\n elif self.is_full:\n self.cache.popitem(last=False)\n self.cache[key] = result\n else:\n self.cache[key] = result\n self.is_full = (len(self.cache) >= self.maxsize)\n return result\n\n wrapper.__name__ = func.__name__\n wrapper.cache = lambda: self.cache\n wrapper.stats = lambda: self.stats\n wrapper.reset = self.reset\n return wrapper\n\n\n\n#TODO: rethink\ndef make_subcube(path, geometry, path_save, i_range, x_range):\n \"\"\" Make subcube from .sgy cube by removing some of its first and\n last ilines and xlines.\n\n Parameters\n ----------\n path : str\n Location of original .sgy cube.\n geometry : SeismicGeometry\n Infered information about original cube.\n path_save : str\n Place to save subcube.\n i_range : array-like\n Ilines to include in subcube.\n x_range : array-like\n Xlines to include in subcube.\n\n Notes\n -----\n Common use of this function is to remove not fully filled slices of .sgy cubes.\n \"\"\"\n i_low, i_high = i_range[0], i_range[-1]\n x_low, x_high = x_range[0], x_range[-1]\n\n with segyio.open(path, 'r', strict=False) as src:\n src.mmap()\n spec = segyio.spec()\n spec.sorting = int(src.sorting)\n spec.format = int(src.format)\n spec.samples = range(geometry.depth)\n spec.ilines = geometry.ilines[i_low:i_high]\n spec.xlines = geometry.xlines[x_low:x_high]\n\n with segyio.create(path_save, spec) as dst:\n # Copy all textual headers, including possible extended\n for i in range(1 + src.ext_headers):\n dst.text[i] = src.text[i]\n\n c = 0\n for il_ in tqdm(spec.ilines):\n for xl_ in spec.xlines:\n tr_ = geometry.il_xl_trace[(il_, xl_)]\n dst.header[c] = src.header[tr_]\n dst.header[c][segyio.TraceField.FieldRecord] = il_\n dst.header[c][segyio.TraceField.TRACE_SEQUENCE_FILE] = il_\n\n dst.header[c][segyio.TraceField.TraceNumber] = xl_ - geometry.xlines_offset\n dst.header[c][segyio.TraceField.TRACE_SEQUENCE_LINE] = xl_ - geometry.xlines_offset\n dst.trace[c] = src.trace[tr_]\n c += 1\n dst.bin = src.bin\n dst.bin = {segyio.BinField.Traces: c}\n\n # Check that repaired cube can be opened in 'strict' mode\n with segyio.open(path_save, 'r', strict=True) as _:\n pass\n\n#TODO: rename, add some defaults\ndef convert_point_cloud(path, path_save, names=None, order=None, transform=None):\n \"\"\" Change set of columns in file with point cloud labels.\n Usually is used to remove redundant columns.\n\n Parameters\n ----------\n path : str\n Path to file to convert.\n path_save : str\n Path for the new file to be saved to.\n names : str or sequence of str\n Names of columns in the original file. Default is Petrel's export format, which is\n ('_', '_', 'iline', '_', '_', 'xline', 'cdp_x', 'cdp_y', 'height'), where `_` symbol stands for\n redundant keywords like `INLINE`.\n order : str or sequence of str\n Names and order of columns to keep. Default is ('iline', 'xline', 'height').\n \"\"\"\n #pylint: disable=anomalous-backslash-in-string\n names = names or ['_', '_', 'iline', '_', '_', 'xline',\n 'cdp_x', 'cdp_y', 'height']\n order = order or ['iline', 'xline', 'height']\n\n names = [names] if isinstance(names, str) else names\n order = [order] if isinstance(order, str) else order\n\n df = pd.read_csv(path, sep='\\s+', names=names, usecols=set(order))\n df.dropna(inplace=True)\n\n if 'iline' in order and 'xline' in order:\n df.sort_values(['iline', 'xline'], inplace=True)\n\n data = df.loc[:, order]\n if transform:\n data = data.apply(transform)\n data.to_csv(path_save, sep=' ', index=False, header=False)\n\n\ndef gen_crop_coordinates(point, horizon_matrix, zero_traces,\n stride, shape, fill_value, zeros_threshold=0,\n empty_threshold=5, safe_stripe=0, num_points=2):\n \"\"\" Generate crop coordinates next to the point with maximum horizon covered area.\n\n Parameters\n ----------\n point : array-like\n Coordinates of the point.\n horizon_matrix : ndarray\n `Full_matrix` attribute of the horizon.\n zero_traces : ndarray\n A boolean ndarray indicating zero traces in the cube.\n stride : int\n Distance between the point and a corner of a crop.\n shape : array-like\n The desired shape of the crops.\n Note that final shapes are made in both xline and iline directions. So if\n crop_shape is (1, 64, 64), crops of both (1, 64, 64) and (64, 1, 64) shape\n will be defined. fill_value : int\n zeros_threshold : int\n A maximum number of bad traces in a crop.\n empty_threshold : int\n A minimum number of points with unknown horizon per crop.\n safe_stripe : int\n Distance between a crop and the ends of the cube.\n num_points : int\n Returned number of crops. The maximum is four.\n \"\"\"\n candidates, shapes = [], []\n orders, intersections = [], []\n hor_height = horizon_matrix[point[0], point[1]]\n ilines_len, xlines_len = horizon_matrix.shape\n\n tested_iline_positions = [max(0, point[0] - stride),\n min(point[0] - shape[1] + stride, ilines_len - shape[1])]\n\n for il in tested_iline_positions:\n if (il > safe_stripe) and (il + shape[1] < ilines_len - safe_stripe):\n num_missing_traces = np.sum(zero_traces[il: il + shape[1],\n point[1]: point[1] + shape[0]])\n if num_missing_traces <= zeros_threshold:\n horizon_patch = horizon_matrix[il: il + shape[1],\n point[1]:point[1] + shape[0]]\n num_empty = np.sum(horizon_patch == fill_value)\n if num_empty > empty_threshold:\n candidates.append([il, point[1],\n hor_height - shape[2] // 2])\n shapes.append([shape[1], shape[0], shape[2]])\n orders.append([0, 2, 1])\n intersections.append(shape[1] - num_empty)\n\n tested_xline_positions = [max(0, point[1] - stride),\n min(point[1] - shape[1] + stride, xlines_len - shape[1])]\n\n for xl in tested_xline_positions:\n if (xl > safe_stripe) and (xl + shape[1] < xlines_len - safe_stripe):\n num_missing_traces = np.sum(zero_traces[point[0]: point[0] + shape[0],\n xl: xl + shape[1]])\n if num_missing_traces <= zeros_threshold:\n horizon_patch = horizon_matrix[point[0]:point[0] + shape[0],\n xl: xl + shape[1]]\n num_empty = np.sum(horizon_patch == fill_value)\n if num_empty > empty_threshold:\n candidates.append([point[0], xl,\n hor_height - shape[2] // 2])\n shapes.append(shape)\n orders.append([2, 0, 1])\n intersections.append(shape[1] - num_empty)\n\n if len(candidates) == 0:\n return None\n\n candidates_array = np.array(candidates)\n shapes_array = np.array(shapes)\n orders_array = np.array(orders)\n\n top = np.argsort(np.array(intersections))[:num_points]\n return (candidates_array[top], \\\n shapes_array[top], \\\n orders_array[top])\n\n\n@njit\ndef groupby_mean(array):\n \"\"\" Faster version of mean-groupby of data along the first two columns.\n Input array is supposed to have (N, 3) shape.\n \"\"\"\n n = len(array)\n\n output = np.zeros_like(array)\n position = 0\n\n prev = array[0, :2]\n s, c = array[0, -1], 1\n\n for i in range(1, n):\n curr = array[i, :2]\n\n if prev[0] == curr[0] and prev[1] == curr[1]:\n s += array[i, -1]\n c += 1\n else:\n output[position, :2] = prev\n output[position, -1] = s / c\n position += 1\n\n prev = curr\n s, c = array[i, -1], 1\n\n output[position, :2] = prev\n output[position, -1] = s / c\n position += 1\n return output[:position]\n\n\n@njit\ndef groupby_min(array):\n \"\"\" Faster version of min-groupby of data along the first two columns.\n Input array is supposed to have (N, 3) shape.\n \"\"\"\n n = len(array)\n\n output = np.zeros_like(array)\n position = 0\n\n prev = array[0, :2]\n s = array[0, -1]\n\n for i in range(1, n):\n curr = array[i, :2]\n\n if prev[0] == curr[0] and prev[1] == curr[1]:\n s = min(s, array[i, -1])\n else:\n output[position, :2] = prev\n output[position, -1] = s\n position += 1\n\n prev = curr\n s = array[i, -1]\n\n output[position, :2] = prev\n output[position, -1] = s\n position += 1\n return output[:position]\n\n\n@njit\ndef groupby_max(array):\n \"\"\" Faster version of min-groupby of data along the first two columns.\n Input array is supposed to have (N, 3) shape.\n \"\"\"\n n = len(array)\n\n output = np.zeros_like(array)\n position = 0\n\n prev = array[0, :2]\n s = array[0, -1]\n\n for i in range(1, n):\n curr = array[i, :2]\n\n if prev[0] == curr[0] and prev[1] == curr[1]:\n s = max(s, array[i, -1])\n else:\n output[position, :2] = prev\n output[position, -1] = s\n position += 1\n\n prev = curr\n s = array[i, -1]\n\n output[position, :2] = prev\n output[position, -1] = s\n position += 1\n return output[:position]\n\n\n\n\n@njit\ndef round_to_array(values, ticks):\n \"\"\" Jit-accelerated function to round values from one array to the\n nearest value from the other in a vectorized fashion. Faster than numpy version.\n\n Parameters\n ----------\n values : array-like\n Array to modify.\n ticks : array-like\n Values to cast to. Must be sorted in the ascending order.\n\n Returns\n -------\n array-like\n Array with values from `values` rounded to the nearest from corresponding entry of `ticks`.\n \"\"\"\n for i, p in enumerate(values):\n if p <= ticks[0]:\n values[i] = ticks[0]\n elif p >= ticks[-1]:\n values[i] = ticks[-1]\n else:\n ix = np.searchsorted(ticks, p)\n\n if abs(ticks[ix] - p) <= abs(ticks[ix-1] - p):\n values[i] = ticks[ix]\n else:\n values[i] = ticks[ix-1]\n return values\n\n\n@njit\ndef find_min_max(array):\n \"\"\" Get both min and max values in just one pass through array.\"\"\"\n n = array.size\n max_val = min_val = array[0]\n for i in range(1, n):\n min_val = min(array[i], min_val)\n max_val = max(array[i], max_val)\n return min_val, max_val\n\n\n\ndef compute_running_mean(x, kernel_size):\n \"\"\" Fast analogue of scipy.signal.convolve2d with gaussian filter. \"\"\"\n k = kernel_size // 2\n padded_x = np.pad(x, (k, k), mode='symmetric')\n cumsum = np.cumsum(padded_x, axis=1)\n cumsum = np.cumsum(cumsum, axis=0)\n return _compute_running_mean_jit(x, kernel_size, cumsum)\n\n@njit\ndef _compute_running_mean_jit(x, kernel_size, cumsum):\n \"\"\" Jit accelerated running mean. \"\"\"\n #pylint: disable=invalid-name\n k = kernel_size // 2\n result = np.zeros_like(x).astype(np.float32)\n\n canvas = np.zeros((cumsum.shape[0] + 2, cumsum.shape[1] + 2))\n canvas[1:-1, 1:-1] = cumsum\n cumsum = canvas\n\n for i in range(k, x.shape[0] + k):\n for j in range(k, x.shape[1] + k):\n d = cumsum[i + k + 1, j + k + 1]\n a = cumsum[i - k, j - k]\n b = cumsum[i - k, j + 1 + k]\n c = cumsum[i + 1 + k, j - k]\n result[i - k, j - k] = float(d - b - c + a) / float(kernel_size ** 2)\n return result\n\n\ndef mode(array):\n \"\"\" Compute mode of the array along the last axis. \"\"\"\n nan_mask = np.max(array, axis=-1)\n return nb_mode(array, nan_mask)\n\n@njit\ndef nb_mode(array, mask):\n \"\"\" Compute mode of the array along the last axis. \"\"\"\n #pylint: disable=not-an-iterable\n i_range, x_range = array.shape[:2]\n temp = np.full((i_range, x_range), np.nan)\n\n for il in prange(i_range):\n for xl in prange(x_range):\n if not isnan(mask[il, xl]):\n\n current = array[il, xl, :]\n counter = {}\n frequency = 0\n for i in current:\n if i in counter:\n counter[i] += 1\n else:\n counter[i] = 0\n\n if counter[i] > frequency:\n element = i\n frequency = counter[i]\n\n temp[il, xl] = element\n return temp\n\n\n@njit\ndef filter_simplices(simplices, points, matrix, threshold=5.):\n \"\"\" Remove simplices outside of matrix. \"\"\"\n #pylint: disable=consider-using-enumerate\n mask = np.ones(len(simplices), dtype=np.int32)\n\n for i in range(len(simplices)):\n tri = points[simplices[i]].astype(np.int32)\n\n middle_i, middle_x = np.mean(tri[:, 0]), np.mean(tri[:, 1])\n heights = np.array([matrix[tri[0, 0], tri[0, 1]],\n matrix[tri[1, 0], tri[1, 1]],\n matrix[tri[2, 0], tri[2, 1]]])\n\n if matrix[int(middle_i), int(middle_x)] < 0 or np.std(heights) > threshold:\n mask[i] = 0\n\n return simplices[mask == 1]\n\n\nclass HorizonSampler(Sampler):\n \"\"\" Compact version of histogram-based sampler for 3D points structure. \"\"\"\n def __init__(self, histogram, seed=None, **kwargs):\n super().__init__(histogram, seed, **kwargs)\n # Bins and their probabilities: keep only non-zero ones\n bins = histogram[0]\n probs = (bins / np.sum(bins)).reshape(-1)\n self.nonzero_probs_idx = np.asarray(probs != 0.0).nonzero()[0]\n self.nonzero_probs = probs[self.nonzero_probs_idx]\n\n # Edges of bins: keep lengths and diffs between successive edges\n self.edges = histogram[1]\n self.lens_edges = np.array([len(edge) - 1 for edge in self.edges])\n self.divisors = [np.array(self.lens_edges[i+1:]).astype(np.int64)\n for i, _ in enumerate(self.edges)]\n self.shifts_edges = [np.diff(edge)[0] for edge in self.edges]\n\n # Uniform sampler\n self.state = np.random.RandomState(seed=seed)\n self.state_sampler = self.state.uniform\n\n def sample(self, size):\n \"\"\" Generate random sample from histogram distribution. \"\"\"\n # Choose bin indices\n indices = np.random.choice(self.nonzero_probs_idx, p=self.nonzero_probs, size=size)\n\n # Convert bin indices to its starting coordinates\n low = generate_points(self.edges, divisors=self.divisors, lengths=self.lens_edges, indices=indices)\n high = low + self.shifts_edges\n return self.state_sampler(low=low, high=high)\n\n@njit\ndef generate_points(edges, divisors, lengths, indices):\n \"\"\" Accelerate sampling method of `HorizonSampler`. \"\"\"\n low = np.zeros((len(indices), len(lengths)))\n\n for i, idx in enumerate(indices):\n for j, (edge, divisors_, length) in enumerate(zip(edges, divisors, lengths)):\n idx_copy = idx\n for divisor in divisors_:\n idx_copy //= divisor\n low[i, j] = edge[idx_copy % length]\n return low\n","sub_path":"seismiqb/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":21107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"382945641","text":"import logging\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.db import transaction\nfrom django.views.generic import CreateView, DeleteView, ListView, UpdateView\n\nfrom questoes.forms import QuestaoObjetivaFormSet, QuestaoDiscursivaFormSet\nfrom questoes.models import QuestaoObjetiva, QuestaoDiscursiva, Questao\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ListQuestoes(ListView):\n \"\"\"\n Retorna a lista de Questoões completa ou filtrada por seus texto.\n \"\"\"\n model = Questao\n\n def get_queryset(self):\n logger.info(\"Listando Questoes\")\n q = self.request.GET.get('q', '')\n if q:\n logger.info(\"Filtrando Questoes por {}\".format(q))\n return Questao.objects.filter(texto_questao__contains=q).select_subclasses()\n\n return Questao.objects.all().select_subclasses()\n\n\n\"\"\"\nAbaixo as views para manipular as ações \ndas Questoes Objetivas e suas Respostas\n\"\"\"\n\n\nclass CreateQuestaoObjetiva(CreateView):\n \"\"\"\n Cria Questão objetiva\n \"\"\"\n model = QuestaoObjetiva\n fields = ['texto_questao']\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Criando Questão Objetiva\")\n return super(CreateQuestaoObjetiva, self).dispatch(*args, **kwargs)\n\n\nclass UpdateQuestaoObjetiva(UpdateView):\n \"\"\"\n Atualiza Questão Objetiva\n \"\"\"\n model = QuestaoObjetiva\n success_url = '/'\n fields = ['texto_questao']\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Atualizando Questão Objetiva\")\n return super(UpdateQuestaoObjetiva, self).dispatch(*args, **kwargs)\n\n\nclass DeleteQuestaoObjetiva(DeleteView):\n \"\"\"\n Remove Questão Objetiva\n \"\"\"\n model = QuestaoObjetiva\n success_url = reverse_lazy('questoes-list')\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Removendo Questão Objetiva\")\n return super(DeleteQuestaoObjetiva, self).dispatch(*args, **kwargs)\n\n\nclass CreateResposta(CreateView):\n \"\"\"\n Cria uma coleção de Respostas para a Questão Objetiva\n \"\"\"\n model = QuestaoObjetiva\n fields = ['texto_questao']\n success_url = reverse_lazy('questoes-list')\n\n def get_context_data(self, **kwargs):\n data = super(CreateResposta, self).get_context_data(**kwargs)\n\n if self.request.POST:\n data['respostas'] = QuestaoObjetivaFormSet(self.request.POST)\n else:\n data['respostas'] = QuestaoObjetivaFormSet()\n\n return data\n\n def form_valid(self, form):\n logger.info(\"Validando Criação Resposta\")\n context = self.get_context_data()\n respostas = context['respostas']\n\n with transaction.atomic():\n self.object = form.save()\n\n if respostas.is_valid():\n respostas.instance = self.object\n respostas.save()\n\n return super(CreateResposta, self).form_valid(form)\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Crinado Resposta\")\n return super(CreateResposta, self).dispatch(*args, **kwargs)\n\n\nclass UpdateResposta(UpdateView):\n \"\"\"\n Atualiza uma coleção de Respostas para a Questão Objetiva\n \"\"\"\n model = QuestaoObjetiva\n fields = ['texto_questao']\n success_url = reverse_lazy('questoes-list')\n\n def get_context_data(self, **kwargs):\n data = super(UpdateResposta, self).get_context_data(**kwargs)\n if self.request.POST:\n data['respostas'] = QuestaoObjetivaFormSet(self.request.POST, instance=self.object)\n else:\n data['respostas'] = QuestaoObjetivaFormSet(instance=self.object)\n\n return data\n\n def form_valid(self, form):\n context = self.get_context_data()\n respostas = context['respostas']\n\n with transaction.atomic():\n self.object = form.save()\n\n if respostas.is_valid():\n respostas.instance = self.object\n respostas.save()\n\n return super(UpdateResposta, self).form_valid(form)\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Atualizando Resposta\")\n return super(UpdateResposta, self).dispatch(*args, **kwargs)\n\n\n\"\"\"\nAbaixo as views para manipular as ações \ndas Questoes Discursivas e a sua Resposta\n\"\"\"\n\n\nclass CreateQuestaoDiscursiva(CreateView):\n \"\"\"\n Cria Questão Discursiva\n \"\"\"\n model = QuestaoDiscursiva\n fields = ['texto_questao']\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Criando Questão Discursiva\")\n return super(CreateQuestaoDiscursiva, self).dispatch(*args, **kwargs)\n\n\nclass UpdateQuestaoDiscursiva(UpdateView):\n \"\"\"\n Atualiza Questão Discursiva\n \"\"\"\n model = QuestaoDiscursiva\n success_url = '/'\n fields = ['texto_questao']\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Atualizando Questão Discursiva\")\n return super(UpdateQuestaoDiscursiva, self).dispatch(*args, **kwargs)\n\n\nclass DeleteQuestaoDiscursiva(DeleteView):\n \"\"\"\n Remove Questão Discursiva\n \"\"\"\n model = QuestaoDiscursiva\n success_url = reverse_lazy('questoes-list')\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Deletando Questão Discursiva\")\n return super(DeleteQuestaoDiscursiva, self).dispatch(*args, **kwargs)\n\n\nclass CreateRespostaDiscursiva(CreateView):\n \"\"\"\n Cria uma Resposta Discursiva para uma Questão Discursiva\n \"\"\"\n model = QuestaoDiscursiva\n fields = ['texto_questao']\n success_url = reverse_lazy('questoes-list')\n\n def get_context_data(self, **kwargs):\n data = super(CreateRespostaDiscursiva, self).get_context_data(**kwargs)\n\n if self.request.POST:\n data['respostas'] = QuestaoDiscursivaFormSet(self.request.POST)\n else:\n data['respostas'] = QuestaoDiscursivaFormSet()\n\n return data\n\n def form_valid(self, form):\n logger.info(\"Validando Resposta Discursiva\")\n context = self.get_context_data()\n respostas = context['respostas']\n\n with transaction.atomic():\n self.object = form.save()\n\n if respostas.is_valid():\n respostas.instance = self.object\n respostas.save()\n\n return super(CreateRespostaDiscursiva, self).form_valid(form)\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n logger.info(\"Criando Resposta Discursiva\")\n return super(CreateRespostaDiscursiva, self).dispatch(*args, **kwargs)\n\n\nclass UpdateRespostaDiscursiva(UpdateView):\n \"\"\"\n Atualiza uma Resposta Discursiva para uma Questão Discursiva\n \"\"\"\n model = QuestaoDiscursiva\n fields = ['texto_questao']\n success_url = reverse_lazy('questoes-list')\n\n def get_context_data(self, **kwargs):\n data = super(UpdateRespostaDiscursiva, self).get_context_data(**kwargs)\n if self.request.POST:\n data['respostas'] = QuestaoDiscursivaFormSet(self.request.POST, instance=self.object)\n else:\n data['respostas'] = QuestaoDiscursivaFormSet(instance=self.object)\n\n return data\n\n def form_valid(self, form):\n logger.info(\"Validando Autalização Resposta Discursiva\")\n context = self.get_context_data()\n respostas = context['respostas']\n\n with transaction.atomic():\n self.object = form.save()\n\n if respostas.is_valid():\n respostas.instance = self.object\n respostas.save()\n\n return super(UpdateRespostaDiscursiva, self).form_valid(form)\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(UpdateRespostaDiscursiva, self).dispatch(*args, **kwargs)\n","sub_path":"questoes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"129441687","text":"class Kartave(object):\n def __call__(self, user, channel, *args):\n parameters = \" \".join(args)\n response = \"User {user} asked me to {parameters} in the {channel} channel\".format(\n user=user,\n parameters=parameters,\n channel=channel)\n return response\n\n\nkartave = Kartave()\n","sub_path":"slackbot/prathamam/src/commands/kartave/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"10754128","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Azure Compute Resources.\"\"\"\n\nfrom time import sleep\nfrom typing import Optional, List, Dict, TYPE_CHECKING\n\n# Pylint complains about the import but the library imports just fine,\n# so we can ignore the warning.\n# pylint: disable=import-error\nfrom azure.mgmt.compute.v2020_05_01 import models\nfrom msrestazure import azure_exceptions\n# pylint: enable=import-error\n\nfrom libcloudforensics import logging_utils\nfrom libcloudforensics.providers.azure.internal import common\n\nif TYPE_CHECKING:\n # TYPE_CHECKING is always False at runtime, therefore it is safe to ignore\n # the following cyclic import, as it it only used for type hints\n from libcloudforensics.providers.azure.internal import account # pylint: disable=cyclic-import\n\nlogging_utils.SetUpLogger(__name__)\nlogger = logging_utils.GetLogger(__name__)\n\n\nclass AZComputeResource:\n \"\"\"Class that represent an Azure compute resource\n\n Attributes:\n az_account (AZAccount): An Azure account object.\n resource_group_name (str): The Azure resource group name for the resource.\n resource_id (str): The Azure resource ID.\n name (str): The resource's name.\n region (str): The region in which the resource is located.\n zones (List[str]): Optional. Availability zones within the region where\n the resource is located.\n \"\"\"\n\n def __init__(self,\n az_account: 'account.AZAccount',\n resource_id: str,\n name: str,\n region: str,\n zones: Optional[List[str]] = None) -> None:\n \"\"\"Initialize the AZComputeResource class.\n\n Args:\n az_account (AZAccount): An Azure account object.\n resource_id (str): The Azure resource ID.\n name (str): The resource's name.\n region (str): The region in which the resource is located.\n zones (List[str]): Optional. Availability zones within the region where\n the resource is located.\n \"\"\"\n\n self.az_account = az_account\n # Format of resource_id: /subscriptions/{id}/resourceGroups/{\n # resource_group_name}/providers/Microsoft.Compute/{resourceType}/{resource}\n self.resource_group_name = resource_id.split('/')[4]\n self.resource_id = resource_id\n self.name = name\n self.region = region\n self.zones = zones\n\n\nclass AZVirtualMachine(AZComputeResource):\n \"\"\"Class that represents Azure virtual machines.\"\"\"\n\n def __init__(self,\n az_account: 'account.AZAccount',\n resource_id: str,\n name: str,\n region: str,\n zones: Optional[List[str]] = None) -> None:\n \"\"\"Initialize the AZVirtualMachine class.\n\n Args:\n az_account (AZAccount): An Azure account object.\n resource_id (str): The Azure ID of the virtual machine.\n name (str): The virtual machine's name.\n region (str): The region in which the virtual machine is located.\n zones (List[str]): Optional. Availability zones within the region where\n the virtual machine is located / replicated.\n \"\"\"\n super(AZVirtualMachine, self).__init__(az_account,\n resource_id,\n name,\n region,\n zones=zones)\n\n def GetBootDisk(self) -> 'AZDisk':\n \"\"\"Get the instance's boot disk.\n\n Returns:\n AZDisk: Disk object if the disk is found.\n\n Raises:\n RuntimeError: If no boot disk could be found.\n \"\"\"\n disks = self.az_account.ListDisks(\n resource_group_name=self.resource_group_name) # type: Dict[str, AZDisk]\n boot_disk_name = self.az_account.compute_client.virtual_machines.get(\n self.resource_group_name, self.name).storage_profile.os_disk.name\n if boot_disk_name not in disks:\n error_msg = 'Boot disk not found for instance: {0:s}'.format(\n self.resource_id)\n raise RuntimeError(error_msg)\n return disks[boot_disk_name]\n\n def GetDisk(self, disk_name: str) -> 'AZDisk':\n \"\"\"Get a disk attached to the instance by ID.\n\n Args:\n disk_name (str): The ID of the disk to get.\n\n Returns:\n AZDisk: The disk object.\n\n Raises:\n RuntimeError: If disk_name is not found amongst the disks attached\n to the instance.\n \"\"\"\n disks = self.ListDisks()\n if disk_name not in disks:\n error_msg = 'Disk {0:s} not found in instance: {1:s}'.format(\n disk_name, self.resource_id)\n raise RuntimeError(error_msg)\n return disks[disk_name]\n\n def ListDisks(self) -> Dict[str, 'AZDisk']:\n \"\"\"List all disks for the instance.\n\n Returns:\n Dict[str, AZDisk]: Dictionary mapping disk names to their respective\n AZDisk object.\n \"\"\"\n disks = self.az_account.ListDisks(\n resource_group_name=self.resource_group_name)\n vm_disks = self.az_account.compute_client.virtual_machines.get(\n self.resource_group_name, self.name).storage_profile\n vm_disks_names = [disk.name for disk in vm_disks.data_disks]\n vm_disks_names.append(vm_disks.os_disk.name)\n return {disk_name: disks[disk_name] for disk_name in vm_disks_names}\n\n def AttachDisk(self, disk: 'AZDisk') -> None:\n \"\"\"Attach a disk to the virtual machine.\n\n Args:\n disk (AZDisk): Disk to attach.\n\n Raises:\n RuntimeError: If the disk could not be attached.\n \"\"\"\n vm = self.az_account.compute_client.virtual_machines.get(\n self.resource_group_name, self.name)\n data_disks = vm.storage_profile.data_disks\n # ID to assign to the data disk to attach\n lun = 0 if len(data_disks) == 0 else len(data_disks) + 1\n\n update_data = {\n 'lun': lun,\n 'name': disk.name,\n 'create_option': models.DiskCreateOption.attach,\n 'managed_disk': {'id': disk.resource_id}\n }\n\n data_disks.append(update_data)\n\n try:\n request = self.az_account.compute_client.virtual_machines.update(\n self.resource_group_name, self.name, vm)\n while not request.done():\n sleep(5) # Wait 5 seconds before checking vm status again\n except azure_exceptions.CloudError as exception:\n raise RuntimeError('Could not attach disk {0:s} to instance {1:s}: '\n '{2:s}'.format(disk.name, self.name, str(exception)))\n\n\nclass AZDisk(AZComputeResource):\n \"\"\"Class that represents Azure disks.\"\"\"\n\n def __init__(self,\n az_account: 'account.AZAccount',\n resource_id: str,\n name: str,\n region: str,\n zones: Optional[List[str]] = None) -> None:\n \"\"\"Initialize the AZDisk class.\n\n Args:\n az_account (AZAccount): An Azure account object.\n resource_id (str): The Azure ID of the disk.\n name (str): The disk name.\n region (str): The region in which the disk is located.\n zones (List[str]): Optional. Availability zone within the region where\n the disk is located.\n \"\"\"\n super(AZDisk, self).__init__(az_account,\n resource_id,\n name,\n region,\n zones=zones)\n\n def Snapshot(self,\n snapshot_name: Optional[str] = None,\n tags: Optional[Dict[str, str]] = None) -> 'AZSnapshot':\n \"\"\"Create a snapshot of the disk.\n\n Args:\n snapshot_name (str): Optional. A name for the snapshot. If none\n provided, one will be generated based on the disk's name.\n tags (Dict[str, str]): Optional. A dictionary of tags to add to the\n snapshot, for example {'TicketID': 'xxx'}.\n\n Returns:\n AZSnapshot: A snapshot object.\n\n Raises:\n ValueError: If the snapshot name does not comply with the RegEx.\n RuntimeError: If the snapshot could not be created.\n \"\"\"\n\n if not snapshot_name:\n snapshot_name = self.name + '_snapshot'\n truncate_at = 80 - 1\n snapshot_name = snapshot_name[:truncate_at]\n if not common.REGEX_SNAPSHOT_NAME.match(snapshot_name):\n raise ValueError('Snapshot name {0:s} does not comply with '\n '{1:s}'.format(snapshot_name,\n common.REGEX_SNAPSHOT_NAME.pattern))\n\n creation_data = {\n 'location': self.region,\n 'creation_data': {\n 'sourceResourceId': self.resource_id,\n 'create_option': models.DiskCreateOption.copy\n }\n }\n\n if tags:\n creation_data['tags'] = tags\n\n try:\n logger.info('Creating snapshot: {0:s}'.format(snapshot_name))\n request = self.az_account.compute_client.snapshots.create_or_update(\n self.resource_group_name,\n snapshot_name,\n creation_data)\n while not request.done():\n sleep(5) # Wait 5 seconds before checking snapshot status again\n snapshot = request.result()\n logger.info('Snapshot {0:s} successfully created'.format(snapshot_name))\n except azure_exceptions.CloudError as exception:\n raise RuntimeError('Could not create snapshot for disk {0:s}: {1:s}'\n .format(self.resource_id, str(exception)))\n\n return AZSnapshot(self.az_account,\n snapshot.id,\n snapshot.name,\n snapshot.location,\n self)\n\n def GetDiskType(self) -> str:\n \"\"\"Return the SKU disk type.\n\n Returns:\n str: The SKU disk type.\n \"\"\"\n disk = self.az_account.compute_client.disks.get(\n self.resource_group_name, self.name)\n disk_type = disk.sku.name # type: str\n return disk_type\n\n\nclass AZSnapshot(AZComputeResource):\n \"\"\"Class that represents Azure snapshots.\n\n Attributes:\n disk (AZDisk): The disk from which the snapshot was taken.\n \"\"\"\n\n def __init__(self,\n az_account: 'account.AZAccount',\n resource_id: str,\n name: str,\n region: str,\n source_disk: AZDisk) -> None:\n \"\"\"Initialize the AZDisk class.\n\n Args:\n az_account (AZAccount): An Azure account object.\n resource_id (str): The Azure ID of the snapshot.\n name (str): The snapshot name.\n region (str): The region in which the snapshot is located.\n source_disk (AZDisk): The disk from which the snapshot was taken.\n \"\"\"\n super(AZSnapshot, self).__init__(az_account,\n resource_id,\n name,\n region)\n\n self.disk = source_disk\n\n def Delete(self) -> None:\n \"\"\"Delete a snapshot.\"\"\"\n\n try:\n logger.info('Deleting snapshot: {0:s}'.format(self.name))\n request = self.az_account.compute_client.snapshots.delete(\n self.resource_group_name, self.name)\n while not request.done():\n sleep(5) # Wait 5 seconds before checking snapshot status again\n logger.info('Snapshot {0:s} successfully deleted.'.format(self.name))\n except azure_exceptions.CloudError as exception:\n raise RuntimeError('Could not delete snapshot {0:s}: {1:s}'\n .format(self.resource_id, str(exception)))\n\n def GrantAccessAndGetURI(self) -> str:\n \"\"\"Grant access to a snapshot and return its access URI.\n\n Returns:\n str: The access URI for the snapshot.\n \"\"\"\n logger.info('Generating SAS URI for snapshot: {0:s}'.format(self.name))\n access_request = self.az_account.compute_client.snapshots.grant_access(\n self.resource_group_name, self.name, 'Read', 3600)\n snapshot_uri = access_request.result().access_sas # type: str\n logger.info('SAS URI generated: {0:s}'.format(snapshot_uri))\n return snapshot_uri\n\n def RevokeAccessURI(self) -> None:\n \"\"\"Revoke access to a snapshot.\"\"\"\n logger.info('Revoking SAS URI for snapshot {0:s}'.format(self.name))\n request = self.az_account.compute_client.snapshots.revoke_access(\n self.resource_group_name, self.name)\n request.wait()\n logger.info('SAS URI revoked for snapshot {0:s}'.format(self.name))\n","sub_path":"libcloudforensics/providers/azure/internal/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":12594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"426979276","text":"# coding: utf-8\nu\"\"\"Procesador de trámites de CECyRD.\"\"\"\nimport csv\nfrom datetime import datetime\nfrom os import listdir\nfrom os.path import isfile, join\nimport psycopg2\nimport pytz\nfrom tqdm import tqdm\n\n\nCAMPOS = (\n 'folio', 'estatus', 'causa_rechazo', 'movimiento_solicitado',\n 'movimiento_definitivo', 'fecha_tramite', 'fecha_recibido_cecyrd',\n 'fecha_registrado_cecyrd', 'fecha_rechazado',\n 'fecha_cancelado_movimiento_posterior', 'fecha_alta_pe',\n 'fecha_afectacion_padron', 'fecha_actualizacion_pe',\n 'fecha_reincorporacion_pe', 'fecha_exitoso', 'fecha_lote_produccion',\n 'fecha_listo_reimpresion', 'fecha_cpv_creada', 'fecha_cpv_registrada_mac',\n 'fecha_cpv_disponible', 'fecha_cpv_entregada', 'fecha_afectacion_ln'\n)\nSEPARADOR = '|'\nTZ = pytz.timezone('Mexico/General')\nfila = []\nFILE = 'data/Trámites_Tlax_01Jul_30Sep18.txt'\n# FILE = 'error.csv'\n# FILE = 'prueba.csv'\n\n\nconn = psycopg2.connect(\n 'dbname=cerebro user=admin password=abc123 host=localhost'\n)\ncur = conn.cursor()\n\ndef ampm(fecha):\n \"\"\"Convierta la fecha a un formato legible.\"\"\"\n return fecha[:-5] + 'AM' if fecha[20:] == 'a. m.' else fecha[:-5] + 'PM'\n\n\ndef fecha_con_dt(fecha):\n \"\"\"Convierte la fecha a un formato procesable.\"\"\"\n if fecha == '':\n return 'Null'\n if len(fecha) <= 10:\n fecha = fecha + ' 00:00:00 a. m.'\n try:\n f = datetime.strptime(\n fecha if fecha[-1] == 'M' else ampm(fecha),\n '%d/%m/%Y %H:%M:%S %p').replace(tzinfo=TZ)\n return \"'%s'\" % str(f)\n except ValueError:\n print(fecha)\n\n\ndef diferencia_fechas(inicio, fin):\n try:\n start = datetime.strptime(inicio if inicio[-1] == 'M' else ampm(inicio), '%d/%m/%Y %H:%M:%S %p').replace(tzinfo=TZ)\n end = datetime.strptime(fin if fin[-1] == 'M' else ampm(fin), '%d/%m/%Y %H:%M:%S %p').replace(tzinfo=TZ)\n delta = end - start\n return f\"@ {int(delta.total_seconds())} SECOND\"\n except IndexError:\n return 0\n\n\ndef file_len(full_path):\n \"\"\"Count number of lines in a file.\"\"\"\n f = open(full_path)\n nr_of_lines = sum(1 for line in f)\n f.close()\n return nr_of_lines\n\n\ndef proceso(FILE):\n \"\"\"Aqui se procesan los registros.\"\"\"\n with open(FILE) as archivo:\n medidor = file_len(FILE)\n print(f\"Procesando el archivo {FILE}...\")\n print(f\"Se procesarán {medidor} registros\")\n contador = 0\n\n t = tqdm(total=medidor)\n lector = csv.DictReader(\n archivo,\n fieldnames=CAMPOS,\n delimiter=SEPARADOR\n )\n\n for row in lector:\n t.update(contador)\n\n folio = row['folio']\n estatus = row['estatus']\n causa_rechazo = row['causa_rechazo']\n movimiento_solicitado = row['movimiento_solicitado']\n movimiento_definitivo = row['movimiento_definitivo']\n fecha_tramite = fecha_con_dt(row[\"fecha_tramite\"])\n fecha_recibido_cecyrd = fecha_con_dt(row[\"fecha_recibido_cecyrd\"])\n fecha_registrado_cecyrd = fecha_con_dt(row[\"fecha_registrado_cecyrd\"])\n fecha_rechazado = fecha_con_dt(row[\"fecha_rechazado\"])\n fecha_cancelado_movimiento_posterior = fecha_con_dt(row[\"fecha_cancelado_movimiento_posterior\"])\n fecha_alta_pe = fecha_con_dt(row[\"fecha_alta_pe\"])\n fecha_afectacion_padron = fecha_con_dt(row[\"fecha_afectacion_padron\"])\n fecha_actualizacion_pe = fecha_con_dt(row[\"fecha_actualizacion_pe\"])\n fecha_reincorporacion_pe = fecha_con_dt(row[\"fecha_reincorporacion_pe\"])\n fecha_exitoso = fecha_con_dt(row[\"fecha_exitoso\"])\n fecha_lote_produccion = fecha_con_dt(row[\"fecha_lote_produccion\"])\n fecha_listo_reimpresion = fecha_con_dt(row[\"fecha_listo_reimpresion\"])\n fecha_cpv_creada = fecha_con_dt(row[\"fecha_cpv_creada\"])\n fecha_cpv_registrada_mac = fecha_con_dt(row[\"fecha_cpv_registrada_mac\"])\n fecha_cpv_disponible = fecha_con_dt(row[\"fecha_cpv_disponible\"])\n fecha_cpv_entregada = fecha_con_dt(row[\"fecha_cpv_entregada\"])\n fecha_afectacion_ln = fecha_con_dt(row[\"fecha_afectacion_ln\"])\n distrito = folio[5]\n mac = folio[2:8]\n tramo_disponible = diferencia_fechas(row[\"fecha_tramite\"], row[\"fecha_cpv_disponible\"])\n tramo_entrega = diferencia_fechas(row[\"fecha_cpv_disponible\"], row[\"fecha_cpv_entregada\"])\n tramo_exitoso = diferencia_fechas(row[\"fecha_tramite\"], row[\"fecha_exitoso\"])\n\n linea = (f\"\"\"\n INSERT INTO cecyrd_tramites VALUES (\n '{folio}',\n '{estatus}',\n '{causa_rechazo}',\n '{movimiento_solicitado}',\n '{movimiento_definitivo}',\n {fecha_tramite},\n {fecha_recibido_cecyrd},\n {fecha_registrado_cecyrd},\n {fecha_rechazado},\n {fecha_cancelado_movimiento_posterior},\n {fecha_alta_pe},\n {fecha_afectacion_padron},\n {fecha_actualizacion_pe},\n {fecha_reincorporacion_pe},\n {fecha_exitoso},\n {fecha_lote_produccion},\n {fecha_listo_reimpresion},\n {fecha_cpv_creada},\n {fecha_cpv_registrada_mac},\n {fecha_cpv_disponible},\n {fecha_cpv_entregada},\n {fecha_afectacion_ln},\n {distrito},\n '{mac}',\n '{tramo_disponible}',\n '{tramo_entrega}',\n '{tramo_exitoso}'\n ) ON CONFLICT (folio) DO UPDATE SET\n \"estatus\" = '{estatus}',\n \"causa_rechazo\" = '{causa_rechazo}',\n \"movimiento_solicitado\" = '{movimiento_solicitado}',\n \"movimiento_definitivo\" = '{movimiento_definitivo}',\n \"fecha_tramite\" = {fecha_tramite},\n \"fecha_recibido_cecyrd\" = {fecha_recibido_cecyrd},\n \"fecha_registrado_cecyrd\" = {fecha_registrado_cecyrd},\n \"fecha_rechazado\" = {fecha_rechazado},\n \"fecha_cancelado_movimiento_posterior\" = {fecha_cancelado_movimiento_posterior},\n \"fecha_alta_pe\" = {fecha_con_dt(row[\"fecha_alta_pe\"])},\n \"fecha_afectacion_padron\" = {fecha_afectacion_padron},\n \"fecha_actualizacion_pe\" = {fecha_actualizacion_pe},\n \"fecha_reincorporacion_pe\" = {fecha_reincorporacion_pe},\n \"fecha_exitoso\" = {fecha_exitoso},\n \"fecha_lote_produccion\" = {fecha_lote_produccion},\n \"fecha_listo_reimpresion\" = {fecha_listo_reimpresion},\n \"fecha_cpv_creada\" = {fecha_cpv_creada},\n \"fecha_cpv_registrada_mac\" = {fecha_cpv_registrada_mac},\n \"fecha_cpv_disponible\" = {fecha_cpv_disponible},\n \"fecha_cpv_entregada\" = {fecha_cpv_entregada},\n \"fecha_afectacion_ln\" = {fecha_afectacion_ln},\n \"distrito\" = {distrito},\n \"mac\" = '{mac}',\n \"tramo_disponible\" = '{tramo_disponible}',\n \"tramo_entrega\" = '{tramo_entrega}',\n \"tramo_exitoso\" = '{tramo_exitoso}'\n \"\"\")\n # print('\\n', folio, row[\"fecha_tramite\"], row[\"fecha_cpv_disponible\"], row[\"fecha_cpv_entregada\"], row[\"fecha_exitoso\"])\n\n cur.execute(linea)\n t.update(cur.rowcount)\n\n conn.commit()\n t.close()\n\n\n# onlyfiles = [f for f in listdir('./data') if isfile(join('./data', f))]\n\n# for f in onlyfiles:\n# f = f'./data/{f}'\n# proceso(f)\n\nproceso(FILE)\n\ncur.close()\n","sub_path":"proceso.py","file_name":"proceso.py","file_ext":"py","file_size_in_byte":7734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"649949028","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.core.exceptions import HttpResponseError\nimport msrest.serialization\n\n\nclass AclFailedEntry(msrest.serialization.Model):\n \"\"\"AclFailedEntry.\n\n :ivar name:\n :vartype name: str\n :ivar type:\n :vartype type: str\n :ivar error_message:\n :vartype error_message: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'type': {'key': 'type', 'type': 'str'},\n 'error_message': {'key': 'errorMessage', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword name:\n :paramtype name: str\n :keyword type:\n :paramtype type: str\n :keyword error_message:\n :paramtype error_message: str\n \"\"\"\n super(AclFailedEntry, self).__init__(**kwargs)\n self.name = kwargs.get('name', None)\n self.type = kwargs.get('type', None)\n self.error_message = kwargs.get('error_message', None)\n\n\nclass BlobHierarchyListSegment(msrest.serialization.Model):\n \"\"\"BlobHierarchyListSegment.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar blob_prefixes:\n :vartype blob_prefixes: list[~azure.storage.filedatalake.models.BlobPrefix]\n :ivar blob_items: Required.\n :vartype blob_items: list[~azure.storage.filedatalake.models.BlobItemInternal]\n \"\"\"\n\n _validation = {\n 'blob_items': {'required': True},\n }\n\n _attribute_map = {\n 'blob_prefixes': {'key': 'BlobPrefixes', 'type': '[BlobPrefix]'},\n 'blob_items': {'key': 'BlobItems', 'type': '[BlobItemInternal]'},\n }\n _xml_map = {\n 'name': 'Blobs'\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword blob_prefixes:\n :paramtype blob_prefixes: list[~azure.storage.filedatalake.models.BlobPrefix]\n :keyword blob_items: Required.\n :paramtype blob_items: list[~azure.storage.filedatalake.models.BlobItemInternal]\n \"\"\"\n super(BlobHierarchyListSegment, self).__init__(**kwargs)\n self.blob_prefixes = kwargs.get('blob_prefixes', None)\n self.blob_items = kwargs['blob_items']\n\n\nclass BlobItemInternal(msrest.serialization.Model):\n \"\"\"An Azure Storage blob.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar name: Required.\n :vartype name: str\n :ivar deleted: Required.\n :vartype deleted: bool\n :ivar snapshot: Required.\n :vartype snapshot: str\n :ivar version_id:\n :vartype version_id: str\n :ivar is_current_version:\n :vartype is_current_version: bool\n :ivar properties: Required. Properties of a blob.\n :vartype properties: ~azure.storage.filedatalake.models.BlobPropertiesInternal\n :ivar deletion_id:\n :vartype deletion_id: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n 'deleted': {'required': True},\n 'snapshot': {'required': True},\n 'properties': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'Name', 'type': 'str'},\n 'deleted': {'key': 'Deleted', 'type': 'bool'},\n 'snapshot': {'key': 'Snapshot', 'type': 'str'},\n 'version_id': {'key': 'VersionId', 'type': 'str'},\n 'is_current_version': {'key': 'IsCurrentVersion', 'type': 'bool'},\n 'properties': {'key': 'Properties', 'type': 'BlobPropertiesInternal'},\n 'deletion_id': {'key': 'DeletionId', 'type': 'str'},\n }\n _xml_map = {\n 'name': 'Blob'\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword name: Required.\n :paramtype name: str\n :keyword deleted: Required.\n :paramtype deleted: bool\n :keyword snapshot: Required.\n :paramtype snapshot: str\n :keyword version_id:\n :paramtype version_id: str\n :keyword is_current_version:\n :paramtype is_current_version: bool\n :keyword properties: Required. Properties of a blob.\n :paramtype properties: ~azure.storage.filedatalake.models.BlobPropertiesInternal\n :keyword deletion_id:\n :paramtype deletion_id: str\n \"\"\"\n super(BlobItemInternal, self).__init__(**kwargs)\n self.name = kwargs['name']\n self.deleted = kwargs['deleted']\n self.snapshot = kwargs['snapshot']\n self.version_id = kwargs.get('version_id', None)\n self.is_current_version = kwargs.get('is_current_version', None)\n self.properties = kwargs['properties']\n self.deletion_id = kwargs.get('deletion_id', None)\n\n\nclass BlobPrefix(msrest.serialization.Model):\n \"\"\"BlobPrefix.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar name: Required.\n :vartype name: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'Name', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword name: Required.\n :paramtype name: str\n \"\"\"\n super(BlobPrefix, self).__init__(**kwargs)\n self.name = kwargs['name']\n\n\nclass BlobPropertiesInternal(msrest.serialization.Model):\n \"\"\"Properties of a blob.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar creation_time:\n :vartype creation_time: ~datetime.datetime\n :ivar last_modified: Required.\n :vartype last_modified: ~datetime.datetime\n :ivar etag: Required.\n :vartype etag: str\n :ivar content_length: Size in bytes.\n :vartype content_length: long\n :ivar content_type:\n :vartype content_type: str\n :ivar content_encoding:\n :vartype content_encoding: str\n :ivar content_language:\n :vartype content_language: str\n :ivar content_md5:\n :vartype content_md5: bytearray\n :ivar content_disposition:\n :vartype content_disposition: str\n :ivar cache_control:\n :vartype cache_control: str\n :ivar blob_sequence_number:\n :vartype blob_sequence_number: long\n :ivar copy_id:\n :vartype copy_id: str\n :ivar copy_source:\n :vartype copy_source: str\n :ivar copy_progress:\n :vartype copy_progress: str\n :ivar copy_completion_time:\n :vartype copy_completion_time: ~datetime.datetime\n :ivar copy_status_description:\n :vartype copy_status_description: str\n :ivar server_encrypted:\n :vartype server_encrypted: bool\n :ivar incremental_copy:\n :vartype incremental_copy: bool\n :ivar destination_snapshot:\n :vartype destination_snapshot: str\n :ivar deleted_time:\n :vartype deleted_time: ~datetime.datetime\n :ivar remaining_retention_days:\n :vartype remaining_retention_days: int\n :ivar access_tier_inferred:\n :vartype access_tier_inferred: bool\n :ivar customer_provided_key_sha256:\n :vartype customer_provided_key_sha256: str\n :ivar encryption_scope: The name of the encryption scope under which the blob is encrypted.\n :vartype encryption_scope: str\n :ivar access_tier_change_time:\n :vartype access_tier_change_time: ~datetime.datetime\n :ivar tag_count:\n :vartype tag_count: int\n :ivar expires_on:\n :vartype expires_on: ~datetime.datetime\n :ivar is_sealed:\n :vartype is_sealed: bool\n :ivar last_accessed_on:\n :vartype last_accessed_on: ~datetime.datetime\n :ivar delete_time:\n :vartype delete_time: ~datetime.datetime\n \"\"\"\n\n _validation = {\n 'last_modified': {'required': True},\n 'etag': {'required': True},\n }\n\n _attribute_map = {\n 'creation_time': {'key': 'Creation-Time', 'type': 'rfc-1123'},\n 'last_modified': {'key': 'Last-Modified', 'type': 'rfc-1123'},\n 'etag': {'key': 'Etag', 'type': 'str'},\n 'content_length': {'key': 'Content-Length', 'type': 'long'},\n 'content_type': {'key': 'Content-Type', 'type': 'str'},\n 'content_encoding': {'key': 'Content-Encoding', 'type': 'str'},\n 'content_language': {'key': 'Content-Language', 'type': 'str'},\n 'content_md5': {'key': 'Content-MD5', 'type': 'bytearray'},\n 'content_disposition': {'key': 'Content-Disposition', 'type': 'str'},\n 'cache_control': {'key': 'Cache-Control', 'type': 'str'},\n 'blob_sequence_number': {'key': 'x-ms-blob-sequence-number', 'type': 'long'},\n 'copy_id': {'key': 'CopyId', 'type': 'str'},\n 'copy_source': {'key': 'CopySource', 'type': 'str'},\n 'copy_progress': {'key': 'CopyProgress', 'type': 'str'},\n 'copy_completion_time': {'key': 'CopyCompletionTime', 'type': 'rfc-1123'},\n 'copy_status_description': {'key': 'CopyStatusDescription', 'type': 'str'},\n 'server_encrypted': {'key': 'ServerEncrypted', 'type': 'bool'},\n 'incremental_copy': {'key': 'IncrementalCopy', 'type': 'bool'},\n 'destination_snapshot': {'key': 'DestinationSnapshot', 'type': 'str'},\n 'deleted_time': {'key': 'DeletedTime', 'type': 'rfc-1123'},\n 'remaining_retention_days': {'key': 'RemainingRetentionDays', 'type': 'int'},\n 'access_tier_inferred': {'key': 'AccessTierInferred', 'type': 'bool'},\n 'customer_provided_key_sha256': {'key': 'CustomerProvidedKeySha256', 'type': 'str'},\n 'encryption_scope': {'key': 'EncryptionScope', 'type': 'str'},\n 'access_tier_change_time': {'key': 'AccessTierChangeTime', 'type': 'rfc-1123'},\n 'tag_count': {'key': 'TagCount', 'type': 'int'},\n 'expires_on': {'key': 'Expiry-Time', 'type': 'rfc-1123'},\n 'is_sealed': {'key': 'Sealed', 'type': 'bool'},\n 'last_accessed_on': {'key': 'LastAccessTime', 'type': 'rfc-1123'},\n 'delete_time': {'key': 'DeleteTime', 'type': 'rfc-1123'},\n }\n _xml_map = {\n 'name': 'Properties'\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword creation_time:\n :paramtype creation_time: ~datetime.datetime\n :keyword last_modified: Required.\n :paramtype last_modified: ~datetime.datetime\n :keyword etag: Required.\n :paramtype etag: str\n :keyword content_length: Size in bytes.\n :paramtype content_length: long\n :keyword content_type:\n :paramtype content_type: str\n :keyword content_encoding:\n :paramtype content_encoding: str\n :keyword content_language:\n :paramtype content_language: str\n :keyword content_md5:\n :paramtype content_md5: bytearray\n :keyword content_disposition:\n :paramtype content_disposition: str\n :keyword cache_control:\n :paramtype cache_control: str\n :keyword blob_sequence_number:\n :paramtype blob_sequence_number: long\n :keyword copy_id:\n :paramtype copy_id: str\n :keyword copy_source:\n :paramtype copy_source: str\n :keyword copy_progress:\n :paramtype copy_progress: str\n :keyword copy_completion_time:\n :paramtype copy_completion_time: ~datetime.datetime\n :keyword copy_status_description:\n :paramtype copy_status_description: str\n :keyword server_encrypted:\n :paramtype server_encrypted: bool\n :keyword incremental_copy:\n :paramtype incremental_copy: bool\n :keyword destination_snapshot:\n :paramtype destination_snapshot: str\n :keyword deleted_time:\n :paramtype deleted_time: ~datetime.datetime\n :keyword remaining_retention_days:\n :paramtype remaining_retention_days: int\n :keyword access_tier_inferred:\n :paramtype access_tier_inferred: bool\n :keyword customer_provided_key_sha256:\n :paramtype customer_provided_key_sha256: str\n :keyword encryption_scope: The name of the encryption scope under which the blob is encrypted.\n :paramtype encryption_scope: str\n :keyword access_tier_change_time:\n :paramtype access_tier_change_time: ~datetime.datetime\n :keyword tag_count:\n :paramtype tag_count: int\n :keyword expires_on:\n :paramtype expires_on: ~datetime.datetime\n :keyword is_sealed:\n :paramtype is_sealed: bool\n :keyword last_accessed_on:\n :paramtype last_accessed_on: ~datetime.datetime\n :keyword delete_time:\n :paramtype delete_time: ~datetime.datetime\n \"\"\"\n super(BlobPropertiesInternal, self).__init__(**kwargs)\n self.creation_time = kwargs.get('creation_time', None)\n self.last_modified = kwargs['last_modified']\n self.etag = kwargs['etag']\n self.content_length = kwargs.get('content_length', None)\n self.content_type = kwargs.get('content_type', None)\n self.content_encoding = kwargs.get('content_encoding', None)\n self.content_language = kwargs.get('content_language', None)\n self.content_md5 = kwargs.get('content_md5', None)\n self.content_disposition = kwargs.get('content_disposition', None)\n self.cache_control = kwargs.get('cache_control', None)\n self.blob_sequence_number = kwargs.get('blob_sequence_number', None)\n self.copy_id = kwargs.get('copy_id', None)\n self.copy_source = kwargs.get('copy_source', None)\n self.copy_progress = kwargs.get('copy_progress', None)\n self.copy_completion_time = kwargs.get('copy_completion_time', None)\n self.copy_status_description = kwargs.get('copy_status_description', None)\n self.server_encrypted = kwargs.get('server_encrypted', None)\n self.incremental_copy = kwargs.get('incremental_copy', None)\n self.destination_snapshot = kwargs.get('destination_snapshot', None)\n self.deleted_time = kwargs.get('deleted_time', None)\n self.remaining_retention_days = kwargs.get('remaining_retention_days', None)\n self.access_tier_inferred = kwargs.get('access_tier_inferred', None)\n self.customer_provided_key_sha256 = kwargs.get('customer_provided_key_sha256', None)\n self.encryption_scope = kwargs.get('encryption_scope', None)\n self.access_tier_change_time = kwargs.get('access_tier_change_time', None)\n self.tag_count = kwargs.get('tag_count', None)\n self.expires_on = kwargs.get('expires_on', None)\n self.is_sealed = kwargs.get('is_sealed', None)\n self.last_accessed_on = kwargs.get('last_accessed_on', None)\n self.delete_time = kwargs.get('delete_time', None)\n\n\nclass CpkInfo(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :ivar encryption_key: Optional. Specifies the encryption key to use to encrypt the data\n provided in the request. If not specified, encryption is performed with the root account\n encryption key. For more information, see Encryption at Rest for Azure Storage Services.\n :vartype encryption_key: str\n :ivar encryption_key_sha256: The SHA-256 hash of the provided encryption key. Must be provided\n if the x-ms-encryption-key header is provided.\n :vartype encryption_key_sha256: str\n :ivar encryption_algorithm: The algorithm used to produce the encryption key hash. Currently,\n the only accepted value is \"AES256\". Must be provided if the x-ms-encryption-key header is\n provided. The only acceptable values to pass in are None and \"AES256\". The default value is\n None.\n :vartype encryption_algorithm: str\n \"\"\"\n\n _attribute_map = {\n 'encryption_key': {'key': 'encryptionKey', 'type': 'str'},\n 'encryption_key_sha256': {'key': 'encryptionKeySha256', 'type': 'str'},\n 'encryption_algorithm': {'key': 'encryptionAlgorithm', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword encryption_key: Optional. Specifies the encryption key to use to encrypt the data\n provided in the request. If not specified, encryption is performed with the root account\n encryption key. For more information, see Encryption at Rest for Azure Storage Services.\n :paramtype encryption_key: str\n :keyword encryption_key_sha256: The SHA-256 hash of the provided encryption key. Must be\n provided if the x-ms-encryption-key header is provided.\n :paramtype encryption_key_sha256: str\n :keyword encryption_algorithm: The algorithm used to produce the encryption key hash.\n Currently, the only accepted value is \"AES256\". Must be provided if the x-ms-encryption-key\n header is provided. The only acceptable values to pass in are None and \"AES256\". The default\n value is None.\n :paramtype encryption_algorithm: str\n \"\"\"\n super(CpkInfo, self).__init__(**kwargs)\n self.encryption_key = kwargs.get('encryption_key', None)\n self.encryption_key_sha256 = kwargs.get('encryption_key_sha256', None)\n self.encryption_algorithm = kwargs.get('encryption_algorithm', None)\n\n\nclass FileSystem(msrest.serialization.Model):\n \"\"\"FileSystem.\n\n :ivar name:\n :vartype name: str\n :ivar last_modified:\n :vartype last_modified: str\n :ivar e_tag:\n :vartype e_tag: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'last_modified': {'key': 'lastModified', 'type': 'str'},\n 'e_tag': {'key': 'eTag', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword name:\n :paramtype name: str\n :keyword last_modified:\n :paramtype last_modified: str\n :keyword e_tag:\n :paramtype e_tag: str\n \"\"\"\n super(FileSystem, self).__init__(**kwargs)\n self.name = kwargs.get('name', None)\n self.last_modified = kwargs.get('last_modified', None)\n self.e_tag = kwargs.get('e_tag', None)\n\n\nclass FileSystemList(msrest.serialization.Model):\n \"\"\"FileSystemList.\n\n :ivar filesystems:\n :vartype filesystems: list[~azure.storage.filedatalake.models.FileSystem]\n \"\"\"\n\n _attribute_map = {\n 'filesystems': {'key': 'filesystems', 'type': '[FileSystem]'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword filesystems:\n :paramtype filesystems: list[~azure.storage.filedatalake.models.FileSystem]\n \"\"\"\n super(FileSystemList, self).__init__(**kwargs)\n self.filesystems = kwargs.get('filesystems', None)\n\n\nclass LeaseAccessConditions(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :ivar lease_id: If specified, the operation only succeeds if the resource's lease is active and\n matches this ID.\n :vartype lease_id: str\n \"\"\"\n\n _attribute_map = {\n 'lease_id': {'key': 'leaseId', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword lease_id: If specified, the operation only succeeds if the resource's lease is active\n and matches this ID.\n :paramtype lease_id: str\n \"\"\"\n super(LeaseAccessConditions, self).__init__(**kwargs)\n self.lease_id = kwargs.get('lease_id', None)\n\n\nclass ListBlobsHierarchySegmentResponse(msrest.serialization.Model):\n \"\"\"An enumeration of blobs.\n\n All required parameters must be populated in order to send to Azure.\n\n :ivar service_endpoint: Required.\n :vartype service_endpoint: str\n :ivar container_name: Required.\n :vartype container_name: str\n :ivar prefix:\n :vartype prefix: str\n :ivar marker:\n :vartype marker: str\n :ivar max_results:\n :vartype max_results: int\n :ivar delimiter:\n :vartype delimiter: str\n :ivar segment: Required.\n :vartype segment: ~azure.storage.filedatalake.models.BlobHierarchyListSegment\n :ivar next_marker:\n :vartype next_marker: str\n \"\"\"\n\n _validation = {\n 'service_endpoint': {'required': True},\n 'container_name': {'required': True},\n 'segment': {'required': True},\n }\n\n _attribute_map = {\n 'service_endpoint': {'key': 'ServiceEndpoint', 'type': 'str', 'xml': {'attr': True}},\n 'container_name': {'key': 'ContainerName', 'type': 'str', 'xml': {'attr': True}},\n 'prefix': {'key': 'Prefix', 'type': 'str'},\n 'marker': {'key': 'Marker', 'type': 'str'},\n 'max_results': {'key': 'MaxResults', 'type': 'int'},\n 'delimiter': {'key': 'Delimiter', 'type': 'str'},\n 'segment': {'key': 'Segment', 'type': 'BlobHierarchyListSegment'},\n 'next_marker': {'key': 'NextMarker', 'type': 'str'},\n }\n _xml_map = {\n 'name': 'EnumerationResults'\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword service_endpoint: Required.\n :paramtype service_endpoint: str\n :keyword container_name: Required.\n :paramtype container_name: str\n :keyword prefix:\n :paramtype prefix: str\n :keyword marker:\n :paramtype marker: str\n :keyword max_results:\n :paramtype max_results: int\n :keyword delimiter:\n :paramtype delimiter: str\n :keyword segment: Required.\n :paramtype segment: ~azure.storage.filedatalake.models.BlobHierarchyListSegment\n :keyword next_marker:\n :paramtype next_marker: str\n \"\"\"\n super(ListBlobsHierarchySegmentResponse, self).__init__(**kwargs)\n self.service_endpoint = kwargs['service_endpoint']\n self.container_name = kwargs['container_name']\n self.prefix = kwargs.get('prefix', None)\n self.marker = kwargs.get('marker', None)\n self.max_results = kwargs.get('max_results', None)\n self.delimiter = kwargs.get('delimiter', None)\n self.segment = kwargs['segment']\n self.next_marker = kwargs.get('next_marker', None)\n\n\nclass ModifiedAccessConditions(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :ivar if_modified_since: Specify this header value to operate only on a blob if it has been\n modified since the specified date/time.\n :vartype if_modified_since: ~datetime.datetime\n :ivar if_unmodified_since: Specify this header value to operate only on a blob if it has not\n been modified since the specified date/time.\n :vartype if_unmodified_since: ~datetime.datetime\n :ivar if_match: Specify an ETag value to operate only on blobs with a matching value.\n :vartype if_match: str\n :ivar if_none_match: Specify an ETag value to operate only on blobs without a matching value.\n :vartype if_none_match: str\n \"\"\"\n\n _attribute_map = {\n 'if_modified_since': {'key': 'ifModifiedSince', 'type': 'rfc-1123'},\n 'if_unmodified_since': {'key': 'ifUnmodifiedSince', 'type': 'rfc-1123'},\n 'if_match': {'key': 'ifMatch', 'type': 'str'},\n 'if_none_match': {'key': 'ifNoneMatch', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword if_modified_since: Specify this header value to operate only on a blob if it has been\n modified since the specified date/time.\n :paramtype if_modified_since: ~datetime.datetime\n :keyword if_unmodified_since: Specify this header value to operate only on a blob if it has not\n been modified since the specified date/time.\n :paramtype if_unmodified_since: ~datetime.datetime\n :keyword if_match: Specify an ETag value to operate only on blobs with a matching value.\n :paramtype if_match: str\n :keyword if_none_match: Specify an ETag value to operate only on blobs without a matching\n value.\n :paramtype if_none_match: str\n \"\"\"\n super(ModifiedAccessConditions, self).__init__(**kwargs)\n self.if_modified_since = kwargs.get('if_modified_since', None)\n self.if_unmodified_since = kwargs.get('if_unmodified_since', None)\n self.if_match = kwargs.get('if_match', None)\n self.if_none_match = kwargs.get('if_none_match', None)\n\n\nclass Path(msrest.serialization.Model):\n \"\"\"Path.\n\n :ivar name:\n :vartype name: str\n :ivar is_directory:\n :vartype is_directory: bool\n :ivar last_modified:\n :vartype last_modified: str\n :ivar e_tag:\n :vartype e_tag: str\n :ivar content_length:\n :vartype content_length: long\n :ivar owner:\n :vartype owner: str\n :ivar group:\n :vartype group: str\n :ivar permissions:\n :vartype permissions: str\n :ivar encryption_scope: The name of the encryption scope under which the blob is encrypted.\n :vartype encryption_scope: str\n :ivar creation_time:\n :vartype creation_time: str\n :ivar expiry_time:\n :vartype expiry_time: str\n \"\"\"\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'is_directory': {'key': 'isDirectory', 'type': 'bool'},\n 'last_modified': {'key': 'lastModified', 'type': 'str'},\n 'e_tag': {'key': 'eTag', 'type': 'str'},\n 'content_length': {'key': 'contentLength', 'type': 'long'},\n 'owner': {'key': 'owner', 'type': 'str'},\n 'group': {'key': 'group', 'type': 'str'},\n 'permissions': {'key': 'permissions', 'type': 'str'},\n 'encryption_scope': {'key': 'EncryptionScope', 'type': 'str'},\n 'creation_time': {'key': 'creationTime', 'type': 'str'},\n 'expiry_time': {'key': 'expiryTime', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword name:\n :paramtype name: str\n :keyword is_directory:\n :paramtype is_directory: bool\n :keyword last_modified:\n :paramtype last_modified: str\n :keyword e_tag:\n :paramtype e_tag: str\n :keyword content_length:\n :paramtype content_length: long\n :keyword owner:\n :paramtype owner: str\n :keyword group:\n :paramtype group: str\n :keyword permissions:\n :paramtype permissions: str\n :keyword encryption_scope: The name of the encryption scope under which the blob is encrypted.\n :paramtype encryption_scope: str\n :keyword creation_time:\n :paramtype creation_time: str\n :keyword expiry_time:\n :paramtype expiry_time: str\n \"\"\"\n super(Path, self).__init__(**kwargs)\n self.name = kwargs.get('name', None)\n self.is_directory = kwargs.get('is_directory', False)\n self.last_modified = kwargs.get('last_modified', None)\n self.e_tag = kwargs.get('e_tag', None)\n self.content_length = kwargs.get('content_length', None)\n self.owner = kwargs.get('owner', None)\n self.group = kwargs.get('group', None)\n self.permissions = kwargs.get('permissions', None)\n self.encryption_scope = kwargs.get('encryption_scope', None)\n self.creation_time = kwargs.get('creation_time', None)\n self.expiry_time = kwargs.get('expiry_time', None)\n\n\nclass PathHTTPHeaders(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :ivar cache_control: Optional. Sets the blob's cache control. If specified, this property is\n stored with the blob and returned with a read request.\n :vartype cache_control: str\n :ivar content_encoding: Optional. Sets the blob's content encoding. If specified, this property\n is stored with the blob and returned with a read request.\n :vartype content_encoding: str\n :ivar content_language: Optional. Set the blob's content language. If specified, this property\n is stored with the blob and returned with a read request.\n :vartype content_language: str\n :ivar content_disposition: Optional. Sets the blob's Content-Disposition header.\n :vartype content_disposition: str\n :ivar content_type: Optional. Sets the blob's content type. If specified, this property is\n stored with the blob and returned with a read request.\n :vartype content_type: str\n :ivar content_md5: Specify the transactional md5 for the body, to be validated by the service.\n :vartype content_md5: bytearray\n :ivar transactional_content_hash: Specify the transactional md5 for the body, to be validated\n by the service.\n :vartype transactional_content_hash: bytearray\n \"\"\"\n\n _attribute_map = {\n 'cache_control': {'key': 'cacheControl', 'type': 'str'},\n 'content_encoding': {'key': 'contentEncoding', 'type': 'str'},\n 'content_language': {'key': 'contentLanguage', 'type': 'str'},\n 'content_disposition': {'key': 'contentDisposition', 'type': 'str'},\n 'content_type': {'key': 'contentType', 'type': 'str'},\n 'content_md5': {'key': 'contentMD5', 'type': 'bytearray'},\n 'transactional_content_hash': {'key': 'transactionalContentHash', 'type': 'bytearray'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword cache_control: Optional. Sets the blob's cache control. If specified, this property is\n stored with the blob and returned with a read request.\n :paramtype cache_control: str\n :keyword content_encoding: Optional. Sets the blob's content encoding. If specified, this\n property is stored with the blob and returned with a read request.\n :paramtype content_encoding: str\n :keyword content_language: Optional. Set the blob's content language. If specified, this\n property is stored with the blob and returned with a read request.\n :paramtype content_language: str\n :keyword content_disposition: Optional. Sets the blob's Content-Disposition header.\n :paramtype content_disposition: str\n :keyword content_type: Optional. Sets the blob's content type. If specified, this property is\n stored with the blob and returned with a read request.\n :paramtype content_type: str\n :keyword content_md5: Specify the transactional md5 for the body, to be validated by the\n service.\n :paramtype content_md5: bytearray\n :keyword transactional_content_hash: Specify the transactional md5 for the body, to be\n validated by the service.\n :paramtype transactional_content_hash: bytearray\n \"\"\"\n super(PathHTTPHeaders, self).__init__(**kwargs)\n self.cache_control = kwargs.get('cache_control', None)\n self.content_encoding = kwargs.get('content_encoding', None)\n self.content_language = kwargs.get('content_language', None)\n self.content_disposition = kwargs.get('content_disposition', None)\n self.content_type = kwargs.get('content_type', None)\n self.content_md5 = kwargs.get('content_md5', None)\n self.transactional_content_hash = kwargs.get('transactional_content_hash', None)\n\n\nclass PathList(msrest.serialization.Model):\n \"\"\"PathList.\n\n :ivar paths:\n :vartype paths: list[~azure.storage.filedatalake.models.Path]\n \"\"\"\n\n _attribute_map = {\n 'paths': {'key': 'paths', 'type': '[Path]'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword paths:\n :paramtype paths: list[~azure.storage.filedatalake.models.Path]\n \"\"\"\n super(PathList, self).__init__(**kwargs)\n self.paths = kwargs.get('paths', None)\n\n\nclass SetAccessControlRecursiveResponse(msrest.serialization.Model):\n \"\"\"SetAccessControlRecursiveResponse.\n\n :ivar directories_successful:\n :vartype directories_successful: int\n :ivar files_successful:\n :vartype files_successful: int\n :ivar failure_count:\n :vartype failure_count: int\n :ivar failed_entries:\n :vartype failed_entries: list[~azure.storage.filedatalake.models.AclFailedEntry]\n \"\"\"\n\n _attribute_map = {\n 'directories_successful': {'key': 'directoriesSuccessful', 'type': 'int'},\n 'files_successful': {'key': 'filesSuccessful', 'type': 'int'},\n 'failure_count': {'key': 'failureCount', 'type': 'int'},\n 'failed_entries': {'key': 'failedEntries', 'type': '[AclFailedEntry]'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword directories_successful:\n :paramtype directories_successful: int\n :keyword files_successful:\n :paramtype files_successful: int\n :keyword failure_count:\n :paramtype failure_count: int\n :keyword failed_entries:\n :paramtype failed_entries: list[~azure.storage.filedatalake.models.AclFailedEntry]\n \"\"\"\n super(SetAccessControlRecursiveResponse, self).__init__(**kwargs)\n self.directories_successful = kwargs.get('directories_successful', None)\n self.files_successful = kwargs.get('files_successful', None)\n self.failure_count = kwargs.get('failure_count', None)\n self.failed_entries = kwargs.get('failed_entries', None)\n\n\nclass SourceModifiedAccessConditions(msrest.serialization.Model):\n \"\"\"Parameter group.\n\n :ivar source_if_match: Specify an ETag value to operate only on blobs with a matching value.\n :vartype source_if_match: str\n :ivar source_if_none_match: Specify an ETag value to operate only on blobs without a matching\n value.\n :vartype source_if_none_match: str\n :ivar source_if_modified_since: Specify this header value to operate only on a blob if it has\n been modified since the specified date/time.\n :vartype source_if_modified_since: ~datetime.datetime\n :ivar source_if_unmodified_since: Specify this header value to operate only on a blob if it has\n not been modified since the specified date/time.\n :vartype source_if_unmodified_since: ~datetime.datetime\n \"\"\"\n\n _attribute_map = {\n 'source_if_match': {'key': 'sourceIfMatch', 'type': 'str'},\n 'source_if_none_match': {'key': 'sourceIfNoneMatch', 'type': 'str'},\n 'source_if_modified_since': {'key': 'sourceIfModifiedSince', 'type': 'rfc-1123'},\n 'source_if_unmodified_since': {'key': 'sourceIfUnmodifiedSince', 'type': 'rfc-1123'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword source_if_match: Specify an ETag value to operate only on blobs with a matching value.\n :paramtype source_if_match: str\n :keyword source_if_none_match: Specify an ETag value to operate only on blobs without a\n matching value.\n :paramtype source_if_none_match: str\n :keyword source_if_modified_since: Specify this header value to operate only on a blob if it\n has been modified since the specified date/time.\n :paramtype source_if_modified_since: ~datetime.datetime\n :keyword source_if_unmodified_since: Specify this header value to operate only on a blob if it\n has not been modified since the specified date/time.\n :paramtype source_if_unmodified_since: ~datetime.datetime\n \"\"\"\n super(SourceModifiedAccessConditions, self).__init__(**kwargs)\n self.source_if_match = kwargs.get('source_if_match', None)\n self.source_if_none_match = kwargs.get('source_if_none_match', None)\n self.source_if_modified_since = kwargs.get('source_if_modified_since', None)\n self.source_if_unmodified_since = kwargs.get('source_if_unmodified_since', None)\n\n\nclass StorageError(msrest.serialization.Model):\n \"\"\"StorageError.\n\n :ivar error: The service error response object.\n :vartype error: ~azure.storage.filedatalake.models.StorageErrorError\n \"\"\"\n\n _attribute_map = {\n 'error': {'key': 'error', 'type': 'StorageErrorError'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword error: The service error response object.\n :paramtype error: ~azure.storage.filedatalake.models.StorageErrorError\n \"\"\"\n super(StorageError, self).__init__(**kwargs)\n self.error = kwargs.get('error', None)\n\n\nclass StorageErrorError(msrest.serialization.Model):\n \"\"\"The service error response object.\n\n :ivar code: The service error code.\n :vartype code: str\n :ivar message: The service error message.\n :vartype message: str\n \"\"\"\n\n _attribute_map = {\n 'code': {'key': 'Code', 'type': 'str'},\n 'message': {'key': 'Message', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n \"\"\"\n :keyword code: The service error code.\n :paramtype code: str\n :keyword message: The service error message.\n :paramtype message: str\n \"\"\"\n super(StorageErrorError, self).__init__(**kwargs)\n self.code = kwargs.get('code', None)\n self.message = kwargs.get('message', None)\n","sub_path":"sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_generated/models/_models.py","file_name":"_models.py","file_ext":"py","file_size_in_byte":36658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"199074738","text":"from flask import Flask, redirect, render_template, request, session, flash\nimport random\napp=Flask(__name__)\napp.secret_key=\"hello\"\n\n@app.route('/')\ndef home():\n session['somekey']=random.randrange(0,100)\n rand=session['somekey']\n return render_template('index.html', rand=session['somekey'])\n\n@app.route('/show', methods=['POST'])\ndef number():\n flag=0\n rand=session['somekey']\n #session['somekey']=random.randrange(0,100)\n guess=int(request.form['answer'])\n if(guess > session['somekey']):\n flash(\"Too High !!!\")\n elif(guess < session['somekey']):\n flash(\"Too low !!!\")\n else:\n flash(\"Exact Match !!!\")\n session.pop('somekey')\n flag=1\n return render_template('index.html',guess=guess,flag=flag,rand=rand)\n\napp.run(debug=True)\n","sub_path":"flask/numberGame/numbergame.py","file_name":"numbergame.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"7612773","text":"import selenium\nimport datetime\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(lineno)d - %(message)s')\n\n\n# todo: this should be an abstract class\nclass Browser:\n def __init__(self, browser):\n self.browser = browser\n\n # this method takes info from current browser location by css and puts it the given title obj\n # it can do both lists and single element\n def get_info(self, info, css_list, obj={}):\n if type(css_list) != list:\n css_list = [css_list]\n for css in css_list:\n try:\n new_info = list(self.browser.find_elements_by_css_selector(css))\n logging.debug(new_info)\n if len(new_info) == 1:\n obj[info] = new_info[0]\n return obj[info]\n obj[info] = []\n for i in new_info:\n obj[info].append(i.text)\n return obj[info]\n except selenium.common.exceptions.NoSuchElementException:\n logging.debug('warning: ' + info + ' not found')\n continue\n return None # if no info grabbed return None\n\n def update_object_info(self, obj, info_list):\n for info, css in info_list.items():\n self.get_info(info, css, obj)\n return obj\n\n # this takes a dictionary list with all the info we want to get to run everything in chunk\n # TODO: this method is currently not in use\n def make_info_object(self, info_list):\n # TODO: make objects using get info\n out = {}\n for info, css in info_list.items():\n self.get_info(info, css, out)\n return out\n\n # todo: this function is some pretty bad practise\n # uses function get_info to compile a list of similar elements on a\n # page as dictionary, input is a dictionary in the form {'info_label': 'css-selector'\n def get_resulting_list(self, info_list):\n out = []\n count = 0\n for info, css in info_list.items():\n results = self.get_info(info, css)\n if results is not None:\n count += 1\n if count == 1:\n for result in results:\n out.append({info: result})\n else:\n for i in range(len(out)):\n out[i][info] = results[i]\n return out\n\n def close_browser(self):\n self.browser.close()\n\n\n# checks if year is less than or equal to delta years old\ndef is_new(year, delta=1):\n year_now = datetime.datetime.now().year\n return (year_now - year) <= delta\n\n\n# todo: we should make this method more advanced\ndef check_title(title, other):\n # l1 = len(title)\n # l2 = len(other)\n # return title in other or other in title or title[:l1//2] in other or other[:l2//2] in title or similarity(title, other) >= 0.6\n return title is other or similarity(title, other) >= 0.65\n\n\n# what proportion of words of one title are contained in another title. If len is 0.5 difference returns 0\ndef similarity(title: str, other: str) -> float:\n proportion = len(title) / len(other)\n if proportion >= 2 or proportion <= 0.5:\n return 0.0\n title_elems = remove_chars(title)\n other_elems = remove_chars(other)\n title_elems = title_elems.split()\n other_elems = other_elems.split()\n count = 0\n if len(title_elems) == 1 and len(other_elems) == 1:\n for i in range(len(title)):\n if title[i] == other[i]:\n count += 1\n return count/len(title)\n # if count >= len(title) - 2:\n # return 1.0\n # return 0.0\n for elem in title_elems:\n if elem in other:\n count += 1\n\n # select the smaller size as the length\n size = len(title_elems)\n if size > len(other_elems):\n size = len(other_elems)\n logging.debug(count / size)\n return count / size\n\n\ndef remove_chars(string):\n string.replace(r\"'\", r'')\n string.replace(r\":\", r'')\n string.replace(r\"-\", r'')\n return string\n","sub_path":"dvd_reporter/scraper/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"114139203","text":"# from tkinter import *\nimport random\n\nfrom Lib.bcolors import bcolors\n\n\ndef StoryGenerator():\n print(bcolors.HEADER + \"Welcome to Story Generator\" + bcolors.ENDC)\n user_name = input(\"What is your Name: \")\n\n names = [\"Cliff\", \"Jenette\", \"Epifania\", \"Effie\", \"Bulah\", \"Albina\", \"Joeann\", \"Antonietta\", \"Kenda\", \"Raymon\",\n \"Jacquie\", \"Rubye\", \"Lenard\", \"Pedro\", \"Oretha\", \"Jacquetta\", \"Marcie\", \"Zoraida\"]\n places = [\"Kelley\", \"Suzi\", \"Vivian\", \"Mayme\", \"Jacki\", \"Conception\", \"Willy\", \"Ima\", \"Teodoro\", \"Dona\", \"Donn\",\n \"Earlene\", \"Patsy\", \"Irmgard\", \"Bridget\", \"Evie\", \"Elizebeth\", \"Melany\", \"Jessia\", \"Salina\"]\n species = [\"witch\", \"droid\", \"human\", \"Demon Lord\", \"ogre\"]\n\n work = [\"lawyer\", \"adventurer\", \"doctor\", \"healer\", \"war front leader\", \"war leader\", \"celebrity actor\"]\n\n randomname = random.choice(names)\n randomplaces = random.choice(places)\n randomspecies = random.choice(species)\n randomwork = random.choice(work)\n\n story1 = \"Hello \" + user_name + \"\\n\" + bcolors.BOLD + \"The Tale of a Young \" + randomspecies + bcolors.ENDC + \"\\n\"\n story2 = \"by \" + user_name + \"\\n \\n This is the story of a young \" + randomspecies + \" who goes by the name \"\n story3 = randomname + \". \\n He is loved by everyone in the city of \" + randomplaces + \".\" + \"He works as a \"\n story4 = randomwork + \". \\n\"\n\n print(story1 + story2 + story3 + story4)\n\n\n # app = Tk()\n #\n # # Nameofchar\n # part_text = StringVar()\n # part_label = Label(app, text='Name of the character', font=('bold', 14), pady=20)\n # part_label.grid(row=0, column=0)\n # enterName = Entry(app, textvariable=part_text)\n # enterName.grid(row=0, column=1)\n #\n # # Nameofchar\n # part_text = StringVar()\n # part_label = Label(app, text='Name of the characte r', font=('bold', 14), pady=20)\n # part_label.grid(row=1, column=0)\n # enterName = Entry(app, textvariable=part_text)\n # enterName.grid(row=1, column=1)\n #\n # # Nameofchar\n # part_text = StringVar()\n # part_label = Label(app, text='Name of the character', font=('bold', 14), pady=20)\n # part_label.grid(row=2, column=0)\n # enterName = Entry(app, textvariable=part_text)\n # enterName.grid(row=2, column=1)\n #\n # # Nameofchar\n # part_text = StringVar()\n # part_label = Label(app, text='Name of the character', font=('bold', 14), pady=20)\n # part_label.grid(row=3, column=0)\n # enterName = Entry(app, textvariable=part_text)\n # enterName.grid(row=3, column=1)\n #\n # app.title(\"Story Generator\")\n # app.geometry('600x300')\n #\n # app.mainloop()\n","sub_path":"EasyProjects/StoryGenerator.py","file_name":"StoryGenerator.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"239841387","text":"# -*- coding=utf8 -*-\n\ndef lambdaSolution(numRows):\n # P => Pascal function\n # i => inputValue\n P=lambda i:(lambda x:x+[[a+b for a,b in zip(x[-1]+[0],[0]+x[-1])]])(P(i-1))if i>1 else[[1]]\n return P(numRows)\n\ndef solution(numRows):\n solutions = []\n for i in range(numRows):\n # make all item value is 1\n answer = [1 for num in range(i+1)] \n # Because i start f rom 0\n # So j loop will run when i bigger then 1\n for j in range(1,i):\n preAnswer = solutions[i-1]\n answer[j] = preAnswer[j-1] + preAnswer[j]\n solutions.append(answer)\n\n return solutions\n\nif __name__ == \"__main__\":\n numRows = 10\n lambdaAnswer = lambdaSolution(numRows)\n answer = solution(numRows)\n \n print(lambdaAnswer)\n print(answer)\n","sub_path":"algothrism/118_PascalTriangle/PythonSolution.py","file_name":"PythonSolution.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"510238629","text":"\"\"\"\nPredicting the salary of employees\n==================================\n\nThe `employee salaries <https://catalog.data.gov/dataset/employee-salaries-2016>`_\ndataset contains information\nabout annual salaries (year 2016) for more than 9,000 employees of the \nMontgomery County (Maryland, US). In this example, we are interested\nin predicting the column *Current Annual Salary*\ndepending on a mix of clean columns and a dirty column.\nWe choose to benchmark different categorical encodings for\nthe dirty column *Employee Position Title*, that contains\ndirty categorical data.\n\n**Warning: this example is using the master branch of scikit-learn**\n\n\"\"\"\n\n################################################################################\n# Data Importing and preprocessing\n# --------------------------------\n#\n# We first download the dataset:\nfrom dirty_cat.datasets import fetch_employee_salaries\nemployee_salaries = fetch_employee_salaries()\nprint(employee_salaries['description'])\n\n################################################################################\n# Then we load it:\nimport pandas as pd\ndf = pd.read_csv(employee_salaries['path']).astype(str)\n\n################################################################################\n# Now, let's carry out some basic preprocessing:\ndf['Current Annual Salary'] = df['Current Annual Salary'].str.strip('$').astype(\n float)\ndf['Date First Hired'] = pd.to_datetime(df['Date First Hired'])\ndf['Year First Hired'] = df['Date First Hired'].apply(lambda x: x.year)\n\ntarget_column = 'Current Annual Salary'\ny = df[target_column].values.ravel()\n\n#########################################################################\n# Choosing columns\n# -----------------\n# For categorical columns that are supposed to be clean, it is \"safe\" to\n# use one hot encoding to transform them:\n\nclean_columns = {\n 'Gender': 'one-hot',\n 'Department Name': 'one-hot',\n 'Assignment Category': 'one-hot',\n 'Year First Hired': 'numerical'}\n\n#########################################################################\n# We then choose the categorical encoding methods we want to benchmark\n# and the dirty categorical variable:\n\nencoding_methods = ['one-hot', 'target', 'similarity']\ndirty_column = 'Employee Position Title'\n#########################################################################\n\n\n#########################################################################\n# Creating a learning pipeline\n# ----------------------------\n# The encoders for both clean and dirty data are first imported:\n\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom dirty_cat import SimilarityEncoder, TargetEncoder\n\nencoders_dict = {\n 'one-hot': OneHotEncoder(handle_unknown='ignore', sparse=False),\n 'similarity': SimilarityEncoder(similarity='ngram',\n handle_unknown='ignore'),\n 'target': TargetEncoder(handle_unknown='ignore'),\n 'numerical': FunctionTransformer(None)}\n\n# We then create a function that takes one key of our ``encoders_dict``,\n# returns a pipeline object with the associated encoder,\n# as well as a Scaler and a RidgeCV regressor:\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n\n\ndef make_pipeline(encoding_method):\n # static transformers from the other columns\n transformers = [(enc + '_' + col, encoders_dict[enc], [col])\n for col, enc in clean_columns.items()]\n # adding the encoded column\n transformers += [(encoding_method, encoders_dict[encoding_method],\n [dirty_column])]\n pipeline = Pipeline([\n # Use ColumnTransformer to combine the features\n ('union', ColumnTransformer(\n transformers=transformers,\n remainder='drop')),\n ('scaler', StandardScaler(with_mean=False)),\n ('clf', RidgeCV())\n ])\n return pipeline\n\n\n#########################################################################\n# Fitting each encoding methods with a RidgeCV\n# --------------------------------------------\n# Eventually, we loop over the different encoding methods,\n# instantiate each time a new pipeline, fit it\n# and store the returned cross-validation score:\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import KFold, cross_val_score\nimport numpy as np\n\nall_scores = dict()\n\ncv = KFold(n_splits=5, random_state=12, shuffle=True)\nscoring = 'r2'\nfor method in encoding_methods:\n pipeline = make_pipeline(method)\n scores = cross_val_score(pipeline, df, y, cv=cv, scoring=scoring)\n print('{} encoding'.format(method))\n print('{} score: mean: {:.3f}; std: {:.3f}\\n'.format(\n scoring, np.mean(scores), np.std(scores)))\n all_scores[method] = scores\n\n#########################################################################\n# Plotting the results\n# --------------------\n# Finally, we plot the scores on a boxplot:\nimport seaborn\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(4, 3))\nax = seaborn.boxplot(data=pd.DataFrame(all_scores), orient='h')\nplt.ylabel('Encoding', size=20)\nplt.xlabel('Prediction accuracy ', size=20)\nplt.yticks(size=20)\nplt.tight_layout()\n\n\n\n","sub_path":"examples/02_predict_employee_salaries.py","file_name":"02_predict_employee_salaries.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"217190542","text":"# Created By: Virgil Dupras\n# Created On: 2007-10-06\n# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)\n\n# This software is licensed under the \"BSD\" License as described in the \"LICENSE\" file, \n# which should be included with this package. The terms are also available at \n# http://www.hardcoded.net/licenses/bsd_license\n\nimport logging\nimport time\nimport traceback\nimport subprocess\nimport sys\n\nimport objc\nfrom jobprogress.job import JobCancelled\nfrom jobprogress.performer import ThreadedJobPerformer as ThreadedJobPerformerBase\n\nfrom .inter import signature\nfrom .objcmin import (NSBundle, NSAutoreleasePool, NSObject, NSArray, NSDictionary,\n NSExceptionHandler, NSLogAndHandleEveryExceptionMask)\n\n\ndef report_crash(type, value, tb):\n mainBundle = NSBundle.mainBundle()\n app_identifier = mainBundle.bundleIdentifier()\n app_version = mainBundle.infoDictionary().get('CFBundleVersion', 'Unknown')\n s = \"Application Identifier: {0}\".format(app_identifier)\n s += \"\\nApplication Version: {0}\\n\\n\".format(app_version)\n s += ''.join(traceback.format_exception(type, value, tb))\n HSErrorReportWindow = mainBundle.classNamed_('HSErrorReportWindow')\n if HSErrorReportWindow is None:\n logging.error(s)\n return\n if app_identifier:\n s += '\\nRelevant Console logs:\\n\\n'\n p = subprocess.Popen(['grep', app_identifier, '/var/log/system.log'], stdout=subprocess.PIPE)\n try:\n s += str(p.communicate()[0], encoding='utf-8')\n except IndexError:\n # This can happen if something went wrong with the grep (permission errors?)\n pass\n HSErrorReportWindow.showErrorReportWithContent_(s)\n\nclass ThreadedJobPerformer(ThreadedJobPerformerBase):\n def _async_run(self, *args):\n pool = NSAutoreleasePool.alloc().init()\n target = args[0]\n args = tuple(args[1:])\n self._job_running = True\n self._last_error = None\n try:\n target(*args)\n except JobCancelled:\n pass\n except Exception:\n self._last_error = sys.exc_info()\n report_crash(*self._last_error)\n finally:\n self._job_running = False\n self.last_progress = None\n del pool\n \n\ndef as_fetch(as_list, as_type, step_size=1000):\n \"\"\"When fetching items from a very big list through applescript, the connection with the app\n will timeout. This function is to circumvent that. 'as_type' is the type of the items in the \n list (found in appscript.k). If we don't pass it to the 'each' arg of 'count()', it doesn't work.\n applescript is rather stupid...\"\"\"\n result = []\n # no timeout. default timeout is 60 secs, and it is reached for libs > 30k songs\n item_count = as_list.count(each=as_type, timeout=0)\n steps = item_count // step_size\n if item_count % step_size:\n steps += 1\n logging.info('Fetching %d items in %d steps' % (item_count, steps))\n # Don't forget that the indexes are 1-based and that the upper limit is included\n for step in range(steps):\n begin = step * step_size + 1\n end = min(item_count, begin + step_size - 1)\n if end > begin:\n result += as_list[begin:end](timeout=0)\n else: # When there is only one item, the stupid fuck gives it directly instead of putting it in a list.\n result.append(as_list[begin:end](timeout=0))\n time.sleep(.1)\n logging.info('%d items fetched' % len(result))\n return result\n\ndef install_exception_hook():\n if '_exceptionHandlerDelegate' in globals():\n # already installed\n return\n def isPythonException(exception):\n return (exception.userInfo() or {}).get('__pyobjc_exc_type__') is not None\n\n class PyObjCExceptionDelegate(NSObject):\n @signature('c@:@@I')\n def exceptionHandler_shouldLogException_mask_(self, sender, exception, aMask):\n if exception.name() == 'NSAccessibilityException':\n return False # These kind of exception are really weird and happen all the time with VoiceOver on.\n if isPythonException(exception):\n userInfo = exception.userInfo()\n type = userInfo['__pyobjc_exc_type__']\n value = userInfo['__pyobjc_exc_value__']\n tb = userInfo.get('__pyobjc_exc_traceback__', [])\n report_crash(type, value, tb)\n return True\n \n @signature('c@:@@I')\n def exceptionHandler_shouldHandleException_mask_(self, sender, exception, aMask):\n return False\n \n # we need to retain this, cause the handler doesn't\n global _exceptionHandlerDelegate\n delegate = PyObjCExceptionDelegate.alloc().init()\n NSExceptionHandler.defaultExceptionHandler().setExceptionHandlingMask_(NSLogAndHandleEveryExceptionMask)\n NSExceptionHandler.defaultExceptionHandler().setDelegate_(delegate)\n _exceptionHandlerDelegate = delegate\n\ndef pythonify(o):\n \"\"\"Changes 'o' into a python class (pyobjc_unicode --> u'', NSDictionary --> {}, NSArray --> [])\n \"\"\"\n if o is None:\n return None\n elif isinstance(o, objc.pyobjc_unicode):\n return str(o)\n elif isinstance(o, (objc._pythonify.OC_PythonLong)):\n return int(o)\n elif isinstance(o, NSArray):\n return [pythonify(item) for item in o]\n elif isinstance(o, NSDictionary):\n return dict((pythonify(k), pythonify(v)) for k, v in list(o.items()))\n elif isinstance(o, (bool, int, list, dict, str)):\n return o # already pythonified\n logging.warning('Could not pythonify {0} (of type {1}'.format(repr(o), type(o)))\n return o\n","sub_path":"hscommon/cocoa/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"197677275","text":"from toolkit.util import isPalindrome\nfrom toolkit.digits import reverse\n\ndef isLychrel(n):\n for i in xrange(51): \n n = n + reverse(n)\n if isPalindrome(n):\n return False\n return True\n \ndef countLychrels(n):\n count = 0\n for i in xrange(n):\n if isLychrel(i):\n count += 1\n return count\n\nprint(countLychrels(10000))\n","sub_path":"python/problems/055/ep055.py","file_name":"ep055.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"178473083","text":"# 4. Реализуйте базовый класс Car.\n# У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).\n# А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда).\n# Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar.\n# Добавьте в базовый класс метод show_speed, который должен показывать текущую скорость автомобиля.\n# Для классов TownCar и WorkCar переопределите метод show_speed.\n# При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение о превышении скорости.\n# Создайте экземпляры классов, передайте значения атрибутов. Выполните доступ к атрибутам, выведите результат.\n# Выполните вызов методов и также покажите результат.\n\nclass Car:\n\n def __init__(self, name, color, speed, is_police=False):\n self.name = name\n self.color = color\n self.speed = speed\n self.is_police = is_police\n print(f\"It's a new car: {self.name} цветом {self.color}. Police: {self.is_police}\")\n\n def go(self):\n print(f\"{self.name}: Машина поехала!\")\n\n def stop(self):\n print(f\"{self.name}: Машина остановилась!\")\n\n def turn(self, direction=\"somewhere\"):\n if direction == \"right\":\n print(f\"{self.name}: Машина повернула направо!\")\n elif direction == \"left\":\n print(f\"{self.name}: Машина повернула налево!\")\n else:\n print(f\"{self.name}: Машина повернула в неизвестном направлении!\")\n\n def show_speed(self):\n print(f'{self.name}: скорость {self.speed}.')\n\nclass TownCar(Car):\n\n def show_speed(self):\n print(f'{self.name}: скорость {self.speed}.', end=\" \")\n if self.speed > 60:\n print(f\"Превышение скорости!\")\n\nclass WorkCar(Car):\n\n def show_speed(self):\n print(f'{self.name}: скорость {self.speed}.', end=\" \")\n if self.speed > 40:\n print(f\"Превышение скорости!\")\n\nclass PoliceCar(Car):\n\n def __init__(self, name, color, speed, is_police=True):\n super().__init__(name, color, speed, is_police)\n\nclass SportCar(Car):\n #\n # def show_speed(self):\n # print(f\"Спортивной машине вcе можно! Скорость {self.speed}.\")\n pass\n\ntown_car = TownCar('Волга', 'черная', 75)\ntown_car.go()\ntown_car.show_speed()\ntown_car.turn(direction=\"left\")\ntown_car.stop()\n\npolice_car = PoliceCar('Другая', \"белая\", 120)\npolice_car.go()\npolice_car.turn(5)\n\nsport_car = SportCar(\"Красивая\", \"Красная\", 220)\nsport_car.show_speed()\n","sub_path":"Python_start/lesson_6/lesson_6.4.py","file_name":"lesson_6.4.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"306422227","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# created 2018/12/14 @Northrend\n# \n# Draw PR curve and F1 curve \n# Input CSV syntax:\n# \n# ImageID,PredLabel,PredScore,GTLabel\n# image_name_0.jpg,0,0.999988,1\n# image_name_1.jpg,1,0.999977,1\n# ...\n#\n\nfrom __future__ import print_function\nimport os,sys\nimport json\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot\n\n\nclass SyntaxErr(RuntimeError):\n def __init__(self, msg):\n self.msg = msg\n print(self.msg)\n\n\ndef is_positive(pred_score, threshold):\n if pred_score >= threshold:\n return True\n else:\n return False\n\n\ndef load_input_file(input_path):\n output_dic = dict()\n gt_labels = list()\n with open(input_path, 'r') as f:\n for idx,line in enumerate(f.readlines()):\n _split = line.strip().split(',')\n if len(_split) != 4:\n raise SyntaxErr('[SYNTAX ERR] line {}: {}'.format(idx+1, line))\n elif line.strip() == \"ImageID,PredLabel,PredScore,GTLabel\":\n continue\n try:\n output_dic[_split[0]] = dict()\n output_dic[_split[0]]['pred_label'] = int(_split[1])\n output_dic[_split[0]]['pred_score'] = round(float(_split[2]), 6)\n output_dic[_split[0]]['gt_label'] = int(_split[3])\n gt_labels.append(output_dic[_split[0]]['gt_label'])\n except:\n raise SyntaxErr('[SYNTAX ERR] line {}: {}'.format(idx+1, line))\n print('==> {} logs loaded.'.format(len(output_dic)))\n return output_dic, list(set(gt_labels))\n\n\ndef draw_2d_curve(lst_x, lst_y, save_path='./tmp.png', style='--r', xlabel='x', ylabel='y'):\n '''\n draw curves\n '''\n # pyplot.axis([0, 1, 0, 1])\n pyplot.plot(lst_x, lst_y, style, lw=1.5)\n pyplot.grid(True)\n pyplot.xlabel(xlabel)\n pyplot.ylabel(ylabel)\n pyplot.title('{}-{} Curve'.format(ylabel, xlabel))\n pyplot.savefig(save_path)\n pyplot.close() # release cache, or next picture will get fucked\n\n\ndef calculate_pr_curve(dict_log, positive_label):\n '''\n calculate list of precision and recall values, for one given class\n '''\n lst_precision, lst_recall, lst_f1, lst_threshold = list(), list(), list(), list()\n for i in xrange(1, 100):\n threshold = float(i) / 100 # not 0.01*i\n tp, fp, fn = 0, 0, 0\n lst_threshold.append(threshold)\n for image in dict_log:\n if dict_log[image]['pred_label'] == positive_label == dict_log[image]['gt_label'] and is_positive(dict_log[image]['pred_score'], threshold):\n tp += 1\n elif dict_log[image]['pred_label'] == positive_label != dict_log[image]['gt_label'] and is_positive(dict_log[image]['pred_score'], threshold): \n fp += 1\n elif (dict_log[image]['gt_label'] == positive_label == dict_log[image]['pred_label'] and not is_positive(dict_log[image]['pred_score'], threshold)) or (dict_log[image]['gt_label'] == positive_label != dict_log[image]['pred_label']):\n fn += 1\n if (tp + fp) == 0 or (tp + fn) == 0: # eps\n fp, fn = float(1e-8), float(1e-8)\n lst_precision.append(float(tp) / (tp + fp))\n lst_recall.append(float(tp) / (tp + fn))\n lst_f1.append(float(2 * tp) / (2 * tp + fp + fn))\n # print(tp,fp,fn)\n return lst_precision, lst_recall, lst_f1, lst_threshold\n\n\ndef main():\n '''\n :params: /path/to/input.csv /path/to/folder/to/save/png/\n '''\n dummy, positive_labels = load_input_file(sys.argv[1])\n result_root_path = sys.argv[2]\n for positive_label in positive_labels:\n print('==> Processing label {} ...'.format(positive_label))\n # calculating pr and f1 list\n lst_precision, lst_recall, lst_f1, lst_threshold = calculate_pr_curve(dummy, positive_label)\n print('==> Drawing...')\n # set saving path\n pr_curve, f1_curve = os.path.join(result_root_path, 'pr-{}.png'.format(positive_label)), os.path.join(result_root_path, 'f1-{}.png'.format(positive_label))\n # save pr curve\n draw_2d_curve(lst_recall, lst_precision, save_path=pr_curve, xlabel='Recall', ylabel='Precision')\n print('==> PR curve saved as:', pr_curve)\n # save f1 curve\n draw_2d_curve(lst_threshold, lst_f1, save_path=f1_curve, xlabel='Threshold', ylabel='F1score')\n print('==> F1 curve saved as:', f1_curve)\n\nif __name__ == '__main__':\n main()\n print('==> done.')\n","sub_path":"draw_pr_curve.py","file_name":"draw_pr_curve.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"605233068","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom bs4 import BeautifulSoup\nimport time\nimport random\nimport re\nimport os\nimport datetime\nimport pandas as pd\n\nclass Dart():\n \"\"\"\n 기업 1 개당 1 instance\n 공시 정보 확인 및 특정 정보 내역 df로 추출 및 정리\n\n - 무결성이 보장됨\n 있는 정보는 확인할 필요 없음(틀리지 않음)\n 없는 정보는 확인 해봐야함\n \n ex) 주주명부는 [누가 무엇을 얼마나] 형식으로 \n 되어 있지 않다면 가져 올 수 없음\n\n - get은 정말 get 밖에 안해줌\n \n - WebDriverWait 또는\n time.sleep를 조정해서 감독 가능... \n <page_list의 경우 refresh 전에 감지 할때가 있어서 sleep 넣는게 좋음>\n\n - 사업보고서 크롤링 코드 미비\n 사업보고서가 나오는 기업의 경우 감사보고서 정보가 아주 예전일 수 있음!\n\n - 파크시스템즈 -> 파크시스템스(개선 알고리즘 구현 필요)\n\n - 전환청구권 행사의 경우 dfs[1] == 본문 으로 취급\n dummy + 정정보도에 대해 filter 필요\n\n - KISLINE의 대표 업체명 upchae_rap 에 넣어야함\n\n - 기한 설정 함수 만들어야함\n\n - 엑셀에 적을때 fillna 해주자\n\n - mul_col_index_fix\n greedy 해서 내용까지 잡아 먹을 수 있음\n SH_list 주로 짤림\n \n - try error로 wrap 해줘서 사용\n\n - 확인코드\n k = list(self.dfs_dic.keys())\n self.dfs_dic[k[0]]\n \"\"\"\n\n #0계층\n def __init__(self, upmoo_name_clean, rep_of_upchae = '기입안됨', specifics=True):\n #variables\n self.upmoo_name_clean = upmoo_name_clean\n self.rep_of_upchae = rep_of_upchae\n self.url_dic = {'dart_root':'https://dart.fss.or.kr'\n ,'dart_search':'https://dart.fss.or.kr/dsab001/main.do'\n }\n self.dfs_dic = {} # deli:df ['dart_name', 'house_info', 'shares_info', 'notice_info', 'audit_info']\n self.delimeters = []\n self.dfs = [] # 1 df 씩\n\n self.candidate_counter = 0 #자꾸 에러나서 하드 코딩...\n self.specifics = specifics\n\n #actions\n self.start_driver()\n self.total_scan()\n \n self.driver.quit()\n \n \n #1계층\n def start_driver(self):\n #chrome driver dir check\n #go to dart\n try:\n self.driver = webdriver.Chrome(\"./chromedriver.exe\")\n except:\n print(\"시스템>>> 현재 디렉토리: {}\".format(os.getcwd()))\n print(\"시스템>>> does this directory contain right version of chromedriver.exe? (Y)/(N): \")\n inp = input()\n if inp == 'N':\n print(\"시스템>>> 크롬드라이버가 있는 위치 입력...\")\n os.chdir(input())\n self.driver = webdriver.Chrome(\"./chromedriver.exe\")\n\n print(\"시스템>>> 드라이버를 실행 합니다...\")\n\n def total_scan(self):\n \"\"\"\n #해당 종목의 dart 정보 모두 스캔해\n #total_history_df = concat(주요사항,지분,거래소)\n #전환청구권 이외의 주권 및 리픽싱 관련 변동사항이 없는지 여기서 확인 필요\n #지분관련 공시는 게시자가 많음으로\n #관심pef 이름만 넣는걸로...\n \"\"\"\n print(\"시스템>>> {} 의 전체 공시자료를 살펴봅니다.\".format(self.upmoo_name_clean))\n \n self.driver.get(self.url_dic['dart_search'])\n\n #get and save\n self.save_dfs_dic(self.get_house_info())\n self.save_dfs_dic(self.get_shares_info())\n self.save_dfs_dic(self.get_notice_info())\n self.save_dfs_dic(self.get_audit_info())\n print(\"시스템>>> {} 의 모든 공시 사항 확인이 완료 되었습니다.\".format(self.upmoo_name_clean))\n print(\"시스템>>> openpyxl을 통해 엑셀에 자동 기입을 추천합니다.\")\n \n #2계층\n \n def get_house_info(self):\n \"\"\"\n get and return {deli:df,deli:df,...}\n \"\"\"\n print(\"시스템>>> {} 의 거래소 공시 사항을 확인합니다.\".format(self.upmoo_name_clean))\n\n #search\n self.basic_settings()\n\n self.driver.find_element('id','publicTypeButton_09').click()\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'total_choice9')))\n self.driver.find_element('id','total_choice9').click()\n self.driver.find_element('id','searchpng').click()\n time.sleep(1)\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'page_list')))\n\n #결과가 없다면 끝내\n page_list = self.get_page_list()\n if len(page_list) == 0:\n print(\"시스템>>> {} 의 거래소 공시 사항이 없습니다.\".format(self.upmoo_name_clean))\n return dict()\n\n #거래소 공시중 이미 시가에 반영된 사항들 filter\n #지분 사항 및 평가대상 증권과 관련 없는 내용들 filter\n #filtering\n filter_list = ['본점소재지변경','단일판매ㆍ공급계약체결','정기주주총회결과','매출액또는손익구조30%'\n ,'감사보고서제출','신규시설투자','주주총회소집결의','임시주주총회결과'\n ,'주주명부폐쇄기간또는기준일설정','기업설명회(IR)개최','주주총회집중일개최사유신고'\n ,'타법인주식및출자증권취득결정','유상증자또는주식관련사채등의청약결과(자율공시)'\n ,'본점소재지변경','주식명의개서정지(주주명부폐쇄)','행사가액결정','단일판매ㆍ공급계약해지'\n ,'연결재무제표기준영업(잠정)실적','유형자산취득결정','영업(잠정)실적','유형자산처분결정'\n ,'영업실적등에대한전망','장래사업ㆍ경영계획','기준가산정','반기검토(감사)보고서제출'\n ,'기타경영사항']\n filter_series = pd.Series(filter_list)\n\n page_list = page_list.loc[page_list.loc[:,'보고서명'].apply(lambda x: not any(filter_series.apply(lambda y: y in x)))]\n\n rights_info = self.get_rights_info(page_list)\n claim_info = self.get_claim_info(page_list)\n refixing_info = self.get_refix_info(page_list)\n\n #출력할 df 들 저장\n result = {}\n result['house_page_list'] = page_list\n result['house_rights_info'] = rights_info\n result['house_claim_info'] = claim_info[0]\n result['house_balance_info'] = claim_info[1]\n result['house_refixing_info'] = refixing_info\n return result\n \n def get_shares_info(self):\n print(\"시스템>>> {} 의 지분 공시 사항을 확인합니다.\".format(self.upmoo_name_clean))\n \n #search\n self.basic_settings()\n\n self.driver.find_element('id','publicTypeButton_04').click()\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'total_choice4')))\n self.driver.find_element('id','total_choice4').click()\n self.driver.find_element('id','searchpng').click()\n time.sleep(1)\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'page_list')))\n\n #결과가 없다면 끝내\n page_list = self.get_page_list()\n if len(page_list) == 0:\n print(\"시스템>>> {} 의 지분 공시 사항이 없습니다.\".format(self.upmoo_name_clean))\n return dict()\n\n if self.specifics:\n specific_info = self.get_specific_info()\n else:\n specific_info = pd.DataFrame(['정보 가져오려면','설정을 바꾸세요'],['설정','안함'])\n #출력할 df 들 저장\n result = {}\n result['shares_page_list'] = page_list\n result['shares_specific_info'] = specific_info\n return result\n\n def get_notice_info(self):\n print(\"시스템>>> {} 의 주요 공시 사항을 확인합니다.\".format(self.upmoo_name_clean))\n\n #search\n self.basic_settings()\n\n self.driver.find_element('id','publicTypeButton_02').click()\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'total_choice2')))\n self.driver.find_element('id','total_choice2').click()\n self.driver.find_element('id','searchpng').click()\n time.sleep(1)\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'page_list')))\n\n #결과가 없다면 끝내\n page_list = self.get_page_list()\n if len(page_list) == 0:\n print(\"시스템>>> {} 의 주요사항 공시 사항이 없습니다.\".format(self.upmoo_name_clean))\n return dict()\n\n #출력할 df 들 저장\n result = {}\n result['notice_page_list'] = page_list\n return result\n\n def get_audit_info(self):\n \"\"\"\n search upchae_name and return [list of reports, [most recent BS, IS, Capital Change, Shareholder List]]\n \"\"\"\n print(\"시스템>>> {} 의 감사보고 사항을 확인합니다.\".format(self.upmoo_name_clean))\n\n #search\n self.basic_settings()\n\n self.driver.find_element('id','publicTypeButton_06').click()\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'total_choice6')))\n self.driver.find_element('id','total_choice6').click()\n self.driver.find_element('id','searchpng').click()\n time.sleep(1)\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'page_list')))\n\n #결과가 없다면 끝내\n page_list = self.get_page_list()\n if len(page_list) == 0:\n print(\"시스템>>> {} 의 감사보고서 공시 사항이 없습니다.\".format(self.upmoo_name_clean))\n return dict()\n\n #첫 FS 에서 [list of reports, most recent BS, IS, Capital Change, Shareholder List] filtering \n viewer_main = self.url_dic['dart_root'] + page_list.loc[0,'links']\n rcpno,dcmno = self.get_rcp_dcm(viewer_main)\n\n self.driver.get(self.viewer_url(rcpno,dcmno))\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'section-1')))\n\n #공시자료 전체 검색\n dfs = pd.read_html(self.driver.page_source)\n audit_info = self.audit_filter(dfs)\n\n #출력할 df 들 저장\n #아주 예전인 경우 사업보고서 참조\n result = {}\n result['audit{}_page_list'.format(rcpno[:8])] = page_list\n result['audit{}_BS_info'.format(rcpno[:8])] = audit_info[0]\n result['audit{}_IS_info'.format(rcpno[:8])] = audit_info[1]\n result['audit{}_CC_info'.format(rcpno[:8])] = audit_info[2]\n result['audit{}_CF_info'.format(rcpno[:8])] = audit_info[3]\n result['audit{}_SH_info'.format(rcpno[:8])] = audit_info[4]\n return result\n\n\n #3계층\n\n def basic_settings(self):\n print(\"시스템>>> {} 검색을 위한 Dart 검색 환경을 세팅합니다.\".format(self.upmoo_name_clean))\n\n #search setting\n self.driver.get(self.url_dic['dart_search'])\n candidate_list = self.select_upchae_name()\n self.save_dfs_dic(candidate_list)\n\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'date7')))\n self.driver.find_element('id','date7').click()\n self.driver.find_element_by_xpath('//*[@id=\"maxResultsCb\"]/option[4]').click()\n\n def get_rights_info(self, page_list):\n \"\"\"\n 권리 행사에 관한 사항들 df\n \"\"\"\n print(\"시스템>>> {} 의 권리 행사 관련 정보를 수집합니다.\".format(self.upmoo_name_clean))\n return page_list.loc[page_list.loc[:,'보고서명'].apply(lambda x: '권행사' in x),:]\n\n def get_claim_info(self, page_list, balance=True):\n \"\"\"\n 청구 관련 정보들 수집\n 현재 : '전환청구권행사' 로만 검색 중\n 무결성을 위한 balance 도 제공\n\n return [df_claim, df_balance]\n \"\"\"\n print(\"시스템>>> {} 의 전환청구권 행사 관련 정보를 수집합니다.\".format(self.upmoo_name_clean))\n\n claim_dfs = page_list.loc[page_list.loc[:,'보고서명'].apply(lambda x: '전환청구권행사' in x),:]\n df_claim = pd.DataFrame()\n df_balance = pd.DataFrame()\n\n for i in claim_dfs.index:\n self.driver.get(self.url_dic['dart_root'] + claim_dfs.loc[i,'links'])\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'ifrm')))\n time.sleep(0.2)\n\n self.driver.switch_to.frame('ifrm')\n dfs = pd.read_html(self.driver.page_source)\n\n #정정보도인 경우 dfs[1] -> dfs[4]로 밀림\n body_df_idx = 1\n if '정정일자' in dfs[0].to_string():\n body_df_idx = 4\n\n #전체 내역인 dfs[0]은 필요 없고 일별만 parsing\n df_claim = pd.concat([df_claim, self.mul_col_idx_fix(dfs[body_df_idx])])\n\n #유효성 검사를 위해 잔액 확인\n #전환가능 주식수*전환가 + 기 SIGMGA(발행 주식수*전환가) = 항상 Total 과 같아야함\n if balance:\n df_balance = pd.concat([df_balance,self.mul_col_idx_fix(dfs[body_df_idx+1])])\n\n return [df_claim, df_balance]\n\n def get_refix_info(self, page_list):\n \"\"\"\n #조정 관련 내역 정보 수집\n #현재는 전환청구권만 가능\n \"\"\"\n print(\"시스템>>> {} 의 청구권 조정 관련 정보를 수집합니다\".format(self.upmoo_name_clean))\n print(\"시스템>>> 청구권 조정 관련 기능은 구현 되지 않았습니다 ㅠㅠ...\".format(self.upmoo_name_clean))\n\n pass \n \n def get_specific_info(self):\n \"\"\"\n #게시자 이름 받아서 하는편이 수월함\n #세부변동내역만 가져옴\n\n return df\n \"\"\"\n print(\"시스템>>> {} 의 주식등의대량보유상황 세부정보를 수집합니다.\".format(self.upmoo_name_clean))\n\n #전체검색 -> 주식등의대량보유상황보고서(일반)만 검색\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'total_choice4')))\n self.driver.find_element('id','total_choice4').click()\n time.sleep(0.5)\n self.driver.find_element('id','publicType20').click()\n time.sleep(0.5)\n self.driver.find_element('id','searchpng').click()\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'page_list')))\n\n page_list = self.get_page_list()\n if len(page_list) == 0:\n print(\"시스템>>> {} 의 주식등의대량보유상황 공시 사항이 없습니다.\".format(self.upmoo_name_clean))\n return dict()\n\n #누구의 history를 보고 싶은지 설정\n pef_name = input(str(set(page_list.loc[:,'제출인']))+' 중 검색 대상 제출인을 골라주세요')\n specific_df_concat = pd.DataFrame()\n\n for i in range(len(page_list)):\n if page_list.loc[i,'제출인'] == pef_name:\n self.driver.get(self.url_dic['dart_root'] + page_list.loc[i,'links'])\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"north\"]/div[2]/ul/li[1]/a/img')))\n time.sleep(1)\n\n viewer_main = self.url_dic['dart_root'] + page_list.loc[i,'links']\n rcp, dcm = self.get_rcp_dcm(viewer_main)\n self.driver.get(self.viewer_url(rcp, dcm))\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'section-1')))\n\n dfs = pd.read_html(self.driver.page_source)\n\n #세부변동내역만 필요\n\n specific_df = self.specific_filter(dfs)\n\n #이중 인덱싱 제거(세부변동내역 페이지는 어떤 종목이든 이중 인덱싱 존재)\n specific_df = self.mul_col_idx_fix(specific_df)\n specific_df_concat = pd.concat([specific_df_concat, specific_df])\n\n\n return specific_df_concat\n\n def get_page_list(self):\n \"\"\"\n page_list 가져옴 빈칸인 경우에는 blank df\n\n get Dart's 'page-list' of all searched results\n \"\"\"\n print(\"시스템>>> 검색 내용의 page_list를 수집합니다.\".format(self.upmoo_name_clean))\n\n page_list = pd.DataFrame()\n src = BeautifulSoup(self.driver.page_source,'lxml')\n page_list_src = src.find('div',{'class':'page_list'})\n for i in range(len(page_list_src.find_all('input',{'onclick':re.compile(r'search.+')})) - 1):\n self.driver.find_element_by_xpath('//*[@id=\"listContents\"]/div[2]/input[{}]'.format(i+1)).click()\n time.sleep(1)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'table_list')))\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'page_list')))\n \n src = BeautifulSoup(self.driver.page_source,'lxml')\n \n html_tb = src.findChildren('div','table_list')[0]\n\n #links\n links = []\n\n articles = html_tb.find_all(lambda x: x.has_attr('href') and x.has_attr('id'))\n for j in range(len(articles)):\n links.append(articles[j]['href'])\n # print('시스템>>>links에 {}가 삽입됨'.format(articles[j]['href']))\n\n page_list = pd.concat([page_list, \n pd.concat([pd.Series(links,name='links')\n , pd.read_html(str(html_tb))[0]]\n ,axis=1)])\n\n return page_list\n\n def audit_filter(self, dfs):\n \"\"\"\n '전체 공시 사항의 전체 표'를 입력받아\n '부채총계'가 들어가는 표 == 재무상태표\n 그 다음 표 == 손익계산서\n 그 다음 표 == 자본변동표\n\n 필요한 information == [누가[주주, 주주명, 구분], 얼마나[지분율, 지분비율], 무엇을[보통주]]\n return [BS,IS,CC,SH_list] or empty df\n \"\"\"\n print(\"시스템>>> audit 공시 자료 전체를 확인중입니다... \")\n #재무상태표 필터어\n bs_str = r'부[\\s\\t\\n]*채[\\s\\t\\n]*총[\\s\\t\\n]*계'\n\n #주주명부 필터어\n who = [r'주[\\s\\t\\n]*주[\\s\\t\\n]*',r'구[\\s\\t\\n]*분[\\s\\t\\n]*']\n what = [r'보[\\s\\t\\n]*통[\\s\\t\\n]*주[\\s\\t\\n]*',r'주[\\s\\t\\n]*식[\\s\\t\\n]*']\n how_much = [r'지[\\s\\t\\n]*분[\\s\\t\\n]*']\n\n ban_words_list = [r'종[\\s\\t\\n]*목[\\s\\t\\n]*',r'피[\\s\\t\\n]*투[\\s\\t\\n]*자[\\s\\t\\n]*',r'취[\\s\\t\\n]*득',r'원[\\s\\t\\n]*가']\n\n bs_df = None\n\n for i in range(len(dfs)):\n #bs\n if len(re.findall(bs_str,dfs[i].to_string())) != 0:\n bs_df = self.mul_col_idx_fix(dfs[i]).apply(lambda x: x.fillna('0'))\n \n #손익계산서, 자본변동표, 현금흐름표는 뒤에 세개 들고오자\n rest_dfs = []\n counter = 1\n while counter < 100:\n if len(dfs[i + counter]) > 4:\n rest_dfs.append(self.mul_col_idx_fix(dfs[i + counter]).apply(lambda x: x.fillna('0')))\n if len(rest_dfs) > 2:\n break\n counter += 1\n \n yes_words = []\n for yes in [who, what, how_much]:\n yess = []\n for _ in yes:\n yess.append((len(re.findall(_,dfs[i].to_string())) != 0))\n yes_words.append(any(yess))\n\n ban_words = []\n for ban_word in ban_words_list:\n ban_words.append((len(re.findall(ban_word,dfs[i].to_string())) != 0))\n \n if (all(yes_words) and (not any(ban_words))):\n holders_df = self.mul_col_idx_fix(dfs[i].apply(lambda x: x.fillna('0')))\n break\n\n #이거 앞줄로 가면... 에러 나던데... 왜지?\n if str(bs_df) == 'None':\n bs_df, rest_dfs, holders_df = pd.DataFrame(), [pd.DataFrame(),pd.DataFrame(), pd.DataFrame()], pd.DataFrame()\n\n return [bs_df,rest_dfs[0],rest_dfs[1],rest_dfs[2],holders_df]\n\n\n #4계층\n\n def select_upchae_name(self):\n \"\"\"\n 현실... : 제일 위에 값\n 이상적 : max(['기타법인','코스닥시장','유가증권시장'])\n\n 선택 업체 정보 반환으로 맞는지 확인\n return {'candidates': df}\n \"\"\"\n print(\"시스템>>> 업체를 선택중입니다.\")\n\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.ID, 'btnOpenFindCrp')))\n # print('이거 하고 끊어지는것 같은데?')\n self.driver.find_element_by_id('btnOpenFindCrp').click()\n\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'x-window-mc')))\n time.sleep(0.5)\n self.driver.find_elements_by_id('textCrpNm')[1].send_keys(self.basic_strip(self.upmoo_name_clean, space=False))\n self.driver.find_elements_by_id('textCrpNm')[1].send_keys(Keys.ENTER)\n time.sleep(1)\n\n #검색 목록 확인\n src = BeautifulSoup(self.driver.page_source,'lxml')\n result = pd.read_html(src.find_all('div',{'id':'ext-comp-1002'})[0].prettify())\n result[0].loc[0,:] = result[1].loc[0,:].to_list()\n\n #검색 결과 없으면 종료\n if result[0].iloc[0,0] == '일치하는 회사명이 없습니다.':\n print(\"시스템>>> Dart에는 {} 의 공시 자료가 없습니다.\".format(self.upmoo_name_clean))\n print(\"시스템>>> 검색을 종료합니다.\")\n self.driver.quit()\n return dict()\n\n #선택 및 확인\n self.driver.find_elements_by_id('checkCorpSelect')[0].click()\n self.driver.find_element_by_xpath('//*[@id=\"corpListContents\"]/div/fieldset/div[3]/a[1]/img').click()\n time.sleep(0.5)\n\n if self.candidate_counter == 0:\n print(\"시스템>>> {} 업종의 '{}'(대표자: {},KISLINE: {})가 선택되었습니다.\".format(result[0].loc[0,'업종명'],result[0].loc[0,'회사명'],result[0].loc[0,'대표자명'],self.rep_of_upchae))\n self.candidate_counter += 1\n\n self.candidates = result[0]\n\n return {'candidates': result[0]}\n\n def check_null(self, deli, df):\n \"\"\"\n input : deli, df\n \"\"\"\n content = (len(df) > 0)\n print(\"시스템>>> {} 의 자료 여부가 {} 입니다.\".format(deli, content))\n return content\n\n def save_dfs_dic(self, _dic):\n \"\"\"\n dic0 == {deli:df,deli:df,...} of 'need to save'들 받아서 \n 하나씩 편성 여부 확인 후 저장\n \"\"\"\n for deli in list(_dic.keys()): \n if not (deli in list(self.dfs_dic.keys())):\n self.delimeters.append(deli)\n self.dfs.append(_dic[deli])\n self.dfs_dic[deli] = _dic[deli]\n print(\"시스템>>> {} 정보 저장됨.\".format(deli))\n\n def viewer_url(self,rcpno,dcmno):\n return 'http://dart.fss.or.kr/report/viewer.do?rcpNo={}&dcmNo={}&eleId=1&offset=0&length=0&dtd=dart3.xsd'.format(rcpno,dcmno)\n\n def mul_col_idx_fix(self, df):\n \"\"\"\n erase overlapping columns until no overlapping neighbor appears\n case of 'mul_col1 in columns and mul_col2 at body', not considered\n multi-index solution needs to be added...\n \"\"\"\n # print(\"시스템>>> erasing multi_column \")\n if type(df.columns)==pd.core.indexes.multi.MultiIndex:\n df.columns = pd.DataFrame(df.columns).loc[:,0].apply(lambda x: x[-1])\n else:\n for i in range(len(df.index)):\n if df.iloc[i,0] == df.iloc[i+1,0]:\n continue\n else:\n #if first row of body is indeed a body... break\n if i == 0:\n break\n df_body = df.loc[i+1:,:]\n df_body.columns = df.loc[i,:]\n df = df_body\n break\n return df\n\n def get_rcp_dcm(self, viewer_main):\n \"\"\"\n input: report article's viewer_main_url\n return [rcpno, dcmno]\n \"\"\"\n self.driver.get(viewer_main)\n time.sleep(0.5)\n WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"north\"]/div[2]/ul/li[1]/a/img')))\n #안에 내용까지 쉬어야 하나???\n time.sleep(1)\n\n src = BeautifulSoup(self.driver.page_source,'lxml')\n print('시스템>>>소스코드 확보됨')\n rcpno, dcmno = re.findall(\"'[0-9]+'\",src.find_all('a',{'href':'#download'})[0]['onclick'])\n rcpno, dcmno = rcpno[1:-1], dcmno[1:-1]\n print('시스템>>>rcpnos에 {}가 삽입됨'.format(rcpno))\n print('시스템>>>dcmnos에 {}가 삽입됨'.format(dcmno))\n\n return [rcpno, dcmno]\n\n def basic_strip(self, with_zoo, space=True):\n result = re.sub(r'\\(.+?\\)','',with_zoo.replace('㈜','')).strip()\n if space:\n return result\n else:\n return result.replace('\\s','')\n\n def specific_filter(self, dfs):\n \"\"\"\n return filtered df for specifics search\n \"\"\"\n print('시스템>>>세부변동 내역 정보 조회 및 필터링 중...')\n distinct_col = ['성명(명칭)', '생년월일 또는사업자등록번호 등', '변동일*', '취득/처분방법', '주식등의종류', '변동전', '증감','변동후', '취득/처분단가**', '비 고']\n\n for df in dfs:\n for i in distinct_col:\n flag = 1\n if not (i in df.to_string()):\n flag = 0\n break\n if flag:\n specific_df = df\n return specific_df\n\n\n","sub_path":"dart_automation.py","file_name":"dart_automation.py","file_ext":"py","file_size_in_byte":26906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"370771302","text":"import pytest\nfrom selenium import webdriver\nimport selenium\nfrom selenium.webdriver import ChromeOptions, FirefoxOptions, IeOptions\n\n\nclass App:\n wd = None\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef session_fixture(request):\n print('\\nSession was started')\n\n browser = request.config.getoption(\"--browser\")\n #\n if browser == 'chrome':\n print(\"chrome will be started\")\n options = ChromeOptions()\n options.add_argument(\"--start-fullscreen\")\n options.add_argument('--headless')\n App.wd = webdriver.Chrome(options=options)\n\n elif browser == 'firefox':\n print(\"firefox will be started\")\n options = FirefoxOptions()\n options.add_argument(\"--start-fullscreen\")\n options.add_argument('--headless')\n App.wd = webdriver.Firefox(options=options)\n else:\n print(\"ie will be started\")\n options = IeOptions()\n options.add_argument(\"--start-fullscreen\")\n options.add_argument('--headless')\n App.wd = webdriver.Ie(options=options)\n #\n # #return wd\n\n def session_fin():\n App.wd.quit()\n print('\\nSesion was finished')\n #\n request.addfinalizer(session_fin)\n\n\n@pytest.fixture(scope=\"function\", autouse=False)\ndef test_fixture():\n return App.wd\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--browser\", action=\"store\", default=None,\n help=\"Enter browser\")\n\n","sub_path":"Lesson5/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"239638117","text":"import matplotlib.pyplot as plt\n\nlabel_list = ['64', '128', '256', '512'] # 横坐标刻度显示值\nlist_docker = [427, 439, 452, 476] # 纵坐标值1\nlist_fre = [18, 20, 21, 23] # 纵坐标值2\nx_label = \"Concurrent Operations\"\ny_label = \"Startup time(ms)\"\noutput = \"output/create_serial.png\"\nfz = 10\nx = range(len(list_docker))\n\nrects1 = plt.bar(x=x, height=list_docker, width=0.3, alpha=0.8, color='#BEBEBE', edgecolor='k', label=\"Docker\")\nrects2 = plt.bar(x=[i + 0.3 for i in x], height=list_fre, width=0.3, color='w', edgecolor='k', label=\"FRE\")\n\n# 编辑文本\nfor rect in rects1:\n height = rect.get_height()\n plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha=\"center\", va=\"bottom\", fontsize=fz)\nfor rect in rects2:\n height = rect.get_height()\n plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha=\"center\", va=\"bottom\", fontsize=fz)\n\nplt.xlabel(x_label, fontsize=fz)\nplt.ylabel(y_label, fontsize=fz)\nplt.xticks([index + 0.15 for index in x], label_list)\nplt.ylim(0, 600) # y轴取值范围\nplt.legend(fontsize=fz) # 设置题注\nplt.tick_params(labelsize=fz)\n\nplt.savefig(output, dpi=300, bbox_inches='tight')\nplt.close()\n","sub_path":"result/6.1-base/backup/create_serial.py","file_name":"create_serial.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"305129136","text":"#!/usr/bin/python3\n'''\n Backend webapi for the shylock program\n'''\nfrom bottle import Bottle, abort, static_file\nfrom cherrypy.wsgiserver import CherryPyWSGIServer\nfrom cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter\nfrom itertools import count\nfrom .bottle_helpers import webapi, picture\nfrom .postgres_helpers import Database\nfrom backend import Pool, MemberNotFoundError, NoneUniqueMemberError\n\n\nclass Server:\n\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.ssl_cert = 'cert.pem'\n self.ssl_key = 'privkey.pem'\n self._app = Bottle()\n self.pool_ids = count(0)\n self.pools = {} # with a simple count could be a list - but this supports any id's\n self.db = Database()\n\n def start(self, use_ssl):\n try:\n if use_ssl:\n CherryPyWSGIServer.ssl_adapter = BuiltinSSLAdapter(\n self.ssl_cert,\n self.ssl_key,\n None\n )\n server = CherryPyWSGIServer(\n (self.host, self.port),\n self._app,\n server_name='SplitPotAPI',\n numthreads=10\n )\n try:\n server.start()\n except KeyboardInterrupt:\n server.stop()\n else:\n self._app.run(host=self.host, port=self.port)\n finally:\n self.db.teardown()\n\n @property\n def pools_dict(self):\n return {pool_id: pool.__dict__ for pool_id, pool in self.pools.items()}\n\n @webapi('GET', '/')\n def home_page(self):\n return self.db.version\n\n @webapi('GET', '/v1/pools')\n def list_pools(self):\n return self.pools_dict\n\n @webapi('GET', '/v1/<pool_id>/members')\n def list_users(self, pool):\n return pool.members\n\n @webapi('GET', '/v1/<pool_id>/balances')\n def list_balances(self, pool):\n return {name: pool.balances.get(name, 0) for name in pool.members}\n\n @webapi('GET', '/v1/<pool_id>/transactions')\n def list_transactions(self, pool):\n return [\n '{0[spender]} spent {0[amount]} on {0[consumers]}'.format(transaction)\n for transaction in pool.old_transactions\n ]\n\n @webapi('POST', '/v1/pools')\n def create_new_pool(self, data):\n name = data.get('name')\n pool_id = str(next(self.pool_ids))\n self.pools[pool_id] = Pool(name)\n\n @webapi('POST', '/v1/users')\n def create_new_user(self, pool):\n pass\n # try:\n # username = data['name']\n # password = data['password']\n # except KeyError:\n # abort(400, 'POST data must contain both a username and a password')\n\n # err_code, msg = self.db.add_user(username, password)\n # if err_code is not None:\n # abort(err_code, msg)\n\n @webapi('POST', '/v1/<pool_id>/members')\n def add_pool_member(self, pool, data):\n name = data.get('name')\n try:\n pool.add_member(name)\n except NoneUniqueMemberError as err:\n abort(403, 'Duplicate names would be confusing and are not allowed')\n\n @webapi('POST', '/v1/<pool_id>/transactions')\n def create_new_transaction(self, pool, data):\n try:\n spender = data['spender']\n amount = data['amount']\n consumers = data['consumers']\n except KeyError:\n abort(400, 'Need a sender, and amount, and consumers')\n\n try:\n pool.add_transaction(spender, amount, consumers)\n except MemberNotFoundError as err:\n abort(404, 'No such member in this pool')\n\n @picture('/images/avatar')\n def avatar(self):\n return static_file('avatar.jpg', 'images')\n","sub_path":"api/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"410074776","text":"import sys\n\nif __name__ == '__main__':\n filename = \"input.txt\"\n if len(sys.argv) == 2:\n filename = sys.argv[1]\n\n with open(filename, \"r\") as read_file:\n for line in read_file:\n line = line.strip()\n if line.strip():\n for i in range(1, len(line)+1):\n if line[0:i] == line[i:2*i] and line.count(line[0:i]) * line[0:i] == line or i == len(line):\n print(i)\n break\n","sub_path":"easy/107-shortest-repetition/shortest_repetition.py","file_name":"shortest_repetition.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"101774158","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import print_function\nfrom decimal import *\nfrom config import *\n\nimport itertools\nimport copy\nimport subprocess\nimport struct\nimport sys\nimport random\nimport functools\nimport re\nimport sympy\nimport math\nimport logging\nimport path\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nlogging.basicConfig(format='%(levelname)s %(asctime)s : %(message)s', level=logging.INFO)\n\n\n# generate runable cpp file according to path, constrain and type\ndef generate_cpp(path_data, paths, implement_type='all'):\n\n if implement_type == 'all':\n generate_cpp(path_data, paths, 'float')\n generate_cpp(path_data, paths, 'real')\n return\n \n # according to different implement type, we should include different header files and use different things\n\n precision_setting = ''\n main_func = ''\n\n if implement_type == 'float':\n implement = FLOAT\n main_func += 'int main(){\\n'\n main_func += '\\tstd::fesetround(FE_DOWNWARD);\\n'\n #main_func += '\\tstd::fesetround(FE_DOWNWARD);\\n'\n precision_setting = implement['cout'] + ' << scientific << setprecision(numeric_limits<double>::digits10);\\n'\n\n elif implement_type == 'real':\n implement = REAL\n main_func += 'void compute(){\\n'\n main_func += '\\tstd::fesetround(FE_DOWNWARD);\\n'\n #main_func += '\\tstd::fesetround(FE_DOWNWARD);\\n'\n precision_setting = implement['cout'] + ' << setRwidth(45);\\n'\n\n main_func += '\\t' + precision_setting + '\\n'\n\n for var in path_data.get_variables():\n main_func += '\\t' + implement[path_data.get_variable_type(var)] + ' ' + var + ';\\n'\n main_func += '\\n'\n\n # 输入对应字符串变量声明\n # main_func += '//输入对应字符串变量声明\\n'\n main_func += '\\tstd::string ' + ','.join([iv + '_str' for iv in path_data.get_input_variables()]) + ';\\n'\n\n # 用户输入\n # main_func += '//用户输入\\n'\n main_func += '\\t' + implement['cin'] + ' >> ' + ' >> '.join([iv + '_str' for iv in path_data.get_input_variables()]) + ';\\n\\n'\n\n # 字符串变量转换为数值变量\n # main_func += '//字符串变量转换为数值变量\\n'\n for iv in path_data.get_input_variables():\n main_func += '\\t' + iv + ' = ' + TRANSFUNC[path_data.get_variable_type(iv)] + '(' + iv + '_str);\\n'\n main_func += '\\n'\n\n for path in paths:\n main_func += '\\tif(' + path.get_constrain() + '){\\n'\n for m in path.get_path_list():\n main_func += m.to_cpp_code(implement_type, indent=2)\n main_func += '\\t}\\n\\n'\n\n if implement == FLOAT:\n main_func += '\\t' + implement['cout'] + ' << double2binary(' + path_data.get_return_expr() + ') << \"\\\\n\";\\n'\n elif implement == REAL:\n main_func += '\\t' + implement['cout'] + ' << double2binary(' + path_data.get_return_expr() + '.as_double()) << \"\\\\n\";\\n'\n\n main_func += '}\\n'\n\n output_file = {'float': FLOATCPP, 'real': REALCPP}\n f = open(output_file[implement_type], 'w')\n print(implement['header'], file=f)\n print(main_func, file=f)\n\n# 将双精度浮点数转换为其二进制表示\ndef double2binary(d):\n return ''.join('{:0>8b}'.format(c) for c in struct.pack('!d', d))\n\n\n# 将整型转换为其二进制表示\ndef int2binary(i):\n return ''.join('{:0>8b}'.format(c) for c in struct.pack('!i', i))\n\n\n# 将二进制表示的双精度浮点数转换为数值形式\ndef binary2double(b):\n # print(b)\n return struct.unpack('d', struct.pack('Q', int('0b'+b, 0)))[0]\n\n\n# 将二进制表示表示的有符号整型转换为数值形式\ndef binary2int(b):\n return struct.unpack('i', struct.pack('I', int('0b'+b, 0)))[0]\n\n\n# 计算begin与end在双精度浮点数数轴上的距离,即中间隔间多少个浮点数+1\ndef double_distance(begin, end):\n\n if begin == end:\n return 0\n if end < begin:\n return double_distance(end, begin)\n if begin == 0:\n return int('0b'+double2binary(end), 0)\n if begin < 0 < end:\n return double_distance(0, -begin)+double_distance(0, end)\n if 0 < begin:\n return double_distance(0, end)-double_distance(0, begin)\n if end <= 0:\n return double_distance(0, -begin)-double_distance(0, -end)\n return 0\n\n\n# 计算两个有符号整型的距离\ndef int_distance(begin, end):\n return abs(begin-end)\n\n\n# 生成双精度浮点数d后面第offset个浮点数\ndef generate_double_by_offset(d, offset):\n if d == 0:\n if offset >= 0:\n return struct.unpack('d', struct.pack('Q', offset))[0]\n else:\n return -struct.unpack('d', struct.pack('Q', -offset))[0]\n if d > 0:\n return generate_double_by_offset(0, offset+double_distance(0, d))\n if d < 0:\n if offset >= double_distance(d, 0.0):\n return generate_double_by_offset(0.0, offset - double_distance(d, 0.0))\n else:\n return -generate_double_by_offset(0.0, double_distance(0.0, -d) - offset)\n\n\n# 生成随机的双精度浮点数\ndef generate_random_double(start=-sys.float_info.max, end=sys.float_info.max):\n# def generate_random_double(start=-0.9, end=-1.1):\n\n if start == end:\n return start\n if start > end:\n return generate_random_double(end, start)\n\n distance = double_distance(start, end)\n\n offset = random.randrange(distance)\n return generate_double_by_offset(start, offset)\n\n\n# 生成随机整型,默认c++ int范围\n# def generate_random_int(start=1, end=1100):\ndef generate_random_int(start=-2147483647, end=2147483647):\n if start > end:\n return generate_random_int(end, start)\n return random.randint(start, end)\n\n\n# 在point附近+-range范围内随机生成其他的点\ndef generate_random_point(point, rge):\n values = list()\n types = copy.copy(point.types)\n for i in range(point.dimension):\n if types[i] == 'decimal':\n d = binary2double(point.values[i])\n s = generate_double_by_offset(d, -rge)\n e = generate_double_by_offset(d, rge)\n values.append(double2binary(generate_random_double(s, e)))\n if types[i] == 'integer':\n i = binary2int(point.values[i])\n values.append(int2binary(generate_random_int(i-rge, i+rge)))\n return Point(values, types)\n\n\n# 计算两个二进制表示的浮点数的相对误差\ndef relative_error(irram_res, opt_res):\n irram = binary2double(irram_res)\n opt = binary2double(opt_res)\n if irram == 0:\n if opt == 0:\n return 0\n return float('inf')\n return abs((irram-opt)/irram)\n\n\n# 计算两个二进制表示的浮点数的比特误差\ndef bits_error(irram_res, opt_res):\n irram_double = binary2double(irram_res)\n opt_double = binary2double(opt_res)\n if math.isnan(opt_double) or math.isnan(irram_double):\n return 64\n distance = double_distance(irram_double, opt_double)\n if distance == 0:\n return 0\n return int(math.log2(distance)+1)\n\n\n# 生成两个浮点数的中位数mid,满足double_distance(left, mid) == double_distance(mid, right) +- 1\ndef get_middle_double(left, right):\n distance = double_distance(left, right)\n return generate_double_by_offset(left, int(distance/2))\n\n\n# 生成两个有符号整型的均值\ndef get_middle_int(left, right):\n return left + int((right-left)/2)\n\n\n# 生成两个输入点的中间的点\ndef get_middle_point(left, right):\n\n values = list()\n types = copy.copy(left.types)\n\n for i in range(len(types)):\n if types[i] == 'decimal':\n lv = binary2double(left.values[i])\n rv = binary2double(right.values[i])\n mv = get_middle_double(lv, rv)\n values.append(double2binary(mv))\n if types[i] == 'integer':\n lv = binary2int(left.values[i])\n rv = binary2int(right.values[i])\n mv = get_middle_int(lv, rv)\n values.append(int2binary(mv))\n\n return Point(values, types)\n\n\nclass Point:\n\n \"\"\"输入点封装类\"\"\"\n\n # values为一个list,双精度浮点数使用一个64位的01串来表示,整数类型即使用普通数值形式表示\n # types与values相对应,有'decimal'与'integer'两种类型\n def __init__(self, values, types):\n assert (len(values) == len(types) and \"Initialize point error, len(values) != len(types)\")\n self.dimension = len(values)\n self.values = values\n self.types = types\n\n def __str__(self):\n s = ''\n for i in range(self.dimension):\n if self.types[i] == 'decimal':\n s += '{:.25e}\\t'.format(binary2double(self.values[i]))\n if self.types[i] == 'integer':\n s += '{:0>10d}\\t'.format(binary2int(self.values[i]))\n return s\n\n def __eq__(self, other):\n if not isinstance(other, Point):\n return False\n if not self.dimension == other.dimension:\n return False\n return self.types == other.types and self.values == other.values\n\n def __hash__(self):\n return hash(' '.join(self.types) + ' ' + str(self))\n\n\n# 稳定性分析\ndef stable_analysis(path_data):\n\n paths = path_data.get_paths()\n input_variables = path_data.get_input_variables()\n\n points = list() # 输入点\n while len(points) < 300: # 300个随机输入\n\n values = list()\n types = list()\n for v in input_variables:\n t = path_data.get_variable_type(v)\n types.append(t)\n if t == 'decimal':\n values.append(double2binary(generate_random_double()))\n elif t == 'integer':\n values.append(int2binary(generate_random_int(1, 10000)))\n\n point = Point(values, types)\n\n # 排除不满足任意一条路径约束的输入\n constrains = [p.get_constrain() for p in paths]\n if not functools.reduce(lambda x, y: x or y, [satisfy(point, input_variables, c) for c in constrains]):\n continue\n\n logging.info(str(point))\n points.append(point)\n\n # 判断输入稳定性\n generate_cpp(path_data, paths) # 根据路径生成cpp文件\n subprocess.call(['make > /dev/null'], shell=True) # 编译\n\n point_stability_output = [(point, is_point_stable(point), real_output(point)) for point in points] # 所有输入点及其稳定性信息,结构:[(p1, True), (p2, False)... ]\n\n # 所有输入点按大小排序,按照输入点的第一个维度的大小\n point_stability_output = sorted(point_stability_output, key=lambda p: binary2double(p[0].values[0]) if p[0].types[0] == 'decimal' else (binary2int(p[0].values[0]) if p[0].types[0] == 'integer' else 0))\n\n for pso in point_stability_output:\n print(\"{}\\t{}\".format(str(pso[0]), str(pso[1])))\n\n # 对稳定性不同的相邻输入点进行进一步划分\n\n new_points = list() # 划分过程中新产生的输入点\n for i in range(len(point_stability_output)-1):\n\n # 相邻输入点稳定性不同,进一步划分\n if point_stability_output[i][1] != point_stability_output[i+1][1]:\n new_points.extend(divide_stable_unstable(point_stability_output, i))\n\n # 新产生的输入点加入并排序\n point_stability_output.extend(new_points)\n point_stability_output = sorted(point_stability_output, key=lambda p: binary2double(p[0].values[0]) if p[0].types[0] == 'decimal' else (binary2int(p[0].values[0]) if p[0].types[0] == 'integer' else 0))\n\n for pso in point_stability_output:\n print(\"{}\\t{}\".format(str(pso[0]), str(pso[1])))\n\n # 对相邻的稳定输入点进一步细化,一直细化到输入点的数量达到一定值\n points_enough = 500 # CONFIG\n while len(point_stability_output) < points_enough:\n\n print(\"points number \" + str(len(point_stability_output)))\n\n # 根据权重对相邻的稳定输入点进一步细化,权重主要取决于下述两个值\n w1 = list()\n w2 = list()\n\n # 相邻稳定输入点 p q, abs((real_output(p)-real_output(q))/(p-q))\n def weight_1(p, q):\n\n # 只考虑相邻的稳定输入点\n if (not p[1]) or (not q[1]):\n return 0\n\n delta_out = abs(binary2double(p[2])-binary2double(q[2]))\n delta_in = 1\n if p[0].types[0] == 'decimal':\n delta_in = abs(binary2double(p[0].values[0])-binary2double(q[0].values[0]))\n elif p[0].types[0] == 'integer':\n delta_in = abs(binary2int(p[0].values[0])-binary2int(q[0].values[0]))\n\n if delta_in == 0:\n delta_in = sys.float_info.min\n\n return delta_out/delta_in\n\n # 相邻稳定输入点距离权重\n def weight_2(p, q):\n\n # 只考虑相邻的稳定输入点\n if (not p[1]) or (not q[1]):\n return 0\n\n d = 0\n if p[0].types[0] == 'decimal':\n d = double_distance(binary2double(p[0].values[0]), binary2double(q[0].values[0]))\n elif p[0].types[0] == 'integer':\n d = int_distance(binary2int(p[0].values[0]), binary2int(q[0].values[0]))\n\n if d == 0:\n return 0\n\n return int(math.log2(d))/64\n\n w1 = [weight_1(point_stability_output[i], point_stability_output[i+1]) for i in range(len(point_stability_output)-1)]\n w2 = [weight_2(point_stability_output[i], point_stability_output[i+1]) for i in range(len(point_stability_output)-1)]\n\n # 归一化\n if max(w1) > 0:\n w1 = [w/max(w1) for w in w1]\n if max(w2) > 0:\n w2 = [w/max(w2) for w in w2]\n\n # 对应权重相加\n w = [sum(x) for x in zip(w1, w2)]\n\n # 最大权重下标\n max_weight_index = w.index(max(w))\n\n # 在该下标处细分\n point_stability_output = divide_stable_stable(point_stability_output, max_weight_index)\n\n for pso in point_stability_output:\n print(\"{}\\t{}\".format(str(pso[0]), str(pso[1])))\n\n return [(pso[0], pso[1]) for pso in point_stability_output]\n\n\n# 根据index对相邻的两个稳定性不同的输入点进一步划分,通过二分查找的方式大致定位稳定与不稳定的分界点,并将新产生的分界点返回\ndef divide_stable_unstable(point_stability_output, index):\n\n left_point = point_stability_output[index][0]\n right_point = point_stability_output[index+1][0]\n\n logging.info(\"divide stable unstable: {} --- {}\".format(str(left_point), str(right_point)))\n\n lsi = point_stability_output[index][1]\n rsi = point_stability_output[index+1][1]\n # assert (lsi != rsi and \"point stability array error!\")\n # can do return\n # if return, return []\n if lsi == rsi: return []\n\n mid_point = get_middle_point(left_point, right_point) # FIXME mid_point是有可能不在输入域上的,如何处理?\n\n # 相距1000个输入点认为足够近,退出循环,参数可调\n close_enough = 1000 # CONFIG\n\n while True:\n\n d = double_distance(binary2double(left_point.values[0]), binary2double(right_point.values[0]))\n print('L:', end='')\n print(left_point)\n print('M:', end='')\n print(mid_point)\n print('R:', end='')\n print(right_point)\n print('D::' + str(d))\n print('')\n\n if left_point.types[0] == 'decimal' and double_distance(binary2double(left_point.values[0]), binary2double(right_point.values[0])) < close_enough:\n break\n # 当前输入为整数的用例均为循环次数,因此这里设置的间隔较小\n if left_point.types[0] == 'integer' and int_distance(binary2int(left_point.values[0]), binary2int(right_point.values[0])) < 2:\n break\n\n msi = is_point_stable(mid_point)\n\n if msi == lsi:\n left_point = mid_point\n else:\n right_point = mid_point\n\n mid_point = get_middle_point(left_point, right_point) # FIXME 同上\n\n # 返回划分过程中新产生的点\n return [(left_point, lsi, real_output(left_point)), (right_point, rsi, real_output(right_point))]\n\n\n# 根据index对相邻的两个稳定的输入点形成的区间进行划分,去中点判定稳定性,稳定则将新的分界点加入到point_stability_output并返回,不稳定则使用divide_stable_unstable进一步划分\ndef divide_stable_stable(point_stability_output, index):\n\n left_point = point_stability_output[index][0]\n right_point = point_stability_output[index+1][0]\n\n logging.info(\"divide stable stable: {} --- {}\".format(str(left_point), str(right_point)))\n\n mid_point = get_middle_point(left_point, right_point)\n point_stability_output.insert(index+1, (mid_point, is_point_stable(mid_point), real_output(mid_point)))\n\n # 中点不稳定,细分\n if not point_stability_output[index+1][1]:\n\n new_points = list()\n new_points.extend(divide_stable_unstable(point_stability_output, index))\n new_points.extend(divide_stable_unstable(point_stability_output, index+1))\n\n # 新产生的输入点加入并排序\n point_stability_output.extend(new_points)\n point_stability_output = sorted(point_stability_output, key=lambda p: binary2double(p[0].values[0]) if p[0].types[0] == 'decimal' else (binary2int(p[0].values[0]) if p[0].types[0] == 'integer' else 0))\n\n return point_stability_output\n\n\n# 判断输入是否满足约束\ndef satisfy(point, variables, constrain):\n\n if constrain == 'true':\n return True\n\n values = list()\n for i in range(point.dimension):\n if point.types[i] == 'decimal':\n values.append(str(binary2double(point.values[i])))\n if point.types[i] == 'integer':\n values.append(str(binary2int(point.values[i])))\n\n stmt1 = ','.join(variables) + \" = sympy.symbols('\" + ' '.join(variables) + \"')\"\n exec(stmt1)\n\n stmt2 = 'constrain_expr=' + constrain\n\n stmt2 = re.sub(r'\\s+', '', stmt2) # 去空格\n stmt2 = re.sub(r'&&', '&', stmt2) # && -> &\n stmt2 = re.sub(r'\\|\\|', '|', stmt2) # || -> |\n stmt2 = re.sub(r'!', '~', stmt2) # ! -> ~\n\n # 加括号\n stmt2 = re.sub(r'=(.*?)([&|])', r'=(\\1)\\2', stmt2)\n stmt2 = re.sub(r'([&|])(.*?)([&|])', r'\\1(\\2)\\3', stmt2)\n stmt2 = re.sub(r'([&|])([^&|]*?)$', r'\\1(\\2)', stmt2)\n stmt2 = re.sub(r'~([^&|~]*)', r'~(\\1)', stmt2)\n\n exec(stmt2)\n\n stmt3 = 'constrain_expr.subs({' + ','.join([variables[i] + ':' + values[i] for i in range(len(values))]) + '})'\n\n return eval(stmt3)\n\n\n# 输入点在任意精度下输出,注意当前的real是否为对应的任意精度程序\ndef real_output(point):\n return subprocess.run(['./real'], stdout=subprocess.PIPE, input=' '.join(point.values), encoding='ascii').stdout\n\n\n# 判断输入点是否稳定,注意调用前必须保证对应路径已经生成可执行程序float与real\ndef is_point_stable(point):\n\n stable = True\n\n # 在稳定输入域与不稳定输入域的交界处,稳定输入点越靠近稳定输入域越密集,不稳定输入点越靠近不稳定输入域越密集\n # 因此,如果只通过单个点来判定稳定性有可能选取到不稳定输入域附近孤立的稳定点,这里采取的策略是在point附近多次采点,均稳定则稳定,出现不稳定则不稳定\n\n # 首先确认选取的点时稳定的\n float_res = subprocess.run(['./float'], stdout=subprocess.PIPE, input=' '.join(point.values), encoding='ascii').stdout\n real_res = subprocess.run(['./real'], stdout=subprocess.PIPE, input=' '.join(point.values), encoding='ascii').stdout\n if (float_res == '1111111111111000000000000000000000000000000000000000000000000000\\n' or\n float_res == '0111111111111000000000000000000000000000000000000000000000000000\\n') and len(real_res) == 0:\n return True\n bits_err = bits_error(real_res, float_res)\n if bits_err >= TOLERANCE:\n return False\n\n # 参数类型为整数时,直接以该点的稳定性作为判断依据\n if point.types[0] == \"integer\":\n return bits_err < TOLERANCE\n\n # 当前策略为+-50范围内选10个点,参数可调整\n points_num = 10 # CONFIG\n points_range = 50 # CONFIG\n\n count = 0\n for _ in range(points_num):\n\n # 距离50范围内采点\n random_point = generate_random_point(point, points_range)\n\n # logging.info('Call subprocess float with parameter {}'.format(' '.join(random_point.values)))\n float_res = subprocess.run(['./float'], stdout=subprocess.PIPE, input=' '.join(random_point.values), encoding='ascii').stdout\n # logging.info('Call subprocess real with parameter {}'.format(' '.join(random_point.values)))\n real_res = subprocess.run(['./real'], stdout=subprocess.PIPE, input=' '.join(random_point.values), encoding='ascii').stdout\n if (float_res == '1111111111111000000000000000000000000000000000000000000000000000\\n' or\n float_res == '0111111111111000000000000000000000000000000000000000000000000000\\n') and len(real_res) == 0:\n real_res = float_res\n bits_err = bits_error(real_res, float_res)\n # stable = (stable and (bits_err < TOLERANCE))\n if bits_err < TOLERANCE:\n count += 1\n else:\n count -= 1\n\n return count >= 4 # 稳定不稳定73开认为稳定,后续调整\n\n\n# added by whj\n\ndef generate_extreme_points(lower: list, upper: list) -> list:\n n = len(lower)\n ret_points = []\n ret_points.append([lower[0]])\n ret_points.append([upper[0]])\n for i in range(1, n):\n copy_points = copy.deepcopy(ret_points)\n for k in range(len(ret_points)):\n ret_points[k].append(lower[i])\n copy_points[k].append(upper[i])\n for p in copy_points:\n ret_points.append(p)\n return ret_points\n\n\ndef get_point_double_distance(pa: list, pb: list):\n assert(len(pa) == len(pb) and \"get_Euclidean_distance2 parameters error, points in different dimension!\")\n n = len(pa)\n res = 0.0\n for i in range(n):\n res += double_distance(pa[i], pb[i])\n return res\n\n\ndef point_c_in_space_of_a_and_b(a: list, b: list, c:list) -> list:\n assert(len(a) == len(b) and len(b) == len(c) and \"point_c_in_space_of_a_and_b parameters error, points in different dimension!\")\n n = len(a)\n\n def c_inside_the_ab(_a, _b, _c):\n return _a < _c < _b or _a > _c > _b\n\n inside = True\n for i in range(n):\n if not c_inside_the_ab(a[i], b[i], c[i]):\n inside = False\n break\n return inside\n\n\ndef get_middle_point_of_a_b(a: list, b: list) -> list:\n assert (len(a) == len(b) and \"get_middle_point_of_a_b parameters error, points in different dimension!\")\n n = len(a)\n c = [(a[i]/2 + b[i]/2) for i in range(n)]\n return c\n\n\ndef get_inside_point_area(a: list, b: list):\n assert (len(a) == len(b) and \"get_inside_point_area parameters error, points in different dimension!\")\n n = len(a)\n lower = [double2binary(min(a[i], b[i])) for i in range(n)]\n upper = [double2binary(max(a[i], b[i])) for i in range(n)]\n return lower, upper\n\n\nclass Points:\n num = 0\n extreme_point_num = 0\n point_list = []\n has_inside_point = [[]]\n distances = [[]]\n dimension = 1\n dimension_upper = []\n dimension_lower = []\n\n def __init__(self, _lower: list, _upper: list, _dimension=1):\n self.dimension = _dimension\n self.dimension_upper = [_upper[i] for i in range(_dimension)]\n self.dimension_lower = [_lower[i] for i in range(_dimension)]\n self.point_list = generate_extreme_points(self.dimension_lower, self.dimension_upper)\n self.num = len(self.point_list)\n self.extreme_point_num = self.num\n # True means there is points in points[i] and points[j], when i == j, it is True\n self.has_inside_point = [[(i == j) for i in range(self.num)] for j in range(self.num)]\n self.distances = [[get_point_double_distance(self.point_list[i], self.point_list[j]) for i in range(self.num)] for j in range(self.num)]\n\n def has_inside(self, i, j) -> bool:\n return self.has_inside_point[i][j]\n\n def set_inside(self, i, j, value):\n self.has_inside_point[i][j] = value\n self.has_inside_point[j][i] = value\n\n def get_distance(self, i, j):\n return self.distances[i][j]\n\n def get_point(self, i) -> list:\n return self.point_list[i]\n\n def add_point(self, _point: list):\n if len(_point) != self.dimension:\n assert False and \"add point with different dimension!\"\n self.point_list.append(_point)\n\n # add inside relationship\n for l in self.has_inside_point:\n l.append(False)\n self.has_inside_point.append([False for i in range(self.num + 1)])\n self.has_inside_point[self.num][self.num] = True\n for i in range(self.num):\n for j in range(self.num):\n if not self.has_inside(i, j) and point_c_in_space_of_a_and_b(self.point_list[i], self.point_list[j], _point):\n self.set_inside(i, j, True)\n if point_c_in_space_of_a_and_b(self.point_list[i], _point, self.point_list[j]):\n self.set_inside(i, self.num, True)\n elif point_c_in_space_of_a_and_b(self.point_list[j], _point, self.point_list[i]):\n self.set_inside(j, self.num, True)\n\n # add new point distance list\n self.distances.append([get_point_double_distance(_point, self.point_list[i]) for i in range(self.num)])\n for i in range(self.num):\n self.distances[i].append(self.distances[self.num][i])\n self.distances[self.num].append(0)\n\n self.num += 1\n\n def get_divide_points_idx(self):\n max_weight = 0\n max_i = -1\n max_j = -1\n for i in range(self.num):\n for j in range(self.num):\n if self.has_inside(i, j):\n continue\n w = self.get_distance(i, j)\n if w > max_weight:\n max_weight = w\n max_i = i\n max_j = j\n return max_i, max_j\n\n def get_connect_points(self, i):\n res = []\n for k in range(self.num):\n if not self.has_inside(i, k):\n res.append(k)\n return res\n\n def get_middle_point_of_ij(self, i, j) -> list:\n return get_middle_point_of_a_b(self.point_list[i], self.point_list[j])\n\ndef stable_analysis2(path_data, initial_points_file_name):\n\n paths = path_data.get_paths()\n input_variables = path_data.get_input_variables()\n\n points = list() # 输入点\n\n # read points from file\n initial_points_file = open(initial_points_file_name, 'r')\n for line in initial_points_file:\n if line == '\\n':\n continue\n values = line.split(' ')\n types = ['decimal' for i in range(len(values))]\n point = Point(values, types)\n logging.info(str(point))\n points.append(point)\n initial_points_file.close()\n\n # 判断输入稳定性\n generate_cpp(path_data, paths) # 根据路径生成cpp文件\n subprocess.call(['make > /dev/null'], shell=True) # 编译\n\n point_stability_output = [(point, is_point_stable(point), real_output(point)) for point in points] # 所有输入点及其稳定性信息,结构:[(p1, True), (p2, False)... ]\n\n # 所有输入点按大小排序,按照输入点的第一个维度的大小\n point_stability_output = sorted(point_stability_output, key=lambda p: binary2double(p[0].values[0]) if p[0].types[0] == 'decimal' else (binary2int(p[0].values[0]) if p[0].types[0] == 'integer' else 0))\n\n for pso in point_stability_output:\n print(\"{}\\t{}\".format(str(pso[0]), str(pso[1])))\n\n # put points into my container\n lower = [-1 for i in range(4)]\n upper = [1 for i in range(4)]\n ps = Points(lower, upper, 4)\n for pso in point_stability_output:\n point_str_list = str(pso[0]).split('\\t')\n point_str_list.pop()\n p = [float(f) for f in point_str_list]\n ps.add_point(p)\n print(ps.num)\n\n idx = 0\n areas = set()\n lower_bounds = []\n upper_bounds = []\n for pso in point_stability_output:\n if not pso[1]:\n con = ps.get_connect_points(idx + ps.extreme_point_num)\n for k in con:\n if k < ps.extreme_point_num:\n continue\n # k is unstable, and current point is unstable\n if point_stability_output[k - ps.extreme_point_num][1]:\n area = get_inside_point_area(ps.point_list[idx + ps.extreme_point_num], ps.point_list[k])\n lower_bounds.append(area[0])\n upper_bounds.append(area[1])\n area_str = \"lower:{},\\nupper:{},\".format(str(area[0]), str(area[1]))\n areas.add(area_str)\n idx += 1\n for a in areas:\n print(a)\n\n return lower_bounds, upper_bounds, [(pso[0], pso[1]) for pso in point_stability_output]\n # return [(pso[0], pso[1]) for pso in point_stability_output]\n\nif __name__ == \"__main__\":\n\n # pth = '../case/herbie/sqrtexp/sqrtexp.pth'\n pth = '../case/iRRAM/midarc/midarc_real.pth'\n # pth = '../case/herbie/2nthrt/2nthrt.pth'\n\n points = '../case/iRRAM/midarc/midarc_points.txt'\n\n # path_data = path.PathData(pth)\n\n # start = 0.1\n # end = 0.25\n #\n # N = 1000\n #\n # points = [[generate_random_double(0.1, 0.25)] for _ in range(N)]\n # points = sorted(points, key=lambda p: p[0])\n # points = [[double2binary(p[0])] for p in points]\n # for p in points:\n # print(binary2double(p[0]), end='\\t')\n # print(is_point_stable(p))\n\n # stable_analysis2(path_data, points)\n irram_bits = '1100001011111100011010111111010100100110001101000000000010010000'\n double_bits = '1100001011111111111111111111111111111111111111111111111111111010'\n opt_bits = '1100001011111100011010111111010100100110001100111111111111111100'\n input_str = '0100000100111000010111100100001101000010000110011111100100010000'\n print(bits_error(irram_bits, double_bits))\n print(bits_error(irram_bits, opt_bits))\n print(str(binary2double(input_str)))\n print(double2binary(10e14))\n\n\n\n\n","sub_path":"1/src/stableAnalysis.py","file_name":"stableAnalysis.py","file_ext":"py","file_size_in_byte":30230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"144872899","text":"\"\"\"\nweather_node\n\nContains the WeatherNode class\n\"\"\"\n\nimport json\nimport logging\nimport urllib.request\nfrom pubsub import pub\nfrom node import Node\n\nLOGGER = logging.getLogger(__name__)\n\nNODE_CLASS_NAME = 'WeatherNode'\n\nOPEN_WEATHER_MAP_URL = 'http://api.openweathermap.org/data/2.5/weather'\n\nclass WeatherNode(Node):\n \"\"\"\n WeatherNode\n\n Node providing an interface to weather data from openweathermap\n \"\"\"\n\n def __init__(self, label, state, config):\n \"\"\"\n Constructor\n \"\"\"\n Node.__init__(self, label, state, config)\n pub.subscribe(self.update_weather, f'{self.label}.update')\n\n def update_weather(self, msg=None):\n \"\"\"\n Helper function to send a request to openweathermap to get the\n weather for the default city.\n \"\"\"\n\n try:\n city = self.config['default_city']\n country = self.config['default_country']\n units = self.config['units']\n api_key = self.config['api_key']\n except KeyError as e:\n LOGGER.debug('Missing key for weather node config')\n raise e\n\n url = f'{OPEN_WEATHER_MAP_URL}?q={city},{country}&units={units}&appid={api_key}'\n\n response = urllib.request.urlopen(url)\n text_response = response.read().decode('utf-8')\n dict_response = json.loads(text_response)\n\n # transfrom API response into a key-value mapping\n description = dict_response['weather'][0]\n temp_pressure_humidity = dict_response['main']\n wind = dict_response['wind']\n\n weather = {\n 'description': description['description'],\n 'current_temp': float(temp_pressure_humidity['temp']),\n 'pressure': float(temp_pressure_humidity['pressure']),\n 'humidity': float(temp_pressure_humidity['humidity']),\n 'min_temp': float(temp_pressure_humidity['temp_min']),\n 'max_temp': float(temp_pressure_humidity['temp_max']),\n 'wind_speed': float(wind['speed']),\n 'wind_direction': int(wind['deg']),\n 'rain_volume': 0.0,\n 'snow_volume': 0.0\n }\n\n if 'rain' in dict_response:\n weather['rain_volume'] = float(dict_response['rain'])\n if 'snow' in dict_response:\n weather['snow_volume'] = float(dict_response['snow'])\n\n LOGGER.debug(weather)\n self.state.update_state(self.label, weather)\n","sub_path":"nodes/weather_node.py","file_name":"weather_node.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"29094360","text":"#coding=utf8\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nclass FNNModel(nn.Module):\r\n\r\n def __init__(self, infeats, outfeats, layers=[], dropout=0.5,\\\r\n nonlinear='relu', batchnorm=False, device=None):\r\n super(FNNModel,self).__init__()\r\n assert type(layers)==list\r\n self.num_layers=len(layers)\r\n self.dropout_layer=nn.Dropout(p=dropout)\r\n self.use_batchnorm = batchnorm\r\n self.nonlinear=nonlinear.lower() \r\n assert self.nonlinear in ['relu','sigmoid','tanh']\r\n linear_layer=[0]*(self.num_layers+1)\r\n if self.use_batchnorm:\r\n batchnorm_layer=[0]*self.num_layers\r\n for idx, hidden_size in enumerate(layers):\r\n linear_layer[idx]=nn.Linear(infeats, layers[idx])\r\n if self.use_batchnorm:\r\n batchnorm_layer[idx]=nn.BatchNorm1d(layers[idx])\r\n infeats=layers[idx]\r\n linear_layer[self.num_layers]=nn.Linear(infeats, outfeats)\r\n self.linear_layer=nn.ModuleList(linear_layer)\r\n if self.use_batchnorm:\r\n self.batchnorm_layer=nn.ModuleList(batchnorm_layer)\r\n self.device = device\r\n\r\n def init_weight(self, weight_scale=0.2):\r\n for each_layer in self.linear_layer:\r\n torch.nn.init.xavier_uniform_(each_layer.weight, weight_scale)\r\n torch.nn.init.constant_(each_layer.bias, 0)\r\n if self.use_batchnorm:\r\n for each_layer in self.batchnorm_layer:\r\n torch.nn.init.xavier_uniform_(each_layer.weight, weight_scale)\r\n torch.nn.init.constant_(each_layer.bias, 0)\r\n\r\n def forward(self, inputs):\r\n infeats = inputs\r\n for idx in range(self.num_layers):\r\n outfeats=self.linear_layer[idx](self.dropout_layer(infeats))\r\n if self.use_batchnorm:\r\n outfeats=self.batchnorm_layer[idx](outfeats)\r\n if self.nonlinear=='relu':\r\n infeats=F.relu(outfeats) \r\n elif self.nonlinear=='sigmoid':\r\n infeats=F.sigmoid(outfeats)\r\n elif self.nonlinear=='tanh':\r\n infeats=F.tanh(outfeats)\r\n else:\r\n infeats = outfeats # no non-linear activation\r\n scores = self.linear_layer[self.num_layers](self.dropout_layer(infeats))\r\n scores = F.log_softmax(scores, dim=-1) # batch_size, num_classes\r\n return scores\r\n\r\n def load_model(self, load_dir):\r\n if self.device.type == 'cuda':\r\n self.load_state_dict(torch.load(open(load_dir, 'rb')))\r\n else:\r\n self.load_state_dict(torch.load(open(load_dir, 'rb'), map_location=lambda storage, loc: storage))\r\n\r\n def save_model(self, save_dir):\r\n torch.save(self.state_dict(), open(save_dir, 'wb')) \r\n","sub_path":"models/fnn.py","file_name":"fnn.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"439008479","text":"\"\"\"Returns the edge label\ncontaining the specified string.\n\"\"\"\nfrom typing import Tuple, Any, Optional\n\nfrom networkx import MultiDiGraph\nfrom tqdm import tqdm\n\n__all__ = [\"find_label\"]\n\n\ndef find_label(\n graph: MultiDiGraph, query: str, verbose: bool = True\n) -> Optional[Tuple[Any, Any]]:\n \"\"\"Returns the edge label\n containing the specified string.\n\n Parameters\n ----------\n graph : MultiDiGraph\n Initial graph.\n\n query : str\n String to find.\n\n verbose : bool\n If true, a progress bar will be displayed.\n\n Examples\n --------\n >>> import cfpq_data\n >>> g = cfpq_data.graph_from_dataset(\"foaf\", verbose=False)\n >>> cfpq_data.find_label(g, \"subClassOf\", verbose=False)\n ('label', rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#subClassOf'))\n\n Returns\n -------\n response : Optional[Tuple[Any, Any]]\n Pair (``edge label key``, ``edge label value``)\n where ``edge label value`` contains ``query``.\n Not if the required ``edge label value`` is not found.\n \"\"\"\n res = None\n\n for _, _, edge_labels in tqdm(\n graph.edges(data=True), disable=not verbose, desc=\"Searching...\"\n ):\n for k, v in edge_labels.items():\n if query in str(v):\n res = (k, v)\n break\n\n return res\n","sub_path":"cfpq_data/graphs/utils/find_label.py","file_name":"find_label.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"447109890","text":"from sklearn.datasets import load_wine\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\n\n\ndef get_data():\n x, y = load_wine(return_X_y=True)\n names = load_wine().target_names\n\n X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3)\n\n modelo = RandomForestClassifier(n_estimators=100)\n modelo.fit(X_train, y_train)\n\n clase = modelo.predict(X_test)\n\n accuracy = metrics.accuracy_score(y_test, clase)\n\n presicion = metrics.precision_score(y_test, clase, average=None)\n\n recall = metrics.recall_score(y_test, clase, average=None)\n\n f1 = metrics.f1_score(y_test, clase, average=None)\n\n data = {\n \"accuracy\": accuracy,\n \"presicion\": presicion.tolist(),\n \"recall\": recall.tolist(),\n \"f1\": f1.tolist()\n }\n return data\n","sub_path":"analysis/scripts/wine/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"451245126","text":"# Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится\n# месяц (зима, весна, лето, осень). Напишите решения через list и через dict.\n\nnum_month = input('Введите номер интересующего вас месяца (от 1 до 12 включительно: ')\nnum_month = int(num_month) if num_month.isdigit() and 0 < int(num_month) < 13 else print('Введены некорректные данные')\n\n# Решение с помощью списка\n# winter = [1, 2, 12]\n# sprint = [3, 4, 5]\n# summer = [6, 7, 8]\n# fall = [9, 10, 11]\n#\n# if num_month in winter:\n# season = 'зима'\n# elif num_month in sprint:\n# season = 'весна'\n# elif num_month in summer:\n# season = 'лето'\n# else:\n# season = 'осень'\n\n# Решение с помощью словаря\nseasons = {\n 1: 'зима', 2: 'зима', 3: 'весна', 4: 'весна', 5: 'весна', 6: 'лето',\n 7: 'лето', 8: 'лето', 9: 'осень', 10: 'осень', 11: 'осень', 12: 'зима',\n}\n\nprint(f'Введенный месяц относится к времени года: {seasons[num_month]}')\n","sub_path":"python/base/dz_lesson2/lesson2_task3.py","file_name":"lesson2_task3.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"276559930","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.init as init\nimport torchvision.utils as vutils\nfrom torch.nn import functional as F\n\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\n\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\n\nimport utils\nfrom utils import Initializer\nfrom dataloader import load_data\n\nprint('Denpendencies Loaded')\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', type=str, default='mnist', help='select dataset')\nparser.add_argument('--dataroot', type=str, default='../data', help='path to dataset')\nparser.add_argument('--workers', type=int, default=4, help='number of data loading workers')\nparser.add_argument('--batchSize', type=int, default=32, help='input batch size')\nparser.add_argument('--imageSize', type=int, default=64, help='the height / width of the input image to network')\nparser.add_argument('--epochs', type=int, default=100, help='number of epochs to train for')\nparser.add_argument('--lr', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--out_dir', default='result', help='folder to output images and model checkpoints')\nparser.add_argument('--seed', type=int, default=7777, metavar='N', help='manual seed')\nparser.add_argument('--log-interval', type=int, default=100, help='how many batches to wait before logging')\nparser.add_argument('--setting', type=str, required=True, help='for saving purpose; e.g.) _test')\n\nargs = parser.parse_args()\ntorch.cuda.manual_seed(args.seed)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nblue = lambda x:'\\033[94m' + x + '\\033[0m'\n\n\ntrain_dataset, args = load_data(args, mode='train')\ntest_dataset, args = load_data(args, mode='test')\ntrain_loader = DataLoader(train_dataset, batch_size=args.batchSize,\n shuffle=True, num_workers=args.workers, pin_memory=True)\ntest_loader = DataLoader(test_dataset, batch_size=args.batchSize,\n shuffle=True, num_workers=args.workers, pin_memory=True)\nprint('Dataset Ready!')\n\n\n\nclass net(nn.Module):\n def __init__(self, args):\n super(net, self).__init__()\n self.args = args\n self.fc1 = nn.Linear(args.imageSize**2, 400)\n self.fc2_1 = nn.Linear(400, 20)\n self.fc2_2 = nn.Linear(400, 20)\n self.fc3 = nn.Linear(20, 400)\n self.fc4 = nn.Linear(400, args.imageSize**2)\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n def encode(self, x):\n x = self.relu(self.fc1(x))\n h1 = self.fc2_1(x)\n h2 = self.fc2_2(x)\n return h1, h2\n\n def reparam(self, mu, logvar):\n if self.training:\n std = logvar.mul(0.5).exp_()\n eps = Variable(std.data.new(std.size()).normal_())\n return eps.mul(std).add_(mu)\n else:\n return mu\n\n def decode(self, z):\n h3 = self.relu(self.fc3(z))\n h3 = self.sigmoid(self.fc4(h3))\n return h3\n\n def forward(self, x):\n mu, logvar = self.encode(x.view(-1, self.args.imageSize**2))\n z = self.reparam(mu, logvar)\n z = self.decode(z)\n return z, mu, logvar\n\n\n\n\nclass Ground(object):\n def __init__(self, args):\n self.args = args\n self.setting = os.path.basename(__file__)[:-3] + args.setting\n self.writer = SummaryWriter(log_dir='runs/'+self.setting)\n self.model = net(args).to(device)\n Initializer.initialize(model=self.model, init_method=init.xavier_normal_)\n\n self.optimizer = optim.Adam(self.model.parameters(), lr=args.lr, betas=(0.5,0.999))\n self.scheduler = optim.lr_scheduler.StepLR(self.optimizer, step_size=30)\n\n utils.mkdir(args.out_dir+'/'+self.setting)\n self.args.outdir = args.out_dir + '/' + self.setting\n\n def criterion(self, recon_x, x, mu, logvar):\n BCE = F.binary_cross_entropy(recon_x, x.view(-1, self.args.imageSize**2), size_average=False)\n KLD = 0.5*torch.sum(1+logvar-mu.pow(2)-logvar.exp())\n return (-KLD+BCE)\n\n def train(self, epoch):\n self.model.train()\n self.scheduler.step()\n train_loss = 0\n\n for batch_idx, (data, _) in enumerate(tqdm(train_loader)):\n data = Variable(data).to(device)\n self.optimizer.zero_grad()\n recon_batch, mu, logvar = self.model(data)\n loss = self.criterion(recon_batch, data, mu, logvar)\n loss.backward()\n self.optimizer.step()\n train_loss += loss.item()\n\n self.writer.add_scalar('train/loss', train_loss/len(train_loader), epoch)\n\n def test(self, epoch):\n self.model.eval()\n test_loss = 0\n\n for batch_idx, (data, _) in enumerate(tqdm(test_loader)):\n data = Variable(data).to(device)\n recon_batch, mu, logvar = self.model(data)\n loss = self.criterion(recon_batch, data, mu, logvar)\n test_loss += loss.item()\n\n self.writer.add_scalar('test/loss', test_loss/len(test_loader), epoch)\n\n sample = self.model.decode(Variable(torch.randn(self.args.batchSize, 20).to(device))).cpu()\n sample = sample.view(self.args.batchSize, self.args.in_channel, self.args.imageSize, self.args.imageSize)\n vutils.save_image(sample.data, '%s/sample_image_%03d.png' % (self.args.outdir, epoch), normalize=True)\n sample = vutils.make_grid(sample.data, normalize=True, scale_each=True)\n self.writer.add_image('sample_image', sample, epoch)\n\n\n def learn(self):\n epochs = self.args.epochs\n for epoch in tqdm(range(0, epochs)):\n self.train(epoch)\n self.test(epoch)\n\n\n\nif __name__ == \"__main__\":\n ground = Ground(args)\n ground.learn()\n\n\n\n\n","sub_path":"04_pytorch/03_vae.py","file_name":"03_vae.py","file_ext":"py","file_size_in_byte":5902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"557712544","text":"\"\"\"\nUtility classes for implementing task queues and sets.\n\"\"\"\n\n# standard libraries\nimport asyncio\nimport copy\nimport queue\nimport threading\n\n# third party libraries\n# None\n\n# local libraries\n# None\n\n\nclass TaskQueue(queue.Queue):\n\n def perform_tasks(self):\n # perform any pending operations\n qsize = self.qsize()\n while not self.empty() and qsize > 0:\n try:\n task = self.get(False)\n except queue.Empty:\n pass\n else:\n task()\n self.task_done()\n qsize -= 1\n\n def clear_tasks(self):\n # perform any pending operations\n qsize = self.qsize()\n while not self.empty() and qsize > 0:\n try:\n task = self.get(False)\n except queue.Empty:\n pass\n else:\n self.task_done()\n qsize -= 1\n\n\n# keeps a set of tasks to do when perform_tasks is called.\n# each task is associated with a key. overwriting a key\n# will discard any task currently associated with that key.\nclass TaskSet(object):\n def __init__(self):\n self.__task_dict = dict()\n self.__task_dict_mutex = threading.RLock()\n def add_task(self, key, task):\n with self.__task_dict_mutex:\n self.__task_dict[key] = task\n def clear_task(self, key):\n with self.__task_dict_mutex:\n if key in self.__task_dict:\n self.__task_dict.pop(key, None)\n def perform_tasks(self):\n with self.__task_dict_mutex:\n task_dict = copy.copy(self.__task_dict)\n self.__task_dict.clear()\n for task in task_dict.values():\n task()\n\n\ndef close_event_loop(event_loop: asyncio.AbstractEventLoop) -> None:\n # give event loop one chance to finish up\n event_loop.stop()\n event_loop.run_forever()\n # wait for everything to finish, including tasks running in executors\n # this assumes that all outstanding tasks finish in a reasonable time (i.e. no infinite loops).\n all_tasks_fn = getattr(asyncio, \"all_tasks\", None)\n if not all_tasks_fn:\n all_tasks_fn = asyncio.Task.all_tasks\n tasks = all_tasks_fn(loop=event_loop)\n if tasks:\n gather_future = asyncio.gather(*tasks, return_exceptions=True)\n else:\n # work around bad design in gather (always uses global event loop in Python 3.8)\n gather_future = event_loop.create_future()\n gather_future.set_result([])\n event_loop.run_until_complete(gather_future)\n # due to a bug in Python libraries, the default executor needs to be shutdown explicitly before the event loop\n # see http://bugs.python.org/issue28464 . this bug manifests itself in at least one way: an intermittent failure\n # in test_document_controller_releases_itself. reproduce by running the contents of that test in a loop of 100.\n _default_executor = getattr(event_loop, \"_default_executor\", None)\n if _default_executor:\n _default_executor.shutdown()\n event_loop.close()\n","sub_path":"nion/utils/Process.py","file_name":"Process.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"469567642","text":"def linear_search(arr, target):\n # Your code here\n for i in range(len(arr)):\n if arr[i] == target:\n return i\n\n return -1 # not found\n\ndef re_linear_search(arr, target, cur=0):\n if cur == len(arr): return -1\n\n if target == arr[cur]: return cur\n\n return re_linear_search(arr, target, cur+1)\n\n\n# Write an iterative implementation of Binary Search\ndef binary_search(arr, target):\n\n # Your code here\n l = 0\n r = len(arr)-1\n\n while r >= l:\n\n middex = ((r - l) // 2) + l\n\n if target == arr[middex]:\n return middex\n \n elif target > arr[middex]:\n l = middex + 1\n\n elif target < arr[middex]:\n r = middex - 1\n\n return -1 # not found\n\n# we perform an in place search so as to preserve the array's entirety for returning the target's index\ndef re_binary_search(arr, target, l=0, r=0):\n if not len(arr): return -1\n \n middex = (r - l) // 2 + l\n if target == arr[middex]: return middex\n\n elif target > arr[middex]:\n l=middex + 1\n if l <= r:\n return re_binary_search(arr, target, l=l, r=r)\n else:\n return -1\n elif target < arr[middex]:\n r=middex - 1\n if l <= r:\n return re_binary_search(arr, target, l=l, r=r)\n else:\n return -1","sub_path":"src/searching/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"342662377","text":"## build a QApplication before building other widgets\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\nimport glob,pandas\nimport numpy as np\nimport time\nimport progressbar\nimport os\npg.mkQApp()\n\n## make a widget for displaying 3D objects\nimport pyqtgraph.opengl as gl\nview = gl.GLViewWidget()\nview.show()\nimport winsound\n\nrootfolder=\"D:\\Project\\ODEA7\\PTrun\\\\\"\npicklefolder=\"F:\\\\A7data\\\\p\\\\\"\nfolders=[\"20190729-cup-longer\",\"20190729-cup-ctktup-longer\"]\nfolder=folders[1]\nfiles = glob.glob(rootfolder+folder+\"\\\\a\\\\allMyNumbers*.csv\")\n\nbar = progressbar.ProgressBar(max_value=len(files))\nprog_i = 0\ndef readfun(f,bar):\n global prog_i\n winsound.Beep(2500, 300)\n bar.update(prog_i)\n prog_i=prog_i+1\n return pandas.read_csv(f, index_col=False)\ndatas = {}\nif os.path.exists(picklefolder+folder):\n print(\"read pickle\")\n datas[folder] = pandas.read_pickle(picklefolder+folder)\nelse:\n print(\"read raw csv\")\n datas[folder] = pandas.concat([ readfun(f,bar) for f in files], ignore_index=True)\n datas[folder].to_pickle(picklefolder+folder)\n\npair = ['time','x1','y1']\nnd = np.array(datas[folder][pair])\n\n## create three grids, add each to the view\nxgrid = gl.GLGridItem()\nygrid = gl.GLGridItem()\nzgrid = gl.GLGridItem()\nview.addItem(xgrid)\nview.addItem(ygrid)\nview.addItem(zgrid)\n\np1 = gl.GLLinePlotItem(pos=nd)\nview.addItem(p1)\n## Start Qt event loop unless running in interactive mode.\nif __name__ == '__main__':\n import sys\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\n QtGui.QApplication.instance().exec_()\n","sub_path":"testpyqtG2.py","file_name":"testpyqtG2.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"57977496","text":"from fields import *\nimport random\n\n'''\nThis program finds the number of solutions to\nAy_0^2 + Cy_1^2 + Fy_2^2 = 0 in projective space; this\nis the number of solutions to Cy_1^2 + Fy_2^2 = -A in\naffine space, plus the number of solutions to Fy_2^2 = -C.\nTests Z/pZ as well as quadratic extensions, which are\nfound by taking (Z/pZ)[x] / (x^2 - a) for a quadratic\nnonresidue a.\n'''\n\ndef test_field(field):\n solns_so_far = None\n for i in range(len(field.elements)):\n for j in range(i, len(field.elements)):\n for k in range(j, len(field.elements)):\n A = field.elements[i]\n C = field.elements[j]\n F = field.elements[k]\n if field.zero in (A,C,F):\n continue\n solns = sum([1 for y1 in field.elements for y2 in\n field.elements if C*y1*y1+F*y2*y2==-A])\n solns += sum([1 for y2 in field.elements if F*y2*y2==-C])\n if solns_so_far is None:\n solns_so_far = solns\n elif solns != solns_so_far:\n print(\"Unexpected result for F_{0} with values \"\n \"(A,C,F) = ({1},{2},{3})\".format(len(field.elements),\n A,C,F))\n return solns_so_far\n\ndef test_field_randomly(field):\n TRIALS = 5\n solns_so_far = None\n for t in range(TRIALS):\n A = random.choice(field.elements[1:]) # exclude zero\n C = random.choice(field.elements[1:])\n F = random.choice(field.elements[1:])\n solns = sum([1 for y1 in field.elements for y2 in\n field.elements if C*y1*y1+F*y2*y2==-A])\n solns += sum([1 for y2 in field.elements if F*y2*y2==-C])\n if solns_so_far is None:\n solns_so_far = solns\n elif solns != solns_so_far:\n print(\"Unexpected result for F_{0} with values \"\n \"(A,C,F) = ({1},{2},{3})\".format(len(field), A,C,F))\n return solns_so_far\n\nprimes = [3, 5, 7, 11, 13, 17]\n\n# Check Z/pZ\n\nfor p in primes:\n print('solutions for F{0}: {1}'.format(p, test_field(Fp(p))))\n\n# Check quadratic extensions incompletely\n\nfor p in primes:\n F = Fp(p)\n squares = [x*x for x in F.elements]\n for el in F.elements:\n if el not in squares:\n break\n else:\n raise Exception(\"couldn't find nonresidue mod {0}\".format(p))\n # el is a nonresidue, so x^2 - el is an irreducible quadratic\n F = F.extend(Polynomial([-el, F.zero, F.one]))\n print('solutions for F{0}: {1}'.format(len(F), test_field_randomly(F)))\n","sub_path":"diagonal_forms.py","file_name":"diagonal_forms.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"187296378","text":"#https://www.hackerrank.com/challenges/ctci-making-anagrams/problem\n\ndef number_needed(a, b):\n set_a = build_set(a)\n set_b = build_set(b)\n intersection = ''\n \n for key,val in set_a.items():\n if set_b.get(key,0) != 0:\n min_val = min(val,set_b[key])\n intersection += key*min_val\n return len(a)+len(b) - 2*len(intersection) \n \n \ndef build_set(a):\n set_a = {}\n for i in a:\n if set_a.get(i,0) == 0:\n set_a[i] = 1\n else:\n set_a[i] += 1\n return set_a\n","sub_path":"min_deletions.py","file_name":"min_deletions.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"393262313","text":"\nfrom django.shortcuts import get_object_or_404, get_list_or_404\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom .models import Post, Comment\nfrom .serializers import (\n PostListSerializer,\n PostSerializer,\n CommentListSerializer,\n CommentSerializer,\n )\n\nfrom django.contrib.auth import get_user_model\n\n\n@api_view(['GET', 'POST'])\ndef post_list_create(request):\n if request.method == 'GET':\n posts = get_list_or_404(Post)\n serializer = PostListSerializer(posts, many=True)\n return Response(serializer.data)\n elif request.method == 'POST':\n serializer = PostSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n ## 포스트맨으로 확인용 : 유저를 강제적으로 넣어서\n # User = get_user_model()\n # user = get_object_or_404(User,pk=11)\n # serializer.save(user=user)\n serializer.save(user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n@api_view(['PUT', 'DELETE', 'GET', 'POST'])\ndef post_delete_update_detail_comment_create(request, post_pk):\n post = get_object_or_404(Post, pk=post_pk)\n if request.method == 'PUT':\n # if post.user == request.user:\n serializer = PostSerializer(post, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n elif request.method == 'DELETE':\n # if post.user == request.user:\n post.delete()\n data = {\n 'delete': f'{post_pk}번 게시글이 삭제되었습니다.'\n }\n return Response(data, status=status.HTTP_204_NO_CONTENT)\n elif request.method == 'GET':\n User = get_user_model()\n user = get_object_or_404(User,pk=post.user.pk)\n # print(user.username)\n # print(type(user))\n serializer_post = PostSerializer(post)\n print(post.comment_set.all())\n if post.comment_set.all():\n comments = get_list_or_404(Comment, post=post)\n serializer_comments = CommentListSerializer(comments, many=True)\n serializer_comments = serializer_comments.data\n else:\n serializer_comments = []\n data = {\n 'serializer_post': serializer_post.data,\n 'serializer_comments': serializer_comments,\n 'username': user.username\n }\n return Response(data)\n elif request.method == 'POST':\n serializer = CommentSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(user=request.user, post=post)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n@api_view(['PUT', 'DELETE'])\ndef comment_update_delete(request, post_pk, comment_pk):\n comment = get_object_or_404(Comment, pk=comment_pk)\n if request.method == 'PUT':\n # if comment.user == request.user:\n serializer = CommentSerializer(comment, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n elif request.method == 'DELETE':\n # if comment.user == request.user:\n comment.delete()\n data = {\n 'delete': f'{comment_pk}번 댓글이 삭제되었습니다.'\n }\n return Response(data, status=status.HTTP_204_NO_CONTENT)\n\n\n\n## 커뮤니티글 좋아요기능\n@api_view(['GET'])\ndef like_post(request, post_pk):\n post = get_object_or_404(Post, pk=post_pk)\n # 포스트맨으로 확인용 : 유저를 강제적으로 넣어서\n # User = get_user_model()\n # user = get_object_or_404(User,pk=11)\n # if not post.like_user.filter(pk=11).exists():\n if not post.like_user.filter(pk=request.user.pk).exists():\n # post.like_user.add(user)\n post.like_user.add(request.user)\n return Response({'message': f'{ post.title } 글 좋아요 누르셨습니다'}, status = status.HTTP_200_OK)\n else:\n # post.like_user.remove(user)\n post.like_user.remove(request.user)\n return Response({'message': f'{ post.title } 글 좋아요 취소했습니다'}, status = status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef post_like_list(request, post_pk):\n post = get_object_or_404(Post, pk=post_pk)\n likeUser = post.like_user.all()\n like_list = []\n for like in likeUser:\n like_list.append(like.id)\n data = {\n 'like_list': like_list\n }\n return Response(data, status=status.HTTP_200_OK)\n","sub_path":"final-pjt-back/community/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"241897066","text":"import json\r\nimport datetime\r\n\r\n\r\nclass DataFactory:\r\n\r\n #symbols = []\r\n\r\n# def findSymbol(symbolspage):\r\n# if\r\n# 'www.nasdaq.com/symbol/' sample: http://www.nasdaq.com/symbol/xlnx\r\n# 'www.nyse.com/quote/XNYS:' sample: https://www.nyse.com/quote/XNYS:XRX\r\n\r\n def json_digest(self, page):\r\n\r\n if page == 99:\r\n self.open_price = 0\r\n self.is_excepttion = 1\r\n\r\n else:\r\n target = json.loads(page)\r\n\r\n #check timezone: make sure target['chart']['result'][0]['meta']['timezone'] == 'EST'\r\n\r\n try:\r\n self.timestamps = target['chart']['result'][0]['timestamp']\r\n self.open_price = target['chart']['result'][0]['indicators']['quote'][0]['open']\r\n self.close_price = target['chart']['result'][0]['indicators']['quote'][0]['close']\r\n self.high_price = target['chart']['result'][0]['indicators']['quote'][0]['high']\r\n self.low_price = target['chart']['result'][0]['indicators']['quote'][0]['low']\r\n self.volume = target['chart']['result'][0]['indicators']['quote'][0]['volume']\r\n self.is_excepttion = 0\r\n\r\n except Exception as e:\r\n print('json_digest: exception on feeding data into lists, skip this symbol')\r\n print(e)\r\n self.is_excepttion = 1\r\n\r\n #self.timestampconvertor(self.timestamps)\r\n\r\n def timestampconvertor(self, timestamps):\r\n self.datetime_format = []\r\n for each in timestamps:\r\n self.datetime_format.append(datetime.datetime.fromtimestamp(each).isoformat())\r\n\r\n\r\n","sub_path":"DataFactory.py","file_name":"DataFactory.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"472706599","text":"import cv2\nimport numpy as np\n\n\ndef showImage():\n fileName = \"../images/lena.jpg\"\n img = cv2.imread(fileName, cv2.IMREAD_COLOR)\n\n cv2.namedWindow('image', cv2.WINDOW_NORMAL)\n cv2.imshow('image', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nshowImage()\n","sub_path":"codes/02. resize_img.py","file_name":"02. resize_img.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"285541740","text":"from __future__ import print_function\n\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom util import *\nimport os\n\nclass Model(object):\n \"\"\"Abstracts a Tensorflow graph for a learning task.\n We use various Model classes as usual abstractions to encapsulate tensorflow\n computational graphs. Each algorithm you will construct in this homework will\n inherit from a Model object.\n \"\"\"\n\n # def add_placeholders(self):\n # \"\"\"Adds placeholder variables to tensorflow computational graph.\n # Tensorflow uses placeholder variables to represent locations in a\n # computational graph where data is inserted. These placeholders are used as\n # inputs by the rest of the model building and will be fed data during\n # training.\n # See for more information:\n # https://www.tensorflow.org/versions/r0.7/api_docs/python/io_ops.html#placeholders\n # \"\"\"\n # raise NotImplementedError(\"Each Model must re-implement this method.\")\n\n def create_feed_dict(self, inputs_batch, labels_batch=None):\n \"\"\"Creates the feed_dict for one step of training.\n A feed_dict takes the form of:\n feed_dict = {\n <placeholder>: <tensor of values to be passed for placeholder>,\n ....\n }\n If labels_batch is None, then no labels are added to feed_dict.\n Hint: The keys for the feed_dict should be a subset of the placeholder\n tensors created in add_placeholders.\n Args:\n inputs_batch: A batch of input data.\n labels_batch: A batch of label data.\n Returns:\n feed_dict: The feed dictionary mapping from placeholders to values.\n \"\"\"\n raise NotImplementedError(\"Each Model must re-implement this method.\")\n\n def add_embedding_op(self):\n \"\"\" Use embedding layer to lookup word vectors\n \"\"\"\n raise NotImplementedError(\"Each Model must re-implement this method.\")\n\n def add_prediction_op(self):\n \"\"\"Implements the core of the model that transforms a batch of input data into predictions.\n Returns:\n pred: A tensor of shape (batch_size, n_classes)\n \"\"\"\n raise NotImplementedError(\"Each Model must re-implement this method.\")\n\n def add_loss_op(self, pred):\n \"\"\"Adds Ops for the loss function to the computational graph.\n Args:\n pred: A tensor of shape (batch_size, n_classes)\n Returns:\n loss: A 0-d tensor (scalar) output\n \"\"\"\n raise NotImplementedError(\"Each Model must re-implement this method.\")\n\n def add_training_op(self, loss):\n \"\"\"Sets up the training Ops.\n Creates an optimizer and applies the gradients to all trainable variables.\n The Op returned by this function is what must be passed to the\n sess.run() to train the model. See\n https://www.tensorflow.org/versions/r0.7/api_docs/python/train.html#Optimizer\n for more information.\n Args:\n loss: Loss tensor (a scalar).\n Returns:\n train_op: The Op for training.\n \"\"\"\n\n raise NotImplementedError(\"Each Model must re-implement this method.\")\n\n def train_on_batch(self, sess, inputs_batch, labels_batch):\n \"\"\"Perform one step of gradient descent on the provided batch of data.\n Args:\n sess: tf.Session()\n input_batch: np.ndarray of shape (n_samples, n_features)\n labels_batch: np.ndarray of shape (n_samples, n_classes)\n Returns:\n loss: loss over the batch (a scalar)\n \"\"\"\n feed = self.create_feed_dict(inputs_batch, labels_batch=labels_batch)\n _, loss = sess.run([self.train_op, self.loss], feed_dict=feed)\n return loss\n\n def predict_on_batch(self, sess, inputs_batch):\n \"\"\"Make predictions for the provided batch of data\n Args:\n sess: tf.Session()\n input_batch: np.ndarray of shape (n_samples, n_features)\n Returns:\n predictions: np.ndarray of shape (n_samples, n_classes)\n \"\"\"\n feed = self.create_feed_dict(inputs_batch)\n predictions = sess.run(self.pred, feed_dict=feed)\n return predictions\n\n def build(self):\n # self.add_placeholders()\n print('start building model ...')\n self.embedding = self.add_embedding_op()\n self.pred = self.add_prediction_op()\n self.loss = self.add_loss_op(self.pred)\n self.train_op = self.add_training_op(self.loss)\n\n total_parameter = sum(v.get_shape().num_elements() for v in tf.trainable_variables())\n print('total number of parameter {}'.format(total_parameter))\n\nclass sequence_2_sequence_LSTM(Model):\n\n def __init__(self, embeddings, flags, batch_size=64, hidden_size=100,\n voc_size = 6169, n_epochs = 50, lr = 1e-3, reg = 1e-4, mode = 1, save_model_file = 'bestModel'):\n '''\n Input Args:\n\n - embeddings: (np.array) shape (vocabulary size, word vector dimension)\n - flags: () store a series of hyperparameters\n -- input_size: (int) default pretrained VGG16 output 7*7*512\n -- batch_size: (int) batch size\n -- num_frames: (int) frame number default is 15\n -- max_sentence_length: (int) max word sentence default is 20\n -- voc_size: (int) vocabulary size\n -- word_vector_size: (int) depend on which vocabulary used\n -- n_epochs: (int) how many epoches to run\n -- hidden_size: (int) hidden state vector size\n -- learning_rate: (float) learning rate\n\n Placeholder variables:\n - frames_placeholder: (train X) tensor with shape (sample_size, frame_num, input_size)\n - caption_placeholder: (label Y) tensor with shape (sample_size, max_sentence_length)\n - is_training_placeholder: (train mode) tensor int32 0 or 1\n - dropout_placeholder: (dropout keep probability) tensor float32 or 1 for testing\n '''\n # control by flags\n self.input_size = flags.input_size\n self.num_frames = flags.num_frames\n self.max_sentence_length = flags.max_sentence_length\n self.word_vector_size = flags.word_vector_size\n self.state_size = flags.state_size\n \n # control by outsider\n self.pretrained_embeddings = embeddings\n self.batch_size = batch_size\n self.hidden_size = hidden_size\n self.voc_size = voc_size\n self.n_epochs = n_epochs\n self.learning_rate = lr\n self.reg = reg\n self.train_embedding = False\n self.best_val = float('inf')\n self.mode = mode\n\n # ==== set up placeholder tokens ========\n self.frames_placeholder = tf.placeholder(tf.float32, shape=(None, self.num_frames, self.input_size))\n self.caption_placeholder = tf.placeholder(tf.int32, shape=(None, self.max_sentence_length))\n self.mode = tf.placeholder(tf.int32, shape = [])\n\n def create_feed_dict(self, input_frames, input_caption, is_training = 1):\n\n feed = {\n self.frames_placeholder: input_frames,\n self.caption_placeholder: input_caption,\n self.mode: is_training\n }\n\n return feed\n\n def add_embedding_op(self):\n \"\"\"\n Loads distributed word representations based on placeholder tokens\n :return:\n \"\"\"\n with tf.variable_scope(\"embeddings\"):\n vec_embeddings = tf.get_variable(\"embeddings\",\n initializer=self.pretrained_embeddings,\n trainable=self.train_embedding,\n dtype=tf.float32)\n return vec_embeddings\n\n def add_prediction_op(self):\n \"\"\" LSTM encoder and decoder layers\n \"\"\"\n with tf.variable_scope(\"LSTM_seq2seq\"):\n encoder_output, encoder_state = self.encoder()\n\n caption_embeddings = tf.nn.embedding_lookup(self.embedding, self.caption_placeholder)\n\n word_ind, batch_loss = self.decoder(encoder_outputs=encoder_output, input_caption=caption_embeddings, \n true_cap = self.caption_placeholder)\n \n self.word_ind = word_ind\n return batch_loss\n\n def add_loss_op(self, batch_loss):\n with tf.variable_scope(\"loss\"):\n\n loss_val = batch_loss\n\n return loss_val\n\n def add_training_op(self, loss_val):\n # learning rate decay\n # https://www.tensorflow.org/versions/r0.11/api_docs/python/train/decaying_the_learning_rate\n starter_lr = self.learning_rate\n lr = tf.train.exponential_decay(starter_lr, global_step = 700*self.n_epochs,\n decay_steps = 300, decay_rate = 0.9, staircase=True)\n #optimizer = tf.train.AdamOptimizer(lr)\n\n optimizer = tf.train.RMSPropOptimizer(learning_rate = lr, decay = 0.95, momentum = 0.9)\n self.updates = optimizer.minimize(loss_val)\n\n def train_on_batch(self, sess, input_frames, input_caption):\n \"\"\"\n Training model per batch using self.updates\n return loss for that batch and prediction\n \"\"\"\n feed = self.create_feed_dict(input_frames=input_frames,\n input_caption=input_caption,\n is_training=1)\n loss, _, train_index = sess.run([self.loss, self.updates, self.word_ind], feed_dict=feed)\n self.train_pred = train_index\n return loss\n\n def test_on_batch(self, sess, input_frames, input_caption):\n \"\"\"\n Test model and make prediction\n return loss for that batch and prediction\n \"\"\"\n feed = self.create_feed_dict(input_frames=input_frames,\n input_caption=input_caption,\n is_training=1)\n loss, test_index = sess.run([self.loss, self.word_ind], feed_dict=feed)\n self.test_pred = test_index\n return loss\n\n def predict_on_batch(self, sess, input_frames, input_captions):\n feed = {\n self.frames_placeholder: input_frames,\n self.caption_placeholder: input_captions,\n self.mode: 0\n }\n predict_index = sess.run([self.word_ind], feed_dict=feed)[0]\n return predict_index\n\n def test(self, sess, valid_data):\n \"\"\"\n Given validation or test dataset, do not update wegiths\n return the validation or test loss and predicted word vector\n \"\"\"\n valid_loss = []\n input_frames, captions = valid_data\n for batch in minibatches(input_frames, captions, self.batch_size, self.max_sentence_length):\n vid, inp, cap = batch\n self.val_id = vid\n loss = self.test_on_batch(sess, inp, cap)\n valid_loss.append(loss)\n return np.mean(valid_loss)\n\n def run_epoch(self, sess, train_data, valid_data, verbose):\n \"\"\"\n The controller for each epoch training.\n This function will call training_on_batch for training and test for checking validation loss\n \"\"\"\n train_losses = []\n input_frames, captions = train_data\n prog = Progbar(target=len(captions)//self.batch_size)\n i = 0\n for batch in minibatches(input_frames, captions, self.batch_size, self.max_sentence_length):\n i += 1\n vid, inp, cap = batch\n self.train_id = vid\n train_loss = self.train_on_batch(sess, inp, cap)\n prog.update(i + 1, exact = [(\"train loss\", train_loss)])\n train_losses.append(train_loss)\n\n # plot batch iteration vs loss figure\n if verbose: plot_loss(train_losses)\n\n avg_train_loss = np.mean(train_losses)\n dev_loss = self.test(sess, valid_data)\n return dev_loss, avg_train_loss\n\n def train(self, sess, train_data, verbose = True):\n '''\n train mode\n '''\n val_losses = []\n train_losses = []\n train, validation = train_test_split(train_data, train_test_ratio=0.8)\n prog = Progbar(target=self.n_epochs)\n for i, epoch in enumerate(range(self.n_epochs)):\n dev_loss, avg_train_loss = self.run_epoch(sess, train, validation, verbose)\n if verbose:\n # print epoch results\n prog.update(i + 1, exact = [(\"train loss\", avg_train_loss), (\"dev loss\", dev_loss)])\n if dev_loss < self.best_val:\n self.best_val = dev_loss\n print(\" \")\n print('Validation loss improved, Save Model!')\n else:\n print(\" \")\n print(\"Validation loss doesn't improve\")\n if dev_loss < self.best_val:\n saver = tf.train.Saver()\n save_path = saver.save(sess, os.getcwd() + \"/model/\" + save_model_file + \".ckpt\")\n val_losses.append(dev_loss)\n train_losses.append(avg_train_loss)\n return val_losses, train_losses, self.train_pred, self.test_pred, self.train_id, self.val_id\n\n def predict(self, sess, input_frames_dict, captions_dict):\n \"\"\"\n Input Args:\n input_frames: (dictionary), {videoId: frames}\n Output:\n list_video_index: (list), [video_id, ...]\n list_predict_index: (list), [[word_index, word_index...],...]\n \"\"\"\n list_predict_index = []\n list_video_index = []\n num_inputs = len(input_frames)\n key_sorted = sorted(captions_dict.keys())\n num_inputs = len(key_sorted) \n \n for batch_start in tqdm(np.arange(0, num_inputs, self.batch_size)):\n keys = key_sorted[batch_start:batch_start+self.batch_size]\n batch_frames = []\n batch_captions = []\n for key in keys:\n list_video_index.append(key)\n batch_frames.append(frames_dict[key])\n batch_captions.append(captions_dict[key])\n \n predict_index = self.predict_on_batch(sess, batch_frames, batch_captions )\n \n for pred in predict_index:\n list_predict_index.append(pred)\n \n # input_frames = []\n # for video_id, frames in input_frames_dict.items():\n #list_video_index.append(video_id)\n #input_frames.append(frames)\n\n # for batch_start in tqdm(np.arange(0, num_inputs, self.batch_size)):\n # batch_frames = input_frames[batch_start:batch_start+self.batch_size]\n # predict_index = self.predict_on_batch(sess, batch_frames)\n # for pred in predict_index:\n # list_predict_index.append(pred)\n\n return list_video_index, list_predict_index\n\n def encoder(self):\n '''\n Input Args:\n input_batch: (tensor) shape (batch_size, frame_num = 15, channels = 4096)\n hidden_size: (int) output vector dimension for each cell in encoder\n dropout: (placeholder variable) dropout probability keep\n max_len: (int) max sentence length\n \n Output:\n outputs: (tensor list) a series of outputs from cells [[batch_size, hidden_size]]\n state: (tensor) [[batch_size, state_size]]\n '''\n input_batch=self.frames_placeholder\n hidden_size=self.hidden_size\n max_len = self.max_sentence_length\n\n if self.mode == 'train':\n dropout = 0.7\n else:\n dropout = 1\n with tf.variable_scope('encoder') as scope:\n \n #lstm_en_cell = tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(hidden_size), output_keep_prob=dropout)\n lstm_en_cell = tf.contrib.rnn.LayerNormBasicLSTMCell(hidden_size, dropout_keep_prob=dropout)\n \n # add <pad> to max length\n inp_shape = tf.shape(input_batch)\n batch_size, frame_num, c = inp_shape[0], inp_shape[1], inp_shape[2]\n pads = tf.zeros([batch_size, max_len, c], tf.float32)\n \n # concatenate input_batch and pads\n enc_inp = tf.concat([input_batch, pads], axis = 1)\n \n outputs, state = tf.nn.dynamic_rnn(lstm_en_cell,\n inputs=enc_inp,\n dtype=tf.float32,\n scope=scope)\n return outputs, state\n\n def decoder(self, encoder_outputs, input_caption, true_cap):\n '''\n Input Args:\n encoder_outputs: (list) a series of hidden states (batch_size, hidden_size)\n input_caption: (tensor) after embedding captions (batch_size, T(frame_num), max_len+frame_num)\n tru_cap: (dict) {video id: captions (string)}\n \n Output:\n outputs: (tensor) save decoder cell output vector\n words: (tensor) save word index \n '''\n\n embedding = self.embedding\n word_vector_size = self.word_vector_size\n voc_size=self.voc_size\n hidden_size=self.hidden_size\n max_len=self.max_sentence_length\n \n def d1():\n return tf.constant(0.7, tf.float32)\n def d2():\n return tf.constant(1, tf.float32)\n dropout = tf.cond(self.mode > 0, lambda: d1(), lambda: d2())\n \n with tf.variable_scope('decoder') as scope:\n \n #lstm_de_cell = tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(hidden_size), output_keep_prob=dropout)\n lstm_de_cell = tf.contrib.rnn.LayerNormBasicLSTMCell(hidden_size, dropout_keep_prob=dropout)\n outputs = []\n\n # add pad\n inp_shape = tf.shape(encoder_outputs)\n batch_size, input_len = inp_shape[0], inp_shape[1]\n pad_len = self.num_frames\n\n # initial state\n state = lstm_de_cell.zero_state(batch_size, tf.float32)\n pads = tf.zeros([batch_size, pad_len, word_vector_size], tf.float32)\n \n # decoder pad part\n for i in range(pad_len):\n if i >= 1: scope.reuse_variables()\n enc_out = encoder_outputs[:, i, :]\n dec_inp = tf.concat([enc_out, pads[:,i,:]], axis = 1)\n temp, state = lstm_de_cell(dec_inp, state)\n \n regularizer = tf.contrib.layers.l2_regularizer(scale = self.reg)\n scores = tf.layers.dense(temp, units = voc_size, name = 'hidden_to_scores', kernel_regularizer = regularizer)\n\n prev_ind = None\n words = []\n losses = tf.constant(0, dtype = tf.float32)\n \n # decoder output words\n for i in range(max_len):\n\n scope.reuse_variables()\n \n mode = tf.cast(self.mode, tf.int32)\n \n # <START>\n if i == 0: prev_vec = tf.ones([tf.shape(input_caption)[0], word_vector_size], tf.float32)\n \n # train mode, input ground-truth \n def f1():\n return input_caption[:, i, :]\n\n # test mode, input previous word vector\n def f2():\n return prev_vec\n\n prev_vec = tf.cond(self.mode > 0, lambda: f1(), lambda: f2())\n \n prev_vec = tf.reshape(prev_vec, [batch_size, word_vector_size])\n \n # concatnate encoder hidden output and ground-truth (training) / previous word (test) vector\n enc_out = encoder_outputs[:, i+pad_len, :]\n try: \n enc_out = tf.reshape(enc_out, [batch_size, hidden_size])\n except:\n raise Exception(\"Decoder hidden size doesn't match with encoder hidden size!\")\n \n dec_inp = tf.concat([enc_out, prev_vec], axis = 1)\n output_vector, state = lstm_de_cell(dec_inp, state)\n \n # scores\n regularizer = tf.contrib.layers.l2_regularizer(scale = 1e-5)\n logits = tf.layers.dense(output_vector, units = voc_size, name = 'hidden_to_scores', kernel_regularizer = regularizer)\n\n targets = tf.reshape(true_cap[:, i], [-1])\n\n # batch loss\n batch_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels = targets, logits = logits))\n losses += batch_loss\n \n def f3(logits):\n return logits\n\n def f4(logits):\n scores = tf.nn.softmax(logits)\n return scores\n \n scores = tf.cond(self.mode > 0, lambda: f3(logits), lambda: f4(logits))\n \n # max score word index \n prev_ind = tf.argmax(scores, axis = 1)\n words.append(prev_ind)\n prev_vec = tf.nn.embedding_lookup(embedding, prev_ind)\n\n \n # convert to tensor\n words = tf.stack(words)\n words = tf.transpose(words)\n return words, losses / tf.cast(max_len, tf.float32)\n\ndef plot_loss(train_losses):\n plt.plot(range(len(train_losses)), train_losses, 'b-')\n plt.grid()\n plt.xlabel('iteration', fontsize = 13)\n plt.ylabel('Train loss', fontsize = 13)\n plt.title('iteration vs loss', fontsize = 15)\n plt.show()\n","sub_path":"model/video_caption.py","file_name":"video_caption.py","file_ext":"py","file_size_in_byte":21572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"83656652","text":"# naive but close - O(n) time, O(n) additional space\ndef firstMissingPositive(array):\n\n seen = set()\n\n for num in array:\n if num > 0:\n seen.add(num)\n\n for i in range(1, len(array) + 1):\n if i not in seen:\n return i\n\n# more efficient - O(n) time, O(1) additional space\n# approach: use array indices as keys to a \"dict\", similar to above\n# solution but without extra space\n# i.e. in [3, 4, 1], to denote that we've seen 1, 3, and 4, we have:\n# [x, o, x], subtracting 1 to adjust for indexing rules\n# with this, we see that 1 (1 - 1 = 0, x), 3 (3 - 1 = 2, x) are seen, and 4 - 1\n# is out of range, so its position is o\n# thus, the missing integer is either an o index (+1 to account for indexing)\n# or if no o's are found, the length of the array +1\ndef firstMissingPositive_improved(array):\n\n array = remove_negatives(array)\n\n # [3, 4, 1] -> [4, 3, 1]\n # [1, 2, 0] -> [2, 1]\n l = len(array) # 3, 2\n\n for i in range(l):\n if abs(array[i]) - 1 < l and array[abs(array[i]) - 1] > 0:\n array[abs(array[i]) - 1] *= -1\n\n # [-4, 3, -1]\n # [-2, -1]\n\n for i in range(l):\n if array[i] > 0:\n return i + 1\n\n return l + 1\n\ndef remove_negatives(array):\n\n index = 0\n\n for i in range(len(array)):\n if array[i] <= 0:\n tmp = array[index]\n array[index] = array[i]\n array[i] = tmp\n index += 1\n\n\n return array[index:]\n\n# test cases\ntest1 = [3, 4, -1, 1]\ntest2 = [1, 2, 0]\ntest3 = [3, 3, 4, -1, 1]\n\nprint(firstMissingPositive(test1)) # expected output: 2\nprint(firstMissingPositive(test2)) # expected output: 3\nprint(firstMissingPositive(test3)) # expected output: 2\n\n# better soln\nprint(firstMissingPositive_improved(test1))\nprint(firstMissingPositive_improved(test2))\n","sub_path":"solutions/problem4.py","file_name":"problem4.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"318047639","text":"# Count pairs in array whose sum is divisible by K\n# https://www.geeksforgeeks.org/count-pairs-in-array-whose-sum-is-divisible-by-k/\n# SGVP 394500 | 15:27 12Mar19\n# Given an array A[] and positive integer K, count total number of pairs in the array\n# whose sum is divisible by K.\n\n# IN : A[] = {2, 2, 1, 7, 5, 3}, K = 4\n# OP : 5\n\n# There are five pairs possible whose sum is divisible by '4' i.e, (2, 2),\n# (1, 7), (7, 5), (1, 3) and (5, 3)\n\ndef countKdivPairs(A, n, K):\n\n # Create a frequency array to count occurrences of all remainders when \n # divide by K\n\n freq = [0] * K\n\n # Countr occurrences of all remainders\n for i in range(n):\n freq[A[i] % K]+= 1\n\n sum = freq[0] * (freq[0] - 1) / 2;\n\n # count for all i and (K - i) )\n i = 1\n while( i <= K//2 and i != (K - i) ):\n sum += freq[i] * freq[K-i]\n i+= 1\n\n\n # If K is even\n if ( K % 2 == 0 ):\n sum += (freq[K//2] * (freq[K//2]-1)/2);\n\n return int(sum)\n\n\n# Drvier code\nA = [2, 2, 1, 7, 5, 3]\nn = len(A)\nK = 4\nprint(countKdivPairs(A, n, K))\n","sub_path":"arrayProgram.py","file_name":"arrayProgram.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"199555616","text":"from functools import partial\nfrom flaskext.script import Manager, Server, Shell\nfrom werkzeug import create_environ\n\nfrom coqd.runner import main as coqd_main\nfrom cockerel.webapp import app\nfrom cockerel.utilities import new_app\nfrom cockerel.models import db, schema\nfrom cockerel.auth import principals\n\n\ndef _make_context():\n return dict(app=new_app(app), db=db, models=schema)\n\n\nmanager = Manager(partial(new_app, app))\nmanager.add_command(\"shell\", Shell(make_context=_make_context))\nmanager.add_command(\"runserver\", Server())\nmanager.add_option('--serialize', action=\"store_true\",\n default=False, help=\"Serialize output to JSON\")\n\n\n@manager.command\ndef initdb():\n # A request_context is required to use these helper functions\n with new_app(app).request_context(create_environ()):\n db.drop_all()\n db.create_all()\n readaction = schema.Action(\"read\")\n insertaction = schema.Action(\"insert\")\n deleteaction = schema.Action(\"delete\")\n editaction = schema.Action(\"edit\")\n db.session.add(readaction)\n db.session.add(insertaction)\n db.session.add(deleteaction)\n db.session.add(editaction)\n administrator = schema.User(username=\"admin\",\n password=\"admin\",\n firstname=\"admin\",\n lastname=\"admin\",\n email=\"admin@cockerel.com\")\n administrator.actions.append(readaction)\n administrator.actions.append(insertaction)\n administrator.actions.append(deleteaction)\n administrator.actions.append(editaction)\n\n db.session.add(administrator)\n db.session.commit()\n\n\n@manager.command\ndef initprincipal():\n principals.app = app\n\n\n@manager.option('--serialize', action=\"store_true\",\n default=False,\n help=\"Serialize output to JSON\")\ndef runcoqd(serialize):\n coqd_main()\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"48386906","text":"\"\"\"\nBook: Building RESTful Python Web Services\nChapter 2: Working with class based views and hyperlinked APIs in Django\nAuthor: Gaston C. Hillar - Twitter.com/gastonhillar\nPublisher: Packt Publishing Ltd. - http://www.packtpub.com\n\"\"\"\nfrom rest_framework import serializers\nfrom search.models import Reviews\n\n\nclass ReviewSerializer(serializers.ModelSerializer):\n class Meta:\n model = Reviews\n fields = ('productId', \n 'userId', \n 'profileName',\n 'helpfulness', \n 'score',\n 'time',\n 'summary',\n 'text',\n 'search_score')\n","sub_path":"search/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"366875417","text":"#!/usr/bin/env python3\nimport csv\nimport sys\nfrom datetime import datetime, timedelta\n\n# ファイル内のデータを1分ごとに区切り、平均化する関数\ndef process_file(file):\n reader = csv.reader(file)\n\n # 時間とデータ列のインデックスに応じて修正\n timestamp_index = 0\n data_start_index = 1\n\n column_count = None\n average_values = None\n start_time = None\n end_time = None\n minute_data = []\n count = 0\n\n # 60秒ごとに平均を取る、データ数が60個とは限らない\n for row in reader:\n if column_count is None:\n column_count= len(row)-1\n average_values = [0] * column_count\n\n timestamp = float(row[timestamp_index])\n values = [float(value) for value in row[data_start_index:]]\n\n if start_time is None:\n start_time = datetime.fromtimestamp(timestamp)\n end_time = start_time + timedelta(minutes=1)\n\n if datetime.fromtimestamp(timestamp) < end_time:\n for i in range(column_count):\n average_values[i] += values[i]\n count += 1\n else:\n if count > 0:\n average_values = [average / count for average in average_values]\n minute_data.append([int(start_time.timestamp())] + average_values)\n average_values = [0] * column_count\n count = 0\n\n while datetime.fromtimestamp(timestamp) >= end_time:\n start_time = end_time\n end_time = start_time + timedelta(minutes=1)\n\n for i in range(column_count):\n average_values[i] += values[i]\n count += 1\n\n if count > 0:\n average_values = [average / count for average in average_values]\n minute_data.append([int(start_time.timestamp())] + average_values)\n\n return minute_data\n\n# utlogファイルを統合する関数\ndef merge_utlogs(utlog_files):\n merged_data = []\n merged_column_names = None\n\n for utlog_file in utlog_files:\n with open(utlog_file, 'r') as file:\n minute_data = process_file(file)\n merged_data.extend(minute_data)\n\n return merged_data\n\nif __name__ == '__main__':\n # コマンドライン引数から入力ファイル名を取得\n input_files = sys.argv[1:]\n\n if not input_files:\n print('Usage: utlog_reduction [filename] ..')\n sys.exit(1)\n\n # 入力ファイルの存在をチェック\n for input_file in input_files:\n try:\n open(input_file, 'r')\n except IOError:\n print(f\"入力ファイル '{input_file}' が見つかりません。\")\n sys.exit(1)\n\n # utlogファイルの統合と変換\n merged_utlog_data = merge_utlogs(input_files)\n\n # 出力ファイル名を作成\n current_datetime = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n output_file = f\"utlog_minutes_{current_datetime}.csv\"\n\n # 結果の出力\n with open(output_file, 'w', newline='') as file:\n writer = csv.writer(file)\n\n for data in merged_utlog_data:\n writer.writerow(data)\n\n print(f\"結果が {output_file} に出力されました。\")\n","sub_path":"bin/utlog_reduction.py","file_name":"utlog_reduction.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"511410873","text":"#!/usr/bin/python3\nfrom models import *\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nimport os\nfrom models.base_model import BaseModel, Base\n\"\"\"\nThis is the City class module. This module creates a City class that inherits\nfrom BaseModel.\n\"\"\"\n\n\nclass City(BaseModel, Base):\n \"\"\" This is the City class and it inherts from BaseModel \"\"\"\n if os.getenv('HBNB_TYPE_STORAGE') == 'db':\n __tablename__ = \"cities\"\n state_id = Column(String(60), ForeignKey('states.id'), nullable=False)\n name = Column(String(128), nullable=False)\n else:\n state_id = \"\"\n name = \"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\" Initiate City object \"\"\"\n super().__init__(*args, **kwargs)\n","sub_path":"models/city.py","file_name":"city.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"215384183","text":"from enum import Enum\nimport time\nfrom distutils.dir_util import mkpath\n\nimport numpy as np\nimport tensorflow as tf\nimport cv2\n\nregularizer_conv = 0.004\nregularizer_dsconv = 0.0004\nbatchnorm_fused = True\nactivation_fn = tf.nn.relu\n\n\nclass CocoPart(Enum):\n Nose = 0\n Neck = 1\n RShoulder = 2\n RElbow = 3\n RWrist = 4\n LShoulder = 5\n LElbow = 6\n LWrist = 7\n RHip = 8\n RKnee = 9\n RAnkle = 10\n LHip = 11\n LKnee = 12\n LAnkle = 13\n REye = 14\n LEye = 15\n REar = 16\n LEar = 17\n Background = 18\n\n\nclass MPIIPart(Enum):\n RAnkle = 0\n RKnee = 1\n RHip = 2\n LHip = 3\n LKnee = 4\n LAnkle = 5\n RWrist = 6\n RElbow = 7\n RShoulder = 8\n LShoulder = 9\n LElbow = 10\n LWrist = 11\n Neck = 12\n Head = 13\n\n @staticmethod\n def from_coco(human):\n # t = {\n # MPIIPart.RAnkle: CocoPart.RAnkle,\n # MPIIPart.RKnee: CocoPart.RKnee,\n # MPIIPart.RHip: CocoPart.RHip,\n # MPIIPart.LHip: CocoPart.LHip,\n # MPIIPart.LKnee: CocoPart.LKnee,\n # MPIIPart.LAnkle: CocoPart.LAnkle,\n # MPIIPart.RWrist: CocoPart.RWrist,\n # MPIIPart.RElbow: CocoPart.RElbow,\n # MPIIPart.RShoulder: CocoPart.RShoulder,\n # MPIIPart.LShoulder: CocoPart.LShoulder,\n # MPIIPart.LElbow: CocoPart.LElbow,\n # MPIIPart.LWrist: CocoPart.LWrist,\n # MPIIPart.Neck: CocoPart.Neck,\n # MPIIPart.Nose: CocoPart.Nose,\n # }\n\n t = [\n (MPIIPart.Head, CocoPart.Nose),\n (MPIIPart.Neck, CocoPart.Neck),\n (MPIIPart.RShoulder, CocoPart.RShoulder),\n (MPIIPart.RElbow, CocoPart.RElbow),\n (MPIIPart.RWrist, CocoPart.RWrist),\n (MPIIPart.LShoulder, CocoPart.LShoulder),\n (MPIIPart.LElbow, CocoPart.LElbow),\n (MPIIPart.LWrist, CocoPart.LWrist),\n (MPIIPart.RHip, CocoPart.RHip),\n (MPIIPart.RKnee, CocoPart.RKnee),\n (MPIIPart.RAnkle, CocoPart.RAnkle),\n (MPIIPart.LHip, CocoPart.LHip),\n (MPIIPart.LKnee, CocoPart.LKnee),\n (MPIIPart.LAnkle, CocoPart.LAnkle),\n ]\n\n pose_2d_mpii = []\n visibilty = []\n for mpi, coco in t:\n if coco.value not in human.body_parts.keys():\n pose_2d_mpii.append((0, 0))\n visibilty.append(False)\n continue\n pose_2d_mpii.append((human.body_parts[coco.value].x, human.body_parts[coco.value].y))\n visibilty.append(True)\n return pose_2d_mpii, visibilty\n\n\nCocoPairs = [(1, 2), (1, 5), (2, 3), (3, 4), (5, 6), (6, 7), (1, 8), (8, 9), (9, 10), (1, 11), (11, 12), (12, 13), (1,\n 0),\n (0, 14), (14, 16), (0, 15), (15, 17), (2, 16), (5, 17)] # = 19\nCocoPairsRender = CocoPairs[:-2]\n# CocoPairsNetwork = [\n# (12, 13), (20, 21), (14, 15), (16, 17), (22, 23), (24, 25), (0, 1), (2, 3), (4, 5),\n# (6, 7), (8, 9), (10, 11), (28, 29), (30, 31), (34, 35), (32, 33), (36, 37), (18, 19), (26, 27)\n# ] # = 19\n\nCocoColors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0],\n [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],\n [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]\n\n\ndef read_imgfile(path, width, height, data_format='channels_last'):\n \"\"\"Read image file and resize to network input size.\"\"\"\n val_image = cv2.imread(path, cv2.IMREAD_COLOR)\n val_image = val_image[:,:,::-1]\n if width is not None and height is not None:\n val_image = cv2.resize(val_image, (width, height))\n if data_format == 'channels_first':\n val_image = val_image.transpose([2, 0, 1])\n return val_image / 255.0\n\n\ndef get_sample_images(w, h):\n val_image = [\n read_imgfile('./images/p1.jpg', w, h),\n read_imgfile('./images/p2.jpg', w, h),\n read_imgfile('./images/p3.jpg', w, h),\n read_imgfile('./images/golf.jpg', w, h),\n read_imgfile('./images/hand1.jpg', w, h),\n read_imgfile('./images/hand2.jpg', w, h),\n read_imgfile('./images/apink1_crop.jpg', w, h),\n read_imgfile('./images/ski.jpg', w, h),\n read_imgfile('./images/apink2.jpg', w, h),\n read_imgfile('./images/apink3.jpg', w, h),\n read_imgfile('./images/handsup1.jpg', w, h),\n read_imgfile('./images/p3_dance.png', w, h),\n ]\n return val_image\n\n\ndef load_graph(model_file):\n \"\"\"Load a freezed graph from file.\"\"\"\n graph_def = tf.GraphDef()\n with open(model_file, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n\n graph = tf.Graph()\n with graph.as_default():\n tf.import_graph_def(graph_def)\n return graph\n\n\ndef get_op(graph, name):\n return graph.get_operation_by_name('import/%s' % name).outputs[0]\n\n\nclass Profiler(object):\n\n def __init__(self):\n self.count = dict()\n self.total = dict()\n\n def __del__(self):\n if self.count:\n self.report()\n\n def report(self):\n sorted_costs = sorted([(t, name) for name, t in self.total.items()])\n sorted_costs.reverse()\n names = [name for _, name in sorted_costs]\n hr = '-' * 80\n print(hr)\n print('%-12s %-12s %-12s %s' % ('tot (s)', 'count', 'mean (ms)', 'name'))\n print(hr)\n for name in names:\n tot, cnt = self.total[name], self.count[name]\n mean = tot / cnt\n print('%-12f %-12d %-12f %s' % (tot, cnt, mean * 1000, name))\n\n def __call__(self, name, duration):\n if name in self.count:\n self.count[name] += 1\n self.total[name] += duration\n else:\n self.count[name] = 1\n self.total[name] = duration\n\n\n_default_profiler = Profiler()\n\n\ndef measure(f, name=None):\n if not name:\n name = f.__name__\n t0 = time.time()\n result = f()\n duration = time.time() - t0\n _default_profiler(name, duration)\n return result\n\n\ndef draw_humans(npimg, humans):\n npimg = np.copy(npimg)\n image_h, image_w = npimg.shape[:2]\n centers = {}\n for human in humans:\n # draw point\n for i in range(CocoPart.Background.value):\n if i not in human.body_parts.keys():\n continue\n\n body_part = human.body_parts[i]\n center = (int(body_part.x * image_w + 0.5), int(body_part.y * image_h + 0.5))\n centers[i] = center\n cv2.circle(npimg, center, 3, CocoColors[i], thickness=3, lineType=8, shift=0)\n\n # draw line\n for pair_order, pair in enumerate(CocoPairsRender):\n if pair[0] not in human.body_parts.keys() or pair[1] not in human.body_parts.keys():\n continue\n cv2.line(npimg, centers[pair[0]], centers[pair[1]], CocoColors[pair_order], 3)\n\n return npimg\n\n\ndef plot_humans(image, heatMat, pafMat, humans, name):\n import matplotlib.pyplot as plt\n fig = plt.figure()\n a = fig.add_subplot(2, 3, 1)\n\n plt.imshow(draw_humans(image, humans))\n\n a = fig.add_subplot(2, 3, 2)\n tmp = np.amax(heatMat[:, :, :-1], axis=2)\n plt.imshow(tmp, cmap=plt.cm.gray, alpha=0.5)\n plt.colorbar()\n\n tmp2 = pafMat.transpose((2, 0, 1))\n tmp2_odd = np.amax(np.absolute(tmp2[::2, :, :]), axis=0)\n tmp2_even = np.amax(np.absolute(tmp2[1::2, :, :]), axis=0)\n\n a = fig.add_subplot(2, 3, 4)\n a.set_title('Vectormap-x')\n plt.imshow(tmp2_odd, cmap=plt.cm.gray, alpha=0.5)\n plt.colorbar()\n\n a = fig.add_subplot(2, 3, 5)\n a.set_title('Vectormap-y')\n plt.imshow(tmp2_even, cmap=plt.cm.gray, alpha=0.5)\n plt.colorbar()\n mkpath('vis')\n plt.savefig('vis/result-%s.png' % name)\n\n\ndef rename_tensor(x, name):\n # FIXME: use tf.identity(x, name=name) doesn't work\n new_shape = []\n for d in x.shape:\n try:\n d = int(d)\n except:\n d = -1\n new_shape.append(d)\n return tf.reshape(x, new_shape, name=name)\n","sub_path":"openpose_plus/inference/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"106982407","text":"from django.shortcuts import render\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nimport numpy as np\n# else:\n# if not attack_with:\n# messages.warning(request, \"Please select the number of battalions you wish to attack with.\")\n# if not defend_with:\n# messages.warning(request, \"Please select the number of battalions you wish to defend with.\")\n\ndef post_to_int(string, request):\n temp = request.POST.get(string, False)\n if temp == \"\":\n temp = 0\n temp = int(temp)\n return temp\ndef sim(request):\n attack_bats = 0\n defend_bats = 0\n die = [1,2,3,4,5,6]\n if request.method == 'POST':\n x_data = []\n y_data = []\n attack_bats = post_to_int('attack_bats', request)\n defend_bats = post_to_int('defend_bats', request)\n attack_limit = post_to_int('a_limit', request)\n defend_limit = post_to_int('d_limit', request)\n attack_times = int(request.POST.get('attack_times', False))\n attack_with = int(request.POST.get('a_number', False))\n defend_with = int(request.POST.get('d_number', False))\n attack_leader = int(bool(request.POST.get('a_leader', False)))\n defend_leader = int(bool(request.POST.get('d_leader', False)))\n defend_fort = int(bool(request.POST.get('d_fortress', False)))\n submit = request.POST.get('action', False)\n STARTING_A_BATS = attack_bats\n STARTING_D_BATS = defend_bats\n sims = 1\n if submit == 'stats':\n sims = 1000\n\n if attack_times == -1:\n attack_times = float(\"inf\")\n\n for it in range(sims):\n attacked = 0\n attack_bats = STARTING_A_BATS\n defend_bats = STARTING_D_BATS\n attack_loss = 0\n defend_loss = 0\n while attack_bats > attack_limit and defend_bats > defend_limit and attacked < attack_times:\n attack_die = min(attack_bats, attack_with)\n defend_die = min(defend_bats, defend_with)\n attack = np.random.choice(die, attack_die) + attack_leader\n defend = np.random.choice(die, defend_die) + defend_leader + defend_fort\n if attack[0] > defend[0]:\n defend_bats = defend_bats -1\n else:\n attack_bats = attack_bats - 1\n\n if attack_die > 1 and defend_die > 1:\n if attack[1] > defend[1]:\n defend_bats = defend_bats - 1\n else:\n attack_bats = attack_bats - 1\n\n attacked = attacked + 1\n\n attack_bats = max(attack_bats, 0)\n defend_bats = max(defend_bats, 0)\n total_attack_loss = STARTING_A_BATS - attack_bats\n total_defend_loss = STARTING_D_BATS - defend_bats\n x_data.append(total_attack_loss)\n y_data.append(total_defend_loss)\n\n if submit == 'roll':\n message = \"Attacker loses \" + str(total_attack_loss) + \" battalions. Defender loses \" + str(total_defend_loss) + \" battalions.\"\n messages.success(request, message)\n\n if submit == 'stats':\n\n losses_range = [min(2*attack_times, STARTING_A_BATS), min(2*attack_times, STARTING_D_BATS)]\n\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib.figure import Figure\n\n fig = Figure(figsize=(12,9))\n ax = fig.add_subplot(111, projection='3d')\n x = np.array(x_data)\n y = np.array(y_data)\n hist, xedges, yedges = np.histogram2d(x_data, y_data, bins=(range(losses_range[0] + 2), range(losses_range[1] + 2)))\n elements = (len(xedges)-1) * (len(yedges) - 1)\n xpos, ypos = np.meshgrid(xedges[:-1]-0.35, yedges[:-1]-0.35)\n xpos = xpos.flatten()\n ypos = ypos.flatten()\n zpos = np.zeros(elements)\n dx = 0.5 * np.ones_like(zpos)\n dy = dx.copy()\n dz = hist.flatten()\n ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')\n ax.invert_xaxis()\n ax.set_xlim(right=0)\n ax.set_ylim(bottom=0)\n ax.set_xlabel(\"Defender Loss\")\n ax.set_ylabel(\"Attacker Loss\")\n ax.set_xticks(range(losses_range[0]+1))\n ax.set_yticks(range(losses_range[1]+1))\n canvas = FigureCanvas(fig)\n response= HttpResponse(content_type='image/png')\n canvas.print_png(response)\n return response\n\n return render(request, \"base.html\",\n locals())\n\n\n\n","sub_path":"calculator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"533188397","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom planeta import Planeta\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ncondicion_inicial = [10, 0, 0, 0.4]\n\np = Planeta(condicion_inicial)\n\ndt = 0.1\niteraciones = 60000\nx = np.zeros(iteraciones)\ny = np.zeros(iteraciones)\nvx = np.zeros(iteraciones)\nvy = np.zeros(iteraciones)\nenergia = np.zeros(iteraciones)\ntiempo = np.zeros(iteraciones)\n\nx[0] = p.y_actual[0]\ny[0] = p.y_actual[1]\nenergia[0] = p.energia_total()\ntiempo[0] = p.t_actual\nvx[0] = p.y_actual[2]\nvy[0] = p.y_actual[3]\n\n#Verlet necesita una iteracion extra\np.avanza_rk4(dt)\nx[1] = p.y_actual[0]\ny[1] = p.y_actual[1]\nenergia[1] = p.energia_total()\ntiempo[1] = p.t_actual\nvx[1] = p.y_actual[2]\nvy[1] = p.y_actual[3]\n\nfor i in range(2, iteraciones):\n y_anterior = np.array([x[i-2], y[i-2], vx[i-2], vy[i-2]])\n p.avanza_verlet(dt, y_anterior)\n x[i] = p.y_actual[0]\n y[i] = p.y_actual[1]\n vx[i] = p.y_actual[2]\n vy[i] = p.y_actual[3]\n energia[i] =p.energia_total()\n tiempo [i] = p.t_actual\n\nplt.figure(1)\nplt.clf()\nplt.plot(x,y,color='green')\nplt.xlabel('x[m]')\nplt.ylabel('y[m]')\nplt.grid(True)\nplt.title(' 'u'Ó''rbita calculada con el m'u'é''todo de Verlet ')\nplt.savefig('Orbita_verlet.eps')\n\nplt.figure(2)\nplt.clf()\nplt.plot(tiempo,energia,'green')\nplt.xlabel('Tiempo [s]')\nplt.ylabel('Energ'u'í''a')\nplt.grid(True)\nplt.title(' Energ'u'í''a en funci'u'ó''n del tiempo, m'u'é''todo de Verlet ')\nplt.savefig('Energia_verlet.eps')\n\nplt.show()\n","sub_path":"solucion_usando_verlet.py","file_name":"solucion_usando_verlet.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"640205957","text":"\"\"\"\n198. House Robber\n\nYou are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you\nfrom robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.\n\nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n Total amount you can rob = 1 + 3 = 4.\nExample 2:\n\nInput: nums = [2,7,9,3,1]\nOutput: 12\nExplanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\n Total amount you can rob = 2 + 9 + 1 = 12.\n\n\"\"\"\n\n\nclass Rob(object):\n\n def doit_dp(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n D = [0 for _ in range(len(nums) + 2)]\n D[0], D[1] = 0, 0\n\n for i in range(2, len(nums) + 2):\n D[i] = max(nums[i-2] + D[i-2], D[i-1])\n \n return D[len(nums)+1]\n\n def doit_dp_2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l1, l2, = 0, 0\n for i in nums:\n l2, l1 = l1, max(l2 + i, l1)\n\n return l1\n\n def doit_dp_3(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n robbed, not_robbed = 0, 0\n\n for i in nums:\n robbed, not_robbed = not_robbed + i, max(not_robbed, robbed)\n\n return max(robbed, not_robbed)\n\n def doit4(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n\n def search(nums, i, D):\n if i == len(nums):\n return 0\n\n if i == len(nums) - 1:\n return nums[-1]\n\n if D[i] != 0:\n return D[i]\n\n res = max(search(nums, i + 1, D), search(nums, i + 2, D) + nums[i])\n\n if D[i] == 0:\n D[i] = res\n\n return res\n\n D = [0 for _ in range(len(nums))]\n return search(nums, 0, D)\n\n\"\"\"\n213. House Robber II\n\nYou are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. \nAll houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, \nadjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.\n\nExample 1:\n\nInput: [2,3,2]\nOutput: 3\nExplanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),\n because they are adjacent houses.\nExample 2:\n\nInput: [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n Total amount you can rob = 1 + 3 = 4.\n\n\"\"\"\n\n\nclass RobII(object):\n\n def doit_dp(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return nums[0]\n\n robbed, not_robbed = 0, 0\n for i in range(1, len(nums)):\n robbed, not_robbed = not_robbed + nums[i], max(robbed, not_robbed)\n res1 = max(robbed, not_robbed)\n\n robbed, not_robbed = 0, 0\n for i in range(0, len(nums)-1):\n robbed, not_robbed = not_robbed + nums[i], max(robbed, not_robbed)\n\n return max(res1, robbed, not_robbed)\n\n def doit2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return nums[0]\n\n def search(nums):\n robbed, not_robbed = 0, 0\n for i in nums:\n robbed, not_robbed = i + not_robbed, max(robbed, not_robbed)\n\n return max(robbed, not_robbed) \n\n return max(search(nums[1:]), search(nums[:-1]))\n\n# leetcode 337. House Robber III\n# The thief has found himself a new place for his thievery again. \n# There is only one entrance to this area, called the \"root.\" \n# Besides the root, each house has one and only one parent house. \n# After a tour, the smart thief realized that \"all houses in this place forms a binary tree\". \n# It will automatically contact the police if two directly-linked houses were broken into on the same night.\n\n# Determine the maximum amount of money the thief can rob tonight without alerting the police.\n\n# 3\n# / \\\n# 2 3\n# / \\ \\ \n# 1 3 1\n\n\"\"\"\n337. House Robber III\n\nThe thief has found himself a new place for his thievery again. There is only one entrance to this area, called the \"root.\" \n\nBesides the root, each house has one and only one parent house. After a tour, the smart thief realized that \"all houses in this place forms a binary tree\". \n\nIt will automatically contact the police if two directly-linked houses were broken into on the same night.\n\nDetermine the maximum amount of money the thief can rob tonight without alerting the police.\n\nExample 1:\n\nInput: [3,2,3,null,3,null,1]\n\n 3\n / \\\n 2 3\n \\ \\ \n 3 1\n\nOutput: 7 \nExplanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\nExample 2:\n\nInput: [3,4,5,1,3,null,1]\n\n 3\n / \\\n 4 5\n / \\ \\ \n 1 3 1\n\nOutput: 9\nExplanation: Maximum amount of money the thief can rob = 4 + 5 = 9.\n\"\"\"\n\n# Definition for a binary tree node.\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass RobIII:\n\n def doit_dfs(self, root):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def search(node):\n if not node:\n return 0, 0\n\n lw_l, lwo_l = search(node.left)\n rw_r, rwo_r = search(node.right)\n\n return node.val + lwo_l + rwo_r, max(lw_l, lwo_l) + max(rw_r, rwo_r)\n\n return max(search(root))\n\n def doit_dfs_1(self, root):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def search(node, D):\n if not node:\n return 0\n\n if node in D:\n return D[node]\n\n resl, resr = 0, 0\n resll, reslr, resrl, resrr = 0, 0, 0, 0\n if node.left:\n resl = search(node.left, D)\n resll = search(node.left.left, D)\n reslr = search(node.left.right, D)\n\n if node.right:\n resr = search(node.right, D)\n resrl = search(node.right.left, D)\n resrr = search(node.right.right, D)\n\n res = max(node.val + resll + reslr + resrl + resrr,\n resl + resr)\n D[node] = res\n return res\n \n D = {}\n return search(root, D)\n\n\nif __name__==\"__main__\":\n\n res = RobIII().doit2([1])\n \n res = RobIII().doit([1])\n\n pass","sub_path":"PythonLeetcode/Leetcode/213_HouseRobber.py","file_name":"213_HouseRobber.py","file_ext":"py","file_size_in_byte":7208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"402563107","text":"import socket\nfrom enum import Enum\nfrom random import randint\nimport math\nimport argparse\nimport heapq\n\nname = 'client_mmueller' # name that will be displayed on the server\n\n\"\"\"\nDer Dijkstra Algorythmus wurde von \"http://www.redblobgames.com/pathfinding/a-star/implementation.html\"\nübernommen und leicht verändert.\n\"\"\"\n\n\nclass PriorityQueue:\n \"\"\"\n This is from http://www.redblobgames.com/pathfinding/a-star/implementation.html\n \"\"\"\n def __init__(self):\n self.elements = []\n\n def empty(self):\n return len(self.elements) == 0\n\n def put(self, item, priority):\n self.elements.append((priority, item))\n self.elements.sort(key=lambda tup: tup[0])\n\n def get(self):\n return heapq.heappop(self.elements)[1]\n\n\nclass FieldType(Enum):\n UNKNOWN = 'U'\n GRASS = 'G'\n CASTLE = 'C'\n FOREST = 'F'\n MOUNTAIN = 'M'\n LAKE = 'L'\n\n\nclass ClientController:\n \"\"\"\n This is a bot for a competition held at my school. In the game, 2 bots compete against each other and the first\n one to find and take the bomb to the enemies castle wins. The game Area is variable and warps around on the edges\n ((9, 9) neighbours (0, 9)). The bot can move only in one direction and every round the server sends the Bot a\n string representing the area seen by the bot.\n \"\"\"\n def __init__(self, ip=\"localhost\", port=\"5050\", size=\"10\", verbose=False):\n \"\"\"\n The Bot gets initialized here and connects to the server.\n\n :param ip: the ip to connect to\n :param port: the port to connect to\n :param size: the size of the map\n :param verbose: weather or not the bot prints various massages in the commandline\n \"\"\"\n self.map = [] # internal Map\n self.mapsize = size # size of the map\n self.xy = [0, 0] # position\n self.xy_scroll = [0, 0] # position of the scroll\n self.xy_Fcast = [0, 0] # position of the enemy castle\n self.g_scroll = False # got scroll\n self.f_scroll = False # found scroll\n self.f_Fcast = False # found enemy castle\n self.turn = 0 # number of turns (total)\n self.last_dir = 0 # last direction we went\n self.verbose = verbose #\n\n while len(self.map) < self.mapsize:\n lst = []\n while len(lst) < self.mapsize:\n lst.append(FieldType.UNKNOWN.value)\n self.map.append(lst)\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.clientsocket:\n try:\n # Verbindung herstellen (Gegenpart: accept() )\n self.clientsocket.connect((ip, port))\n msg = name\n # Nachricht schicken\n self.clientsocket.send(msg.encode())\n # Antwort empfangen\n data = self.clientsocket.recv(1024).decode()\n if not data or not data == \"OK\":\n # Schließen, falls Verbindung geschlossen wurde\n self.clientsocket.close()\n\n while self.msg_rec(): # the main loop\n self.go()\n\n if self.verbose:\n print(\"end\")\n self.clientsocket.close()\n except socket.error as serr:\n print(\"Socket error: \" + serr.strerror)\n\n def addView(self, view):\n \"\"\"\n The field of view is being added to the internal map.\n\n :param view: a 2d list, containing all fields\n \"\"\"\n dist = (len(view)-1)/2 # the viewing distance\n if self.verbose: # if the bot is in verbose mode, a lot of information is displayed here\n print()\n print(\"%i ter Zug:\" % (self.turn+1))\n print(\"Sichtweite: %d\" % dist)\n print(\"Position: %i, %i\" % (self.xy[0], self.xy[1]))\n gscroll = \"\"\n if self.g_scroll:\n gscroll = \"(got it)\"\n if self.f_scroll:\n print(\"Found Scroll: %i, %i %s\" % (self.xy_scroll[0], self.xy_scroll[1], gscroll))\n if self.f_Fcast:\n print(\"Found Castle: %i, %i\" % (self.xy_Fcast[0], self.xy_Fcast[1]))\n\n for y in range(0, len(view)):\n if self.verbose:\n print(view[y])\n for x in range(0, len(view)):\n ab = self.translate(x, y, dist)\n a = ab[0] # x position on the real map\n b = ab[1] # y position on the real map\n if view[y][x].upper() == FieldType.CASTLE.value and a != 0 and b != 0:\n # if the field type is 'G' and it is not on (0, 0) the bot recognises it as the enemies castle\n self.f_Fcast = True\n self.xy_Fcast = [a, b]\n self.map[b][a] = view[y][x].upper()\n\n def clearView(self):\n \"\"\"\n Clears the internal map, not really usefull though\n \"\"\"\n self.map = []\n while len(self.map) < self.mapsize:\n lst = []\n while len(lst) < self.mapsize:\n lst.append(FieldType.UNKNOWN.value)\n self.map.append(lst)\n\n def dijkstra_search(self, goal):\n \"\"\"\n This find the most efficient path from the current position to the specified goal\n this has been taken from: http://www.redblobgames.com/pathfinding/a-star/implementation.html\n and modified for my needs. (dont really know how it works tbh)\n\n :param goal: the destination\n \"\"\"\n frontier = PriorityQueue()\n frontier.put(tuple(self.xy), 0)\n goal = tuple(goal)\n came_from = {}\n cost_so_far = {}\n came_from[tuple(self.xy)] = None\n cost_so_far[tuple(self.xy)] = 0\n\n while not frontier.empty():\n current = frontier.get()\n\n if current == goal:\n break\n\n for nextN in self.getNeighbours(current):\n nextN = tuple(nextN)\n new_cost = cost_so_far[current] + self.weight(list(current))\n if nextN not in cost_so_far or new_cost < cost_so_far[nextN]:\n cost_so_far[nextN] = new_cost\n priority = new_cost\n frontier.put(nextN, priority)\n came_from[nextN] = current\n\n path = ClientController.reconstruct_path(came_from, tuple(self.xy), goal)\n if self.verbose:\n print(path)\n if len(path) == 0:\n if self.f_scroll == False:\n pass\n else:\n self.g_scroll = True\n self.go()\n else:\n neighbours = self.getNeighbours(self.xy)\n for i in range(0, len(neighbours)):\n if neighbours[i] == list(path[0]):\n self.goStep(str(i))\n\n return path[0]\n\n def go(self):\n \"\"\"\n Deferments what Algorithm to use and where to go to\n \"\"\"\n if self.f_scroll and not self.g_scroll:\n self.goTo(self.xy_scroll)\n elif self.g_scroll and self.f_Fcast:\n self.goTo(self.xy_Fcast)\n else:\n self.goRandom()\n\n def goRandom(self):\n \"\"\"\n This is being called, if the next target is not discovered yet, not really random.\n In the first 3 rounds, it goes to the field with the least weight, after that, it goes to the field with the\n most neighbours(and neighbours of neighbours and ...) that are undiscovered, trying to reveal the whole map.\n \"\"\"\n if self.turn < 3:\n # this part gets all neighbouring fields and puts them in a PriorityQueue() in order to get the one\n # with the lowest wight\n neig = self.getNeighbours(self.xy)\n if self.turn > 0:\n neig.pop((self.last_dir+2)%len(neig))\n pqueue = PriorityQueue()\n for i in neig:\n pqueue.put(tuple(i), self.weight(i, 5))\n\n # this takes the step with the least weight and translates it to a number and then goes that direction\n step = pqueue.get()\n neighbours = self.getNeighbours(self.xy)\n for i in range(0, len(neighbours)):\n if neighbours[i] == list(step):\n self.goStep(str(i))\n else:\n pqueue = PriorityQueue()\n for y in range(0, len(self.map)):\n for x in range(0, len(self.map)):\n pqueue.put((x, y), self.findUnknown([x, y], 4))\n\n tmp = pqueue.get()\n if self.verbose:\n print(tmp)\n self.dijkstra_search(tmp)\n\n def findUnknown(self, xy, level):\n \"\"\"\n This method finds the field on the map with the most unknown neighbours (recursively)\n\n :param xy: position of field\n :param level: how many levels to go down (rate of recursion)\n :return: a weight calculated\n \"\"\"\n neigh = self.getNeighbours(xy)\n u = 1\n if self.map[xy[1]][xy[0]] == FieldType.UNKNOWN.value:\n u -= 1\n for f in neigh:\n if level > 0:\n u += self.findUnknown(f, level-1)/len(self.getNeighbours(f))\n return u\n\n def goStep(self, step):\n \"\"\"\n This takes the specified number, translates it to a direction and then sends the server the right command.\n\n :param step:\n \"\"\"\n dir = {\n '0': 'up',\n '1': 'right',\n '2': 'down',\n '3': 'left'\n }[step]\n self.last_dir = int(step)\n self.clientsocket.send(dir.encode())\n self.moveX(step)\n\n def goTo(self, xy):\n \"\"\"\n This was useful in the past :/\n\n :param xy: target\n \"\"\"\n self.dijkstra_search(xy)\n\n def getNeighbours(self, xy):\n \"\"\"\n This method returns a list of all neighbouring fields of a specified source field.\n\n :param xy: the source field\n :return: a list of al neighbouring fields\n \"\"\"\n lst = []\n xy = list(xy)\n for i in range(0, 2):\n if i == 1:\n a = xy[0] - 1\n b = xy[1] + 1\n else:\n a = xy[0] + 1\n b = xy[1] - 1\n a = self.warp(a)\n b = self.warp(b)\n lst.append([self.warp(xy[0]), b])\n lst.append([a, self.warp(xy[1])])\n\n return lst\n\n def getNewFields(self, xy):\n \"\"\"\n This Method returns how many fields are unknown in the area of the given field.\n\n :param xy: the field to test\n :return: amount of unknown fields\n \"\"\"\n i = 0\n lst = []\n dist = 1 # field of view\n ftype = self.map[xy[1]][xy[0]]\n if ftype == FieldType.GRASS.value:\n dist = 2\n elif ftype == FieldType.MOUNTAIN.value:\n dist = 3\n\n for y in range(0, (dist+1)*2):\n for x in range(0, (dist+1)*2):\n ab = self.translate(x, y, dist)\n a = ab[0]\n b = ab[1]\n if self.map[b][a] == FieldType.UNKNOWN.value:\n i += 1\n return i\n\n def msg_rec(self):\n \"\"\"\n this receives a message from the server and decodes it.\n \"\"\"\n data = self.clientsocket.recv(1024).decode()\n view = []\n\n if not data:\n return False\n\n if data[1] != ' ' and data[1] != 'B':\n print(data)\n return False\n\n i = int(math.sqrt(len(data)/2)) # diameter viewing distance\n\n for y in range(0, i):\n row = []\n for x in range(0, i):\n row.append(data[(i*2*y)+x*2])\n if data[(i*2*y)+x*2+1] == 'B':\n ab = self.translate(x, y, (i-1)/2)\n a = ab[0]\n b = ab[1]\n self.f_scroll = True\n self.xy_scroll = [a, b]\n view.append(row)\n\n self.addView(view)\n if self.verbose:\n self.printMap()\n return True\n\n def moveX(self, i):\n \"\"\"\n This updates the internal Position.\n\n :param i: direction of movement\n \"\"\"\n if i == '0':\n self.xy[1] -= 1\n elif i == '1':\n self.xy[0] += 1\n elif i == '2':\n self.xy[1] += 1\n elif i == '3':\n self.xy[0] -= 1\n self.warpX()\n self.turn += 1\n\n def printMap(self):\n \"\"\"\n This prints the internal map with numbers representing line and row numbers.\n \"\"\"\n ustr = ''\n while len(ustr) < len(str(len(self.map[1]))):\n ustr += ' '\n for i in range(0, len(self.map[1])):\n tstr = \"%i:\" % i\n ustr += '%5s' % tstr\n\n print(ustr) # top row\n for i in range(0, len(self.map)):\n fstr = str(i) + ':'\n while len(fstr) < len(str(len(self.map[1])))+1:\n fstr += ' '\n print(fstr + str(self.map[i]))\n\n @staticmethod\n def reconstruct_path(came_from, start, goal):\n \"\"\"\n This has also been taken from: http://www.redblobgames.com/pathfinding/a-star/implementation.html\n\n :param came_from: a list of tuples representing the chosen path\n :param start: xy pos\n :param goal: py pos of target\n :return:\n \"\"\"\n current = goal\n path = [current]\n while current != start:\n current = came_from[current]\n path.append(current)\n path.pop()\n path.reverse()\n return path\n\n def translate(self, x, y, dist):\n \"\"\"\n This translates coordinates from the server-input to the coordinates on the internal map.\n\n :param x: x position on the servers massage\n :param y: y position on the servers massage\n :param dist: diameter of the viewing distance\n :return: list containing x, y position, converted to the relative position on the internal map\n \"\"\"\n a = self.xy[0] + x - dist\n b = self.xy[1] + y - dist\n a = self.warp(a)\n b = self.warp(b)\n return [a, b]\n\n def warp(self, a):\n return int(a%len(self.map))\n\n def warpX(self):\n \"\"\"\n Translates the internal xy position if it gets near te edge.\n \"\"\"\n self.xy[0] %= len(self.map)\n self.xy[1] %= len(self.map)\n\n def weight(self, xy, neighbours=0):\n \"\"\"\n This calculates the weight of a field, don't ask what went through my mind\n\n :param xy: Field to check\n :param neighbours: determines how many levels of neighbouring fields should\n :return:\n \"\"\"\n xy[0] = self.warp(xy[0])\n xy[1] = self.warp(xy[1])\n if self.f_Fcast and self.f_scroll:\n uvalue = 150\n else:\n uvalue = 100\n\n b = {\n FieldType.UNKNOWN.value: uvalue,\n FieldType.GRASS.value: 100,\n FieldType.FOREST.value: 100,\n FieldType.MOUNTAIN.value: 200,\n FieldType.LAKE.value: 9999999,\n FieldType.CASTLE.value: 100\n }[self.map[xy[1]][xy[0]]]\n\n if not self.f_Fcast and not self.f_scroll:\n b -= self.getNewFields(xy)*5\n b += randint(0, 10)\n if neighbours > 0:\n neighbours -= 1\n c = 0\n for i in self.getNeighbours(xy):\n c += self.weight(i, neighbours)\n b += c/len(self.getNeighbours(xy))\n return b\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-i', '--ip-address=', type=str, help='server to connect to', default='localhost', dest='server')\n parser.add_argument(\n '-p', '--port=', type=int, help='port number', default=5050, dest='port')\n parser.add_argument(\n '-s', '--size=', type=int, help='size of the map', default=10, dest='size')\n parser.add_argument(\n '-v', '--verbose', help='if true it displays the steps in the commandline', action=\"store_true\")\n args = parser.parse_args()\n print(args)\n client = ClientController(args.server, args.port, args.size, args.verbose)\n","sub_path":"ipc/Game/client_mmueller.py","file_name":"client_mmueller.py","file_ext":"py","file_size_in_byte":16202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"591908797","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/pyams_utils/container.py\n# Compiled at: 2020-02-18 19:11:13\n# Size of source mod 2**32: 5160 bytes\n__doc__ = 'PyAMS_utils.container module\\n\\nThis module provides several classes, adapters and functions about containers.\\n'\nfrom BTrees.OOBTree import OOBTree\nfrom persistent.list import PersistentList\nfrom pyramid.threadlocal import get_current_registry\nfrom zope.container.interfaces import IContained, IContainer\nfrom zope.container.ordered import OrderedContainer\nfrom zope.lifecycleevent.interfaces import IObjectMovedEvent\nfrom zope.location.interfaces import ISublocations\nfrom pyams_utils.adapter import ContextAdapter, adapter_config\n__docformat__ = 'restructuredtext'\n\nclass BTreeOrderedContainer(OrderedContainer):\n \"\"\"BTreeOrderedContainer\"\"\"\n\n def __init__(self):\n self._data = OOBTree()\n self._order = PersistentList()\n\n\nclass ParentSelector:\n \"\"\"ParentSelector\"\"\"\n\n def __init__(self, ifaces, config):\n if not isinstance(ifaces, (list, tuple, set)):\n ifaces = (\n ifaces,)\n self.interfaces = ifaces\n\n def text(self):\n \"\"\"Predicate string output\"\"\"\n return 'parent_selector = %s' % str(self.interfaces)\n\n phash = text\n\n def __call__(self, event):\n if not IObjectMovedEvent.providedBy(event):\n return False\n for intf in self.interfaces:\n try:\n if intf.providedBy(event.newParent):\n return True\n except (AttributeError, TypeError):\n if isinstance(event.newParent, intf):\n return True\n\n return False\n\n\n@adapter_config(context=IContained, provides=ISublocations)\nclass ContainerSublocationsAdapter(ContextAdapter):\n \"\"\"ContainerSublocationsAdapter\"\"\"\n\n def sublocations(self):\n \"\"\"See `zope.location.interfaces.ISublocations` interface\"\"\"\n context = self.context\n registry = get_current_registry()\n for name, adapter in registry.getAdapters((context,), ISublocations):\n if not name:\n pass\n else:\n yield from adapter.sublocations()\n\n if IContainer.providedBy(context):\n yield from context.values()\n\n\ndef find_objects_matching(root, condition, ignore_root=False):\n \"\"\"Find all objects in root that match the condition\n\n The condition is a Python callable object that takes an object as\n argument and must return a boolean result.\n\n All sub-objects of the root will also be searched recursively.\n\n :param object root: the parent object from which search is started\n :param callable condition: a callable object which may return true for a given\n object to be selected\n :param boolean ignore_root: if *True*, the root object will not be returned, even if it matches\n the given condition\n :return: an iterator for all root's sub-objects matching condition\n \"\"\"\n if not ignore_root and condition(root):\n yield root\n locations = ISublocations(root, None)\n if locations is not None:\n for location in locations.sublocations():\n if condition(location):\n yield location\n yield from find_objects_matching(location, condition, ignore_root=True)\n\n\ndef find_objects_providing(root, interface):\n \"\"\"Find all objects in root that provide the specified interface\n\n All sub-objects of the root will also be searched recursively.\n\n :param object root: object; the parent object from which search is started\n :param Interface interface: interface; an interface that sub-objects should provide\n :return: an iterator for all root's sub-objects that provide the given interface\n \"\"\"\n yield from find_objects_matching(root, interface.providedBy)","sub_path":"pycfiles/pyamtrack-0.1.4-py3-none-manylinux1_x86_64/container.cpython-35.py","file_name":"container.cpython-35.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"381899819","text":"# 10 - Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou V-Vespertino ou N- Noturno. Imprima a mensagem \"Bom Dia!\", \"Boa Tarde!\" ou \"Boa Noite!\" ou \"Valor Inválido!\", conforme o caso.\n\ndef função():\n\n print('Digite o turno que você estuda...')\n turno = input('(M) para matutino, (V) para vespertino e (N) para Noturno: ')\n\n if turno == 'M' or turno == 'm':\n print('\\nBom Dia!!')\n\n elif turno == 'V' or turno == 'v':\n print('\\nBoa Tarde!!')\n\n elif turno == 'N' or turno == 'n':\n print('\\nBoa Noite!!')\n\nfunção()","sub_path":"Lista 3/Lista 3 Ex10.py","file_name":"Lista 3 Ex10.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"338895135","text":"from django.urls import path\nfrom accounts.api.views import (\n registration_view,\n account_properties_view,\n update_account_view,\n)\n\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nurlpatterns = [\n #Accounts\n path('register', registration_view, name='register'),\n path('login', obtain_auth_token, name='login'),\n path('properties', account_properties_view, name='properties'),\n path('properties/update', update_account_view, name='update_properties'),\n\n]","sub_path":"accounts/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"182638407","text":"import argparse\nimport csv\nimport os\nimport re\n\nfrom bs4 import BeautifulSoup\n\ndef likes_and_reactions(data_path):\n \"\"\"\n Parse likes_and_reactions/posts_and_comments.html to a csv file that can be used\n in the processing functions.\n\n Parameters\n ----------\n data_path : str\n Path to the root directory of your personal facebook data.\n\n \"\"\"\n path = os.path.join(data_path, \"likes_and_reactions/\")\n html_path = os.path.join(path, \"posts_and_comments.html\")\n soup = BeautifulSoup(open(html_path), \"html.parser\")\n csv_path = os.path.join(path, \"posts_and_comments.csv\")\n\n reg_1 = re.compile(r\"^(.*?)(?: like(?:s|d) | reacted to )(.*?)(?:'s| own)\")\n reg_2 = re.compile(r\"(\\w+)\\.png\")\n with open(csv_path, 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=\",\")\n header = ['time', 'reaction', 'liker', 'poster']\n writer.writerow(header)\n for reaction_div in soup.find_all(\"div\", \"pam _3-95 _2pi0 _2lej uiBoxWhite noborder\"):\n reaction_text = reaction_div.find(\"div\", \"_3-96 _2pio _2lek _2lel\").get_text()\n liker = reg_1.match(reaction_text).group(1)\n poster = reg_1.match(reaction_text).group(2)\n full_reaction = reaction_div.find(\"div\", \"_2pin\").find(\"img\")['src']\n reaction = reg_2.search(full_reaction).group(1)\n time = reaction_div.find(\"div\", \"_3-94 _2lem\").get_text()\n writer.writerow([time, reaction, liker, poster])\n\ndef messages(data_path):\n \"\"\"\n Parse message from conversation to a csv file that can be used\n in the processing functions.\n\n Parameters\n ----------\n data_path : str\n Path to the root directory of your personal facebook data.\n \"\"\"\n path = os.path.join(data_path, \"messages/inbox\")\n\n conversations = os.listdir(path)\n for conversation in conversations:\n conversation_path = os.path.join(path, conversation)\n messages_html_path = os.path.join(conversation_path, \"message.html\")\n if os.path.isfile(messages_html_path):\n print(conversation)\n print(\"Loading html source ...\")\n soup = BeautifulSoup(open(messages_html_path), \"html.parser\")\n csv_path = os.path.join(conversation_path, \"message.csv\")\n print(\"Writing csv ...\")\n with open(csv_path, 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=\",\")\n header = ['time', 'sender', 'text']\n writer.writerow(header)\n for message_div in soup.select('div[role=\"main\"] > div.pam._3-95._2pi0._2lej.uiBoxWhite.noborder'):\n sender_div = message_div.find(\"div\", \"_3-96 _2pio _2lek _2lel\")\n if sender_div:\n sender = sender_div.get_text()\n else:\n sender = \"unknown\"\n time_text = message_div.find(\"div\", \"_3-94 _2lem\").get_text()\n text_div = message_div.select('div._3-96._2let > div > div')\n if len(text_div) > 1:\n text = text_div[1].get_text()\n else:\n text = \"unknown\"\n writer.writerow([time_text, sender, text])\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('path', type=str,\n help='path to the root directory of the downloaded Facebook data.')\n args = parser.parse_args()\n messages(args.path)","sub_path":"insights/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"102125313","text":"# %load q01_load_data_and_add_column_names/build.py\nimport pandas as pd\npath = './data/GermanData.csv'\n\ndef q01_load_data_and_add_column_names(path):\n df = pd.read_csv(path, sep=',', header=None, names=['account_status', 'month', 'credit_history', 'purpose', 'credit_amount', 'savings_account/bonds','employment','installment_rate','personal_status/sex','guarantors','residence_since','property','age','other_installment_plans','housing','number_of_existing_credits','job','liable','telephone','foreign_worker','good/bad'])\n df.loc[df['good/bad'] == 1, 'good/bad'] = 0\n df.loc[df['good/bad'] == 2, 'good/bad'] = 1\n return df\nq01_load_data_and_add_column_names(path)\n\n\n","sub_path":"q01_load_data_and_add_column_names/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"288773286","text":"import numpy as np\nimport cv2\nimport matplotlib.image as mpimg\nimport camera\nimport pickle\nfrom image_processor import ImageProcessor\nimport os.path\nimport matplotlib.pyplot as plt\nfrom line import Line\nfrom moviepy.editor import VideoFileClip\n\nif os.path.exists(camera.CAL_FILE_NAME): \n (mtx, dist) = pickle.load(open( \"cal_data.p\", \"rb\" ) )\nelse:\n mtx, dist = camera.calibrate_camera(9,6)\n pickle.dump( (mtx, dist), open( \"cal_data.p\", \"wb\" ) )\n\nsrc = [(600, 460), (710, 460), (1100, 690), (260, 690)]\ndst = [(260, 80), (1000, 80), (1000, 700), (260, 700)]\nM = cv2.getPerspectiveTransform(np.float32(src), np.float32(dst))\n\nleft = Line()\nright = Line()\nproc = ImageProcessor(mtx, dist, M)\n\ndef process_image(img):\n proc.process_image(img, left, right)\n img = proc.overlay_route(img, left, right)\n \n half_of_route = (right.line_base_pos - left.line_base_pos) / 2\n diff = left.line_base_pos + half_of_route\n half_of_image = left.shape[1]/2 - diff\n distance_from_center = half_of_image * left.xm_per_pix\n\n cv2.putText(img, 'Curvature left: {:.0f}m; right: {:.0f}m'.format(left.radius_of_curvature, right.radius_of_curvature) ,(10,100), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2)\n cv2.putText(img, 'Distance from the center: {:.3f}m'.format(distance_from_center) ,(10,150), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255),2)\n return img\n\n# img = mpimg.imread('test_images/vlc.jpg')\n# overlayed = process_image(img)\n\n# fig = plt.figure()\n# a=fig.add_subplot(4,2,1)\n# plt.imshow(img)\n# a=fig.add_subplot(4,2,2)\n# plt.imshow(proc.warped)\n\n# a=fig.add_subplot(4,2,3)\n# plt.imshow(proc.s_channel, cmap='gray')\n\n# a=fig.add_subplot(4,2,4)\n# plt.imshow(proc.s_binary, cmap='gray')\n\n# a=fig.add_subplot(4,2,5)\n# plt.imshow(proc.l_channel, cmap='gray')\n\n# a=fig.add_subplot(4,2,6)\n# plt.imshow(proc.sxbinary, cmap='gray')\n\n# a=fig.add_subplot(4,2,7)\n# plt.imshow(proc.out_img)\n# plt.plot(left.fitx, left.ploty, color='yellow')\n# plt.plot(right.fitx, left.ploty, color='yellow')\n\n# a=fig.add_subplot(4,2,8)\n# plt.imshow(overlayed)\n\n# fig.show()\n# input()\n\nwhite_output = 'output_images/project_video.mp4'\nclip1 = VideoFileClip(\"materials/project_video.mp4\") \nwhite_clip = clip1.fl_image(process_image)\nwhite_clip.write_videofile(white_output, audio=False)","sub_path":"recognition.py","file_name":"recognition.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"598275292","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\n\nclass UserProfile(models.Model):\n \"\"\"To keep extra user data\"\"\"\n #user mapping\n\n user = models.OneToOneField(User)\n\n class Meta(object):\n verbose_name = u\"Профіль користувача\"\n\n #extra user data\n\n photo = models.ImageField(\n blank=True,\n verbose_name=u'Аватар',\n null=True,\n upload_to='user-avatar')\n\n sex = models.ForeignKey('UserSex',\n blank=True,\n verbose_name=u'Стать',\n null=True)\n\n\n views = models.IntegerField(\n verbose_name=u'Перегляди',\n blank=True,\n null=True)\n\n birthday = models.DateField(\n verbose_name=u'День народження',\n blank=True,\n null=True)\n\n about_yourself = models.TextField(\n verbose_name=u'Про себе',\n blank=True,\n default=u'I love DjangoBlog')\n\n def __unicode__(self):\n return self.user.username\n\nclass UserSex(models.Model):\n\n class Meta(object):\n verbose_name = u'Стать'\n\n user_sex = models.CharField(\n max_length=100,\n verbose_name=u'Стать')\n\n def __unicode__(self):\n return self.user_sex","sub_path":"userprofile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"104877543","text":"'''\nhttps://www.youtube.com/watch?v=1Xa_iDqvg94&list=PLGLfVvz_LVvTn3cK5e6LjhgGiSeVlIRwt&index=5\n'''\n\n#Ex1\n# this global name is not going to change\ndef change_name(name):\n name = 'Tanvi' # local var\nname = \"Manasvi\" # globale var\nchange_name('Satheesh')\nprint(name)\nprint('\\n')\n# this global name is going to change\ndef change_name(name):\n return name # local var\nname = \"Manasvi\" # globale var\nname = change_name('Satheesh')\nprint(name)\nprint('\\n')\n#Ex1 - using global var in local to change name should not implact on global name\n\ngbl_name = \"Tanvi Satheesh\"\ndef change_name():\n global gbl_name\n gbl_name = 'Manasvi Satheesh'\n\nchange_name()\nprint(gbl_name)\n","sub_path":"Cory_Basic/Function/Fun1.py","file_name":"Fun1.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"199025245","text":"#!/usr/bin/env python\n\"\"\"\nWritten by Chen Yang on Mar 25th, 2015\nTo get the length of head, aligned, and tail regions of an alignment.\n\nMajor change in Apr 22nd\n\nUpdated in Nov 25th\n\"\"\"\n\nfrom __future__ import with_statement\nimport sys\nimport getopt\nimport numpy\n\n\ndef head_align_tail(outfile):\n out1 = open(outfile + '_aligned_length_ecdf', 'w')\n out2 = open(outfile + '_aligned_reads_ecdf', 'w')\n out3 = open(outfile + '_ht_ratio', 'w')\n out4 = open(outfile + \"_align_ratio\", 'w')\n\n aligned = []\n total = []\n ht_total = []\n ht_ratio = {\n (0, 10): [], (10, 20): [], (20, 30): [], (30, 40): [], (40, 50): [], (50, 100): [], (100, 300): [], (300, 1000): [],\n (1000, 2000): [], (2000, 3000): [], (3000, 5000): [], (5000, 7500): [], (7500, 10000): [], (10000, \"Inf\"): []}\n align_ratio = {\n (0, 1000): [], (1000, 2000): [], (2000, 3000): [], (3000, 4000): [], (4000, 5000): [], (5000, 6000): [],\n (6000, 7000): [], (7000, 8000): [], (8000, 9000): [], (9000, 10000): [], (10000, 11000): [], (11000, 12000): [],\n (12000, 13000): [], (13000, 15000): [], (15000, 20000): [], (20000, 25000): [], (25000, \"Inf\"): []}\n\n besthit_out = outfile + \"_besthit.maf\"\n with open(besthit_out, 'r') as f:\n for line in f:\n new = line.strip().split()\n aligned_ref = int(new[3])\n aligned.append(aligned_ref)\n new = next(f).strip().split()\n head = int(new[2])\n # tail = int(new[5])-int(new[2])-int(new[3])\n total.append(int(new[5]))\n ht = int(new[5])-int(new[3])\n ht_total.append(ht)\n ratio = float(new[3])/float(new[5])\n for key in align_ratio.keys():\n if key[0] <= int(new[3]) < key[1]:\n align_ratio[key].append(ratio)\n break\n for k in ht_ratio.keys():\n if k[0] <= ht < k[1]:\n if ht != 0:\n r = float(head) / ht\n ht_ratio[k].append(r)\n break\n\n max_length = max(total)\n max_ht_length = max(ht_total)\n \n #remove keys that are larger than max_length\n a_ratio_keys = align_ratio.keys()\n for pair in a_ratio_keys:\n lowerKey = pair[0]\n if lowerKey >= max_length:\n del align_ratio[pair]\n \n #remove keys that are larger than max_length\n ht_ratio_keys = ht_ratio.keys()\n for pair in ht_ratio_keys:\n lowerKey = pair[0]\n if lowerKey >= max_ht_length:\n del ht_ratio[pair]\n \n # The last key in align_ratio and ht_ratio are to Inf, needs to be replaced with the maximum length\n last_key = sorted(align_ratio.keys())[-1]\n last_values = align_ratio[last_key]\n del align_ratio[last_key]\n align_ratio[(last_key[0], max_length)] = last_values\n\n last_key = sorted(ht_ratio.keys())[-1]\n last_values = ht_ratio[last_key]\n del ht_ratio[last_key]\n ht_ratio[(last_key[0], max_ht_length)] = last_values\n\n # ecdf of align ratio\n align_cum = dict.fromkeys(align_ratio.keys(), [])\n for key, value in align_ratio.items():\n if value:\n hist_ratio, bin_edges = numpy.histogram(value, bins=numpy.arange(0, 1.001, 0.001), density=True)\n cdf = numpy.cumsum(hist_ratio * 0.001)\n else:\n cdf = [0] * 1000\n align_cum[key] = cdf\n\n out4.write(\"bins\\t\" + '\\t'.join(\"%s-%s\" % tup for tup in sorted(align_cum.keys())) + '\\n')\n for i in xrange(len(cdf)):\n out4.write(str(bin_edges[i]) + '-' + str(bin_edges[i+1]) + \"\\t\")\n for key in sorted(align_cum.keys()):\n out4.write(str(align_cum[key][i]) + \"\\t\")\n out4.write(\"\\n\")\n\n # ecdf of head/total ratio\n ht_cum = dict.fromkeys(ht_ratio.keys(), [])\n for key, value in ht_ratio.items():\n if value:\n hist_ratio, bin_edges = numpy.histogram(value, bins=numpy.arange(0, 1.001, 0.001), density=True)\n cdf = numpy.cumsum(hist_ratio * 0.001)\n else:\n cdf = [0] * 1000\n ht_cum[key] = cdf\n\n out3.write(\"bins\\t\" + \"\\t\".join(\"%s-%s\" % tup for tup in sorted(ht_cum.keys())) + \"\\n\")\n for i in xrange(len(cdf)):\n out3.write(str(bin_edges[i]) + '-' + str(bin_edges[i+1]) + \"\\t\")\n for key in sorted(ht_cum.keys()):\n out3.write(str(ht_cum[key][i]) + \"\\t\")\n out3.write(\"\\n\")\n\n # ecdf of length of aligned regions\n hist_aligned, bin_edges = numpy.histogram(aligned, bins=numpy.arange(0, max_length + 51, 50), density=True)\n cdf = numpy.cumsum(hist_aligned * 50)\n out1.write(\"bin\\t0-\" + str(max_length) + '\\n')\n for i in xrange(len(cdf)):\n out1.write(str(bin_edges[i]) + '-' + str(bin_edges[i+1]) + \"\\t\" + str(cdf[i]) + '\\n')\n num_aligned = len(aligned)\n\n # ecdf of length of aligned reads\n hist_reads, bin_edges = numpy.histogram(total, bins=numpy.arange(0, max_length + 51, 50), density=True)\n cdf = numpy.cumsum(hist_reads * 50)\n out2.write(\"bin\\t0-\" + str(max_length) + '\\n')\n for i in xrange(len(cdf)):\n out2.write(str(bin_edges[i]) + '-' + str(bin_edges[i+1]) + \"\\t\" + str(cdf[i]) + '\\n')\n\n out1.close()\n out2.close()\n out3.close()\n out4.close()\n return num_aligned\n","sub_path":"src/head_align_tail_dist.py","file_name":"head_align_tail_dist.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"17658994","text":"import time\nimport logging\nfrom pathlib import Path\n\n\ndef call_log():\n print(\"This is my first week's homework.\")\n #文件路径设置\n filepath = 'E:/var/log/python-{}/'.format(time.strftime('%Y%m%d',time.localtime()))\n #创建文件目录\n Path(filepath).mkdir(parents = True , exist_ok = True)\n #日志格式配置\n logging.basicConfig(\n filename = filepath + 'call.log' ,\n level = logging.INFO ,\n datefmt=\"%Y-%m-%d %H:%M:%S\" ,\n format = '%(asctime)s %(message)s'\n )\n logging.info('is when this function was called')\n \nif __name__ == '__main__':\n call_log()\n\n\n\n","sub_path":"week01/week01.py","file_name":"week01.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"22550930","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd \nimport numpy as np\n\n\n# In[14]:\n\n\ndataset_a_aac = pd.read_csv(\"C:/Users/user1/Desktop/AAC_Data/AAC_Based_On_SS3_ClassA.csv\")\ndataset_b_aac = pd.read_csv(\"C:/Users/user1/Desktop/AAC_Data/AAC_Based_On_SS3_ClassB.csv\")\ndataset_c_aac = pd.read_csv(\"C:/Users/user1/Desktop/AAC_Data/AAC_Based_On_SS3_ClassC.csv\")\ndataset_d_aac = pd.read_csv(\"C:/Users/user1/Desktop/AAC_Data/AAC_Based_On_SS3_ClassD.csv\")\n\n\n# In[15]:\n\n\nX_a_aac = dataset_a_aac.iloc[:, 1:21].values \ny_a_aac = dataset_a_aac.iloc[:, 21].values\nX_b_aac = dataset_b_aac.iloc[:, 1:21].values \ny_b_aac = dataset_b_aac.iloc[:, 21].values\nX_c_aac = dataset_c_aac.iloc[:, 1:21].values \ny_c_aac = dataset_c_aac.iloc[:, 21].values\nX_d_aac = dataset_d_aac.iloc[:, 1:21].values \ny_d_aac = dataset_d_aac.iloc[:, 21].values\n\n\n# In[16]:\n\n\nX_a = X_a_aac\nX_b = X_b_aac\nX_c = X_c_aac\nX_d = X_d_aac\ny_a = y_a_aac\ny_b = y_b_aac\ny_c = y_c_aac\ny_d = y_d_aac\nprint(X_a[0])\nprint(y_a[0])\n\n\n# In[17]:\n\n\nfrom sklearn.model_selection import train_test_split\n\nX_train_a, X_test_a, y_train_a, y_test_a = train_test_split(X_a, y_a, test_size=0.3, random_state=0) \nX_train_b, X_test_b, y_train_b, y_test_b = train_test_split(X_b, y_b, test_size=0.3, random_state=0)\nX_train_c, X_test_c, y_train_c, y_test_c = train_test_split(X_c, y_c, test_size=0.3, random_state=0) \nX_train_d, X_test_d, y_train_d, y_test_d = train_test_split(X_d, y_d, test_size=0.3, random_state=0)\nX_train=np.concatenate((X_train_a, X_train_b, X_train_c, X_train_d), axis=0)\nX_test=np.concatenate((X_test_a, X_test_b, X_test_c, X_test_d), axis=0)\ny_train=np.concatenate((y_train_a, y_train_b, y_train_c, y_train_d), axis=0)\ny_test=np.concatenate((y_test_a, y_test_b, y_test_c, y_test_d), axis=0)\n\n\n# In[18]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nclassifier = RandomForestClassifier(n_estimators=100, random_state=0) \nclassifier.fit(X_train, y_train) \ny_pred = classifier.predict(X_test)\n\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n\nprint(confusion_matrix(y_test,y_pred)) \nprint(classification_report(y_test,y_pred)) \nprint(accuracy_score(y_test, y_pred))\n\n# AAC Performance\n# [[423 45 146 140]\n# [ 49 483 124 184]\n# [ 51 57 944 139]\n# [127 183 278 433]]\n# precision recall f1-score support\n\n# a 0.65 0.56 0.60 754\n# b 0.63 0.57 0.60 840\n# c 0.63 0.79 0.70 1191\n# d 0.48 0.42 0.45 1021\n\n# avg / total 0.60 0.60 0.59 3806\n\n# 0.5998423541776143\n\n\n# In[19]:\n\n\nimport pandas as pd \nimport numpy as np\nimport os\npath1=\"E:\\\\Dropbox\\\\Apurva\\\\PHD\\\\Second Year\\\\Datasets\\\\Feature Data\\\\SS Group Pattern Composition\\\\SS3\\\\All\\\\7 Pattern\"\npath2=\"E:\\\\Dropbox\\\\Apurva\\\\PHD\\\\Second Year\\\\Datasets\\\\Feature Data\\\\Functional Features\"\n\npath3=\"E:\\\\Dropbox\\\\Apurva\\\\PHD\\\\Second Year\\\\Datasets\\\\Feature Data\\\\AAComposition\\\\AAC_Data\"\n\n\n# In[21]:\n\n\nSCOPe_a_aac = pd.read_csv(os.path.join(path3,\"AAC_Based_On_SS3_ClassA.csv\"))\nSCOPe_b_aac = pd.read_csv(os.path.join(path3,\"AAC_Based_On_SS3_ClassB.csv\"))\nSCOPe_c_aac = pd.read_csv(os.path.join(path3,\"AAC_Based_On_SS3_ClassC.csv\"))\nSCOPe_d_aac = pd.read_csv(os.path.join(path3,\"AAC_Based_On_SS3_ClassD.csv\"))\n\n\nSCOPe_a_ss3 = pd.read_csv(os.path.join(path1,\"SS3_Group_Patterns_ClassA3.csv\"))\nSCOPe_b_ss3 = pd.read_csv(os.path.join(path1,\"SS3_Group_Patterns_ClassB3.csv\"))\nSCOPe_c_ss3 = pd.read_csv(os.path.join(path1,\"SS3_Group_Patterns_ClassC3.csv\"))\nSCOPe_d_ss3 = pd.read_csv(os.path.join(path1,\"SS3_Group_Patterns_ClassD3.csv\"))\n\nSCOPe_a_ss3_part = pd.read_csv(os.path.join(path1,\"SS3_Group_Part_Patterns_ClassA3.csv\"))\nSCOPe_b_ss3_part = pd.read_csv(os.path.join(path1,\"SS3_Group_Part_Patterns_ClassB3.csv\"))\nSCOPe_c_ss3_part = pd.read_csv(os.path.join(path1,\"SS3_Group_Part_Patterns_ClassC3.csv\"))\nSCOPe_d_ss3_part = pd.read_csv(os.path.join(path1,\"SS3_Group_Part_Patterns_ClassD3.csv\"))\n\nSCOPe_a_fun = pd.read_csv(os.path.join(path2,\"FunctionalFeatures_A1.csv\"))\nSCOPe_b_fun = pd.read_csv(os.path.join(path2,\"FunctionalFeatures_B1.csv\"))\nSCOPe_c_fun = pd.read_csv(os.path.join(path2,\"FunctionalFeatures_C1.csv\"))\nSCOPe_d_fun = pd.read_csv(os.path.join(path2,\"FunctionalFeatures_D1.csv\"))\n\n\n# In[23]:\n\n\nSCOPe_X_a_aac = SCOPe_a_aac.iloc[:, 1:21].values \nSCOPe_y_a_aac = SCOPe_a_aac.iloc[:, 21].values\nSCOPe_X_b_aac = SCOPe_b_aac.iloc[:, 1:21].values \nSCOPe_y_b_aac = SCOPe_b_aac.iloc[:, 21].values\nSCOPe_X_c_aac = SCOPe_c_aac.iloc[:, 1:21].values \nSCOPe_y_c_aac = SCOPe_c_aac.iloc[:, 21].values\nSCOPe_X_d_aac = SCOPe_d_aac.iloc[:, 1:21].values \nSCOPe_y_d_aac = SCOPe_d_aac.iloc[:, 21].values\n\nSCOPe_X_a_ss3 = SCOPe_a_ss3.iloc[:,1:8].values\nSCOPe_y_a_ss3 = SCOPe_a_ss3.iloc[:,8].values\nSCOPe_X_b_ss3 = SCOPe_b_ss3.iloc[:,1:8].values\nSCOPe_y_b_ss3 = SCOPe_b_ss3.iloc[:,8].values\nSCOPe_X_c_ss3 = SCOPe_c_ss3.iloc[:,1:8].values\nSCOPe_y_c_ss3 = SCOPe_c_ss3.iloc[:,8].values\nSCOPe_X_d_ss3 = SCOPe_d_ss3.iloc[:,1:8].values\nSCOPe_y_d_ss3 = SCOPe_d_ss3.iloc[:,8].values\n\n\nSCOPe_X_a_ss3_part = SCOPe_a_ss3_part.iloc[:,1:29].values\nSCOPe_y_a_ss3_part = SCOPe_a_ss3_part.iloc[:,29].values\nSCOPe_X_b_ss3_part = SCOPe_b_ss3_part.iloc[:,1:29].values\nSCOPe_y_b_ss3_part = SCOPe_b_ss3_part.iloc[:,29].values\nSCOPe_X_c_ss3_part = SCOPe_c_ss3_part.iloc[:,1:29].values\nSCOPe_y_c_ss3_part = SCOPe_c_ss3_part.iloc[:,29].values\nSCOPe_X_d_ss3_part = SCOPe_d_ss3_part.iloc[:,1:29].values\nSCOPe_y_d_ss3_part = SCOPe_d_ss3_part.iloc[:,29].values\n\nSCOPe_X_a_fun = SCOPe_a_fun.iloc[:,1:40].values\nSCOPe_y_a_fun = SCOPe_a_fun.iloc[:,68].values\nSCOPe_X_b_fun = SCOPe_b_fun.iloc[:,1:40].values\nSCOPe_y_b_fun = SCOPe_b_fun.iloc[:,68].values\nSCOPe_X_c_fun = SCOPe_c_fun.iloc[:,1:40].values\nSCOPe_y_c_fun = SCOPe_c_fun.iloc[:,68].values\nSCOPe_X_d_fun = SCOPe_d_fun.iloc[:,1:40].values\nSCOPe_y_d_fun = SCOPe_d_fun.iloc[:,68].values\n\n\nprint(SCOPe_X_a_aac[0])\nprint(SCOPe_y_a_aac[0])\n\n\n# In[24]:\n\n\nSCOPe_X_a = np.concatenate((SCOPe_X_a_aac, SCOPe_X_a_ss3, SCOPe_X_a_ss3_part, SCOPe_X_a_fun), axis=1)\nSCOPe_X_b = np.concatenate((SCOPe_X_b_aac, SCOPe_X_b_ss3, SCOPe_X_b_ss3_part, SCOPe_X_b_fun), axis=1)\nSCOPe_X_c = np.concatenate((SCOPe_X_c_aac, SCOPe_X_c_ss3, SCOPe_X_c_ss3_part, SCOPe_X_c_fun), axis=1)\nSCOPe_X_d = np.concatenate((SCOPe_X_d_aac, SCOPe_X_d_ss3, SCOPe_X_d_ss3_part, SCOPe_X_d_fun), axis=1)\n\nSCOPe_y_a = SCOPe_y_a_ss3\nSCOPe_y_b = SCOPe_y_b_ss3\nSCOPe_y_c = SCOPe_y_c_ss3\nSCOPe_y_d = SCOPe_y_d_ss3\n\n\n# In[25]:\n\n\nfrom sklearn.model_selection import train_test_split\n\nSCOPe_X_train_a, SCOPe_X_test_a, SCOPe_y_train_a, SCOPe_y_test_a = train_test_split(SCOPe_X_a, SCOPe_y_a, test_size=0.3, random_state=0) \nSCOPe_X_train_b, SCOPe_X_test_b, SCOPe_y_train_b, SCOPe_y_test_b = train_test_split(SCOPe_X_b, SCOPe_y_b, test_size=0.3, random_state=0)\nSCOPe_X_train_c, SCOPe_X_test_c, SCOPe_y_train_c, SCOPe_y_test_c = train_test_split(SCOPe_X_c, SCOPe_y_c, test_size=0.3, random_state=0) \nSCOPe_X_train_d, SCOPe_X_test_d, SCOPe_y_train_d, SCOPe_y_test_d = train_test_split(SCOPe_X_d, SCOPe_y_d, test_size=0.3, random_state=0)\n\nSCOPe_X_train=np.concatenate((SCOPe_X_train_a, SCOPe_X_train_b, SCOPe_X_train_c, SCOPe_X_train_d), axis=0)\nSCOPe_X_test=np.concatenate((SCOPe_X_test_a, SCOPe_X_test_b, SCOPe_X_test_c, SCOPe_X_test_d), axis=0)\nSCOPe_y_train=np.concatenate((SCOPe_y_train_a, SCOPe_y_train_b, SCOPe_y_train_c, SCOPe_y_train_d), axis=0)\nSCOPe_y_test=np.concatenate((SCOPe_y_test_a, SCOPe_y_test_b, SCOPe_y_test_c, SCOPe_y_test_d), axis=0)\n\n\n# In[27]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nclassifier = RandomForestClassifier(n_estimators=100, random_state=0)\nclassifier.fit(SCOPe_X_train, SCOPe_y_train)\nSCOPe_y_pred = classifier.predict(SCOPe_X_test)\n \nprint(confusion_matrix(SCOPe_y_test,SCOPe_y_pred)) \nprint(classification_report(SCOPe_y_test,SCOPe_y_pred)) \nprint(accuracy_score(SCOPe_y_test, SCOPe_y_pred))\n\n# AAC + Pattern + Species\n# [[ 704 0 0 50]\n# [ 1 750 0 89]\n# [ 0 0 1191 0]\n# [ 29 38 0 954]]\n# precision recall f1-score support\n\n# a 0.96 0.93 0.95 754\n# b 0.95 0.89 0.92 840\n# c 1.00 1.00 1.00 1191\n# d 0.87 0.93 0.90 1021\n\n# avg / total 0.95 0.95 0.95 3806\n\n# 0.9456121912769312\n\n","sub_path":"Python Codes/Program 11.py","file_name":"Program 11.py","file_ext":"py","file_size_in_byte":8496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"260182005","text":"#!/usr/bin/python3\n################## SERVEUR.py #####################\n# auteur: Equipe Smart\n# date: 5 avril\n#\n# Description: cette application sert de client\n###################################################\n\nimport socket, sys\nfrom script.led.SimulLed import SimulLed\n\n# Adresse de connexion\nHOST = '127.0.0.1'\n# Port de connexion\nPORT = 50000\n# Nom du RPI se connectant\nNOM = \"RP1\"\n\n \nmySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Realisaion de la connection\ntry:\n mySocket.connect((HOST, PORT))\nexcept socket.error:\n print(\"La connexion a echoue.\")\n sys.exit() \nprint(\"Connexion etablie avec le serveur.\")\n \n# identification du RPI\nmessage = str.encode(\"%s\" % (NOM))\nmySocket.send(message)\n\nmsgServeur = bytes.decode(mySocket.recv(1024))\nprint(msgServeur)\n\n\nled = \"\"\nledHisto = \"\"\n# Permet de simuler l'acquisition as port GPIO\n# Il suffit de changer cette fonction pour que le code soit adapter \n# au radiogoniometre branche au port GPIO\nsim = SimulLed(NOM)\n\nwhile 1:\n try:\n led = sim.getLed() # recuperation de l'etat des led a cet instant\n if led!=ledHisto:\n print(\"la led allume:\", led)\n mySocket.send(str.encode(led))\n ledHisto = led\n except KeyboardInterrupt:\n # fin de la socket sur une interruption de type Ctrl-C\n mySocket.send(str.encode(\"FIN\"))\n print(\"Connexion interrompue.\")\n mySocket.close() \n break\n \n\n\n\n\n\n \n","sub_path":"InterfaceWeb/Client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"239719961","text":"'''\nJarron Bailey\nHomework 13\nDate: May 6th, 2019\nDescription: Python program to input the number of each type of coin a user has in their possession and then compute and\ndisplay the total dollar and cents value of these coins. Solution must accommodate Quarter, Dime, Nickel, and Penny, Half-dollar and Dollar coins as well.\nSolution must be robust against invalid inputs (i.e., negative value entered into any coin entry widget).\n'''\ntry:\n from tkinter import *\n from tkinter import ttk\n from ttkthemes import themed_tk as tk\n import tkinter.messagebox\nexcept ImportError: # If Import error -> Try again\n from tkinter import *\n from tkinter import ttk\n from ttkthemes import themed_tk as tk\n import tkinter.messagebox\n\n\nclass AppGui(ttk.Frame):\n '''Class is responsible for the applications gui, a header frame and two content frames splitting th content'''\n\n def __init__(self, *args, **kwargs):\n ttk.Frame.__init__(self, *args, **kwargs)\n\n # Header Frame\n self.__headerFrame = ttk.Frame(self)\n self.__headerFrame.pack(side=TOP, fill=X, pady=15)\n self.__headerLabel = ttk.Label(\n self.__headerFrame, text=\"Change Counter\", font=\"Helvetica 18 bold\", anchor=\"center\", relief=\"raised\")\n self.__headerLabel.pack()\n\n # Content Frame\n self.__contentFrame = ttk.Frame(self)\n self.__contentFrame.pack(side=TOP, fill=BOTH, pady=15)\n self.__headerLabel = ttk.Label(\n self.__contentFrame, text=\"Enter the number of each coin type and hit, Compute:\", font=\"Helvetica 16 bold\", anchor=\"center\")\n\n # Left side\n self.__leftFrame = ttk.Frame(self.__contentFrame)\n self.__leftFrame.pack(side=LEFT, padx=(50, 0))\n\n self.__quarterLabel = ttk.Label(\n self.__leftFrame, text=\"Quarters:\", font=\"Helvetica 12 bold\")\n self.__quarterEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15)\n\n self.__dimesLabel = ttk.Label(\n self.__leftFrame, text=\"Dimes:\", font=\"Helvetica 12 bold\")\n self.__dimesEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15)\n\n self.__nickelsLabel = ttk.Label(\n self.__leftFrame, text=\"Nickels:\", font=\"Helvetica 12 bold\")\n self.__nickelsEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15)\n\n self.__penniesLabel = ttk.Label(\n self.__leftFrame, text=\"Pennies:\", font=\"Helvetica 12 bold\")\n self.__penniesEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15)\n\n self.__halfDollarLabel = ttk.Label(\n self.__leftFrame, text=\"Half Dollars:\", font=\"Helvetica 12 bold\")\n self.__halfDollarEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15)\n\n self.__dollarCoinsLabel = ttk.Label(\n self.__leftFrame, text=\"Dollar Coins:\", font=\"Helvetica 12 bold\")\n self.__dollarCoinsEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15)\n\n self.__calculateButton = ttk.Button(self.__leftFrame, text=\"Calculate\",\n command=self.__getInputs)\n\n # Layout\n self.__quarterLabel.grid(row=1, column=0)\n self.__quarterEntry.grid(row=1, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__dimesLabel.grid(row=2, column=0)\n self.__dimesEntry.grid(row=2, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__nickelsLabel.grid(row=3, column=0)\n self.__nickelsEntry.grid(row=3, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__penniesLabel.grid(row=4, column=0)\n self.__penniesEntry.grid(row=4, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__halfDollarLabel.grid(row=5, column=0)\n self.__halfDollarEntry.grid(row=5, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__dollarCoinsLabel.grid(row=6, column=0)\n self.__dollarCoinsEntry.grid(row=6, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__calculateButton.grid(row=7, column=0, columnspan=2, sticky=(\n N, S, E, W), pady=5)\n\n # Right side / Values\n self.__leftFrame = ttk.Frame(self.__contentFrame)\n self.__leftFrame.pack(side=LEFT, padx=(50, 0))\n\n self.__quarterLabelValue = ttk.Label(\n self.__leftFrame, text=\"Quarter values:\", font=\"Helvetica 12 bold\")\n self.__quartersResultVar = StringVar()\n self.__quartersResultVar.set(\"$0.00\")\n self.__quarterEntryValue = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__quartersResultVar, state=\"readonly\")\n\n self.__dimesLabelValue = ttk.Label(\n self.__leftFrame, text=\"Dime values:\", font=\"Helvetica 12 bold\")\n self.__dimesResultVar = StringVar()\n self.__dimesResultVar.set(\"$0.00\")\n self.__dimesEntryValue = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__dimesResultVar, state=\"readonly\")\n\n self.__nickelsLabelValue = ttk.Label(\n self.__leftFrame, text=\"Nickel values:\", font=\"Helvetica 12 bold\")\n self.__nickelsResultVar = StringVar()\n self.__nickelsResultVar.set(\"$0.00\")\n self.__nickelsEntryValue = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__nickelsResultVar, state=\"readonly\")\n\n self.__penniesLabelValue = ttk.Label(\n self.__leftFrame, text=\"Penny values:\", font=\"Helvetica 12 bold\")\n self.__penniesResultVar = StringVar()\n self.__penniesResultVar.set(\"$0.00\")\n self.__penniesEntryValue = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__penniesResultVar, state=\"readonly\")\n\n self.__halfDollarLabelValue = ttk.Label(\n self.__leftFrame, text=\"Half Dollar values:\", font=\"Helvetica 12 bold\")\n self.__halfDollarResultVar = StringVar()\n self.__halfDollarResultVar.set(\"$0.00\")\n self.__halfDollarEntryValue = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__halfDollarResultVar, state=\"readonly\")\n\n self.__dollarCoinsLabelValue = ttk.Label(\n self.__leftFrame, text=\"Dollar Coin values:\", font=\"Helvetica 12 bold\")\n self.__dollarCoinsResultVar = StringVar()\n self.__dollarCoinsResultVar.set(\"$0.00\")\n self.__dollarCoinsEntryValue = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__dollarCoinsResultVar, state=\"readonly\")\n\n self.__totalAmountLabel = ttk.Label(\n self.__leftFrame, text=\"Total change value:\", font=\"Helvetica 14 bold\")\n self.__totalAmountResultVar = StringVar()\n self.__totalAmountResultVar.set(\"$00.00\")\n self.__totalAmountEntry = ttk.Entry(\n self.__leftFrame, font=\"Helvetica 12\", width=15, textvariable=self.__totalAmountResultVar, state=\"readonly\")\n\n # Layout\n self.__quarterLabelValue.grid(row=1, column=0)\n self.__quarterEntryValue.grid(row=1, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__dimesLabelValue.grid(row=2, column=0)\n self.__dimesEntryValue.grid(row=2, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__nickelsLabelValue.grid(row=3, column=0)\n self.__nickelsEntryValue.grid(row=3, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__penniesLabelValue.grid(row=4, column=0)\n self.__penniesEntryValue.grid(row=4, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__halfDollarLabelValue.grid(row=5, column=0)\n self.__halfDollarEntryValue.grid(row=5, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__dollarCoinsLabelValue.grid(row=6, column=0)\n self.__dollarCoinsEntryValue.grid(row=6, column=1, sticky=(\n N, S, E, W), pady=5)\n\n self.__totalAmountLabel.grid(row=7, column=0)\n self.__totalAmountEntry.grid(row=7, column=1, sticky=(\n N, S, E, W), pady=5)\n\n def __vaildateInt(self, number):\n '''Function validates an integer passed in as an string or number and returns valid or not and the number'''\n valid = False\n number.strip()\n if isinstance(number, str):\n try:\n number = int(number)\n except ValueError:\n valid = False\n if isinstance(number, int):\n if number < 0:\n valid = False\n else:\n valid = True\n\n return {\"valid\": valid, \"number\": number}\n\n def __getInputs(self):\n '''Function get the input from the entries and validates the number, if not valid error is returned'''\n # Quarters\n quarters = self.__quarterEntry.get()\n validationVars = self.__vaildateInt(quarters)\n valid = validationVars[\"valid\"]\n if not valid:\n return tkinter.messagebox.showerror(\n \"Invalid Entry\", \"Quarters must be a positive integer\")\n quarters = validationVars[\"number\"]\n\n # Dimes\n dimes = self.__dimesEntry.get()\n validationVars = self.__vaildateInt(dimes)\n valid = validationVars[\"valid\"]\n if not valid:\n return tkinter.messagebox.showerror(\n \"Invalid Entry\", \"Dimes must be a positive integer\")\n dimes = validationVars[\"number\"]\n\n # Nickels\n nickels = self.__nickelsEntry.get()\n validationVars = self.__vaildateInt(nickels)\n valid = validationVars[\"valid\"]\n if not valid:\n return tkinter.messagebox.showerror(\n \"Invalid Entry\", \"Nickels must be a positive integer\")\n\n # Pennies\n pennies = validationVars[\"number\"]\n pennies = self.__penniesEntry.get()\n validationVars = self.__vaildateInt(pennies)\n valid = validationVars[\"valid\"]\n if not valid:\n return tkinter.messagebox.showerror(\n \"Invalid Entry\", \"Pennies must be a positive integer\")\n pennies = validationVars[\"number\"]\n\n # Half dollar\n halfDollars = self.__halfDollarEntry.get()\n validationVars = self.__vaildateInt(halfDollars)\n valid = validationVars[\"valid\"]\n if not valid:\n return tkinter.messagebox.showerror(\n \"Invalid Entry\", \"Half dollars must be a positive integer\")\n halfDollars = validationVars[\"number\"]\n\n # Dollar coins\n dollarCoins = self.__dollarCoinsEntry.get()\n validationVars = self.__vaildateInt(dollarCoins)\n valid = validationVars[\"valid\"]\n if not valid:\n return tkinter.messagebox.showerror(\n \"Invalid Entry\", \"Dollar coins must be a positive integer\")\n dollarCoins = validationVars[\"number\"]\n print(\"[COINS AMOUNT]\", quarters, dimes,\n nickels, pennies, halfDollars, dollarCoins)\n return self.__calculateMoney(quarters, dimes, nickels, pennies, halfDollars, dollarCoins)\n\n def __calculateMoney(self, quarters, dimes, nickels, pennies, halfDollars, dollarCoins):\n '''Function returns each coin value entered to the set values function'''\n quarters = float(quarters) * 0.25\n dimes = float(dimes) * 0.10\n nickels = float(nickels) * 0.05\n pennies = float(pennies) * 0.01\n halfDollars = float(halfDollars) * 0.50\n dollarCoins = float(dollarCoins) * 1.00\n total = quarters + dimes + nickels + pennies + halfDollars + dollarCoins\n print(\"[CALC]\", quarters, dimes, nickels,\n pennies, halfDollars, dollarCoins, total)\n return self.__setEntryValues(quarters, dimes, nickels, pennies, halfDollars, dollarCoins, total)\n\n def __setEntryValues(self, quarters, dimes, nickels, pennies, halfDollars, dollarCoins, total):\n '''Function set the coins values to associated variable text'''\n self.__quartersResultVar.set(\"${:,.2f}\".format(quarters))\n self.__dimesResultVar.set(\"${:,.2f}\".format(dimes))\n self.__nickelsResultVar.set(\"${:,.2f}\".format(nickels))\n self.__penniesResultVar.set(\"${:,.2f}\".format(pennies))\n self.__halfDollarResultVar.set(\"${:,.2f}\".format(halfDollars))\n self.__dollarCoinsResultVar.set(\"${:,.2f}\".format(dollarCoins))\n self.__totalAmountResultVar.set(\"${:,.2f}\".format(total))\n return print(\"Values set...\")\n","sub_path":"hw-13/AppGui.py","file_name":"AppGui.py","file_ext":"py","file_size_in_byte":12532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"317670271","text":"import requests\nfrom bs4 import BeautifulSoup as BS\n\nURL = 'https://vpobede.ru/movies/list/schedule?firstDate=2020-02-14&date=2020-02-14'\n\nPAGE = requests.get(URL).content\n\nschedule_soup = BS(PAGE, 'html.parser').body\n\nschedule = schedule_soup.find('app-root', {'ng-version':'7.2.15'})\n\nprint(schedule)\n","sub_path":"pobeda_schedule.py","file_name":"pobeda_schedule.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"441578488","text":"from cliente import Cliente\nimport pickle\n\nCLIENTES_CADASTRADOS = []\n\ndef save(loadfile):\n try:\n with open('database.db', 'wb') as file:\n pickle.dump(loadfile, file)\n print('Save')\n except Exception as e:\n print('Erro ao salvar')\n print(e)\n\n\ndef save_alugar(lista):\n try:\n with open('database.db', 'wb') as file:\n pickle.dump(lista, file)\n print('Save')\n except:\n print('erro ao salvar alugar')\n\n\ndef cadastrar_cliente(nome, cpf, rg, telefone, endereco, loadfile):\n cadastro = Cliente(nome, cpf, rg, telefone, endereco)\n loadfile.append(cadastro)\n print('Cadastrado com sucesso.')\n\n\ndef ver_clientes_cadastrados(lista):\n for cliente in lista:\n print(cliente)\n\n\ndef ver_cadastro_cliente(pos: int, lista):\n cliente = lista[pos]\n nome = cliente.nome\n cpf = cliente.cpf\n rg = cliente.rg\n telefone = cliente.telefone\n endereco = cliente.endereco\n return 'Nome: {}\\nCpf: {}\\nRg: {}' \\\n '\\nTelefone: {}\\nEndereço: {}'.format(nome, cpf, rg,\n telefone, endereco)\n\n\ndef relatorio(cliente, carro_alugado):\n qnt_dias = input('Quantos dias alugar carro?: ')\n data = input('Qual a data do aluguel?: ')\n valor = input('Qual o valor total do aluguel?: ')\n return (\n '-----------------------------------------------------------\\n'\n 'Nome: {} - Carro alugado: {} - Carro alugado a {} dias - \\n'\n 'Valor: {} - Data do aluguel: {}\\n'.format(cliente, carro_alugado,\n qnt_dias, valor, data)\n\n )\n\n\ndef geradorRelatorio(nome_cliente, relatorio):\n nome_arquivo = '{}.txt'.format(nome_cliente)\n try:\n with open('{}'.format(nome_arquivo), 'a') as file:\n file.write('{}'.format(relatorio))\n file.close()\n except Exception as e:\n print('Erro ao gerar relatório')\n print(e)\n","sub_path":"funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"328580051","text":"#Parms\n#python3 ingest_cputemperature.py <start_time> <duration>\n#<start_time> cpu temperature will increase for <duration> minutes\n\nimport requests, time, sched, random, datetime, sys\nfrom datetime import datetime\n\n# datetime object containing current date and time\nnow = datetime.now()\ntimenow = int(now.strftime(\"%H%M\"))\n\nif (len(sys.argv) > 1):\n droptime = int(sys.argv[1])\n duration = int(sys.argv[2])\nelse:\n droptime = \"0000\"\n duration = 10\n\nprint(\"Current time: \" + now.strftime(\"%H%M\"))\nprint(\"Start simulation at: \" + str(droptime) + \" for \" + str(duration) + \" minutes\")\n\nMETRICS_DROP = [\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu1'}, 'min' : 120, 'max' : 150 },\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu2'}, 'min' : 120, 'max' : 150 },\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu3'}, 'min' : 120, 'max' : 150 },\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu4'}, 'min' : 120, 'max' : 150 }\n ]\n\nMETRICS = [\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu1'}, 'min' : 30, 'max' : 90 },\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu2'}, 'min' : 30, 'max' : 90 },\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu3'}, 'min' : 30, 'max' : 90 },\n {'id' : 'cpu.temperature', 'dims' : {'cpu' : 'cpu4'}, 'min' : 30, 'max' : 90 }\n ]\nscheduler = sched.scheduler(time.time, time.sleep)\n\ndef genSeries():\n mStr = \"\"\n now = datetime.now()\n timenow = int(now.strftime(\"%H%M\"))\n if (timenow > int(droptime)) and (timenow < (int(droptime) + duration)):\n CURR_METRICS=METRICS_DROP\n print(\"Simulating high cpu temperature...\")\n else:\n CURR_METRICS=METRICS \n for metric in CURR_METRICS:\n dimStr = \"\"\n for dK in metric['dims']:\n dimStr += \",\" + dK + \"=\" + metric['dims'][dK]\n mStr += metric['id'] + dimStr + \" \" + str(random.randint(metric['min'], metric['max'])) + \"\\n\"\n return mStr\n\n\ndef doit():\n scheduler.enter(60, 1, doit)\n payload = genSeries()\n print(payload)\n r = requests.post('http://localhost:14499/metrics/ingest', headers={'Content-Type': 'text/plain; charset=utf-8'}, data=payload)\n print(r)\n print(r.text)\n\nprint(\"START\")\nscheduler.enter(1, 1, doit)\nscheduler.run()\n","sub_path":"Ingest all the metrics/ingest_cputemperature.py","file_name":"ingest_cputemperature.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"518397884","text":"# GUI 圖形使用者介面\r\n\r\nimport tkinter as tk\r\n\r\nimport tkinter.messagebox\r\n\r\nfrom pytube import YouTube\r\n\r\nwindow = tk.Tk()\r\n\r\nwindow.title(\"默默好可愛GUI\") #視窗命名\r\n\r\nwindow.geometry('600x600') #視窗大小\r\n\r\n#↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑基本設定↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑#\r\n\r\nwindow.iconbitmap(\"mus.ico\")#icon change\r\n\r\n#video download\r\n\r\nyt = YouTube(\"https://www.youtube.com/watch?v=cCSwsDMySqg\")\r\n\r\nstream = yt.streams.first()\r\n\r\nstream.download(\"C:\\\\Users\\\\arthu\\\\Desktop\\\\Python\\\\tkinter\",\"123\")\r\n\r\n#stream = yt.streams.filter(only_audio = True).first() #only audio\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nwindow.mainloop() #視窗出現()","sub_path":"yt mp4.py","file_name":"yt mp4.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"504556369","text":"import psycopg2\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom django.views.generic import TemplateView\n\nfrom secoed import settings\n\n\nclass DashboardView(View):\n def get(self, request):\n greeting = {'heading': \"Inicio\", 'pageview': \"Inicio\"}\n if 'username' in request.session:\n return render(request, 'dashboard/dashboard.html', greeting)\n else:\n return redirect('pages-login')\n\n\nclass AjaxEvent(View):\n def jsnCountLogin(request):\n sql = \"SELECT string_agg(CAST(valor AS text),',') FROM(SELECT EXTRACT(dow FROM datetime), COUNT(id) as valor \" \\\n \"FROM easyaudit_loginevent WHERE username = '\" \\\n + str(request.session['username']) + \"' AND login_type=0 GROUP BY 1 ORDER BY 1 ASC ) aux\"\n conexion = psycopg2.connect(database=settings.CONEXION_NAME, user=settings.CONEXION_USER,\n password=settings.CONEXION_PASSWORD, host=settings.CONEXION_HOST,\n port=settings.CONEXION_PORT)\n query = conexion.cursor()\n query.execute(sql)\n array = []\n for fila in query:\n items = fila[0].split(',')\n for item in items:\n array.append(int(item))\n json_object = {\n 'key': array\n }\n return JsonResponse(json_object)\n\n\nclass Error404View(TemplateView):\n template_name = \"utility/utility-404error.html\"\n\n\ndef error_500(solicitud):\n datos = {}\n return render(solicitud, 'utility/utility-500error.html', datos)\n","sub_path":"secoed/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"345687631","text":"from setuptools import setup\nimport os\n\nrootdir = os.path.abspath(os.path.dirname(__file__))\nwith open(\"README.md\", \"r\", encoding=\"utf8\") as file:\n long_description = file.read()\n\n# Write a versions.py file for class attribute\nVERSION = \"0.0.6\"\n\n\ndef write_version_py(filename=None):\n doc = (\"\\\"\\\"\\\"\\n\" +\n \"This is a VERSION file and should NOT be manually altered\" +\n \"\\n\\\"\\\"\\\"\")\n doc += \"\\nversion = \\\"%s\\\"\" % VERSION\n\n if not filename:\n filename = os.path.join(\n os.path.dirname(__file__), \"rvlib\", \"version.py\")\n\n f = open(filename, \"w\")\n try:\n f.write(doc)\n finally:\n f.close()\n\n\nwrite_version_py()\n\n# Setup\nsetup(name=\"rvlib\",\n packages=[\"rvlib\"],\n setup_requires=[\"cffi>=1.0.0\",\"PyYAML\"],\n scripts=[\"./build_interface.py\"],\n cffi_modules=[\"build_lib.py:ffi\"],\n install_requires=[\"cffi>=1.0.0\", \"numba>=0.49\", \"numpy\", \"PyYAML\"],\n include_package_data=True,\n version=VERSION,\n description=\"Probability distributions mimicking Distrbutions.jl\",\n author=\"Daniel Csaba, Spencer Lyon\",\n author_email=\"daniel.csaba@nyu.edu, spencer.lyon@stern.nyu.edu\",\n url=\"https://github.com/QuantEcon/rvlib\", # URL to the github repo\n keywords=[\"statistics\", \"distributions\"],\n long_description=long_description,\n long_description_content_type='text/markdown')\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"647396163","text":"import pandas as pd\nfrom sklearn.model_selection import TimeSeriesSplit\n\n\ndef validate(X: pd.DataFrame, y: pd.DataFrame, splits: int, callback):\n\n tscv = TimeSeriesSplit(n_splits=splits)\n for train_index, test_index in tscv.split(X):\n X_train = pd.DataFrame(X.values[train_index], columns=X.columns.values)\n X_test = pd.DataFrame(X.values[test_index], columns=X.columns.values)\n y_train = pd.DataFrame(y.values[train_index], columns=y.columns.values)\n y_test = pd.DataFrame(y.values[test_index], columns=y.columns.values)\n\n train_dataset = y_train.join(X_train)\n validation_dataset = y_test.join(X_test)\n\n callback(X, y, train_dataset, validation_dataset)\n","sub_path":"notebooks/src/time_series_cross_validator.py","file_name":"time_series_cross_validator.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"239863823","text":"\"\"\"\nAn importer for the Personal Format Excel Files downloaded\nfrom Landsbankin in Iceland.\n\nSample Row/Headers are:\nDagsetning\tVaxtadagur\tTilvísun\tSkýring\tTexti\tUpphæð\tStaða\tNúmer útibús\tStutt tilvísun\n5/15/20 0:00\t5/15/20 0:00\tGV165636\tFj.skatt gengishagnað\tGuðmundur Rúnar Pétursson\t-199.2\t7,258.2\t0152\n\nCurrent version of these rhese files are in Excel, but usually pretty clean.\n\"\"\"\nimport pathlib\nimport datetime\nimport decimal\nimport typing\nimport dataclasses\nimport logging\nimport pprint\n\nimport openpyxl\n\nfrom beancount.ingest import importer, cache\nfrom coolbeans.tools.loader import load_file, Meta\nfrom beancount.core import data, amount, account\n\n\n\nlogger = logging.getLogger(__name__)\n\n\nHEADER_MAP = dict(\n date='Dagsetning',\n# posting_date='Vaxtadagur',\n refference='Tilvísun',\n tx_id='Stutt tilvísun',\n payee='Texti',\n narration='Skýring',\n amount='Upphæð',\n balance='Staða',\n# bank_number='Númer útibús',\n)\nMAP_BY_VALUE = dict((v.lower(), k) for (k, v) in HEADER_MAP.items())\n\nINFO_MAP = dict(\n account_number=\"B2\",\n balance=\"B3\",\n currency=\"B4\",\n owner=\"B5\",\n social=\"B6\",\n account_name=\"B7\"\n)\n\n\n@dataclasses.dataclass\nclass PossibleRow:\n date: datetime.date\n payee: str\n narration: str\n amount: decimal.Decimal\n meta: dict = dataclasses.field(default_factory=dict)\n currency: str = \"ISK\"\n\n @classmethod\n def from_row(cls, row: list, map: dict) -> 'PossibleRow':\n parameters = dict(meta=Meta())\n for field, index in map.items():\n cell = row[index]\n value = cell.value\n if field == 'date':\n value = datetime.date(\n year=value.year,\n month=value.month,\n day=value.day\n )\n\n if field == 'amount':\n value = decimal.Decimal(value).quantize(decimal.Decimal(\"0.01\"))\n\n if field in cls.__dataclass_fields__:\n parameters[field] = value\n elif value:\n parameters['meta'][field] = str(value)\n return cls(**parameters)\n\n\ndef map_header(row:list, value_map: dict):\n # Reverse the Map to be by Foreign Character\n # print(f\"{row} | {value_map}\")\n row = [cell.value.lower().strip() for cell in row]\n return dict(\n (v, row.index(k)) for (k, v) in value_map.items()\n )\n\n\nclass Importer(importer.ImporterProtocol):\n\n accounts = None\n possible_accounts:dict = None\n header:dict = None\n bean_file:str = \"\"\n\n def __init__(\n self,\n accounts: typing.Dict[str, str],\n bean_file: str=None,\n ):\n \"\"\"We need the account.\n next is to match on the meta tag and check the second TAB of the Excel sheet for Account number\n\n \"\"\"\n self.accounts = accounts\n self.bean_file = bean_file\n self.possible_accounts = {}\n self.header = {}\n\n if bean_file:\n self._auto_configure(bean_file)\n\n def _auto_configure(self, bean_file):\n self.possible_accounts = {}\n entries, errors, context = load_file(bean_file)\n for entry in entries:\n if not isinstance(entry, data.Open):\n continue\n acct = entry.meta.get('account_number', '').replace('-', '')\n self.possible_accounts[acct] = entry.account\n\n def get_root(self):\n root = self.accounts.get('root', None)\n if root:\n return root\n\n if self.possible_accounts and self.header:\n assert 'account_number' in self.header, f\"XXX {self.header}\"\n statement_account = str(self.header.get('account_number'))\n acct = self.possible_accounts.get(\n statement_account, None)\n if acct:\n logger.info(f\"Auto-Resolved account {statement_account} to {acct}\")\n return acct\n else:\n logger.info(f\"{pprint.pformat(self.possible_accounts)}\")\n logger.info(f\"statement_account = {statement_account}\")\n\n\n def name(self):\n return \"landsbankinn.Importer\"\n\n def identify(self, file: cache._FileMemo):\n try:\n name = file.name\n self._read_file(name)\n except Exception as exc:\n# logger.info(\"\", exc_info=exc)\n return False\n return True\n\n def file_account(self, file):\n name = file.name\n return f\"{self.get_root()}\"\n\n def file_date(self, file: cache._FileMemo):\n name = file.name\n entries, context = self._read_file(name)\n if entries:\n return entries[0].date\n\n def file_name(self, file):\n name = file.name\n entries, context = self._read_file(name)\n\n if entries:\n first_entry = entries[-1].date\n\n return f\"s{first_entry.strftime('%Y-%m-%d')}.{context['account_number']}.statement.xlsx\"\n\n def extract(self, file: cache._FileMemo, existing_entries=None) -> data.Entries:\n \"\"\"Given a File, let's extract the records\"\"\"\n\n name = file.name\n possible, context = self._read_file(name)\n root_account = self.get_root()\n if not root_account:\n logger.error(f\"Unable to find an account {context}\")\n return []\n\n new_entries = []\n\n for entry in possible:\n target_account = self.accounts['default-transfer']\n\n new_entries.append(data.Transaction(\n date=entry.date,\n narration=entry.narration,\n payee=entry.payee,\n meta=entry.meta,\n tags=set(),\n links=set(),\n flag=\"!\",\n postings=[\n data.Posting(\n account=root_account,\n units=data.Amount(entry.amount, entry.currency),\n flag=\"*\",\n cost=None,\n price=None,\n meta=None\n ),\n data.Posting(\n account=target_account,\n units=data.Amount(-entry.amount, entry.currency),\n flag=\"!\",\n cost=None,\n price=None,\n meta=None\n )\n ]\n ))\n return new_entries\n\n\n def pull_info(self, wb) -> dict:\n sheet = wb['Reikningur']\n result = {}\n for field, loc in INFO_MAP.items():\n result[field] = sheet[loc].value\n return result\n\n def _read_file(self, file: str):\n \"\"\"\n Create an Excel file reader\n\n @param file:\n @return:\n \"\"\"\n wb = openpyxl.open(\n file,\n read_only=True,\n )\n sheet = wb.active\n\n header = None\n col_map = {}\n data_rows = []\n for row in sheet.rows:\n if not col_map:\n col_map = map_header(row, MAP_BY_VALUE)\n else:\n record = PossibleRow.from_row(row, col_map)\n if record.amount:\n data_rows.append(record)\n\n context = self.pull_info(wb)\n context['header'] = col_map\n self.header = context\n return data_rows, context\n\nif __name__ == \"__main__\":\n import sys\n logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)\n document = pathlib.Path(\"statements/landsbankinn.xlsx\")\n assert document.exists()\n importer = Importer(\n accounts={\n 'root': \"Assets:Banks:Landsbankinn\",\n 'default-transfer': \"Assets:Transfer:FIXME\",\n 'default-expense': \"Expenses:FIXME\"\n }\n )\n\n from beancount.loader import printer\n for entry in importer.extract(document):\n printer.print_entry(entry)\n","sub_path":"src/coolbeans/importers/landsbankinn.py","file_name":"landsbankinn.py","file_ext":"py","file_size_in_byte":7867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"102492690","text":"import mysql.connector\r\nfrom mysql.connector import errorcode\r\n\r\n#create database\r\nDB_NAME='mysql'\r\n\r\nTABLE = {}\r\nTABLE['AdminUsers'] = (\r\n \"CREATE TABLE `AdminUsers` (\"\r\n \" `user_no` int(1) NOT NULL AUTO_INCREMENT,\"\r\n \" `emailad` varchar(90),\"\r\n \" `uname` varchar(50),\"\r\n \" `new_pin` char(5),\"\r\n \" `old_pin` char(5),\"\r\n \" PRIMARY KEY (`user_no`))\")\r\n\r\ncnx = mysql.connector.connect(user='root',\r\n password='parasathesis',\r\n host='localhost',\r\n database='mysql')\r\ncursor = cnx.cursor()\r\n\r\ndef create_database(cursor):\r\n try:\r\n cursor.execute(\r\n \"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'\".format(DB_NAME))\r\n except mysql.connector.Error as err:\r\n print(\"Failed creating database: {}\".format(err))\r\n exit(1)\r\n\r\ntry:\r\n cnx.database = DB_NAME \r\nexcept mysql.connector.Error as err:\r\n if err.errno == errorcode.ER_BAD_DB_ERROR:\r\n create_database(cursor)\r\n cnx.database = DB_NAME\r\n else:\r\n print(err)\r\n exit(1)\r\n\r\nfor name, ddl in TABLE.items():\r\n try:\r\n print(\"Creating table {}: \".format(name), end='')\r\n cursor.execute(ddl)\r\n except mysql.connector.Error as err:\r\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\r\n print(\"already exists.\")\r\n else:\r\n print(err.msg)\r\n else:\r\n print(\"OK\")\r\n\r\n#insert data from user\r\nuser_no = cursor.lastrowid\r\ndata_email = input(\"Enter your email address: \")\r\ndata_uname = input(\"Username: \")\r\ndata_newpin = input(\"PIN: \")\r\nresult=''\r\nfor i in range(0, len(data_newpin)):\r\n result = result + chr(ord(data_newpin[i]) - 2)\r\ncursor.execute(\"\"\"\r\n INSERT INTO AdminUsers\r\n (user_no, emailad, uname, new_pin) VALUES\r\n (%s, %s, %s, %s)\"\"\" , (user_no, data_email, data_uname, result))\r\n\r\ncnx.commit()\r\n\r\n#query\r\nquery = \"SELECT user_no, emailad, uname, new_pin FROM AdminUsers\"\r\n\r\ncursor.execute(query)\r\nrecords = cursor.fetchall()\r\nfor row in records:\r\n #user_no = row[0]\r\n #emailad = row[1]\r\n #uname = row[2]\r\n #new_pin = row[3]\r\n#print (\"User No. = %s, Email Address = %s, Username = %s, Pin = %s\" % \\\r\n #(user_no, emailad, uname, new_pin))\r\n print (row)\r\ncursor.close()\r\ncnx.close()\r\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"130636201","text":"list = (\"a\",\"B\",\"c\",\"A\")\n\ndef selectionSort(list):\n\n #Kører alle elementer i listen igennem\n for index in range(len(list)):\n\n # Find den mindste værdi i resten af listen\n min_idx = index\n for j in range(index+1, len(list)):\n if list[min_idx] > list[j]:\n min_idx = j\n\n #Bytter rundt på de 2 værdier\n list[index], list[min_idx] = list[min_idx], list[index]\n\n #Returnerer listen\n return list\n\ndef insertionSort(list):\n\n #Kører alle elementer i listen igennem fra 1 af\n for index in range(1, len(list)):\n\n #Vi gemmer hvilken værdi den er nået til\n #sådan at algoritmen kan fortsætte derfra\n #når den er færdig med at sammenligne og bytte\n temp = list[index]\n j = index - 1\n\n #Sammenligner de 2 værdier\n #Hvis den til højre er mindre end den til venstre\n while (j >= 0 and temp < list[j]):\n\n #Byt rundt på de 2 værdier\n list[j + 1] = list[j]\n j = j - 1\n list[j + 1] = temp\n","sub_path":"sorteringsAlgoritmer.py","file_name":"sorteringsAlgoritmer.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"636217526","text":"import numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#获取数据\ndata = pd.read_csv('ex1data1.txt',names=['population', 'profit'])\nX = data['population']\ny = data['profit'] #使用列名作为索引\nm = len(y)\n\n#为矩阵X增加列\nones = pd.DataFrame({'ones': np.ones(m)}) #学习一下\nX = pd.concat([ones, X], axis=1)\nprint(X)\n\n#参数个数即为X特征值\ntheta = np.zeros(X.shape[1])\n\n#获取代价函数,单独定义是:theta不同对应的代价函数不同\ndef J_function(X,y,theta):\n h_theta = X.dot(theta) #矩阵乘积\n cost = ( (h_theta - y).dot((h_theta - y).T) ) / (2*m)\n return cost\n\n#梯度下降算法\ndef gradient(X,y,theta):\n gradient = (X.T).dot( X.dot(theta) - y )\n return gradient/m\n\ndef batch_gradient_descent(X,y,theta,alpha,iterations):\n cost_data = [J_function(X,y,theta)]\n _theta = theta.copy()\n\n for _ in range(iterations):\n _theta = _theta - alpha * gradient(X,y, _theta)\n cost_data.append( J_function(X,y,_theta) )\n\n return _theta, cost_data\n\nalpha = 0.01\niterations = 500\nfinal_theta, cost_data = batch_gradient_descent(X, y, theta ,alpha, iterations)\nfinal_costdata = J_function( X,y,final_theta)\n\n\nb = final_theta[0]\nk = final_theta[1]\nplt.scatter(data['population'],data['profit'], label='Training data')\nplt.plot(data['population'],data['population']*k + b , label='Prediction')\nplt.xlabel(('Population of City in 10,000s')),plt.ylabel(('Profit in $10,000s'))\nplt.show()\n","sub_path":"linearRegression/oneVariable.py","file_name":"oneVariable.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"651905127","text":"\"\"\"Test indexing of plots.\"\"\"\n\nimport os\nimport random\nimport argparse\n\nfrom collections import defaultdict\n\nimport dtoolcore\n\nimport numpy as np\n\nfrom jicbioimage.core.image import Image\n\nfrom dtoolutils import (\n temp_working_dir,\n stage_outputs\n)\n\n\ndef ensure_uri(path_or_uri):\n\n if ':' in path_or_uri:\n return path_or_uri\n else:\n return \"disk:{}\".format(path_or_uri)\n\n\ndef generate_plots_image(dataset, dates_to_identifiers):\n\n images = []\n sorted_dates = sorted(dates_to_identifiers)\n\n for date in sorted_dates:\n identifier = dates_to_identifiers[date]\n image_abspath = dataset.item_content_abspath(identifier)\n image = Image.from_file(image_abspath)\n images.append(image)\n\n output_image = join_horizontally(images)\n\n return output_image\n\n\ndef generate_plot_image_list(dataset, dates_to_identifiers):\n\n images = []\n sorted_dates = sorted(dates_to_identifiers)\n\n for date in sorted_dates:\n identifier = dates_to_identifiers[date]\n image_abspath = dataset.item_content_abspath(identifier)\n image = Image.from_file(image_abspath)\n image = generate_image_with_colour_summary(image)\n images.append(image)\n\n return images\n\n\ndef generate_tidy_data_table(dataset, working_dir):\n\n indexed_by_label = index_plots_by_label(dataset)\n\n complete_sets = [k for k, v in indexed_by_label.items() if len(v) == 5]\n\n # sample_labels = complete_sets[0:100]\n sample_labels = complete_sets\n\n output_fpath = os.path.join(working_dir, 'plot_colours.csv')\n with open(output_fpath, 'w') as fh:\n headers = ['plot', 'date', 'R', 'G', 'B']\n fh.write(','.join(headers) + '\\n')\n for label in sample_labels:\n dates_to_identifiers = indexed_by_label[label]\n for date, identifier in dates_to_identifiers.items():\n image_abspath = dataset.item_content_abspath(identifier)\n image = Image.from_file(image_abspath)\n R, G, B = np.median(image, axis=[0, 1])\n items = [str(i) for i in [label, date, R, G, B]]\n fh.write(','.join(items) + '\\n')\n\n return [('plot_colours.csv', {})]\n\n\ndef index_plots_by_label(dataset):\n \"\"\"Return dictionary of dictionaries such that all plots are indexed by\n a unique label, and then by date, so any individual plot is:\n\n index_by_label[label][date].\"\"\"\n\n date_overlay = dataset.get_overlay('date')\n ordering_overlay = dataset.get_overlay('ordering')\n plot_number_overlay = dataset.get_overlay('plot_number')\n\n def generate_plot_label(identifier):\n return \"{}_{}\".format(\n ordering_overlay[identifier],\n plot_number_overlay[identifier]\n )\n\n indexed_by_label = defaultdict(dict)\n for i in dataset.identifiers:\n label = generate_plot_label(i)\n date = date_overlay[i]\n indexed_by_label[label][date] = i\n\n return indexed_by_label\n\n\ndef arrange_in_grid(image_series):\n\n n_rows = len(image_series[0])\n n_cols = len(image_series)\n\n x_dims = []\n y_dims = []\n for row in image_series:\n for image in row:\n x_dim, y_dim, _ = image.shape\n x_dims.append(x_dim)\n y_dims.append(y_dim)\n\n xmax = max(x_dims)\n ymax = max(y_dims)\n\n output_x_dim = max(x_dims) * n_rows\n output_y_dim = max(y_dims) * n_cols\n\n output_image = np.zeros((output_x_dim, output_y_dim, 3), dtype=np.uint8)\n\n y_offset = 0\n for col in image_series:\n x_offset = 0\n for image in col:\n i_xdim, i_ydim, _ = image.shape\n output_image[x_offset:x_offset+i_xdim, y_offset:i_ydim+y_offset] = image\n x_offset = x_offset + xmax\n y_offset = y_offset + ymax\n\n return output_image.view(Image)\n\n\ndef explore_plot_indexing(dataset, working_dir):\n\n indexed_by_label = index_plots_by_label(dataset)\n\n complete_sets = [k for k, v in indexed_by_label.items() if len(v) == 5]\n\n # sample_labels = random.sample(complete_sets, 10)\n sample_labels = complete_sets[0:20]\n\n time_progression_image_series = [\n generate_plot_image_list(dataset, indexed_by_label[l])\n for l in sample_labels\n ]\n\n joined_image = arrange_in_grid(time_progression_image_series)\n\n output_fpath = os.path.join(working_dir, 'joined.png')\n with open(output_fpath, 'wb') as fh:\n fh.write(joined_image.png())\n\n return [('joined.png', {})]\n\n\ndef generate_image_with_colour_summary(image):\n \"\"\"Return image containing both original image and solid block colour\n summary below it.\"\"\"\n\n xdim, ydim, _ = image.shape\n\n output_image = np.zeros((xdim * 2, ydim, 3), dtype=np.uint8)\n\n output_image[0:xdim, 0:ydim] = image\n output_image[xdim:2*xdim,0:ydim,:] = np.median(image, axis=[0, 1])\n\n return output_image\n\n\ndef test_plot_colour_summary(dataset, working_dir):\n\n identifiers = dataset.identifiers\n\n identifier = identifiers[2004]\n\n plot_image = Image.from_file(dataset.item_content_abspath(identifier))\n output_image = generate_image_with_colour_summary(plot_image)\n\n output_fpath = os.path.join(working_dir, 'colour.png')\n with open(output_fpath, 'wb') as fh:\n fh.write(output_image.view(Image).png())\n\n return [('colour.png', {})]\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset-uri')\n parser.add_argument('--output-uri')\n\n args = parser.parse_args()\n\n dataset_uri = ensure_uri(args.dataset_uri)\n output_uri = ensure_uri(args.output_uri)\n dataset = dtoolcore.DataSet.from_uri(dataset_uri)\n output_dataset = dtoolcore.ProtoDataSet.from_uri(output_uri)\n\n with temp_working_dir() as working_dir:\n # outputs = explore_plot_indexing(dataset, working_dir)\n outputs = generate_tidy_data_table(dataset, working_dir)\n # outputs = test_plot_colour_summary(dataset, working_dir)\n stage_outputs(\n outputs,\n working_dir,\n dataset,\n output_dataset,\n [],\n None\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/test_plot_indexing.py","file_name":"test_plot_indexing.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"160244700","text":"import random\nimport math\nimport numpy as np\nimport time\nfrom getNet import get_adj, divide_name\nfrom getEdgeTime import is_different_time, get_all_edge_time\n\n\ndef get_all_edge_pairs(net_name):\n \"\"\"\n 获取所有的边对(可以分辨新旧边的边对)\n 生成器函数减少内存开销\n :param net_name: 网络的名字\n :return: 生成器\n \"\"\"\n edges = get_adj(net_name)\n edge_days = get_all_edge_time(net_name)\n for edge1 in edges:\n _edge2s = edges[edges.index(edge1):]\n for edge2 in _edge2s:\n edge_pair = (edge1, edge2)\n new = is_different_time(edge_pair, edge_days)\n if new != -1:\n yield edge_pair, new\n\n\ndef get_random_edge_pairs(num, net_name):\n \"\"\"\n 获取随机的边对(可以分辨新旧边的边对)\n 生成器函数减少内存开销\n :param num: 随机数量\n :param net_name: 网络的名字\n :return: 生成器\n \"\"\"\n edges = get_adj(net_name)\n edge_days = get_all_edge_time(net_name)\n edge1_index = list(range(len(edges)))\n edge2_index = list(range(len(edges)))\n choosed_edge2_index_for_edge1_index = [] # 对于每一条edge1边,将选过的edge2边存起来\n for i in range(len(edges)):\n choosed_edge2_index_for_edge1_index.append([])\n for i in range(num):\n new = -1\n edge_pair = None\n while new == -1:\n edge1_i = random.choice(edge1_index)\n edge2_indexs = list(\n set(edge2_index[edge1_i:]) - {edge1_i} - set(choosed_edge2_index_for_edge1_index[edge1_i]))\n # 若edge1对应的edge2选完了则之后不选这个edge1了\n while edge2_indexs == []:\n edge1_index.remove(edge1_i)\n edge1_i = random.choice(edge1_index)\n edge2_indexs = list(\n set(edge2_index[edge1_i:]) - {edge1_i} - set(choosed_edge2_index_for_edge1_index[edge1_i]))\n edge2_i = random.choice(edge2_indexs)\n edge_pair = (edges[edge1_i], edges[edge2_i])\n new = is_different_time(edge_pair, edge_days)\n choosed_edge2_index_for_edge1_index[edge1_i].append(edge2_i)\n yield edge_pair, new\n\n\ndef get_ep_for_train_test(train_size, test_size, net_name, ep_num):\n \"\"\"\n 训练集和测试集边对\n 会根据网络大小选择全部边对或者train_size+test_size边对\n 若网络可区分新旧边对没有那么多,则取所有边对按train_size:test_size分开\n 否则在网络所有可区分新旧边对中随机选train_size+test_size对边\n :param train_size:\n :param test_size:\n :param net_name:\n :param ep_num\n :return: [train_edge_pairs, ...], [train_new, ...], [test_edge_pairs, ...], [test_news, ...]\n \"\"\"\n edges = get_adj(net_name)\n edge_pairs = []\n news = []\n if ep_num > (train_size+test_size):\n # 若ep_num大于train_size+test_size,则随机选train_size+test_size对边\n for edge_pair, new in get_random_edge_pairs(train_size+test_size, net_name):\n edge_pairs.append(edge_pair)\n news.append(new)\n # 随机打乱\n index_ = list(range(len(edge_pairs)))\n random.shuffle(index_)\n edge_pairs_shuffle = []\n news_shuffle = []\n for i in index_:\n edge_pairs_shuffle.append(edge_pairs[i])\n news_shuffle.append(news[i])\n\n train_edge_pairs = edge_pairs[:train_size]\n test_edge_pairs = edge_pairs[train_size:]\n train_news = news[:train_size]\n test_news = news[train_size:]\n return train_edge_pairs, train_news, test_edge_pairs, test_news\n else:\n # 否则选所有边对\n for edge_pair, new in get_all_edge_pairs(net_name):\n edge_pairs.append(edge_pair)\n news.append(new)\n # 随机打乱\n index_ = list(range(len(edge_pairs)))\n random.shuffle(index_)\n edge_pairs_shuffle = []\n news_shuffle = []\n for i in index_:\n edge_pairs_shuffle.append(edge_pairs[i])\n news_shuffle.append(news[i])\n\n train_ep_num = math.floor(len(edge_pairs) * train_size / (train_size + test_size))\n train_edge_pairs = edge_pairs[:train_ep_num]\n test_edge_pairs = edge_pairs[train_ep_num:]\n train_news = news[:train_ep_num]\n test_news = news[train_ep_num:]\n return train_edge_pairs, train_news, test_edge_pairs, test_news\n\n\ndef get_closure_edge_pairs(input_edge_pairs_dict, net_name):\n \"\"\"\n 获取输入边对的新旧关系闭包(先传递闭包,使用Warshall算法)\n :param input_edge_pairs_dict: {(edge1, edge2):1/0, ....}\n :param net_name:\n :return: dict {(a, b):new?, ... } !!!!(b, a) not exist\n \"\"\"\n # 构造关系矩阵\n '''将边从0排序'''\n edge_index_dict = dict() # {edge:0, edge:1, ...}\n edge_id = 0\n for edge_pair in input_edge_pairs_dict.keys():\n if edge_pair[0] not in edge_index_dict.keys():\n edge_index_dict[edge_pair[0]] = edge_id\n edge_id += 1\n if edge_pair[1] not in edge_index_dict.keys():\n edge_index_dict[edge_pair[1]] = edge_id\n edge_id += 1\n w = np.zeros((edge_id, edge_id))\n for edge_pair in input_edge_pairs_dict.keys():\n '''每一对边都存在一个记录(总有一个边为新边)为1'''\n w[edge_index_dict[edge_pair[0]], edge_index_dict[edge_pair[1]]] = input_edge_pairs_dict[edge_pair]\n w[edge_index_dict[edge_pair[1]], edge_index_dict[edge_pair[0]]] = 1 - input_edge_pairs_dict[edge_pair]\n print(\"Matrix complete and begin warshall!! edge num:\", edge_id)\n # warshall 算法 O(n^3)\n for k in range(edge_id):\n since = time.time()\n for i in range(edge_id):\n for j in range(edge_id):\n w[i, j] = int(w[i, j]) or (int(w[i, k]) and int(w[k, j]))\n print(\"Warshall k:\" + str(k), \" time:\" + str(time.time() - since))\n print(\"Warshall done!!!!\")\n # 返回闭包边对集合,只返回上三角矩阵\n input_edge_pairs = set(input_edge_pairs_dict.keys())\n ids = list(edge_index_dict.values())\n edges = list(edge_index_dict.keys())\n for i in range(edge_id):\n for j in range(i+1, edge_id):\n if w[i, j] == 1 or w[j, i] == 1:\n edge1 = edges[ids.index(i)]\n edge2 = edges[ids.index(j)]\n if (edge1, edge2) not in input_edge_pairs and (edge2, edge1) not in input_edge_pairs:\n yield (edge1, edge2), w[i, j]\n\n\ndef get_train_test_edges(train_ratio, net_name):\n \"\"\"\n 按边分训练集,测试集\n 之后取训练集中所有可区分新旧的边对作为训练边对,和测试集中可区分新旧的边对以及测试集和训练集之间的边对最为测试边对。\n 对时间粒度大的网络我们对每个时间点取train_ratio条边,对时间粒度小的网络我们整体取train_ratio条边\n :param train_ratio:\n :param net_name:\n :return: train_edges, test_edges\n \"\"\"\n edges = get_adj(net_name)\n if divide_name(net_name)[0] in [\"sci_net_contacts\", \"fungi\", \"human\", \"fruit_fly\", \"worm\", \"bacteria\"]:\n edge_days = get_all_edge_time(net_name)\n # 获取各个时间点的边列表\n day_edges = dict()\n for edge in edge_days.keys():\n day = edge_days[edge]\n if day not in day_edges.keys():\n day_edges[day] = [edge]\n else:\n day_edges[day].append(edge)\n train_edges = []\n test_edges = []\n # 各个时间点取train_ratio条边\n for day in day_edges.keys():\n temp_edge_list = day_edges[day]\n random.shuffle(temp_edge_list)\n train_num = math.ceil(len(temp_edge_list) * train_ratio) # 向上取整,保证每个时间点至少1条边\n train_edges = train_edges + temp_edge_list[:train_num]\n test_edges = test_edges + temp_edge_list[train_num:]\n # 防止出现��面的边总是比后面的边旧\n random.shuffle(train_edges)\n random.shuffle(test_edges)\n else:\n random.shuffle(edges)\n train_num = int(len(edges) * train_ratio)\n train_edges = edges[:train_num]\n test_edges = edges[train_num:]\n return train_edges, test_edges\n\n\ndef ensemble_get_train_test_edges(train_ratio, net_name, ensemble_train_ratio=0.5):\n \"\"\"\n 按边分训练集,测试集\n 之后取训练集中所有可区分新旧的边对作为训练边对,和测试集中可区分新旧的边对以及测试集和训练集之间的边对最为测试边对。\n 对时间粒度大的网络我们对每个时间点取train_ratio条边,对时间粒度小的网络我们整体取train_ratio条边\n :param train_ratio:\n :param net_name:\n :param ensemble_train_ratio: 集成模型训练边集占总训练边集的比例\n :return: base_train_edges, ensemble_train_edges, test_edges\n \"\"\"\n edges = get_adj(net_name)\n if divide_name(net_name)[0] in [\"sci_net_contacts\", \"fungi\", \"human\", \"fruit_fly\", \"worm\", \"bacteria\"]:\n edge_days = get_all_edge_time(net_name)\n # 获取各个时间点的边列表\n day_edges = dict()\n for edge in edge_days.keys():\n day = edge_days[edge]\n if day not in day_edges.keys():\n day_edges[day] = [edge]\n else:\n day_edges[day].append(edge)\n base_train_edges = []\n ensemble_train_edges = []\n test_edges = []\n # 各个时间点取train_ratio条边\n for day in day_edges.keys():\n temp_edge_list = day_edges[day]\n random.shuffle(temp_edge_list)\n train_num = math.ceil(len(temp_edge_list) * train_ratio) # 向上取整,保证每个时间点至少1条边\n ensemble_train_num = int(train_num * ensemble_train_ratio)\n base_train_edges = base_train_edges + temp_edge_list[:train_num-ensemble_train_num]\n ensemble_train_edges = ensemble_train_edges + temp_edge_list[train_num-ensemble_train_num:train_num]\n test_edges = test_edges + temp_edge_list[train_num:]\n else:\n random.shuffle(edges)\n train_num = int(len(edges) * train_ratio)\n ensemble_train_num = int(train_num * ensemble_train_ratio)\n base_train_edges = edges[:train_num-ensemble_train_num]\n ensemble_train_edges = edges[train_num-ensemble_train_num:train_num]\n test_edges = edges[train_num:]\n # 防止出现前面的边总是比后面的边旧\n random.shuffle(base_train_edges)\n random.shuffle(ensemble_train_edges)\n random.shuffle(test_edges)\n return base_train_edges, ensemble_train_edges, test_edges\n\n\ndef get_double_eps_from_edges(edges, net_name):\n \"\"\"\n 根据输入的边列表获取边对\n :param edges:\n :param net_name:\n :return:\n \"\"\"\n edge_days = get_all_edge_time(net_name)\n for edge1 in edges:\n # _edge2s = edges[edges.index(edge1):]\n for edge2 in edges:\n if edge2 != edge1:\n edge_pair = (edge1, edge2)\n if type(edge1) is list or type(edge2) is list:\n print(\"wrong place:\", edge_pair)\n new = is_different_time(edge_pair, edge_days)\n if new != -1:\n yield edge_pair, new\n\n\ndef get_single_eps_from_edges(edges, net_name, random_ratio=1):\n \"\"\"\n 根据输入的边列表获取边对\n :param edges:\n :param net_name:\n :param random_ratio: 随机取边对的比例,默认全选\n :return:\n \"\"\"\n edge_days = get_all_edge_time(net_name)\n for edge1 in edges:\n _edge2s = edges[edges.index(edge1):]\n for edge2 in _edge2s:\n if edge2 != edge1:\n if random.random() < random_ratio:\n edge_pair = (edge1, edge2)\n if type(edge1) is list or type(edge2) is list:\n print(\"wrong place:\", edge_pair)\n new = is_different_time(edge_pair, edge_days)\n if new != -1:\n yield edge_pair, new\n\n\ndef get_single_eps_from_two_edges(train_edges, test_edges, net_name, random_ratio=1):\n \"\"\"\n 获取输入的两个边列表之间的边对\n :param train_edges:\n :param test_edges:\n :param net_name:\n :param random_ratio: 随机取边对的比例,默认全选\n :return:\n \"\"\"\n edge_days = get_all_edge_time(net_name)\n for edge1 in train_edges:\n for edge2 in test_edges:\n if random.random() < random_ratio:\n edge_pair = (edge1, edge2)\n new = is_different_time(edge_pair, edge_days)\n if new != -1:\n yield edge_pair, new\n\n\n# if __name__ == '__main__':\n# input_edge_pairs_dict = dict({(0, 1): 1, (1, 2): 1, (0, 3): 1, (4, 1): 0})\n# for edge_pair, new in get_closure_edge_pairs(input_edge_pairs_dict, None):\n# print(\"closure:\", edge_pair, new)\n","sub_path":"getEdgePair.py","file_name":"getEdgePair.py","file_ext":"py","file_size_in_byte":12994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"583101516","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nfrom mpmath import *\r\n\r\nmp.dps=30\r\n\r\nmTerms=300\r\nnPart=100\r\nmass0=1.\r\nomega0=1.\r\nlamb0=.01\r\n\r\ndef Energy( T, N=50, D=1, gamma=1., lamb=0.01, mass=1., omega=1. ):\r\n \r\n l=T/( mass*omega**2./2)\r\n \r\n den=sqrt((l**-2+lamb**-2)**2-lamb**-4)\r\n \r\n interaction= gamma*N*N/(l*l*den)\r\n \r\n kosc= 2*N*D*T\r\n \r\n total= kosc + interaction\r\n \r\n return [kosc, interaction, total]\r\n\r\ndef DEnergy( T, N=50, D=1, gamma=1., lamb=0.01, mass=1., omega=1. ):\r\n \r\n T0= mass*omega*omega*lamb*lamb/4.\r\n \r\n BigGamma=gamma*N/T0\r\n \r\n tau=T/T0\r\n \r\n dE= N*T0*(2-BigGamma/(2.*(1+tau)**1.5))\r\n \r\n return dE\r\n \r\n\r\ndef LegendreApprox(l,lamb=.01,n=10):\r\n \r\n base=1./sqrt((l**-2+lamb**-2)**2-lamb**-4)\r\n \r\n base1=sqrt(1./2.)*lamb*l/sqrt(1.+.5*(lamb/l)**2)\r\n \r\n leg=0.\r\n \r\n factor=lamb/(sqrt(2.)*l)\r\n pow0=1.\r\n \r\n for i in range(n):\r\n \r\n leg+= legendre(i,0.)*pow0\r\n \r\n pow0*= factor\r\n \r\n apprx= sqrt(1./2.)*lamb*l*leg\r\n \r\n return[base,base1, apprx]\r\n\r\n\r\ndef EnergyL( T, N=50, D=1, gamma=1., lamb=0.01, mass=1., omega=1.,m=10 ):\r\n \r\n l=T/( mass*omega**2./2)\r\n \r\n den=LegendreApprox(l,lamb,m)[2]\r\n \r\n interaction= gamma*N*N*den/(l*l)\r\n \r\n kosc= 2*N*D*T\r\n \r\n total= kosc + interaction\r\n \r\n return total\r\n\r\ndef EntropyL( T, N=50, gamma=1., lamb=0.01, mass=1., omega=1.,m=10 ):\r\n \r\n T0=mass*omega**2*lamb**2/4.\r\n \r\n S=2*N*ln(T/T0)\r\n \r\n factor= sqrt(T0/T)\r\n \r\n pow0= (T0/T)**1.5\r\n \r\n leg=0\r\n \r\n for kn in range(m):\r\n \r\n leg+=((kn+1)/(kn+3))*pow0*legendre(kn,0.)\r\n \r\n pow0*=factor\r\n \r\n S+=gamma*N*N*leg/T0\r\n \r\n return S\r\n\r\ndef epsilonF( tau, bgamma=1. ):\r\n \r\n epson= 2.*tau + bgamma/sqrt(1.+tau)\r\n\r\n return epson\r\n\r\ndef DepsilonF(tau, bgamma=1. ):\r\n \r\n depson= 2. -0.5*bgamma/(1+tau)**(1.5)\r\n\r\n return depson\r\n\r\ndef entropyF( tau, bgamma=1. ):\r\n \r\n gentropy= quad( lambda t: DepsilonF(t,bgamma)/t, [1.,tau ] )\r\n \r\n return gentropy\r\n\r\n\r\nif __name__==\"__main__\":\r\n \r\n try:\r\n import psyco\r\n psyco.log()\r\n psyco.full()\r\n \r\n except ImportError:\r\n \r\n pass\r\n \r\n import numpy as np\r\n import matplotlib.pyplot as plt\r\n \r\n gm=1.\r\n \r\n T0=mass0*omega0**2*lamb0**2/4.\r\n \r\n BigGamma= gm*nPart/T0\r\n \r\n tc= T0*(BigGamma/4.)**(2./3.)-1.\r\n \r\n tr=np.linspace(0.,1.,500)\r\n \r\n E=[]\r\n \r\n S=[]\r\n \r\n epsilon= lambda t: EnergyL(t,mass=mass0,omega=omega0,lamb=lamb0, \\\r\n gamma=gm, N=nPart, m=mTerms)\r\n smallS= lambda t: EntropyL(t,mass=mass0,omega=omega0,lamb=lamb0, \\\r\n gamma=gm, N=nPart, m=mTerms)\r\n \r\n epsilonA= lambda t: Energy(t,mass=mass0,omega=omega0,lamb=lamb0, \\\r\n gamma=gm, N=nPart)[2]\r\n \r\n dE= lambda t: DEnergy(t,mass=mass0,omega=omega0,lamb=lamb0, \\\r\n gamma=gm, N=nPart)\r\n \r\n \r\n \r\n \r\n for ttr in tr:\r\n \r\n E.append(epsilonF(ttr,bgamma=gm))\r\n \r\n S.append(entropyF(ttr,bgamma=gm))\r\n \r\n fig=plt.figure()\r\n \r\n ax=plt.subplot(111)\r\n \r\n ax.plot(E,S, label='gamma: ' + str(gm))\r\n \r\n ax.legend()\r\n \r\n plt.show()\r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n \r\n \r\n\r\n","sub_path":"ECast1.py","file_name":"ECast1.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"544156394","text":"import pandas as pd\n\n\ndef clean_title(data):\n \"\"\"\n purpose to remove not relevant items like xbox, iphone 8 and so on\n :param data: the original dataframe\n :return: new dataframe\n \"\"\"\n def dealer_title(series):\n series = series.lower()\n key_words = ['iphone x', 'iphonex']\n if series.find(key_words[0]) == -1 and series.find(key_words[-1]) == -1:\n return -1\n return 1\n\n def dealer_price(series):\n if series == 'Sold!':\n return -1\n return 1\n\n assert isinstance(data, pd.DataFrame)\n info_tit = data['Title'].apply(dealer_title)\n info_tit = info_tit[info_tit == -1].index.tolist()\n data = data.drop(axis=0, index=info_tit, inplace=False)\n\n info_pri = data['Price'].apply(dealer_price)\n info_pri = info_pri[info_pri == -1].index.tolist()\n data = data.drop(axis=0, index=info_pri, inplace=False)\n\n data = data.reset_index(drop=True)\n return data\n\ndef compare_csv(data_yst,data_td):\n '''\n Comparing two csv file from two consecutive days to get new and sold post\n \n :param yst: yesterday's scraping data\n :type yst: pd.DataFrame\n :param td: today's scraping data\n :type td: pd.DataFrame\n \n :return sold: the number of sold items\n :return new: the number of new items\n '''\n \n sold = 0\n new = 0\n \n ID_yst = data_yst['Item ID']\n ID_td = data_td['Item ID']\n \n for item in ID_td:\n if item not in ID_yst.values:\n new += 1\n \n for item in ID_yst:\n if item not in ID_td.values:\n sold += 1\n \n return sold, new\n\ndef compute_avg(df):\n '''\n Calculate the average price per type of conditions.\n \n :param df: input pandas dataframe for scraping of one day\n :type df: pd.DataFrame\n \n :return: average price for each condition\n '''\n s1 = df['Condition']\n s2 = df['Price'].astype('float32')\n avg = s2.mean()\n df = pd.concat([s1, s2], axis=1)\n grp = df.groupby(['Condition'])\n composition = s1.value_counts()\n composition.to_csv('composition_of_condition.csv')\n condition_avg = grp.mean()\n condition_avg.to_csv('avg_price_for_conditions.csv')\n return avg, condition_avg\n\n\n\nfile = './old_scrap/IPhoneX_2019-11-21 19:28:16.667516_Result_Offerup.csv'\ndf = pd.read_csv(file)\ndf.drop(axis=1, columns='Unnamed: 0', inplace=True)\ndf = clean_title(df)\navg, conditional_avg = compute_avg(df)\nprint(avg)\nprint(conditional_avg)\n#print(df['Title'])","sub_path":"process_v0.1_offerup.py","file_name":"process_v0.1_offerup.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"234577417","text":"\"\"\"\nDownload and unpack a TensorFlow Object Detection model.\nThe model zoo can be found at:\nhttps://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md\n\"\"\"\n\n__author__ = 'Ian Randman'\n\nimport logging\nimport os\nfrom tqdm import tqdm\nimport requests\nimport shutil\nimport sys\n\nfrom scripts.util.file_utils import create_directory_if_not_exists, full_path\n\nfrom scripts import ROOT_DIR\n\nlogger = logging.getLogger(__name__)\n\n\ndef download_and_unpack_model(model_name, model_date='20200711'):\n \"\"\"\n Download a model (tar.gz) from the TensorFlow Object Detection Model Zoo if it not yet downloaded.\n Unpack the model archive. If unpacking fails, try re-downloading the model first.\n\n :param model_name: the name of the model to download\n :param model_date: the date of the model to download\n :return: none\n \"\"\"\n\n # pretrained models\n pretrained_models_dir = os.path.join(ROOT_DIR, 'pre-trained-models')\n create_directory_if_not_exists(pretrained_models_dir)\n\n # pretrained model archives\n model_archive_dir = os.path.join(pretrained_models_dir, 'archives')\n create_directory_if_not_exists(model_archive_dir)\n\n # determine the (expected) path of the downloaded model\n model_file = f'{model_name}.tar.gz'\n model_archive_path = os.path.join(model_archive_dir, model_file)\n\n # if the tar.gz exists, try to unpack it\n retry = False\n if os.path.exists(model_archive_path):\n logger.info(f'Attempting to unpack {full_path(model_archive_path)}...')\n try:\n shutil.unpack_archive(model_archive_path, os.path.dirname(model_archive_dir))\n except EOFError:\n logger.info('Cannot unpack. Archive is corrupt. Attempting to retry...')\n retry = True\n\n # if the tar.gz does not exist or is corrupt (unpacking failed), download it, then unpack it\n if not os.path.exists(model_archive_path) or retry:\n base_url = 'http://download.tensorflow.org/models/object_detection/tf2/'\n url = base_url + model_date + '/' + model_file\n logger.info(f'Downloading from {url}...')\n\n # download file as stream\n response = requests.get(url, stream=True)\n with open(model_archive_path, 'wb') as handle:\n progress_bar = tqdm(unit=\"B\", total=int(response.headers['Content-Length']), unit_scale=True, unit_divisor=1024)\n for data in response.iter_content(chunk_size=8192):\n progress_bar.update(len(data))\n handle.write(data)\n progress_bar.close()\n\n # try to unpack tar.gz\n logger.info(f'Attempting to unpack {full_path(model_archive_path)}...')\n try:\n shutil.unpack_archive(model_archive_path, os.path.dirname(model_archive_dir))\n except EOFError:\n # give up if unpacking failed\n logger.info('Archive cannot be unpacked')\n sys.exit(1)\n\n logger.info('Successfully downloaded and unpacked model')\n","sub_path":"AI/scripts/util/download_model.py","file_name":"download_model.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"536378925","text":"import os\n\nBeacon = tuple[int, int, int]\n\n\nclass Scanner:\n _orientation_lambdas = [\n lambda x, y, z: (x, y, z),\n lambda x, y, z: (x, z, -y),\n lambda x, y, z: (x, -y, -z),\n lambda x, y, z: (x, -z, y),\n lambda x, y, z: (-x, -y, z),\n lambda x, y, z: (-x, z, y),\n lambda x, y, z: (-x, y, -z),\n lambda x, y, z: (-x, -z, -y),\n #\n lambda x, y, z: (-y, x, z),\n lambda x, y, z: (-z, x, -y),\n lambda x, y, z: (y, x, -z),\n lambda x, y, z: (z, x, y),\n lambda x, y, z: (y, -x, z),\n lambda x, y, z: (z, -x, -y),\n lambda x, y, z: (-y, -x, -z),\n lambda x, y, z: (-z, -x, y),\n #\n lambda x, y, z: (z, -y, x),\n lambda x, y, z: (-y, -z, x),\n lambda x, y, z: (-z, y, x),\n lambda x, y, z: (y, z, x),\n lambda x, y, z: (z, y, -x),\n lambda x, y, z: (y, -z, -x),\n lambda x, y, z: (-z, -y, -x),\n lambda x, y, z: (-y, z, -x),\n ]\n\n def __init__(self, beacons) -> None:\n self.beacons = set(beacons)\n self.scanner_locs = [(0, 0, 0)]\n\n def extend(\n self,\n new_scanner: \"Scanner\",\n new_becons: set[Beacon],\n new_scanner_pos: tuple[int, int, int],\n ):\n [self.beacons.add(b) for b in new_becons]\n for c in new_scanner.scanner_locs:\n self.scanner_locs.append(tuple([i + j for i, j in zip(c, new_scanner_pos)]))\n\n def orientations(self):\n for o in self._orientation_lambdas:\n yield [o(*b) for b in self.beacons]\n\n\ndef compare(scanner_1, scanner_2):\n for beacons_2 in scanner_2.orientations():\n for b1 in scanner_1.beacons:\n for b2 in beacons_2:\n offset = [i - j for i, j in zip(b1, b2)]\n\n beacons_2_in_1_coords = {\n tuple([i + j for i, j in zip(bb2, offset)]) for bb2 in beacons_2\n }\n overlap = beacons_2_in_1_coords.intersection(scanner_1.beacons)\n if len(overlap) >= 12:\n scanner_1.extend(scanner_2, beacons_2_in_1_coords, offset)\n return True\n\n return False\n\n\ndef run(inputs):\n scanners = []\n beacons = []\n for line in inputs.split(os.linesep):\n if \"scanner\" in line:\n continue\n elif not line:\n scanners.append(Scanner(beacons))\n beacons = []\n else:\n beacons.append(tuple(map(int, line.split(\",\"))))\n if beacons:\n scanners.append(Scanner(beacons))\n\n while len(scanners) > 1:\n to_remove = []\n\n for i, s1 in enumerate(scanners):\n for j, s2 in enumerate(scanners):\n if j in to_remove:\n continue\n if i == j:\n continue\n result = compare(s1, s2)\n if result:\n to_remove.append(j)\n print(\n f\"Combining scanner {j} into {i}, {len(scanners)-len(to_remove)} scanners left\",\n )\n\n else:\n print(f\"Not combining {j} into {i}\")\n if len(to_remove):\n break\n\n if not to_remove:\n msg = \"Should not be here, nothing to remove\"\n raise RuntimeError(msg)\n\n for i, r in enumerate(to_remove):\n del scanners[r - i]\n\n return len(scanners[0].beacons)\n","sub_path":"2021/19/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"415071802","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n#\n# Copyright (c) 2016 ASMlover. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list ofconditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materialsprovided with the\n# distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport PathHelper as PH\nPH.addPathes('../')\n\nimport sys\nimport time\nimport AsyncIo as asio\n\nclass AsyncTask(object):\n def __init__(self):\n super(AsyncTask, self).__init__()\n self.tasks = []\n\n def addDelay(self, delayTime):\n \"\"\"添加延时时间\"\"\"\n self.tasks.append(delayTime)\n\n def addTask(self, func):\n if callable(func):\n self.tasks.append(func)\n\n def execute(self):\n lastCheck = time.time()\n delta = 0\n while True:\n asio.loop(0.1, True, None, 1)\n time.sleep(0.01)\n\n now = time.time()\n if now - lastCheck > delta:\n lastCheck = now\n if len(self.tasks) == 0:\n break\n t = self.tasks.pop(0)\n\n if callable(t):\n t()\n else:\n delta = t\n\nif __name__ == '__main__':\n executor = AsyncTask()\n executor.addTask(lambda: print('111'))\n executor.addDelay(1)\n executor.addTask(lambda: print('222'))\n executor.addDelay(1)\n executor.execute()\n","sub_path":"server/Mars/MarsRpc/AsyncTask.py","file_name":"AsyncTask.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"8017546","text":"\nproject = 'LiteX SoC Project'\ncopyright = '2020, Anonymous'\nauthor = 'Anonymous'\nextensions = [\n 'sphinx.ext.autosectionlabel',\n 'sphinxcontrib.wavedrom',\n]\ntemplates_path = ['_templates']\nexclude_patterns = []\noffline_skin_js_path = \"https://wavedrom.com/skins/default.js\"\noffline_wavedrom_js_path = \"https://wavedrom.com/WaveDrom.js\"\nhtml_theme = 'alabaster'\nhtml_static_path = ['_static']\n\n","sub_path":"build/documentation/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"514728736","text":"#!/usr/bin/env python\n\n# rapid random trees\n#todo: cleanup these imports\n\nfrom skimage.io import imread\nfrom skimage.io import imsave\nfrom skimage import measure\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport time\nimport sys\nimport os\nimport math\n\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport rospy\nfrom gazebo_msgs.msg import ModelState\nfrom gazebo_msgs.srv import GetModelState\n\nfrom skimage.io import imread\nfrom skimage.draw import line_aa\nfrom scipy.sparse import coo_matrix\nfrom scipy.sparse.csgraph import shortest_path\nimport numpy as np\n\nimport roslaunch\n\n\n#with the help of image routines, see if paths are valid\ndef does_path_intersect(config_map, point1, point2):\n # make a line and extract the map along that line\n point1 = point1.astype(int)\n point2 = point2.astype(int)\n rr, cc, val = line_aa(point1[0], point1[1], point2[0], point2[1])\n # add 1 so the free space as 255 overflows to 0 (uint8)\n intersect = np.sum((config_map[rr, cc]+1).astype(int))\n # if the value is non-zero, the path must have intersected with something somewhere.\n return bool(intersect)\n\n\n#build the prm graph, and allow extensions if needed\ndef build_rrt_graph(config_map, voxel_size, start_pos, end_pos, max_length):\n # following the same graph format, we make two, graph_start, graph_end\n # I imagine sampling with something like an expanding wald distribution may\n # be better, but for time, sample uniformly across the space and build the tree\n rng = np.random.default_rng()\n\n graph_start = []\n graph_start.append([np.asarray(start_pos)])\n graph_start.append([])\n graph_start.append([])\n graph_start.append([])\n graph_end = []\n graph_end.append([np.asarray(end_pos)])\n graph_end.append([])\n graph_end.append([])\n graph_end.append([])\n\n graph_final = [[],[],[],[]]\n end_node = 0\n\n while True:\n #sample 20 points randomly\n internal_points = rng.uniform(0,10.0,(20, 2))\n #remove any invalids\n mask = np.transpose((internal_points / voxel_size).astype(int))\n mask = (config_map[tuple(mask)]).astype(bool)\n sample = internal_points[mask]\n\n #test each one (only test against the last 20 points added to the graph)\n offset_start = 0\n offset_end = 0\n# if len(graph_start[0]) > 20:\n# graph_start_points = np.array(graph_start[0][-20:])\n# offset_start = len(graph_start[0])-20\n# else:\n# graph_start_points = np.array(graph_start[0])\n#\n# if len(graph_end[0]) > 20:\n# graph_end_points = np.array(graph_end[0][-20:])\n# offset_end = len(graph_end[0])-20\n# else:\n# graph_end_points = np.array(graph_end[0])\n graph_start_points = np.array(graph_start[0])\n graph_end_points = np.array(graph_end[0])\n\n delta_start = np.linalg.norm(np.expand_dims(sample, axis=1) - np.array(graph_start_points), axis=2)\n delta_end = np.linalg.norm(np.expand_dims(sample, axis=1) - np.array(graph_end_points), axis=2)\n # column indexes the tree point, row indexes the sample point\n\n #threshold and identify any overlap\n delta_start[delta_start>max_length] = -1\n delta_end[delta_end>max_length] = -1\n \n\n start_mask = np.max(delta_start, axis=1)\n start_mask[start_mask<=0] = 0\n start_mask = start_mask.astype(bool)\n\n end_mask = np.max(delta_end, axis=1)\n end_mask[end_mask<=0] = 0\n end_mask = end_mask.astype(bool)\n\n delta_start[delta_start<0] = float('inf')\n delta_end[delta_end<0] = float('inf')\n\n overlap_mask = np.copy(start_mask)\n overlap_mask[~end_mask] = 0\n if np.any(overlap_mask):\n # we have overlap, so we fill it in and break\n ov_s = sample[overlap_mask]\n # update the start tree\n ov_l_start = delta_start[overlap_mask]\n ov_i_start = np.argmin(ov_l_start, axis=1)\n offset = len(graph_start[0])\n added_start = []\n added_end = []\n graph_final[0] = graph_start[0]\n graph_final[1] = graph_start[1]\n graph_final[2] = graph_start[2]\n graph_final[3] = graph_start[3]\n ids = []\n for index in range(len(ov_i_start)):\n #check and skip if there's a barrier\n if does_path_intersect(config_map, graph_final[0][ov_i_start[index] + offset_start]/voxel_size, sample[index]/voxel_size):\n ids.append(-1)\n offset = offset - 1\n continue\n graph_final[0].append(sample[index])\n graph_final[1].append(ov_i_start[index] + offset_start)\n graph_final[2].append(index + offset)\n graph_final[3].append(ov_l_start[index,ov_i_start[index]])\n ids.append(index + offset)\n # note the id to make sure we don't fail by accident\n added_start.append(index)\n\n # grab new offset\n new_offset_end = offset_end + len(graph_final[0])-1\n end_node = len(graph_final[0])\n # append the end tree\n graph_final[0].extend(graph_end[0])\n graph_final[1].extend([x + end_node for x in graph_end[1]])\n graph_final[2].extend([x + end_node for x in graph_end[2]])\n graph_final[3].extend(graph_end[3])\n offset = len(graph_final[0])\n\n # update the tree with the final connections\n ov_l_end = delta_end[overlap_mask]\n ov_i_end = np.argmin(ov_l_end, axis=1)\n for index in range(len(ov_i_end)):\n #check and skip if there's a barrier\n if does_path_intersect(config_map, graph_final[0][ov_i_end[index] + new_offset_end]/voxel_size, sample[index]/voxel_size):\n offset = offset - 1\n continue\n # don't need to readd the same nodes\n graph_final[1].append(ov_i_end[index] + new_offset_end)\n if (ids[index] != -1):\n graph_final[2].append(ids[index])\n offset = offset - 1\n else:\n graph_final[0].append(sample[index])\n graph_final[2].append(index + offset)\n graph_final[3].append(ov_l_end[index,ov_i_end[index]])\n # note the id to make sure we don't fail by accident\n added_end.append(index)\n # as long as at least one node is in common...\n if set(added_start) & set(added_end):\n # stop building the tree here if we have overlap\n break\n\n #build the start tree points\n if np.any(start_mask):\n # we have overlap, so we fill it in and break\n ov_s = sample[start_mask]\n # update the start tree\n ov_l_start = delta_start[start_mask]\n ov_i_start = np.argmin(ov_l_start, axis=1)\n offset = len(graph_start[0])\n for index in range(len(ov_i_start)):\n #check and skip if there's a barrier\n if does_path_intersect(config_map, graph_start[0][ov_i_start[index] + offset_start]/voxel_size, sample[index]/voxel_size):\n offset = offset - 1\n continue\n graph_start[0].append(sample[index])\n graph_start[1].append(ov_i_start[index] + offset_start)\n graph_start[2].append(index + offset)\n graph_start[3].append(ov_l_start[index,ov_i_start[index]])\n\n #build the end tree points\n if np.any(end_mask):\n # we have overlap, so we fill it in and break\n ov_s = sample[end_mask]\n # update the start tree\n ov_l_end = delta_end[end_mask]\n ov_i_end = np.argmin(ov_l_end, axis=1)\n offset = len(graph_end[0])\n for index in range(len(ov_i_end)):\n #check and skip if there's a barrier\n if does_path_intersect(config_map, graph_end[0][ov_i_end[index] + offset_end]/voxel_size, sample[index]/voxel_size):\n offset = offset - 1\n continue\n graph_end[0].append(sample[index])\n graph_end[1].append(ov_i_end[index] + offset_end)\n graph_end[2].append(index + offset)\n graph_end[3].append(ov_l_end[index,ov_i_end[index]])\n\n # the graph is sparsely defined to later use scipy coo matrix and shortest path\n # also nice because it can handle duplicates\n graph_start[0] = {index: value for index, value in enumerate(graph_start[0])}\n print(graph_start)\n print(end_node)\n return (graph_start, 0, end_node)\n\n\ndef run_plan(plan):\n #use bug2 to execute the plan\n package = rospy.get_param('local_motion_package')\n exe = rospy.get_param('local_motion_exe')\n extra_args = rospy.get_param('local_motion_extra_args')\n evaluator = rospy.get_param('local_motion_eval')\n uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)\n roslaunch.configure_logging(uuid)\n launch = roslaunch.scriptapi.ROSLaunch()\n launch.start()\n nodes = []\n for next in plan:\n nodes.append(roslaunch.core.Node(package, exe, args=str(next[0])+' '+str(next[1])+' '+extra_args))\n\n #launch the evaluation node!\n eval_node = launch.launch(roslaunch.core.Node(package, evaluator, cwd=\"node\"))\n for node in nodes:\n process = launch.launch(node)\n while process.is_alive():\n time.sleep(0.02)\n eval_node.stop()\n# cli_args = [launch_file, 'x:='+str(next[0]), 'y:='+str(next[1]), 'stopdone:=false']\n# roslaunch_args = cli_args[1:]\n# roslaunch_file = roslaunch.rlutil.resolve_launch_arguments(cli_args)\n# roslaunch_file = [(roslaunch_file[0], roslaunch_args)]\n#\n# parent = roslaunch.parent.ROSLaunchParent(uuid, roslaunch_file)\n#\n# parent.start(auto_terminate=False)\n# parent.spin()\n\n\n# run the main planner routine\ndef rrt_planner(targetx, targety):\n\n rospy.init_node('rrt_planner', anonymous=True)\n\n # load in the map\n map_path = rospy.get_param('/map/free_space_map', \"./room.pgm\")\n free_space = imread(map_path)\n map_path = rospy.get_param('/map/configuration_map', \"./room.pgm\")\n config_space = imread(map_path)\n room_voxel = rospy.get_param('/map/voxel_size', 0.05)\n # rotate it to match the room (room_map[x][y])\n free_space = np.rot90(free_space, k=-1, axes=(0,1))\n config_space = np.rot90(config_space, k=-1, axes=(0,1))\n\n # get the only parameter for rrt\n max_length = rospy.get_param('rrt_max_length', 1.0)\n\n # get the state & goal\n # we're running off the assumption that everything is already running\n get_model_state = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)\n robot = get_model_state('maru2','')\n initial_pos = np.array([robot.pose.position.x, robot.pose.position.y], dtype=float)\n goal = np.array([targetx, targety], dtype=float)\n\n # start timing\n time_planning_start = rospy.Time.now()\n graph, start_node, end_node = build_rrt_graph(config_space, room_voxel, initial_pos, goal, max_length)\n\n # Find shortest path\n start = np.append(graph[1], graph[2])\n end = np.append(graph[2], graph[1])\n length = np.append(graph[3], graph[3])\n size = max(graph[0])+1\n coo_graph = coo_matrix((length, (start, end)), shape=(size,size))\n dist, pred = shortest_path(coo_graph, directed=False, indices=end_node, return_predecessors=True)\n\n print(dist, pred)\n\n path = [pred[start_node]]\n current = pred[start_node]\n while current != end_node:\n path.append(pred[current])\n current = pred[current]\n\n #save the time of planning completion\n time_planning_done = rospy.Time.now()\n time_difference = time_planning_done.to_sec()-time_planning_start.to_sec()\n plan = [graph[0][key] for key in path]\n print(\"Planning took\", time_difference)\n print(\"Path is\", plan)\n\n #create a visualization of the points and lines\n \n #save the visualizations\n #and dump the stats locally\n # for each list, get the numpy representation\n date = time.strftime(\"%Y-%m-%d_%H-%M-%S\", time.localtime())\n\n x = np.array(plan)[:,0]\n y = np.array(plan)[:,1]\n \n\n all_points = np.array([graph[0][key] for key in range(0,max(graph[0])+1)])/room_voxel\n\n if not os.path.isdir(\"plans/\"):\n os.makedirs(\"plans/\")\n\n #plot path\n plt.figure()\n plt.imshow(free_space)\n for row in zip(graph[1],graph[2]):\n sp = graph[0][row[0]]/room_voxel\n ep = graph[0][row[1]]/room_voxel\n plt.plot([sp[1],ep[1]], [sp[0],ep[0]], 'r:', linewidth=.5)\n plt.plot(all_points[:,1], all_points[:,0], 'b.')\n plt.plot(y/room_voxel, x/room_voxel, 'k')\n plt.plot(goal[1]/room_voxel, goal[0] / room_voxel,'go')\n plt.plot(initial_pos[1]/room_voxel, initial_pos[0]/room_voxel,'co')\n plt.title('Plan generated by algorithm (with all points and connections)\\nTime to generate: '+str(time_difference)+'s')\n plt.savefig(\"plans/\"+date+\"_rrt_plan.png\")\n plt.draw()\n\n run_plan(plan)\n\n\nif __name__ == '__main__':\n try:\n argv = rospy.myargv(argv=sys.argv)\n if len(argv) < 3:\n print(\"Please enter a position x y\")\n rrt_planner(argv[1], argv[2])\n except rospy.ROSInterruptException:\n pass\n\n","sub_path":"planner/rrt_planner.py","file_name":"rrt_planner.py","file_ext":"py","file_size_in_byte":13493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"389787481","text":"from flask_squirrel.table.dbutil import get_label_for_lang, SELF_REF_SUFFIX\n\nfrom typing import Dict, Union, Tuple\n\nimport logging\nfrom flask.logging import default_handler\nlog = logging.getLogger('view_spec_generator')\nlog.setLevel(logging.INFO)\nlog.addHandler(default_handler)\n\n\nclass ViewSpecGenerator:\n def __init__(self, customview_spec, translation_spec, db_spec):\n self.customview_spec = customview_spec\n self.translation_spec = translation_spec\n self.db_spec = db_spec\n self.current_lang = 'en'\n\n def generate_default_spec(self, table_name: str, lang: str):\n # lang is an ISO631 language code\n self.current_lang = lang\n\n view_spec = self._generate_resource_view_spec(table_name)\n log.debug('generated view spec for table {0} and lang {1}: {2}'.format(table_name, lang, view_spec))\n return view_spec\n\n def _generate_resource_view_spec(self, table_name: str) -> Dict[str, Union[str, list]]:\n # generate the resource view specification out of the 3 passed json files\n view_spec = {}\n if table_name in self.customview_spec:\n if '_attributes' in self.customview_spec[table_name]:\n if 'hidden' in self.customview_spec[table_name]['_attributes']:\n # this is a table which is not show on the user interface as it used by the backend itself\n return view_spec\n\n self._generate_table(table_name, view_spec)\n\n return view_spec\n\n def _generate_table(self, table_name: str, view_spec: Dict[str, Union[str, list]]) -> None:\n table_spec = None\n\n # check if the table is \"virtual\" - some business logic, but not a real table\n if table_name in self.customview_spec:\n if '_columns' in self.customview_spec[table_name]:\n table_spec = self.customview_spec[table_name]['_columns']\n\n if not table_spec:\n if table_name not in self.db_spec:\n log.error('The table named \"{0}\" is not specified in the database specification. JSON file not loaded?'\n .format(table_name))\n return\n else:\n table_spec = self.db_spec[table_name]['columns']\n\n if table_name not in self.translation_spec:\n log.error('The table named \"{0}\" is not specified in the translation specification. JSON file not loaded?'\n .format(table_name))\n return\n\n if table_name not in self.translation_spec[table_name]:\n log.error('The table name \"{0}\" itself is not translated. Append missing label!'\n .format(table_name))\n return\n table_label = self.translation_spec[table_name][table_name]\n view_spec['label'] = get_label_for_lang(self.current_lang, table_label)\n\n # Note about editor-fields:\n # This is a specification of how a row of a table should be edited (some fields read only, some fields not-null\n # etc.).\n view_spec['editor-fields'] = []\n\n # Note about table-fields:\n # This is a specification of how to present the database content in a table.\n view_spec['table-fields'] = []\n\n ref_table_count = {}\n\n for col_spec in table_spec:\n read_spec, edit_spec = self._generate_column(table_name, col_spec, ref_table_count)\n if read_spec:\n view_spec['table-fields'].append(read_spec)\n if edit_spec:\n view_spec['editor-fields'].append(edit_spec)\n\n def _generate_column(self, table_name: str, col_spec: Dict[str, Union[None, str, bool, list, int]], ref_table_count)\\\n -> Tuple[Dict[str, Union[str, bool]], Dict[str, Union[str, bool]]]:\n col_name = col_spec['name']\n col_type = col_spec['type']\n col_func = None\n if 'func' in col_spec:\n col_func = col_spec['func']\n if col_func == 'primarykey':\n # do currently nothing with primary key\n return None, None\n\n title = col_name\n try:\n title = get_label_for_lang(self.current_lang, self.translation_spec[table_name][col_name])\n except Exception as e:\n log.error('No translation found for field {0} in table {1}'.format(col_name, table_name))\n\n name = '{0}.{1}'.format(table_name, col_name)\n if col_func == 'foreignkey':\n try:\n ref_table_name, ref_col_name = col_spec['reference'].split('.')\n if ref_table_name == table_name:\n # This is a reference to itself! Example: reference from one employee to an other who is the chief of him.\n # In this case a suffix must be added to the table name to refence it correctly!\n ref_table_name = '{0}{1}'.format(ref_table_name, SELF_REF_SUFFIX)\n\n if ref_table_name not in ref_table_count:\n ref_table_count[ref_table_name] = 0\n\n ref_text_list = self.customview_spec[table_name][col_name]['ref_text']\n new_ref_text_list = []\n for ref in ref_text_list:\n cref_table_name, cref_col_name = ref.split('.')\n # it's expected that cref_table_name is always the same as ref_table_name; otherwise it the parameters\n # would be strange... -> use ref_table_name here as it is fixed for self referencing columns\n new_ref = '{0}.{1}.{2}'.format(ref_table_name, ref_table_count[ref_table_name], cref_col_name)\n new_ref_text_list.append(new_ref)\n name = ' '.join(new_ref_text_list)\n\n ref_table_count[ref_table_name] += 1\n\n except Exception as e:\n log.error('No custom view specification found for foreign key {0} in table {1}'.format(col_name,\n table_name))\n\n field_view_read_spec = {'data': name, 'title': title}\n field_view_edit_spec = {'name': name, 'label': title}\n\n if ('not-null' in col_spec) and (col_spec['not-null'] is True):\n field_view_edit_spec['not-null'] = True\n\n if col_type == 'date':\n field_view_read_spec['type'] = 'date'\n field_view_edit_spec['type'] = 'datetime'\n elif col_type == 'decimal':\n field_view_read_spec['type'] = 'num-fmt'\n # unclear in editor: field_view_edit_spec['type'] = 'num-fmt'\n elif col_type == 'enum':\n field_view_edit_spec['type'] = 'select'\n # field_view_read_spec['type'] = 'string'\n field_view_read_spec['data'] = '{0}_{1}.name'.format(table_name, col_name)\n elif col_func == 'foreignkey':\n # ref_table_name, ref_id_name = col_spec['reference'].split('.')\n field_view_edit_spec['type'] = 'select'\n field_view_edit_spec['name'] = '{0}.{1}'.format(table_name, col_name) # (ref_table_name, col_name)\n\n # handle fields as links\n link = None\n try:\n link = self.customview_spec[table_name][col_name]['filelink']\n # leaves if no link field found\n field_view_read_spec['link'] = True\n except TypeError:\n pass\n except KeyError:\n pass\n\n # handle readonly fields\n try:\n if 'editor_readonly' in self.customview_spec[table_name][col_name]['_attributes']:\n # use 'disabled' instead of readonly because it is used for date types as well as for strings etc.\n field_view_edit_spec['disabled'] = True\n except KeyError:\n pass\n\n try:\n if 'password' in self.customview_spec[table_name][col_name]['_attributes']:\n # use 'disabled' instead of readonly because it is used for date types as well as for strings etc.\n field_view_edit_spec['type'] = 'password'\n field_view_read_spec = None\n except KeyError:\n pass\n\n return field_view_read_spec, field_view_edit_spec\n","sub_path":"flask_squirrel/util/view_spec_generator.py","file_name":"view_spec_generator.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"437199608","text":"\"\"\"tanzhou URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom users.views import UserInfoView,ChangePwdView,UploadImageView,UserCourseView,UserWorkView,UserOrderView\n# from users.views import UserInfoView\n\n\nurlpatterns = [\n #用户信息\n url(r'info/$',UserInfoView.as_view(),name='info'),\n #修改密码\n url(r'change_pwd/$',ChangePwdView.as_view(),name='change_pwd'),\n #用户头像上传\n url(r'^image/upload/$',UploadImageView.as_view(),name='image_upload'),\n\n #我的订单\n url(r'order/$',UserOrderView.as_view(),name='order'),\n #我的作业\n url(r'homework/$',UserWorkView.as_view(),name='homework'),\n #我的课程\n url(r'course/$',UserCourseView.as_view(),name='course'),\n\n]\n","sub_path":"tanzhou/apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"458241271","text":"import calendar\nimport datetime as dt\n\nimport numpy as np\nfrom individual.anton.periodiscore.periodi_date_amount import *\n\n__author__ = \"Anton Suchaneck\"\n__email__ = \"a.suchaneck@gmail.com\"\n\nHOLIDAYS = [\n dt.datetime(year, month, day)\n for year in [2016, 2017]\n for day, month in [(1, 1), (25, 12), (26, 12)]\n]\n\n\ndef create_day_float_map(cnt_daydiff, start_date, holidays):\n busdaycal = np.busdaycalendar(holidays=holidays)\n\n result = {}\n for daydiff in range(cnt_daydiff):\n date = start_date + dt.timedelta(daydiff)\n first_day_in_month = date.replace(day=1)\n last_day_in_month = date.replace(\n day=calendar.monthrange(date.year, date.month)[1]\n )\n max_cnt_busdays = np.busday_count(\n first_day_in_month, last_day_in_month, busdaycal=busdaycal\n )\n cnt_busdays = np.busday_count(first_day_in_month, date, busdaycal=busdaycal)\n result[date] = (\n 12 * date.year\n + (date.month - 1)\n + float(cnt_busdays / (max_cnt_busdays + 1))\n )\n\n return result\n\n\nbusday_float = create_day_float_map(\n cnt_daydiff=1000, start_date=dt.datetime(2016, 1, 1), holidays=HOLIDAYS\n).get\n\n\ndef npdatetime2datetime(npdt):\n return dt.datetime.utcfromtimestamp(\n (npdt - np.datetime64(\"1970-01-01T00:00:00Z\")) / np.timedelta64(1, \"s\")\n )\n # return dt.datetime.utcfromtimestamp(npdt.astype(int))\n\n\ndef create_yearmonth_func(years, holidays):\n def yearmonth_func(year, month, day_float):\n max_cnt_busdays = yearmonth__max_cnt_busdays[year, month]\n target_bday = int(\n round(day_float * (max_cnt_busdays + 1))\n ) # int needed since round(np.float64) yields float\n first_day_in_month = dt.datetime(year, month, 1)\n\n return npdatetime2datetime(\n np.busday_offset(\n first_day_in_month, target_bday, \"forward\", busdaycal=busdaycal\n )\n )\n\n busdaycal = np.busdaycalendar(holidays=holidays)\n\n yearmonth__max_cnt_busdays = {}\n\n for year in years:\n for month in range(1, 13):\n first_day_in_month = dt.datetime(year, month, 1)\n last_day_in_month = dt.datetime(\n year, month, calendar.monthrange(year, month)[1]\n )\n max_cnt_busdays = np.busday_count(\n first_day_in_month, last_day_in_month, busdaycal=busdaycal\n )\n yearmonth__max_cnt_busdays[year, month] = int(max_cnt_busdays)\n\n return yearmonth_func\n\n\nfloat_busdate = create_yearmonth_func(years=[2016, 2017], holidays=HOLIDAYS)\n\n\ndef futuremoney(data):\n \"\"\"\n :param data: [(datetime, amount), ...]\n :result: future (datetime, amount)\n \"\"\"\n if len(data) > 15:\n return None, None\n\n months = None\n\n periodi = periodi_amount_time(\n data,\n amount_binnum_width=1,\n amount_cap=0.5,\n time_step_num=30,\n time_binnum_width=10,\n time_cap=0.5,\n amount_step=49,\n power=1,\n date_to_float=date_to_float,\n )\n tops = periodi.get_top()\n\n if tops:\n key, scorer, score = tops[0]\n return float_to_date(scorer.avg_time), scorer.avg_amount\n else:\n return None, None\n\n\nif __name__ == \"__main__\":\n for d in range(60):\n date = dt.datetime(2016, 1, 1) + dt.timedelta(days=d)\n f = day_float(date)\n print(date, f, float_date(date.year, date.month, f))\n","sub_path":"dstk/periodiscore/futuremoney.py","file_name":"futuremoney.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"107074416","text":"import lib.pytorch.cnn.python_layer as cnn_layer\nimport lib.pytorch.dataset.pytorch_dataset as j_data\nimport numpy as np\nimport lib.utils.ProgressBar as j_bar\nimport torch\nimport torchvision\n\nCONFIG = {\n \"EPOCHS\" : 100,\n \"BATCH_SIZE\" : 64,\n \"LEARNING_RATE\" : 1e-4\n}\n\ndataset = j_data.MNISTDataSetForPytorch(radio=0.9, transform=torchvision.transforms.ToTensor())\ntrain_loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=CONFIG[\"BATCH_SIZE\"], shuffle=True)\n\nconv1 = cnn_layer.Conv2D([CONFIG[\"BATCH_SIZE\"], 28, 28, 1], 12, 5, 1)\nrelu1 = cnn_layer.Relu(conv1.output_shape)\npool1 = cnn_layer.MaxPooling(relu1.output_shape)\nconv2 = cnn_layer.Conv2D(pool1.output_shape, 24, 3, 1)\nrelu2 = cnn_layer.Relu(conv2.output_shape)\npool2 = cnn_layer.MaxPooling(relu2.output_shape)\nfc = cnn_layer.FullyConnect(pool2.output_shape, 10)\nsf = cnn_layer.Softmax(fc.output_shape)\n\nbar = j_bar.ProgressBar(CONFIG[\"EPOCHS\"], len(train_loader), \"train:%.3f,%.3f\")\n\nfor epoch in range(1, CONFIG[\"EPOCHS\"] + 1):\n batch_loss = 0\n batch_acc = 0\n val_acc = 0\n val_loss = 0\n\n # train\n train_acc = 0\n train_loss = 0\n for i, (train_image, train_label) in enumerate(train_loader):\n img = train_image.data.numpy().transpose((0, 2, 3, 1))\n label = train_label.data.numpy().squeeze()\n\n conv1_out = relu1.forward(conv1.forward(img))\n pool1_out = pool1.forward(conv1_out)\n conv2_out = relu2.forward(conv2.forward(pool1_out))\n pool2_out = pool2.forward(conv2_out)\n fc_out = fc.forward(pool2_out)\n batch_loss += sf.cal_loss(fc_out, np.array(label))\n train_loss = sf.cal_loss(fc_out, np.array(label))\n train_acc = 0\n for j in range(train_image.shape[0]):\n if np.argmax(sf.softmax[j]) == label[j]:\n train_acc += 1\n\n sf.gradient()\n conv1.gradient(relu1.gradient(pool1.gradient(\n conv2.gradient(relu2.gradient(pool2.gradient(\n fc.gradient(sf.eta)))))))\n\n if i % 1 == 0:\n fc.backward(alpha=CONFIG[\"LEARNING_RATE\"], weight_decay=0.0004)\n conv2.backward(alpha=CONFIG[\"LEARNING_RATE\"], weight_decay=0.0004)\n conv1.backward(alpha=CONFIG[\"LEARNING_RATE\"], weight_decay=0.0004)\n batch_loss = 0\n batch_acc = 0\n\n bar.show(epoch, train_loss / (train_image.shape[0]), train_acc / (train_image.shape[0]))\n\n","sub_path":"03.DeepLearning/01.Basic/MNIST_Python.py","file_name":"MNIST_Python.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"487947673","text":"from src.authentication.oauth.consumer import consumer_base\n\nCONSUMER_KEY = ''\nCONSUMER_SECRET = ''\nREQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'\nAUTHORIZE_URL = 'https://api.twitter.com/oauth/authorize'\nACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'\nCALLBACK_URL = 'http://localhost:8080/api/provider_authorize/'\nUSER_INFO_URL = 'http://api.twitter.com/1/account/verify_credentials.json'\n\nclass TwitterConsumer(consumer_base.ConsumerBase):\n\n def __init__(self, oauth_token='', oauth_secret=''):\n super(TwitterConsumer, self).__init__(oauth_token, oauth_secret)\n self.consumer_key = CONSUMER_KEY\n self.consumer_secret = CONSUMER_SECRET\n self.request_token_url = REQUEST_TOKEN_URL\n self.authorize_url = AUTHORIZE_URL\n self.access_token_url = ACCESS_TOKEN_URL\n self.callback_url = CALLBACK_URL\n self.user_info_url = USER_INFO_URL\n","sub_path":"oauth/consumer/facebook_consumer.py","file_name":"facebook_consumer.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"178781955","text":"#!/usr/bin/env python\r\n# _*_ coding: utf-8 _*_\r\n\r\nimport os\r\nimport argparse\r\n\r\n\r\n\r\nfrom pymatflow.vasp.static import static_run\r\n\r\n\"\"\"\r\nusage:\r\n\"\"\"\r\n\r\nparams = {}\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-d\", \"--directory\", help=\"directory of the static running\", type=str, default=\"tmp-vasp-sigma\")\r\n parser.add_argument(\"-f\", \"--file\", help=\"the xyz file name\", type=str)\r\n\r\n parser.add_argument(\"--runopt\", type=str, default=\"gen\",\r\n help=\"gen, run, or genrun\")\r\n\r\n parser.add_argument(\"--auto\", type=int, default=3,\r\n help=\"auto:0 nothing, 1: copying files to server, 2: copying and executing in remote server, 3: pymatflow used in server with direct submit, in order use auto=1, 2, you must make sure there is a working ~/.pymatflow/server_[pbs|yh].conf\")\r\n\r\n parser.add_argument(\"--range\", help=\"sigma test range\", nargs='+', type=float)\r\n\r\n # --------------------------------------------------------\r\n # INCAR PARAMETERS\r\n # --------------------------------------------------------\r\n parser.add_argument(\"--prec\", type=str, default=\"Normal\",\r\n choices=[\"Normal\", \"Accurate\", \"A\", \"N\"],\r\n help=\"PREC, default value: Normal\")\r\n\r\n parser.add_argument(\"--encut\", type=int, default=300,\r\n help=\"ENCUT, default value: 300 eV\")\r\n\r\n parser.add_argument(\"--ediff\", type=float, default=1.0e-4,\r\n help=\"EDIFF, default value: 1.0e-4\")\r\n\r\n parser.add_argument(\"--kpoints-mp\", type=int, nargs=\"+\",\r\n default=[1, 1, 1, 0, 0, 0],\r\n help=\"set kpoints like -k 1 1 1 0 0 0\")\r\n\r\n parser.add_argument(\"--ismear\", type=int, default=0,\r\n help=\"smearing type(methfessel-paxton(>0), gaussian(0), fermi-dirac(-1), tetra(-4), tetra-bloch-dorrected(-5)), default: 0\")\r\n\r\n parser.add_argument(\"--ivdw\", type=int, default=None,\r\n choices=[0, 11, 12, 21, 202, 4],\r\n help=\"IVDW = 0(no correction), 1(dft-d2), 11(dft-d3 Grimme), 12(dft-d3 Becke-Jonson), default: None which means 0, no correction\")\r\n # -----------------------------------------------------------------\r\n\r\n\r\n # -----------------------------------------------------------------\r\n # run params\r\n # -----------------------------------------------------------------\r\n\r\n parser.add_argument(\"--mpi\", type=str, default=\"\",\r\n help=\"MPI command\")\r\n\r\n parser.add_argument(\"--server\", type=str, default=\"pbs\",\r\n choices=[\"pbs\", \"yh\", \"lsf_sz\"],\r\n help=\"type of remote server, can be pbs or yh or lsf_sz\")\r\n\r\n parser.add_argument(\"--jobname\", type=str, default=\"converge-sigma\",\r\n help=\"jobname on the pbs server\")\r\n\r\n parser.add_argument(\"--nodes\", type=int, default=1,\r\n help=\"Nodes used in server\")\r\n\r\n parser.add_argument(\"--ppn\", type=int, default=32,\r\n help=\"ppn of the server\")\r\n\r\n\r\n\r\n\r\n # ==========================================================\r\n # transfer parameters from the arg parser to static_run setting\r\n # ==========================================================\r\n args = parser.parse_args()\r\n params[\"PREC\"] = args.prec\r\n params[\"ENCUT\"] = args.encut\r\n params[\"EDIFF\"] = args.ediff\r\n params[\"ISMEAR\"] = args.ismear\r\n params[\"IVDW\"] = args.ivdw\r\n\r\n\r\n\r\n task = static_run()\r\n task.get_xyz(args.file)\r\n task.set_params(params=params)\r\n task.set_kpoints(kpoints_mp=args.kpoints_mp)\r\n task.set_run(mpi=args.mpi, server=args.server, jobname=args.jobname, nodes=args.nodes, ppn=args.ppn)\r\n task.converge_sigma(args.range[0], args.range[1], args.range[2], directory=args.directory, runopt=args.runopt, auto=args.auto)\r\n","sub_path":"pymatflow/vasp/scripts/vasp-converge-sigma.py","file_name":"vasp-converge-sigma.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"186955106","text":"from odoo import models, fields, api, exceptions,_\nfrom datetime import date, datetime, time, timedelta\nfrom dateutil.relativedelta import relativedelta\n\nclass check_cycle_accs(models.TransientModel):\n\n _name = 'check.cycle.accounts.default'\n\n @api.model\n def get_check_lines(self):\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n app_checks = []\n for ch in reversed(checks):\n val = {}\n val['check_number'] = ch.check_number\n val['check_id'] = ch.id\n val['check_amt'] = ch.amount\n val['paid_amt'] = ch.open_amount\n val['open_amt'] = ch.open_amount\n line = self.env['appove.check.lines'].create(val)\n # app_checks.append((0,0, val))\n app_checks.append(line.id)\n return app_checks\n\n name = fields.Char(default=\"Please choose the bank Account\",readonly=True)\n name_cancel = fields.Char(default=\"Are you sure you want to cancel the checks\", readonly=True)\n name_reject = fields.Char(default=\"Are you sure you want to reject the checks\", readonly=True)\n name_return = fields.Char(default=\"Are you sure you want to return the checks to company\", readonly=True)\n name_approve = fields.Char(default=\"Please choose the bank Account\", readonly=True)\n name_debit = fields.Char(default=\"Please choose the bank Account\", readonly=True)\n name_csreturn = fields.Char(default=\"Are you sure you want to return the checks to customer\", readonly=True)\n name_split_merge = fields.Char(default=\"Please create the new checks\", readonly=True)\n account_id = fields.Many2one('account.account',string=\"Account\")\n journal_id = fields.Many2one('account.journal',string=\"Journal\")\n reject_reason = fields.Text(string=\"Rejection reason\")\n approve_check = fields.Many2many('appove.check.lines',ondelete=\"cascade\",default=get_check_lines)\n total_amt_checks = fields.Float(string=\"total Amount of Checks\",compute=\"getcheckstotamt\")\n merge_split_checks = fields.Many2many('split.merge.check',ondelete=\"cascade\")\n\n\n @api.multi\n @api.depends('name_split_merge')\n def getcheckstotamt(self):\n for rec in self:\n rec.total_amt_checks = 0\n checks = rec.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for ch in checks:\n rec.total_amt_checks += ch.open_amount\n @api.multi\n def action_save(self):\n if 'action_wiz' in self.env.context:\n if self.env.context['action_wiz'] == 'depoist':\n if not self.journal_id:\n raise exceptions.ValidationError(_('Please provide the bank account'))\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for check in checks:\n # if not check.dep_bank:\n # raise exceptions.ValidationError(_('Please provide the deposit bank '))\n # if not check.will_collection_user:\n # raise exceptions.ValidationError(_('Please Put Bank Maturity Date For Reporting '))\n move = {\n 'name': 'Depoisting Check number ' + check.check_number,\n 'journal_id': self.journal_id.id,\n 'ref': 'Depoisting Check number ' + check.check_number,\n 'company_id': self.env.user.company_id.id\n }\n\n move_line = {\n 'name': 'Depoisting Check number ' + check.check_number,\n 'partner_id': check.investor_id.id,\n 'ref': 'Depoisting Check number ' + check.check_number,\n }\n\n debit_account = []\n credit_account = []\n debit_account.append({'account': self.journal_id.default_debit_account_id.id, 'percentage': 100})\n if check.notes_rece_id:\n credit_account.append({'account': check.notes_rece_id.id, 'percentage': 100})\n else:\n credit_account.append({'account': check.unit_id.project_id.NotesReceivableAccount.id, 'percentage': 100})\n self.sudo().env['create.moves'].create_move_lines(move=move, move_line=move_line,\n debit_account=debit_account,\n credit_account=credit_account,\n src_currency=self.env['res.users'].search([('id', '=', self.env.user.id)]).company_id.currency_id,\n amount=check.open_amount)\n check.state = 'depoisted'\n check.under_collect_id = self.journal_id.default_debit_account_id.id\n check.under_collect_jour = self.journal_id.id\n elif self.env.context['action_wiz'] == 'approve':\n if not self.journal_id:\n raise exceptions.ValidationError(_('Please provide the bank account'))\n for approve_ch_line in self.approve_check:\n z=\"\"\n for x in self.approve_check:\n z=z+(str(x.open_amt))+\",\"\n if approve_ch_line.open_amt < approve_ch_line.paid_amt:\n raise exceptions.ValidationError(_('The paid amount is greater than open amount for some checks\\n'+z))\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for check in checks:\n debit_account = []\n credit_account = []\n move = {\n 'name': 'Approving Check number ' + check.check_number,\n 'journal_id': self.journal_id.id,\n 'ref': 'Approving Check number ' + check.check_number,\n 'company_id': self.env.user.company_id.id\n }\n move_line = {\n 'name': 'Approving Check number ' + check.check_number,\n 'partner_id': check.investor_id.id,\n 'ref': 'Approving Check number ' + check.check_number,\n }\n checkamt = check.amount\n for approve_ch_line in self.approve_check:\n if approve_ch_line.check_id == check.id:\n checkamt = approve_ch_line.paid_amt\n check.open_amount -= approve_ch_line.paid_amt\n if check.investor_id:\n debit_account.append({'account': self.journal_id.default_debit_account_id.id, 'percentage': 100})\n if check.under_collect_id:\n credit_account.append({'account': check.under_collect_id.id, 'percentage': 100})\n else:\n credit_account.append({'account': check.notes_rece_id.id, 'percentage': 100})\n\n if check.state == 'returned':\n if check.notes_rece_id:\n credit_account.append({'account': check.notes_rece_id.id, 'percentage': 100})\n else:\n credit_account.append(\n {'account': check.unit_id.project_id.NotesReceivableAccount.id, 'percentage': 100})\n # elif check.state != 'returned':\n # if check.under_collect_id:\n # credit_account.append(\n # {'account': check.under_collect_id.id, 'percentage': 100})\n # else:\n # if check.notes_rece_id:\n # credit_account.append({'account': check.notes_rece_id.id, 'percentage': 100})\n # else:\n # credit_account.append(\n # {'account': check.unit_id.project_id.NotesReceivableAccount.id, 'percentage': 100})\n\n if checkamt > 0.0:\n self.sudo().env['create.moves'].create_move_lines(move=move, move_line=move_line,\n debit_account=debit_account,\n credit_account=credit_account,\n src_currency=self.env['res.users'].search([('id', '=', self.env.user.id)]).company_id.currency_id,\n amount=checkamt)\n if check.open_amount == 0.0:\n check.state = 'approved'\n elif self.env.context['action_wiz'] == 'reject':\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for check in checks:\n check.state = 'rejected'\n check.message_post(_(\"Rejection Reason is \" + str(self.reject_reason)))\n elif self.env.context['action_wiz'] == 'return':\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for check in checks:\n move = {\n 'name': 'Returning Check number ' + check.check_number,\n 'journal_id': check.under_collect_jour.id,\n 'ref': 'Returning Check number ' + check.check_number,\n 'company_id': self.env.user.company_id.id\n }\n\n move_line = {\n 'name': 'Returning Check number ' + check.check_number,\n 'partner_id': check.partner_id.id or check.investor_id.id,\n 'ref': 'Returning Check number ' + check.check_number,\n }\n debit_account = []\n credit_account = []\n credit_account.append({'account': check.under_collect_jour.default_debit_account_id.id, 'percentage': 100})\n if check.notes_rece_id:\n debit_account.append({'account': check.notes_rece_id.id, 'percentage': 100})\n else:\n debit_account.append({'account': check.unit_id.project_id.NotesReceivableAccount.id, 'percentage': 100})\n self.sudo().env['create.moves'].create_move_lines(move=move, move_line=move_line,\n debit_account=debit_account,\n credit_account=credit_account,\n src_currency=self.env['res.users'].search([('id', '=', self.env.user.id)]).company_id.currency_id,\n amount=check.open_amount)\n check.state = 'returned'\n\n elif self.env.context['action_wiz'] == 'debit':\n if not self.journal_id:\n raise exceptions.ValidationError(_('Please provide the bank account'))\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for check in checks:\n move = {\n 'name': 'Debiting Check number ' + check.check_number,\n 'journal_id': self.journal_id.id,\n 'ref': 'Debiting Check number ' + check.check_number,\n 'company_id': self.env.user.company_id.id\n }\n move_line = {\n 'name': 'Debiting Check number ' + check.check_number,\n 'partner_id': check.investor_id.id,\n 'ref': 'Debiting Check number ' + check.check_number,\n }\n\n\n debit_account = []\n credit_account = []\n credit_account.append({'account': self.journal_id.default_debit_account_id.id, 'percentage': 100})\n debit_account.append({'account': check.notespayable_id.id, 'percentage': 100})\n self.sudo().env['create.moves'].create_move_lines(move=move, move_line=move_line,\n debit_account=debit_account,\n credit_account=credit_account,\n src_currency=self.env['res.users'].search([('id', '=', self.env.user.id)]).company_id.currency_id,\n amount=check.amount)\n check.state = 'debited'\n elif self.env.context['action_wiz'] == 'cs_return':\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n journal_id = self.env.ref('check_managementtttt.rece_check_journal').id\n for check in checks:\n move = {\n 'name': 'Returning Check number ' + check.check_number + ' to customer',\n 'journal_id': journal_id,\n 'ref': 'Returning Check number ' + check.check_number + ' to customer',\n 'company_id': self.env.user.company_id.id,\n\n }\n move_line = {\n 'name': 'Returning Check number ' + check.check_number + ' to customer',\n 'partner_id': check.investor_id.id,\n 'ref': 'Returning Check number ' + check.check_number + ' to customer',\n }\n\n if check.investor_id:\n debit_account = [{'account':check.investor_id.property_account_receivable_id.id , 'percentage' : 100}]\n credit_account = [{'account': check.notespayable_id.id,'percentage' : 100}]\n self.env['create.moves'].create_move_lines(move=move, move_line=move_line,\n debit_account=debit_account,\n credit_account=credit_account,\n src_currency=self.env['res.users'].search([('id', '=', self.env.user.id)]).company_id.currency_id,\n amount=check.amount)\n\n\n check.state = 'cs_return'\n check.check_state = 'suspended'\n elif self.env.context['action_wiz'] == 'split_merge':\n checks = self.env['check.management'].search([('id', 'in', self.env.context['active_ids'])])\n for x in checks:\n if not x.notes_rece_id:\n raise exceptions.ValidationError(_('Action not allowed on normal checks'))\n new_tot_amt = 0\n notes_rece_id = 0\n ch_state = 'holding'\n if checks[0]:\n\n notes_rece_id = checks[0].notes_rece_id.id\n ch_state = checks[0].state\n else:\n raise exceptions.ValidationError(_('Action not allowed on normal checks'))\n for ch in checks:\n if notes_rece_id != ch.notes_rece_id.id:\n raise exceptions.ValidationError(\n _('You can not merge checks from different journals'))\n for sp_mr_checks in self.merge_split_checks:\n new_tot_amt += sp_mr_checks.amount\n if new_tot_amt != self.total_amt_checks:\n raise exceptions.ValidationError(_('Amount of new Checks is not equal to amount of selected checks'))\n i =0\n cur_chk_amt = self.merge_split_checks[i].amount\n check_line_val = {}\n check_line_val['check_number'] = self.merge_split_checks[i].check_number\n check_line_val['check_date'] = self.merge_split_checks[i].check_date\n check_line_val['check_bank'] = self.merge_split_checks[i].bank.id\n check_line_val['dep_bank'] = self.merge_split_checks[i].dep_bank.id\n check_line_val['amount'] = self.merge_split_checks[i].amount\n check_line_val['open_amount'] = self.merge_split_checks[i].amount\n check_line_val['amount_res'] = 0\n check_line_val['amount_con'] = 0\n check_line_val['amount_gar'] = 0\n check_line_val['amount_mod'] = 0\n check_line_val['amount_ser'] = 0\n check_line_val['amount_reg'] = 0\n check_line_val['state'] = ch_state\n rel_vals_array = []\n check_line_val['type'] = 'regular'\n check_line_val['check_type'] = 'rece'\n check_line_val['notes_rece_id'] = notes_rece_id\n check_line_val['notespayable_id'] = notes_rece_id\n new_check = self.env['check.management'].create(check_line_val)\n for acc_ins in rel_vals_array:\n\n\n #jump to next check\n i += 1\n if i < len(self.merge_split_checks):\n check_line_val = {}\n check_line_val['check_number'] = self.merge_split_checks[i].check_number\n check_line_val['check_date'] = self.merge_split_checks[i].check_date\n check_line_val['check_bank'] = self.merge_split_checks[i].bank.id\n check_line_val['dep_bank'] = self.merge_split_checks[i].dep_bank.id\n check_line_val['amount'] = self.merge_split_checks[i].amount\n check_line_val['open_amount'] = self.merge_split_checks[i].amount\n check_line_val['amount_res'] = 0\n check_line_val['amount_con'] = 0\n check_line_val['amount_gar'] = 0\n check_line_val['amount_mod'] = 0\n check_line_val['amount_ser'] = 0\n check_line_val['amount_reg'] = 0\n check_line_val['state'] = ch_state\n cur_chk_amt = self.merge_split_checks[i].amount\n for x in checks:\n x.unlink()\n else:\n raise exceptions.ValidationError(_('Unknown Action'))\n return True\n\n\n\n\n\n\nclass approve_check_lines(models.Model):\n\n _name = 'appove.check.lines'\n\n check_number = fields.Char()\n check_id = fields.Integer()\n check_amt = fields.Float()\n paid_amt = fields.Float()\n open_amt = fields.Float()\n\n\nclass split_merge_check(models.Model):\n\n _name = 'split.merge.check'\n _order = 'check_number asc'\n\n check_number = fields.Char(string=_(\"Check number\"),required=True)\n check_date = fields.Date(string=_('Check Date'),required=True)\n amount = fields.Float(string=_('Amount'),required=True)\n bank = fields.Many2one('res.bank',string=_(\"Check Bank Name\"))\n dep_bank = fields.Many2one('res.bank',string=_(\"Depoist Bank\"))\n","sub_path":"check_managementtttt/wizard/check_cycle_wizard first one.py","file_name":"check_cycle_wizard first one.py","file_ext":"py","file_size_in_byte":19755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"264309446","text":"class Solution:\r\n def lengthOfLIS(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: int\r\n \"\"\"\r\n if not nums:\r\n return 0\r\n lengths = [1 for _ in range(len(nums))]\r\n for i in range(1, len(nums)):\r\n for j in range(i):\r\n if nums[i] > nums[j]:\r\n lengths[i] = max(lengths[j] + 1, lengths[i])\r\n return max(lengths)\r\n\r\ns = Solution()\r\nnums = [10,9,2,5,3,7,101,18]\r\nprint(s.lengthOfLIS(nums))","sub_path":"leetcode/python/longestIncreasingSbs.py","file_name":"longestIncreasingSbs.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"108751137","text":"\"\"\"Compute RHDCE frequencies\n and combine with other\n antigens.\"\"\"\nimport sys, simplejson, itertools\nfrom collections import defaultdict\n\ninfinite_defaultdict = lambda: defaultdict(infinite_defaultdict)\n\ndef hashGeno(g):\n # Ce.DCE\n h = ''\n if 'D' in g:\n h += 'D+'\n else:\n h += 'D-'\n if 'C' in g:\n h += 'C+'\n else:\n h += 'C-'\n if 'E' in g:\n h += 'E+'\n else:\n h += 'E-'\n return h\n\ndef intd():\n return defaultdict(int)\n\ndef fillRh(geno):\n locus_geno_pop_percent = infinite_defaultdict()\n acc = defaultdict(intd)\n for pop in geno:\n for g in geno[pop]['DCE']:\n h = hashGeno(g)\n acc[pop][h] += geno[pop]['DCE'][g]\n for pop in acc:\n for h in acc[pop]:\n locus_geno_pop_percent[pop]['DCE_sero'][h] = acc[pop][h]\n return locus_geno_pop_percent\n\ndef mkGenotypeFreqFromHaloptypeFreq(rhJson):\n infinite_defaultdict = lambda: defaultdict(infinite_defaultdict)\n fullJson = infinite_defaultdict()\n for pop in rhJson:\n for rh in rhJson[pop]:\n percent = rhJson[pop][rh]**2 / float(100)\n fullJson[pop][rh + '.' + rh] = percent\n for rh1,rh2 in itertools.combinations(rhJson[pop], 2):\n ls = [rh1,rh2]\n ls.sort()\n key = '.'.join(ls)\n percent = 2*rhJson[pop][rh1]*rhJson[pop][rh2]/float(100)\n fullJson[pop][key] = percent\n return fullJson\n\ndef combine(rhdceJson, otherJson, outJson, outAfrJson, outEurJson):\n with open(rhdceJson) as f:\n rh = simplejson.loads( f.read() )\n with open(otherJson) as f:\n otherAntigens = simplejson.loads( f.read() )\n\n newRh = mkGenotypeFreqFromHaloptypeFreq(rh)\n otherAntigens[\"EUR\"][\"DCE\"] = newRh[\"EUR\"]\n otherAntigens[\"AFR\"][\"DCE\"] = newRh[\"AFR\"]\n\n seroRh = fillRh(otherAntigens)\n otherAntigens[\"EUR\"][\"DCE_sero\"] = seroRh[\"EUR\"][\"DCE_sero\"]\n otherAntigens[\"AFR\"][\"DCE_sero\"] = seroRh[\"AFR\"][\"DCE_sero\"]\n\n with open(outJson, 'w') as fout:\n print(simplejson.dumps(otherAntigens),\n file=fout)\n with open(outAfrJson, 'w') as fout:\n print(simplejson.dumps(otherAntigens['AFR']),\n file=fout)\n with open(outEurJson, 'w') as fout:\n print(simplejson.dumps(otherAntigens['EUR']),\n file=fout)\n\nif __name__ == '__main__':\n rhdceJson, otherJson, outJson, outAfrJson, outEurJson = sys.argv[1:]\n combine(rhdceJson, otherJson, outJson, outAfrJson, outEurJson)\n","sub_path":"code/mkPhenoPercents.py","file_name":"mkPhenoPercents.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"563909204","text":"import matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nfrom scipy.stats import binned_statistic\n\ndef plot_residuals(data, weights, range, fit, proportions, title, x_label, dataset, fname=None):\n fsize = 18\n fig = plt.figure(figsize=(8*1.618,8))\n gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) \n ax = fig.add_subplot(gs[0])\n ax.set_title(title, fontsize=fsize)\n \n step = 0.5*(fit[1,0] - fit[0,0])\n data_bin_counts, bin_edges = np.histogram(data, bins=100, weights=weights,\n normed=True, range=(range[0]-step,range[1]-step))\n stacked_counts = [np.sum(x[1:]*proportions) for x in fit]\n sum_n = np.sum(weights)\n bin_result = binned_statistic(data, weights, \n statistic=lambda lst: ((sum_n-np.sum(lst))/sum_n**2/(2*step))**2*np.dot(lst,lst),\n bins=100, range=(range[0]-step,range[1]-step))\n \n ax.errorbar(0.5*(bin_edges[:-1] + bin_edges[1:]), data_bin_counts, \n yerr=np.sqrt(bin_result.statistic), fmt='.', color='black', label=dataset)\n ax.plot(fit[:,0], stacked_counts, lw=1.5, color='r', label='MC')\n ax.set_xlabel(x_label, fontsize=fsize)\n ax.set_ylabel('Density', fontsize=fsize)\n ax.set_xlim(range[0], range[1])\n ax.set_ylim(0)\n ax.legend(prop={'size':fsize})\n ax.tick_params(length=8, width=1, labelsize=fsize)\n \n ax = fig.add_subplot(gs[1])\n diff_counts = [(x-y)/y for x,y in zip(data_bin_counts, stacked_counts)]\n #diff_errors = [(z/x**2)*dx for dx,x,z in zip(np.sqrt(bin_result.statistic), data_bin_counts, diff_counts)]\n diff_errors = [dx/y for dx,y in zip(np.sqrt(bin_result.statistic), stacked_counts)]\n ax.errorbar(fit[:,0], diff_counts, yerr=diff_errors, color='black', fmt='.')\n ax.set_xlabel(x_label, fontsize=fsize)\n ax.set_ylabel('(MC-{0})/{0}'.format(dataset), fontsize=fsize)\n ax.set_xlim(range[0], range[1])\n ax.set_ylim(-0.3,0.3)\n ax.tick_params(length=8, width=1, labelsize=fsize-1)\n ax.grid(True, which='both')\n ax.axhline(y=0, color='k')\n \n if fname: plt.savefig(fname, format='pdf', bbox_inches='tight')\n","sub_path":"utils/plot_residuals.py","file_name":"plot_residuals.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"277662710","text":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\n## data_loader\ndef get_data_loader(data_list, batch_size, shuffle=True,num_workers=3, drop_last=True):\n dataset = Make_Dataset(data_list)\n data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, drop_last=drop_last, collate_fn=make_padding)\n return data_loader\n\n\ndef make_padding(samples):\n def padd(samples):\n length = [len(s) for s in samples]\n max_length = 128\n batch = torch.zeros(len(length), max_length).to(torch.long)\n for idx, sample in enumerate(samples):\n if length[idx] < max_length:\n batch[idx, :length[idx]] = torch.LongTensor(sample)\n\n else:\n batch[idx, :max_length] = torch.LongTensor(sample[:max_length])\n #batch[idx, max_length-1] = torch.LongTensor([2])\n return torch.LongTensor(batch)\n encoder = [sample[\"encoder\"] for sample in samples]\n decoder = [sample[\"decoder\"] for sample in samples]\n encoder = padd(encoder)\n decoder = padd(decoder)\n assert len(encoder) == len(decoder)\n return {'encoder':encoder.contiguous(),\"decoder\":decoder.contiguous()}\n\n\nclass Make_Dataset(Dataset):\n def __init__(self, path):\n self.encoder_input = torch.load(path[0])\n self.decoder_input = torch.load(path[1])\n\n self.encoder_input = np.array(self.encoder_input, dtype=object)\n self.decoder_input = np.array(self.decoder_input, dtype=object)\n\n assert len(self.encoder_input) == len(self.decoder_input)\n\n def __len__(self):\n return len(self.encoder_input)\n\n def __getitem__(self, idx):\n return {\"encoder\":torch.LongTensor(self.encoder_input[idx]), \"decoder\":torch.LongTensor(self.decoder_input[idx])}\n\n","sub_path":"src/data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"78814569","text":"import discord\nimport requests\nfrom bs4 import BeautifulSoup\nimport random\n\nclient = discord.Client()\n\n@client.event\nasync def on_message(message):\n if str(message.content).startswith(\"/stick\"):\n find = str(message.content).split(\"/stick \")[-1]\n print(find)\n url = \"https://icons8.com/icon/set/\"+find\n r = requests.get(url)\n if r.text.count(\"Nothing Found\")>0:\n await client.send_message(message.channel,\"Nothing found\")\n await client.delete_message(message)\n return\n soup = BeautifulSoup(r.text,\"html.parser\")\n icon_list = soup.find('div', {'class': 'c-icon-list m-with-name'})\n if icon_list == None:\n await client.send_message(message.channel, \"Nothing found\")\n await client.delete_message(message)\n return\n icons = []\n for icon in icon_list:\n a = icon.find('img')\n if len(icons)<20 and a!=-1:\n icons.append(str(a.get('src')).replace('50','256'))\n print(icons)\n if icons == []:\n await client.send_message(message.channel, \"Nothing found\")\n await client.delete_message(message)\n return\n await client.send_message(message.channel,random.choice(icons)+\" from \"+message.author.name)\n await client.delete_message(message)\n@client.event\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\nclient.run(\"MzMyODA3OTA2MzE3NTY1OTUz.DEDhVA.Qp-VWzru13riCZV_3rUQHMt-xI8\")\n","sub_path":"Stickers.py","file_name":"Stickers.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"529661111","text":"import numpy as np\nimport math\nimport pickle\nfrom Feature import Feature\nfrom Integral import Integral\nfrom Region import Region\nfrom WeakClassifier import WeakClassifier\n\n\nclass ViolaJones:\n def __init__(self, weak_classifiers = 10):\n self.weak_classifiers = weak_classifiers\n self.alphas = []\n self.clfs = []\n \n def train(self, images, labels, pos_num, neg_num):\n weights = np.zeros(len(labels))\n training_data = []\n for fl_pair in range(len(labels)):\n training_data.append(Integral(images[fl_pair]))\n if labels[fl_pair] == 1:\n weights[fl_pair] = 1 / (2 * pos_num)\n else:\n weights[fl_pair] = 1 / (2 * neg_num) \n \n feature_templates = self.build_features(training_data[0].image.shape)\n features = self.apply_features(feature_templates, training_data)\n\n for t in range(self.weak_classifiers):\n weights = weights / np.linalg.norm(weights)\n weak_classifiers = self.train_weak(features, labels, feature_templates, weights)\n clf, error, accuracy = self.select_best(weak_classifiers, weights, training_data, labels)\n beta = error / (1.0 - error)\n for i in range(len(accuracy)):\n weights[i] = weights[i] * (beta ** (1 - accuracy[i]))\n alpha = math.log(1.0/beta)\n self.alphas.append(alpha)\n self.clfs.append(clf) \n print(\"Chose classifier: %s with accuracy: %f and alpha: %f\" % (str(clf), len(accuracy) - sum(accuracy), alpha)) \n \n def build_features(self, image_shape):\n height, width = image_shape\n features = []\n # TODO: play with minimum feature size\n for w in range(1, width+1):\n for h in range(1, height+1):\n x = 0\n while x + w < width:\n y = 0\n while y + h < height:\n # 2 horizontally aligned blocks\n root = Region(x,y,w, h)\n right = Region(x+w, y, w,h)\n # check if the VJ feature can be fit into the image\n if x + 2 * w < width:\n features.append(Feature([right], [root]))\n bottom = Region(x, y+h, w, h)\n # 2 vertically aligned blocks\n if y + 2 * h < height:\n features.append(Feature([root],[bottom]))\n # 3 horizontally aligned blocks \n right2 = Region(x+2*w, y, w,h)\n if x + 3 * w < width:\n features.append(Feature([right], [right2, root]))\n cross_bottom = Region(x+w, y+h, w, h)\n if x + 2 * w < width and y + 2 * h < height:\n features.append(Feature([right, bottom], [root, cross_bottom]))\n y += 1\n x += 1\n return features\n\n def apply_features(self, feature_templates, integrals):\n features = np.zeros((len(feature_templates), len(integrals)))\n count = 0\n for feature in feature_templates:\n features[count] = list(map(lambda integral: feature.compute(integral), integrals))\n count += 1\n return features\n \n def train_weak(self, features, labels, feature_templates, weights):\n total_pos, total_neg = 0, 0\n for w, label in zip(weights, labels):\n if label == 1:\n total_pos += w\n else:\n total_neg += w\n\n classifiers = []\n total_features = features.shape[0]\n for index, feature in enumerate(features):\n if len(classifiers) % 1000 == 0 and len(classifiers) != 0:\n print(\"Trained %d classifiers out of %d\" % (len(classifiers), total_features))\n\n applied_feature = sorted(zip(weights, feature, labels), key=lambda x: x[1])\n\n pos_seen, neg_seen = 0, 0\n pos_weights, neg_weights = 0, 0\n min_error, best_feature, best_threshold, best_polarity = float('inf'), None, None, None\n for w, f, label in applied_feature:\n error = min(neg_weights + total_pos - pos_weights, pos_weights + total_neg - neg_weights)\n if error < min_error:\n min_error = error\n best_feature = feature_templates[index]\n best_threshold = f\n best_polarity = 1 if pos_seen > neg_seen else -1\n\n if label == 1:\n pos_seen += 1\n pos_weights += w\n else:\n neg_seen += 1\n neg_weights += w\n \n clf = WeakClassifier(best_feature, best_threshold, best_polarity)\n classifiers.append(clf)\n return classifiers\n\n def select_best(self, classifiers, weights, integrals, labels):\n best_clf, best_error, best_accuracy = None, float('inf'), None\n for clf in classifiers:\n error, accuracy = 0, []\n for integral, label, w in zip(integrals, labels, weights):\n correctness = abs(clf.classify(integral) - label)\n accuracy.append(correctness)\n error += w * correctness\n error = error / len(labels)\n if error < best_error:\n best_clf, best_error, best_accuracy = clf, error, accuracy\n return best_clf, best_error, best_accuracy\n \n\n def classify(self, image):\n total = 0\n integral = Integral(image)\n for alpha, clf in zip(self.alphas, self.clfs):\n total += alpha * clf.classify(integral)\n return 1 if total >= 0.5 * sum(self.alphas) else 0 \n\n def save(self, filename):\n with open(filename+\".pkl\", 'wb') as f:\n pickle.dump(self, f)\n \n def test_model(self, images, labels):\n correct = 0\n for index, image in enumerate(images):\n correct += 1 if self.classify(image) == labels[index] else 0\n print(f\" correct: {correct} out of {len(labels)} percentage: {correct/len(labels)}\")\n \n @staticmethod\n def load(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n","sub_path":"custom_face_detection/ViolaJones.py","file_name":"ViolaJones.py","file_ext":"py","file_size_in_byte":6357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"351159769","text":"import matplotlib.pyplot as plt\nfrom itertools import izip\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport matplotlib.gridspec as gridspec\nimport os\nimport argparse\nimport pybedtools\nimport cPickle as pickle\n\n### do this to avoid making tons of dots in svg files:\nimport matplotlib\nfrom matplotlib import rc\n\nrc('text', usetex=False)\nmatplotlib.rcParams['svg.fonttype'] = 'none'\nrc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})\n\n### Set default color scheme for stuff\npalette = sns.color_palette(\"hls\", 8)\n\nREGIONS = {\n 'noncoding_exon': palette[0],\n '3utr': palette[1],\n '5utr': palette[2],\n 'intron': palette[3],\n 'noncoding_intron': palette[4],\n 'CDS': palette[5],\n 'intergenic': palette[6],\n '5utr_and_3utr': palette[7]\n}\n\n\ndef split_single_cols(df, col, sep='|'):\n \"\"\"\n Splits a df['col'] into two separated by 'sep'\n ie. -0.9201|0.00000 -> -0.9201 0.00000\n \"\"\"\n df[\"{} l2fc\".format(col.split(sep)[1])], \\\n df[\"{} l10p\".format(col.split(sep)[1])] = zip(\n *df[col].map(lambda x: x.split(sep))\n )\n return df\n\n\ndef split_l2fcwithpval_enr(df, discard=True):\n \"\"\"\n Splits a dataframe into its l2fc and log10 pvalue\n ie. -0.9201|0.00000 -> -0.9201 0.00000\n\n Parameters\n ----------\n df : pandas.DataFrame\n dataframe of l2fcwithpval_enr file\n discard : bool\n if True, discard the original column.\n if False, keep the original column.\n\n Returns\n -------\n df : pandas.DataFrame\n \"\"\"\n\n for col in df.columns:\n df = split_single_cols(df, col)\n if discard:\n del df[col]\n return df\n\n\ndef read_l2fcwithpval_enr(fn):\n \"\"\"\n Reads in a *l2fcwithpval_enr.csv file and returns a dataframe.\n\n :param fn: \n :return: \n \"\"\"\n df = pd.read_table(\n fn,\n index_col=0,\n )\n df = split_l2fcwithpval_enr(df)\n df = df.replace('NaN', np.nan)\n df = df.apply(pd.to_numeric)\n return df\n\n\ndef scatter_matrix(ip_l2fc, inp_reads_by_loc):\n \"\"\"\n Inner joins the ip l2fc and input reads by loc files\n and builds a dataframe containing: input reads by location,\n ip\n Parameters\n ----------\n ip_l2fc : basestring\n \"IP*_ReadsByLoc_combined.csv.l2fcwithpval_enr.csv\"\n inp_reads_by_loc : basestring\n \"INPUT*reads_by_loc.csv\"\n\n Returns\n -------\n x : pandas.DataFrame\n intersection of fold-enrichment and input reads covering each gene.\n \"\"\"\n\n plot_x = pd.read_table(\n inp_reads_by_loc,\n index_col=0,\n )\n\n plot_y = read_l2fcwithpval_enr(ip_l2fc)\n\n x = pd.merge(plot_x, plot_y, how='inner', left_index=True,\n right_index=True)\n return x\n\n\ndef filter_input_norm(file_name, l2fc, l10p, col_names, as_bedtool=False):\n \"\"\"\n Filters an \"input norm\"-formatted file given\n log2 fold change and log10 pvalue thresholds.\n See data/input_norm_bed.bed file for an example.\n\n :param file_name: basestring\n filename of the input normalized file.\n :param l2fc: float\n log2 fold change cutoff\n :param l10p: float\n -log10 pvalue cutoff\n :param col_names: list\n column names of the bed or bedlike file.\n :param as_bedtool: bool\n if True, return as bedtool.\n if False, return dataframe.\n :return:\n \"\"\"\n try:\n df = pd.read_table(file_name, names=col_names)\n df = filter_df(df, l10p, l2fc)\n if as_bedtool:\n return pybedtools.BedTool.from_dataframe(df)\n\n return df\n\n except Exception as e:\n print(e)\n return 1\n\n\ndef filter_df(df, l10p, l2fc):\n \"\"\"\n Returns a dataframe filtered using l10p and l2fc values.\n Assumes the columns are aptly named 'l2fc' and 'l10p'.\n\n :param df:\n :param l2fc:\n :param l10p:\n :return:\n \"\"\"\n return df[(df['l2fc'] >= float(l2fc)) & (df['l10p'] >= l10p)]\n\n\ndef return_region_eric(row):\n \"\"\"\n Given a row of a inputnormed bedfile, return region\n Row must be in the same format as a line in Eric's\n *.annotated file.\n\n \"\"\"\n try:\n if row['annotation'] == 'intergenic':\n return 'intergenic'\n region = row['annotation'].split('|')[0]\n\n return region\n except Exception as e:\n print(e)\n print(row)\n\n\ndef read_annotated_file(fn, headers=None, src='brian'):\n \"\"\"\n Reads in an annotated bedfile from either eric or me.\n Ensures that 'region' column is defined and set.\n Returns dataframe\n\n :param fn: basestring\n filename\n :param headers: list\n if src isn't from eric or me, you have to\n explicitly set the header columns.\n :param src: basestring\n either 'brian' or 'eric' depending on whose script you use.\n :return df: pandas.DataFrame\n \"\"\"\n if src == 'brian':\n headers = [\n 'chrom', 'start', 'end', 'l10p', 'l2fc', 'strand', 'geneid',\n 'genename', 'region', 'alloverlapping'\n ]\n df = pd.read_table(fn, names=headers)\n elif src == 'eric':\n headers = [\n 'chrom', 'start', 'end', 'l10p', 'l2fc',\n 'strand', 'annotation', 'geneid'\n ]\n df = pd.read_table(fn, names=headers)\n df['region'] = df.apply(return_region_eric, axis=1)\n else:\n assert 'region' in headers\n df = pd.read_table(fn, names=headers)\n return df\n\n\ndef get_counts(lst, headers=None, src='brian'):\n \"\"\"\n Returns the counts of each region in the annotation file.\n\n :param lst: list\n list of annotated files\n :param headers: list\n optional if either 'brian' or 'eric' are src. Otherwise,\n this MUST contain a 'region' category.\n :param src: basestring\n either 'brian' or 'eric' to denote the annotation structure.\n :return merged: pandas.DataFrame\n table containing the sum of counts for each region in the annotated\n file.\n \"\"\"\n assert len(lst) > 0\n annotated_file = lst[0]\n merged = pd.DataFrame(\n read_annotated_file(\n annotated_file, headers, src)['region'].value_counts()\n )\n merged.columns = [os.path.basename(annotated_file)]\n for annotated_file in lst[1:]:\n df = pd.DataFrame(\n read_annotated_file(\n annotated_file, headers, src\n )['region'].value_counts()\n )\n df.columns = [os.path.basename(annotated_file)]\n merged = pd.merge(merged, df, how='left', left_index=True,\n right_index=True)\n return merged\n\n\n# LEGACY FUNCTIONS for working with older data ###\n\ndef bed6_to_bed8(interval):\n \"\"\"\n Basically appends the start/stop fields to 'thickStart/thickStop' fields\n Turns BED6 into BED8 (formerly called: make_clipper_ish)\n (Helps with clip_analysis.py in CLIPper).\n\n Parameters\n ----------\n interval : pybedtools.Interval\n\n Returns\n -------\n\n \"\"\"\n interval.name = interval[7]\n interval[6] = interval.start\n interval[7] = interval.stop\n\n return interval\n\n\ndef filter_data(interval, l2fc, pval):\n \"\"\"\n col4 is -log10 p-val\n col5 is -log2 fold enrichment\n\n Expects the standard input norm file format.\n\n Parameters\n ----------\n interval : pybedtools.Interval\n l2fc : float\n pval : float\n\n Returns\n -------\n\n \"\"\"\n\n return (float(interval[4]) >= pval) and (float(interval[3]) >= l2fc)\n\n\n# Plotting functions #\n\ndef plot_ip_foldchange_over_input_reads(\n ip_l2fc, inp_reads_by_loc,\n ax=None,\n field_list=REGIONS,\n alpha=0.3\n):\n \"\"\"\n Plots the region-based analysis of genes enriched in IP over\n reads in size-matched input. This is the same figure used in Figure2b\n of Ann's IMP paper.\n\n Parameters\n ----------\n ip_l2fc : basestring\n inp_reads_by_loc : basestring\n field_list : dict\n dictionary of {region: color} to plot\n Returns\n -------\n :param field_list:\n :param ip_l2fc:\n :param inp_reads_by_loc: \n :param alpha: \n :param ax: \n\n \"\"\"\n df = scatter_matrix(ip_l2fc, inp_reads_by_loc)\n\n if ax is None:\n ax = plt.gca()\n for region, color in field_list.iteritems():\n if region in df.columns:\n ax.scatter(\n np.log2(df[region] + 1),\n df[\"{} l2fc\".format(region)],\n color=color,\n alpha=alpha\n )\n else:\n print(\"region {} not found in dataframe matrix\".format(\n region\n ))\n ax.set_title(\"Region-based analysis of genes enriched\")\n ax.set_xlabel(\"Reads in SMInput (log2)\")\n ax.set_ylabel(\"Fold Enrichment (log2)\")\n ax.legend()\n return ax\n\n\ndef plot_region_distribution(\n df, ax=None\n):\n \"\"\"\n\n :param ax: \n :param df: pandas.DataFrame()\n dataframe containing samples (columns) and regions (rows)\n Use peak_parsers.get_counts() to get this dataframe\n :return:\n \"\"\"\n dfdiv = df / df.sum()\n cumsum_events = dfdiv.cumsum()\n\n if ax is None:\n ax = plt.gca()\n\n legend_builder = []\n legend_labels = []\n for region, color in izip(\n reversed(cumsum_events.index),\n sns.color_palette(\"hls\", len(cumsum_events.index) + 1)\n ):\n names = np.array(\n [\"\".join(item) for item in cumsum_events.columns]\n )\n\n sns.barplot(\n names,\n y=cumsum_events.ix[region], color=color, ax=ax\n )\n\n legend_builder.append(\n plt.Rectangle((0, 0), .25, .25, fc=color, edgecolor='none')\n )\n legend_labels.append(region)\n\n sns.despine(ax=ax, left=True)\n\n ax.set_ylim(0, 1)\n\n l = ax.legend(legend_builder,\n legend_labels, loc=1, ncol=1,\n prop={'size': 12},\n bbox_to_anchor=(1.4, 0.8))\n l.draw_frame(False)\n [tick.set_rotation(90) for tick in ax.get_xticklabels()]\n\n ax.set_ylabel(\"Fraction of Peaks\", fontsize=14)\n [tick.set_fontsize(12) for tick in ax.get_xticklabels()]\n ax.set_title(\n \"Fraction of Peaks among RBPs\"\n )\n return ax\n\n\ndef plot_zscores(rep1_scores, rep2_scores, highlight, label='all 6mers',\n color=palette[4], highlight_color=palette[5], ax=None):\n \"\"\"\n \n :param highlight_color: \n :param ax: \n :param color: tuple\n color or tuple representing a color.\n :param label: basestring\n legend label for the scatter plot.\n :param rep1_scores: pandas.DataFrame\n table of zscore enrichments (indexed by Kmer)\n :param rep2_scores: pandas.DataFrame\n table of zscore enrichments (indexed by Kmer)\n :param highlight: \n any Kmer you would like to highlight in the plot.\n :return ax: ax\n \"\"\"\n\n if ax is None:\n ax = plt.gca()\n\n merged = pd.merge(\n rep1_scores,\n rep2_scores,\n how='left',\n left_index=True,\n right_index=True\n )\n merged.columns = ['rep1', 'rep2']\n ax.scatter(\n merged['rep1'], merged['rep2'], color=color, label=label\n )\n if len(highlight) > 0: # we have some kmers of interest to highlight\n for kmer in highlight:\n ax.scatter(\n merged['rep1'].loc[kmer], merged['rep2'].loc[kmer],\n color=highlight_color\n )\n\n labels = merged.loc[highlight].index\n for label, x, y in zip(\n labels, merged['rep1'].loc[labels], merged['rep2'].loc[labels]\n ):\n plt.annotate(\n label,\n xy=(x, y), xytext=(-20, 20),\n textcoords='offset points', ha='right', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')\n )\n ax.set_xlabel('Z-score ({})'.format(rep1_scores.columns[0]))\n ax.set_ylabel('Z-score ({})'.format(rep2_scores.columns[0]))\n plt.legend()\n return ax\n\n\ndef plot_compare_rbp_enriched_regions(\n l2fc_pval_enr1, l2fc_pval_enr2,\n regions=None,\n equivalent_axis=True,\n drop_all_nans=True,\n ax=None\n):\n \"\"\"\n Plots region enriched values for 2 replicates. \n Similar to Figure 2CDEF of Ann's IMP paper.\n\n :param ax: \n :param l2fc_pval_enr1: basestring\n :param l2fc_pval_enr2: basestring\n :param equivalent_axis: bool\n if True, this will make the figure axes equal to each other.\n This generally makes it easier to see any skews between reps.\n :param regions: list\n List of regions to plot over each other.\n This list needs to match the columns listed in each l2fc_pval_enr file.\n :param drop_all_nans: bool\n if True, drops genes which have NaN values in one or both replicates.\n if False, drops genes which have NaN values in both replicates only, \n imputing missing values with 0.\n :return ax: \n \"\"\"\n df1 = read_l2fcwithpval_enr(l2fc_pval_enr1)\n df2 = read_l2fcwithpval_enr(l2fc_pval_enr2)\n\n # this drops any nonexisting ENSGs that don't appear in both reps\n merged = pd.merge(df1, df2, how='inner', left_index=True, right_index=True)\n\n # set initial axis limits to be some impossible number.\n min_lim = 1000000\n max_lim = -1\n buf = 1\n\n # sets default regions:\n if regions is None:\n regions = ['intron', 'CDS', '3utr', '5utr']\n\n if ax is None:\n ax = plt.gca()\n for region in regions:\n region_df = merged[\n ['{} l2fc_x'.format(region), '{} l2fc_y'.format(region)]\n ]\n region_df.columns = ['rep1', 'rep2']\n\n # this drops any NaNs present in both ('all') or either ('any') rep.\n how = 'any' if drop_all_nans else 'all'\n region_df.dropna(inplace=True, how=how, subset=['rep1', 'rep2'])\n\n # gets the correlation for the label\n corr = region_df.corr().iloc[0, 1]\n\n sns.regplot(\n 'rep1', 'rep2', region_df,\n label=\"{0} - r2: {1:.2f}\".format(\n region,\n corr * corr # r^2\n ),\n ax=ax,\n scatter_kws={'alpha': 0.4},\n truncate=False\n )\n\n # this ensures that the plot is x=y\n min_clim = min(\n region_df['rep1'].min(), region_df['rep2'].min()\n )\n max_clim = min(\n region_df['rep1'].max(), region_df['rep2'].max()\n )\n\n if min_clim < min_lim:\n min_lim = min_clim\n if max_clim > max_lim:\n max_lim = max_clim\n # this makes it easier to see any skews from good correlation.\n if equivalent_axis:\n ax.set_xlim(min_lim - buf, max_lim + buf)\n ax.set_ylim(min_lim - buf, max_lim + buf)\n\n ax.legend()\n return ax\n\n\ndef plot_histogram_enriched_regions(\n l2fc_pval_enr, regions=None,\n xlabel='eCLIP log2 fold-enrichment',\n ylabel='fraction of regions in bin',\n xlim=(-10, 10),\n ax=None\n):\n \"\"\"\n Plots a histogram of enriched regions\n \"\"\"\n if ax is None:\n ax = plt.gca()\n # init default regions\n if regions is None:\n regions = ['CDS', '3utr', 'intron']\n df = read_l2fcwithpval_enr(l2fc_pval_enr)\n bins = np.arange(0, 100 + 1, 1)\n for region in regions:\n n, bins = np.histogram(\n df['{} l2fc'.format(region)].dropna(),\n bins=100, range=xlim\n )\n pdf = [float(b) / sum(n) for b in n] # sum all histogram bins to 1\n ax.bar(range(100), pdf, label=region, alpha=0.4)\n\n ## For some reason, getting the PDF doesn't work this way... ugh\n # sns.distplot(\n # df['{} l2fc'.format(region)].dropna(),\n # ax=ax, norm_hist=False,\n # label=region # , hist_kws={'density':True}\n # )\n\n # set the x, ylabel\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.set_xticks(np.arange(0, 100 + 1, 10.0)) # set ticks every 10\n\n ax.set_xticklabels(bins[::10]) # label every 10\n ax.legend()\n return ax\n\n\n# LEGACY functions to handle some of the old gabe and eric stuff #\n\ndef read_kmer_enrichment_from_pickle(pickle_file, region='all', k=6):\n \"\"\"\n Reads in a pickle file from gabe's clip_analysis script and returns a\n dataframe containing kmers and their enriched z-scores\n\n :param pickle_file: basestring\n pickle filename output from gabe's clip_analysis script.\n :param region: basestring\n one of: \n 'all', 'three_prime_utrs', 'five_prime_utrs', 'distintron500',\n 'cds', 'proxintron500'\n :return df: pandas.DataFrame \n \"\"\"\n loaded = pickle.load(open(pickle_file, 'rb'))\n df = pd.DataFrame(loaded['kmer_results'][region][k]).T\n df.columns = ['fg', 'bg', 'zscore delta']\n return df[['zscore delta']]\n\n\ndef plot_all(l2fcwithpval_enr_r1, l2fcwithpval_enr_r2, inp_reads_by_loc_r1,\n inp_reads_by_loc_r2, out_file, annotated_files):\n nrows = 3\n ncols = 2\n\n full_grid = gridspec.GridSpec(\n nrows, ncols,\n height_ratios=[1 for i in range(nrows)],\n width_ratios=[1 for i in range(ncols)],\n hspace=0.5, wspace=3\n )\n fig = plt.figure(figsize=(15, 25))\n\n map_rows = []\n\n for row in range(0, nrows):\n map_rows.append(gridspec.GridSpecFromSubplotSpec(1, ncols,\n subplot_spec=full_grid[\n row, :]))\n\n plot_histogram_enriched_regions(\n l2fcwithpval_enr_r1, ax=plt.subplot(map_rows[0][0])\n )\n plot_histogram_enriched_regions(\n l2fcwithpval_enr_r2, ax=plt.subplot(map_rows[0][1])\n )\n\n plot_ip_foldchange_over_input_reads(\n l2fcwithpval_enr_r1, inp_reads_by_loc_r1,\n ax=plt.subplot(map_rows[1][0]))\n plot_ip_foldchange_over_input_reads(l2fcwithpval_enr_r2,\n inp_reads_by_loc_r2,\n ax=plt.subplot(map_rows[1][1]))\n\n plot_compare_rbp_enriched_regions(l2fcwithpval_enr_r1, l2fcwithpval_enr_r2,\n ax=plt.subplot(map_rows[2][0]))\n\n counts = get_counts(annotated_files)\n plot_region_distribution(counts, ax=plt.subplot(map_rows[2][1]))\n fig.savefig(out_file)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--l2fcwithpval_enr_r1\",\n required=True\n )\n parser.add_argument(\n \"--l2fcwithpval_enr_r2\",\n required=False,\n default=''\n )\n parser.add_argument(\n \"--inp_reads_by_loc_r1\",\n required=True\n )\n parser.add_argument(\n \"--inp_reads_by_loc_r2\",\n required=False,\n default=''\n )\n parser.add_argument(\n \"--annotated_files\",\n required=True,\n nargs='+'\n )\n parser.add_argument(\n \"--out_file\",\n required=True,\n )\n\n # Process arguments\n args = parser.parse_args()\n l2fcwithpval_enr_r1 = args.l2fcwithpval_enr_r1\n l2fcwithpval_enr_r2 = args.l2fcwithpval_enr_r2\n inp_reads_by_loc_r1 = args.inp_reads_by_loc_r1\n inp_reads_by_loc_r2 = args.inp_reads_by_loc_r2\n out_file = args.out_file\n annotated_files = args.annotated_files\n\n # main func\n plot_all(\n l2fcwithpval_enr_r1, l2fcwithpval_enr_r2,\n inp_reads_by_loc_r1, inp_reads_by_loc_r2,\n out_file, annotated_files\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pyscripts/clipseq/clip_analysis.py","file_name":"clip_analysis.py","file_ext":"py","file_size_in_byte":19454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"181766570","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n import heapq\n p = head\n h = []\n while p:\n heapq.heappush(h, p.val)\n p = p.next\n\n p = head\n while h:\n p.val = heapq.heappop(h)\n p = p.next\n return head\n\n\nif __name__ == '__main__':\n sn = Solution()\n head = [4, 2, 1, 3]\n from gen_node import gen_node\n\n print(sn.sortList(gen_node(head)))\n","sub_path":"字节/148.py","file_name":"148.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"299912532","text":"import re\n\nclass Aggregator(object):\n \"\"\"\n procedure:\n 1. starting from the master table. do a forward(), which find all the outcoming tables, ready to do step 3.\n 2. all the forwarded tables, do a backward(), which aggreates all incoming tables, using groupby count()\n 3. master table joins all the aggreated tables.\n\n naming conventions:\n 1. for step 2, the resulted columns are renamed as: belonged_table_name+\"_\"+column_name+\"_COUNT\"\n 2. for step 1, the resulted columns (joined back to master table) are renamed as: table_name+\"_\"+column_name\n \"\"\"\n\n def __init__(self, relations, data, verbose):\n self.visited = set() # set of table names, store the tables that already in the queue (to be processed)\n self.delimiter = \"_\"\n self.relations = relations\n self.tables = data # dict, key: name; value : pandas.DataFrame\n self.verbose = verbose\n\n def get_names(self, tableCol):\n \"\"\"\n Input:\n String: eg. `loan.csv_account_id`\n Output:\n tuple of String: eg. (`loan.csv`, `account_id`)\n \"\"\"\n split = re.split(self.delimiter, tableCol)\n table_name = split[0] + self.delimiter[:-1]\n column_name = split[1]\n return table_name, column_name\n\n\n def forward(self, curt_table):\n \"\"\"\n Input:\n curt_table: String, name of table. eg. `loan.csv_account_id`\n Output:\n result: Pandas.DataFrame, big featurized table (join)\n \"\"\"\n maximum_allow_table_size = 3 * pow(10,7)\n table_name, key_column_name = self.get_names(curt_table)\n k_tables = self.get_forward_tables(table_name)\n if self.verbose: print (\"current forward tables: {}\".format(k_tables))\n result = self.tables[table_name]\n\n table_name_set = {} # prevent: same table (name) happen; key is table name; value if the number of occurence\n for table_key in k_tables:\n if self.verbose: print (\"current forward table: {}\".format(table_key))\n foreign_table_name = re.split(self.delimiter, table_key)[0] + self.delimiter[:-1]\n if (foreign_table_name in table_name_set.keys()):\n table_name_set[foreign_table_name] += 1\n foreign_table_name += str(table_name_set[foreign_table_name])\n else:\n table_name_set[foreign_table_name] = 0\n\n foreign_table_key = re.split(self.delimiter, table_key)[1]\n table = self.backward(table_key)\n table_size = table.shape[0] * table.shape[1]\n # only continue when the target join table size is less than the maximum allow table size\n if (table_size > maximum_allow_table_size):\n if self.verbose: print (\"backward finished\")\n table = table.rename(columns = lambda x : foreign_table_name+\"_\"+x)\n ## DEBUG code: check the intermediate tables\n if self.verbose: table.to_csv(\"./backwarded_table_\"+foreign_table_name, index=False)\n\n # join back to central table, need to find the corresponding column name\n central_table_key = self.get_corresponding_column_name(table_name, table_key)\n if self.verbose: print(\"central_table_key is: {}\".format(central_table_key)) # name of primary-foreign key\n if self.verbose: print(\"foreign_table_key is: {}\".format(foreign_table_key))\n table_reindex = table.set_index(foreign_table_name+\"_\"+foreign_table_key)\n result_reindex = result.set_index(central_table_key)\n result_return = result_reindex.join(other=table_reindex, rsuffix=\"_COPY\")\n\n return result_return\n\n\n def backward(self, curt_table):\n \"\"\"\n Input:\n curt_table: String, name of table. eg. `account.csv_account_id`\n Output:\n result: Pandas.DataFrame, big featurized table (join of groupby count)\n \"\"\"\n central_table_name, column_name = self.get_names(curt_table)\n k_tables = self.get_backward_tables(central_table_name)\n result = self.tables[central_table_name]\n if self.verbose:\n print (\"backward tables: {}\".format(k_tables))\n\n for table_key in k_tables:\n # aggregated result of : groupby + count()\n if self.verbose: print (\"current backward table: {}\".format(table_key))\n table_name, column_name = self.get_names(table_key)\n table = self.tables[table_name]\n rr = table.groupby(column_name).count() # after groupby count(), the index of r will be `column_name` automatically\n rr = rr.rename(columns = lambda x : table_name+\"_\"+x+\"_COUNT\")\n #result = result.rename(columns = lambda x : table_name+\"_\"+x)\n # join back to central table, need to find the corresponding column name\n central_table_key = self.get_corresponding_column_name(central_table_name, table_key)\n if self.verbose: print(\"central_table_key is: {}\".format(central_table_key)) # name of primary-foreign key\n result = result.join(other=rr, on=central_table_key) # no need to set_index for r, because its index is alreayd column_name\n\n return result\n\n def backward_new(self, curt_table):\n \"\"\"\n Input:\n curt_table: String, name of table. eg. `account.csv_account_id`\n Output:\n result: Pandas.DataFrame, big featurized joined table\n \"\"\"\n central_table_name, central_column_name = self.get_names(curt_table)\n k_tables = self.get_backward_tables(central_table_name)\n result = self.tables[central_table_name]\n result = result.rename(columns = lambda x : central_table_name + \"_\" + x)\n\n if self.verbose:\n print (\"backward tables: {}\".format(k_tables))\n\n for table_key in k_tables:\n # aggregated result of : groupby + count()\n if self.verbose: print (\"current backward table: {}\".format(table_key))\n table_name, column_name = self.get_names(table_key)\n table = self.tables[table_name]\n primary_key_column_name = central_table_name + \"_\" + central_column_name\n\n # The backward table may use a different name\n # foreign_key_column_name = table_name + \"_\" + central_column_name\n foreign_key_column_name = table_name + \"_\" + column_name\n\n table = table.rename(columns = lambda x : table_name + \"_\" + x)\n table = table.rename(columns = {foreign_key_column_name : primary_key_column_name})\n table = table.set_index(primary_key_column_name)\n # join back to central table, need to find the corresponding column name\n #central_table_key = self.get_corresponding_column_name(central_table_name, table_key)\n if self.verbose: print(\"central_table_key is: {}\".format(central_column_name)) # name of primary-foreign key\n result = result.join(other=table,on = primary_key_column_name, rsuffix=\"_COPY\", how = \"left\")\n result = result.rename(columns = {primary_key_column_name+\"_COPY\" : primary_key_column_name})\n return result\n\n def get_corresponding_column_name(self, table1, table2_col):\n \"\"\"\n Input:\n - table1: a table name\n - table2: a table name + key column name\n Output:\n - corresponding (primary or foreign) key column name of table1\n \"\"\"\n # print(\"DEBUG: trying to get the key for {}, with relations of {}\".format(table1, table2_col))\n column_name = None\n for relation in self.relations:\n if (table2_col==relation[0]):\n if self.verbose: print(relation)\n table_name = re.split(self.delimiter, relation[1])[0]# + \".csv\"\n if (table_name == table1):\n column_name = re.split(self.delimiter, relation[1])[1]\n return column_name\n\n elif (table2_col==relation[1]):\n if self.verbose: print(relation)\n table_name = re.split(self.delimiter, relation[0])[0]# + \".csv\"\n if (table_name == table1):\n column_name = re.split(self.delimiter, relation[0])[1]\n return column_name\n\n raise ValueError(\"there is no relations between {} and {}\".format(table2_col, table1))\n\n\n\n\n def get_forward_tables(self, table_name):\n \"\"\"\n Input:\n table_name: string, eg: \"loan.csv\"\n\n Output:\n list of String, String is the second element in `relations` tuples (Primary key),\n which is the forward table of current table\n \"\"\"\n result = list()\n for relation in self.relations:\n # assumption: the name like \"loan.csv\", always represent a table\n if (table_name in relation[0]):\n result.append(relation[1])\n self.visited.add(relation[0])\n return result\n\n def get_backward_tables(self, table_name):\n \"\"\"\n Output:\n list of String, String is the first element in `relations` tuples (Primary key)\n \"\"\"\n result = list()\n # print (visited)\n for relation in self.relations:\n if (table_name in relation[1] and (relation[0] not in self.visited)):\n result.append(relation[0])\n # visited.add(relation[0])\n return result\n","sub_path":"dsbox/datapreprocessing/featurizer/multiTable/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":9475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"545019533","text":"a = int(input('Введите целое число:'))\nb = int(input('Введите второе целое число:'))\nc = input('Введите арифметический знак в формате + - / *:')\nd = (a + b)\ne = (a - b)\nf = (a * b)\ng = (a / b)\nif c == '+':\n print(d)\nelif c == '-':\n print(e)\nelif c == '*':\n print(f)\nelif c == '/':\n print(g)\nelse:\n print('Вы ввели нерпавильное значение')\n","sub_path":"Урок1/Задание1.py","file_name":"Задание1.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"389406126","text":"import boto3\nsession=boto3.session.Session(profile_name=\"root\")\nec2_res=session.resource(service_name=\"ec2\",region_name=\"us-east-2\")\nec2_cli=session.client(service_name=\"ec2\",region_name=\"us-east-2\")\nsts_cli=session.client(\"sts\")\nownaccounid=sts_cli.get_caller_identity().get(\"Account\")\n\nprint(\"Below is coming from Resources\")\nfor each_snap in ec2_res.snapshots.filter(OwnerIds=[ownaccounid]):\n\tprint (each_snap)\n\nprint (\"Below is coming from client\")\nfor each_snap in ec2_cli.describe_snapshots(OwnerIds=[ownaccounid])['Snapshots']:\n\tprint (each_snap['SnapshotId'])\n\n","sub_path":"Notes/Notes/Udemy/Aws-automation-with-boto3/Session-8-working-with-snapshots-in-aws/list-all-snapshots.py","file_name":"list-all-snapshots.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"25549186","text":"from army import Army\nfrom battalion_processor import BattalionProcessor\nfrom battalion_types import BattalionType\nfrom battle_planner import BattlePlanner\nfrom copy import deepcopy\n\n\ndef main():\n battalion_processor = BattalionProcessor(2,horses=1, elephants=2,\n armoured_tanks=3,\n sling_guns=4)\n battalion_processor.add_battalion_substituation(BattalionType.ELEPHANTS,\n BattalionType.HORSES, 2)\n battalion_processor.add_battalion_substituation(BattalionType.ARMOUREDTANKS,\n BattalionType.ELEPHANTS, 2)\n battalion_processor.add_battalion_substituation(BattalionType.SLINGGUNS,\n BattalionType.ARMOUREDTANKS, 2) \n lengaburu_army = Army(horses=100, elephants=50,\n armoured_tanks=10, sling_guns=5)\n\n \n\n with open(\"input.txt\", \"r\") as testcases:\n for testcase in testcases:\n input = [int(x.strip()) for x in testcase.split(\",\")]\n enemy_army = Army(horses=input[0], elephants=input[1],\n armoured_tanks=input[2], sling_guns=input[3])\n planner = BattlePlanner(battalion_processor, deepcopy(lengaburu_army))\n result, army = planner.get_winning_army(enemy_army)\n display_result(input, result, army)\n \ndef display_result(input, result, army):\n print(\"Input : Falicornia attacks with {0} H, {1} E, {2} AT, {3} SG \".format(input[0], input[1], input[2], input[3]))\n print(\"Output : Lebangaru deploys\")\n for k, v in army.items():\n print(\"{0} : {1}\".format(k.name, v))\n print(\"Lebangaru {0}\".format(\"Wins\" if result is True else \"Loses\"))\n print()\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"390284695","text":"# -*- coding: utf-8 -*-\n\nfrom openerp.osv import osv,fields\nimport netsvc\nfrom openerp import netsvc\nimport openerp.addons.decimal_precision as dp\n\nclass account_invoice(osv.osv):\n _inherit = 'account.invoice'\n\n def _exonerado(self, cr, uid, ids, field, arg, context=None):\n res = {}\n for invoice in self.browse(cr, uid, ids, context=context):\n exo=0.0\n for line in invoice.invoice_line:\n if not line.invoice_line_tax_id:\n exo += line.price_subtotal\n res[invoice.id] = exo\n return res\n _columns = {\n 'exonerado': fields.function(_exonerado,digits_compute=dp.get_precision('Account'), string='Exonerado de IGV',method=True,store=True)\n }\n","sub_path":"account_exonerado/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"343433449","text":"from tensorflow.keras.applications import MobileNet\nimport tfcoreml\n\nkeras_model = MobileNet(weights=None, input_shape=(224, 224, 3))\nkeras_model.save('./dice', save_format='tf')\n# tf.saved_model.save(keras_model, './savedmodel')\n\nmodel = tfcoreml.convert(defaults.FLAGS.coreML,\n mlmodel_path='./dicemodel.mlmodel',\n input_name_shape_dict={'input_1': (1, 224, 224, 3)},\n output_feature_names=['Identity'],\n minimum_ios_deployment_target='13')\n","sub_path":"Tensorflow-Workbench/conversion/SavedModelToCoreML.py","file_name":"SavedModelToCoreML.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"383939035","text":"__author__ = 'Matt'\n\nfrom abc import ABCMeta\nimport pickle\n\nclass NullObject(object):\n pass\n\nclass MyObj:\n\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self.a = 3\n self.b = 4\n self.c = 5\n\ndef obj_to_dict(obj):\n \"\"\"\n Converts an object to a dictionary with key-values of the name of the methods/members as keys and\n the method/member themselves as the values. Requires classes to be an 'ABCmeta' __metaclass__ type.\n See: http://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/\n for a brief turotial on ABCmeta classes.\n :param obj: Object to convert\n :return:\n \"\"\"\n\n is_abcmeta = False\n\n if hasattr(obj, '__metaclass__'):\n if not obj.__metaclass__ == ABCMeta:\n not_abcmeta = True\n else:\n not_abcmeta = True\n\n if is_abcmeta:\n raise Exception(\"Object must be an ABCmeta class to comply with python new-style classes.\")\n\n obj_dict = obj.__dict__\n obj_dict['__class__'] = obj.__class__\n\n return obj_dict\n\ndef dict_to_obj(obj_dict):\n \"\"\"\n Converts a dictionary back into an object created from obj_to_dict method\n :param obj_dict: Dictionary corresponding to an object\n :return:\n \"\"\"\n\n if not obj_dict.has_key('__class__'): raise Exception(\"This is not a dictionary created from the obj_to_dict procedure.\")\n\n obj_class = obj_dict['__class__']\n new_obj = NullObject()\n new_obj.__class__ = obj_class\n\n for attr in obj_dict.keys():\n new_obj.__setattr__(attr, obj_dict[attr])\n\n return new_obj\n\ndef make_copy(obj):\n \"\"\"\n Makes a copy (without using copy.copy) by calling obj_to_dict and then dict_to_obj\n :param obj: obj to copy\n :return: copy of obj\n \"\"\"\n copy_dict = obj_to_dict(obj)\n copy_obj = dict_to_obj(copy_dict)\n return copy_obj\n\n\n","sub_path":"obj_dumper.py","file_name":"obj_dumper.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"454491562","text":"# Left Green Blocks\n# Eric Olenski\n# 5-5-16\n\nimport pygame\n\nGREEN = (50, 205, 50)\nsnakeWidth = 18\nsnakeHeight = 18\n\nclass LeftGreenBlock(pygame.sprite.Sprite):\n \n \"\"\" Takes length away from your own snake. \"\"\"\n \n def __init__(self, x, y):\n # Call the parent's constructor\n super().__init__()\n \n # Set height, width\n self.image = pygame.Surface([snakeWidth, snakeHeight])\n self.image.fill(GREEN)\n \n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n","sub_path":"LeftGreenBlock.py","file_name":"LeftGreenBlock.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"153421198","text":"import random\nimport time\n\nimport datetime\nfrom django.contrib import auth\nfrom django.contrib.auth.hashers import make_password, check_password\nfrom django.http import HttpResponseRedirect, HttpResponse, JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework import mixins, viewsets\n\nfrom users.models import MainWheel, MainShop, MainNav, MainMustBuy, MainShow, FoodType, Goods, UserModel, OrderModel, \\\n OrderGoodsModel, CartModel\n\nfrom django.contrib.auth.models import User\n\nfrom users.serializers import OrderGoodsModelSerializer\n\n\ndef djlogin(request):\n if request.method == 'GET':\n return render(request, 'user/user_login.html')\n if request.method == 'POST':\n name = request.POST.get('username')\n password = request.POST.get('password')\n user = auth.authenticate(username=name,\n password=password) #如果验证通过,返回user, 验证不通过返回none\n if user:\n auth.login(request, user)\n return HttpResponseRedirect('/users/home/')\n else:\n return HttpResponse('用户名或密码错误')\n\n\ndef djregist(request):\n if request.method == 'GET':\n return render(request, 'user/user_register.html')\n if request.method == 'POST':\n name = request.POST.get('username')\n if User.objects.filter(username=name).exists():\n return HttpResponse('用户名已经存在')\n else:\n password = request.POST.get('password')\n email = request.POST.get('email')\n icon = request.FILES.get('icon')\n User.objects.create_user(\n username=name,\n password=password,\n is_superuser=0,\n first_name = name,\n last_name = name,\n email= email,\n is_staff=1,\n is_active=1,\n )\n return render(request, 'home/home.html')\n\n\ndef djlogout(request):\n if request.method == 'GET':\n auth.logout(request)\n return render(request, 'home/home.html')\n\n\ndef foodtypes(request, i):\n if request.method == 'GET':\n user = request.user\n path = request.path.split('/')[2]\n foodtypes = FoodType.objects.all()\n goods = Goods.objects.all()\n list_name = '综合排序'\n list1_name = '全部分类'\n if i == '1' :\n goods = goods.order_by('-price')\n list_name = '价格降序'\n elif i == '2':\n goods = goods.order_by('price')\n list_name = '价格升序'\n elif i == '3':\n goods = goods.order_by('productnum')\n list_name = '销量排序'\n elif i == '4':\n goods = goods.order_by('storenums')\n list_name = '综合排序'\n return render(request, 'market/market.html', {'foodtypes': foodtypes, 'goods':goods, 'path':path, 'list_name':list_name, 'list1_name': list1_name, 'user':user})\n\ndef fenlei(request, typeid, i, k):\n if request.method == 'GET':\n user = request.user\n path = request.path.split('/')[2] + '/' + request.path.split('/')[3]\n foodtypes = FoodType.objects.all()\n x = foodtypes.get(typeid=typeid).childtypenames.split('#')[1:]\n ms = {}\n for m in range(len(x)):\n fooname = (x[m].split(':')[0])\n fooid = (x[m].split(':')[1])\n ms[fooid] = fooname\n goods = Goods.objects.filter(categoryid=typeid)\n list_name = '综合排序'\n if i == '1' :\n goods = goods.order_by('-price')\n list_name = '价格降序'\n elif i == '2':\n goods = goods.order_by('price')\n list_name = '价格升序'\n elif i == '3':\n goods = goods.order_by('productnum')\n list_name = '销量排序'\n elif i == '4':\n goods = goods.order_by('storenums')\n list_name = '综合排序'\n if k != '0':\n goods = goods.filter(childcid=k)\n list1_name = ms[k]\n else:\n list1_name = '全部分类'\n return render(request, 'market/market.html', {'foodtypes': foodtypes, 'goods':goods, 'path': path, 'ms':ms, 'typeid':typeid, 'k':k, 'list_name':list_name, 'list1_name': list1_name, 'user':user})\n\n\ndef home(request):\n\n banners = MainWheel.objects.all()\n navs = MainNav.objects.all()\n mustbuys = MainMustBuy.objects.all()\n mainshows = MainShow.objects.all()\n mainshops = MainShop.objects.all()\n return render(request, 'home/home.html',\n {'banners': banners,\n 'navs':navs,\n 'mustbuys':mustbuys,\n 'mainshows':mainshows,\n 'mainshops':mainshops})\n\n\ndef regist(request):\n if request.method == 'GET':\n return render(request, 'user/user_register.html')\n if request.method == 'POST':\n username = request.POST.get('username')\n if UserModel.objects.filter(username=username).exists():\n return HttpResponse('用户名已经存在')\n else:\n password= request.POST.get('password')\n email = request.POST.get('email')\n icon = request.FILES.get('icon')\n UserModel.objects.create(\n username=username,\n password=make_password(password),\n email=email,\n icon=icon\n )\n return HttpResponseRedirect('/users/login/')\n\n\ndef login(request):\n if request.method == 'GET':\n return render(request, 'user/user_login.html')\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n if UserModel.objects.filter(username=username).exists():\n user = UserModel.objects.get(username=username)\n if check_password(password, user.password):\n s = 'qwertyuiopasdfghjklzxcvbnm'\n ticket = ''\n for i in range(15):\n ticket += random.choice(s)\n now_time = int(time.time())\n ticket += str(now_time)\n response = HttpResponseRedirect('/users/home/')\n response.set_cookie('ticket', ticket, max_age=60000)\n user.t_ticket = ticket\n user.save()\n return response\n else:\n return HttpResponse('密码错误')\n else:\n return HttpResponse('用户名错误')\n\n\n\n\ndef logout(request):\n response = HttpResponseRedirect('/users/home/')\n response.delete_cookie('ticket')\n return response\n\ndef deal_mine(request):\n user = request.user\n nopay,waited = 0, 0\n if user.id:\n orders = user.ordermodel_set.all()\n if orders.first():\n for order in orders:\n if order.o_status == 0:\n nopay += 1\n elif order.o_status == 1:\n waited += 1\n user.nopay = nopay\n user.waited = waited\n user.order = orders\n return user\n\ndef mine(request):\n user = deal_mine(request)\n return render(request, 'mine/mine.html', {'user':user})\n\n\ndef cart(request):\n if request.method == 'GET':\n carts = CartModel.objects.all()\n totalprice = caltotal()\n data = {'carts':carts, 'totalprice':totalprice}\n return render(request, 'cart/cart.html', data)\n\n\ndef addnum(request):\n if request.method == 'POST':\n data = {\n 'msg':'请求成功',\n 'code':'200'\n }\n user = request.user\n if user.id:\n good_id = request.POST.get('good_id')\n carts = CartModel.objects.filter(user_id=user.id,goods_id=good_id)\n instance = carts.first()\n if carts.exists():\n instance.c_num += 1\n instance.save()\n data['c_num'] = instance.c_num\n else:\n CartModel.objects.create(\n c_num=1,\n is_select=1,\n goods_id=good_id,\n user_id=user.id\n )\n data['c_num'] = 1\n totalprice = caltotal()\n data['totalprice'] = round(totalprice,2)\n return JsonResponse(data)\n\n\ndef subnum(request):\n if request.method == 'POST':\n data = {\n 'msg':'请求成功',\n 'code':'200'\n }\n user = request.user\n if user.id:\n good_id = request.POST.get('good_id')\n carts = CartModel.objects.filter(user_id=user.id,goods_id=good_id)\n instance = carts.first()\n if carts.exists():\n instance.c_num -= 1\n instance.save()\n data['c_num'] = instance.c_num\n if instance.c_num == 0:\n instance.delete()\n totalprice = caltotal()\n data['totalprice'] = round(totalprice,2)\n return JsonResponse(data)\n\n\ndef caltotal():\n totalprice = 0\n carts = CartModel.objects.all()\n for cart in carts:\n if cart.is_select:\n totalprice += (cart.c_num * cart.goods.price)\n return totalprice\n\n\ndef change(request):\n if request.method == 'POST':\n data = {\n 'msg':'请求成功',\n 'code':'200'\n }\n user = request.user\n if user.id:\n goods_id = request.POST.get('good_id')\n user_cart = CartModel.objects.get(user_id=user.id, goods_id=goods_id)\n user_cart.is_select = not user_cart.is_select\n user_cart.save()\n data['is_select'] = user_cart.is_select\n if user_cart.is_select:\n price = user_cart.goods.price\n midprice = user_cart.c_num * price\n data['midprice'] = midprice\n totalprice = caltotal()\n data['totalprice'] = round(totalprice,2)\n return JsonResponse(data)\n\n\ndef selectall(request):\n if request.method == 'POST':\n data = {\n 'msg': '请求成功',\n 'code': '200'\n }\n user = request.user\n if user.id:\n carts = CartModel.objects.all()\n for cart in carts:\n if not cart.is_select:\n cart.is_select = not cart.is_select\n cart.save()\n totalprice = caltotal()\n data['totalprice'] = round(totalprice,2)\n return JsonResponse(data)\n\n\ndef take_order(request):\n if request.method == 'GET':\n user = deal_mine(request)\n carts = CartModel.objects.filter(is_select=True)\n for cart in carts:\n if cart.is_select ==True:\n order = OrderModel.objects.create(\n o_status=0,\n o_create=time.time(),\n user_id=user.id\n )\n for cart in carts:\n OrderGoodsModel.objects.create(\n goods_num=cart.c_num,\n goods_id=cart.goods_id,\n order_id=order.id\n )\n totalprice = caltotal()\n carts.delete()\n ordergoods = OrderGoodsModel.objects.filter(order_id=order.id)\n data = {\n 'id':order.id,\n 'ordergoods': ordergoods,\n 'totalprice':round(totalprice,2),\n 'user' : deal_mine(request)\n }\n return render(request, 'order/order_info.html', data)\n return render(request, 'mine/mine.html', {'user':user})\n\n\ndef alipay(request, id):\n if request.method == 'GET':\n user = request.user\n if user.id:\n order = OrderModel.objects.filter(id=id).first()\n order.o_status = 1\n order.save()\n user = deal_mine(request)\n return render(request, 'mine/mine.html', {'user':user})\n\n\ndef wait_pay(request):\n if request.method == 'GET':\n user = request.user\n if user.id:\n ordergoods = OrderGoodsModel.objects.filter(order__o_status=0)\n orders = OrderModel.objects.filter(o_status=0, user_id=user.id)\n return render(request, 'order/order_list_wait_pay.html', {'orders':orders})\n\n\ndef wait_send(request):\n if request.method == 'GET':\n user = request.user\n if user.id:\n orders = OrderModel.objects.filter(o_status=1, user_id=user.id)\n return render(request, 'order/order_list_payed.html', {'orders':orders})","sub_path":"aixianfeng2.0/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"387016659","text":"class Solution(object):\n def detectCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n break\n \n if not (fast and fast.next):\n return None\n \n while head is not slow:\n head = head.next\n slow = slow.next\n \n return head\n\n# a more consice version https://leetcode.com/problems/linked-list-cycle-ii/discuss/44783/Share-my-python-solution-with-detailed-explanation\ndef detectCycle(self, head):\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n slow2 = head\n while slow != slow2:\n slow = slow.next\n slow2 = slow2.next\n return slow","sub_path":"142. Linked List Cycle II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"294146163","text":"\"\"\"\nMaze game.\n\nCopyright (c) 2014 Grant Jenks\nhttp://www.grantjenks.com/\n\nExercises\n1. Change where the end is placed.\n2. Change where the player starts.\n3. Display only the player's immediate surroundings (no history).\n\"\"\"\n\nimport sys, pygame\nimport random\nfrom pygame.locals import *\n\n\"\"\"Initialize system.\ntiles represents how many squares the maze is made up of, block is the size of each tile.\nsize is a tuple representing (width,height) of the board.\ndirs is a tuple containing the difference in index each direction is from the current location\nview defines the difference in index the 3x3 space the user can currently see\nhall wall boundary extra define the different tiles that can be within the maze.\nred, green, blue, white, grey and black define RGB triplets for their corresponding colours.\n\"\"\"\npygame.init()\n\ntiles, block = 24, 20\nsize = width, height = (tiles * block), (tiles * block + 10)\n\ndirs = up, right, down, left = (-tiles, 1, tiles, -1) # Left and right are +1 or -1 index within the maze array, up and down are -width or +width\nview = (up, right, down, left, up - 1, up + 1, down - 1, down + 1) # Tuple defines a 3x3 (center omitted) space representing the tiles the player can see\n\nhall, wall, boundary, extra = 0, 1, 2, 3 # Defines the type each tile can be\n\nred, green, blue = (255, 0, 0), (0, 255, 0), (0, 0, 255)\nwhite, grey, black = (255, 255, 255), (100, 100, 100), (0, 0, 0)\n\nfont = pygame.font.Font(None, 14)\nclock = pygame.time.Clock()\nscreen = pygame.display.set_mode(size)\n\ndef make_maze():\n \"\"\"Function to define the game world.\n The blank maze is generated and populated, finally the goal is placed.\n \"\"\"\n global maze, player, end, moves\n\n # Create the initial, empty maze.\n\n maze = [boundary] * tiles\n maze += ([boundary] + [wall] * (tiles - 2) + [boundary]) * (tiles - 2)\n maze += [boundary] * tiles\n\n # Make the maze. This is a randomized version of Prim's algorithm\n # to build a minimum spanning tree.\n\n player = tiles + 1 # Defines starting location\n maze[player] = 0 # Set starting location to be a walkable tile (hall)\n frontier = [tiles + 2, 2 * tiles + 1]\n while len(frontier) > 0:\n pos = random.randrange(len(frontier))\n frontier[pos], frontier[-1] = frontier[-1], frontier[pos]\n spot = frontier.pop()\n\n if maze[spot] != wall: continue\n\n if map(lambda diff: maze[spot + diff], dirs).count(0) != 1: # If there is not 1 hall connected to the current square\n continue\n\n maze[spot] = hall\n\n frontier.extend(map(lambda diff: spot + diff, dirs)) # Adds all directions around current square to frontier array\n\n # End goal should be farthest reachable hall.\n\n frontier = [player]\n while True:\n next = [] # Defines spaces further away than the current location\n for front in frontier:\n maze[front] = extra\n next.extend(filter(lambda pos: maze[pos] == hall,\n map(lambda diff: front + diff, dirs))) # Adds areas around current location to next if they are halls\n if next: # If next has any entries\n frontier = next\n else: # If no spaces are further away\n last = random.choice(frontier) # Choose any space that is equally far away to be the goal\n break\n\n # Set all tiles of type extra to halls\n for pos, val in enumerate(maze):\n if val == extra: maze[pos] = hall\n\n moves = 0\n end = last\n\ndef draw_tile(func, color, pos):\n \"\"\"draw_tile is given a function to draw with as well as a colour.\n This function is called while looping over every tile within the maze to\n draw each tile as either black or white if it is a hall or wall/boundary.\n \"\"\"\n left = (pos % tiles) * block\n top = (pos / tiles) * block\n func(screen, color, (left, top, block, block))\n\ndef draw_maze():\n \"\"\"draw_maze iterates through the maze list and uses draw_tile to draw\n the maze to the screen defined earlier.\n \"\"\"\n for pos, val in enumerate(maze): # for every tile, tile type in maze\n color = white if val == hall else black # Specify a colour for that space\n draw_tile(pygame.draw.rect, color, pos) # Draw it\n\ndef draw_view():\n \"\"\"draw_view draws what the player has seen in the past and can currently see.\n This overwrites the initial state where all tiles are grey every time the player moves.\n \"\"\"\n for diff in view: # For each tile in the defined 3x3 window the player can see\n pos = player + diff # Defines position of square to be drawn\n color = white if maze[pos] == hall else black # Chooses colour for current square\n draw_tile(pygame.draw.rect, color, pos) # Draws the specified tile with the specified colour\n\n draw_tile(pygame.draw.rect, white, player) # Draws the space the player is on white.\n draw_tile(pygame.draw.rect, green, end) # Draws the goal green.\n draw_tile(pygame.draw.ellipse, blue, player) # Draws the player over the square they are on as a blue elipse.\n\n pygame.draw.rect(screen, (0, 0, 0), (0, width, width, 10)) # Draws main screen\n surface = font.render(str(moves), True, (255, 255, 255)) # Counter keeping track of the users total moves. \n screen.blit(surface, (5, tiles * block)) # Draws the total number of moves in the bottom left corner.\n\n pygame.display.flip() # Function that updates the display\n\ndef restart():\n \"\"\"Restarts the game by creating an entirely new maze and drawing it grey\"\"\"\n make_maze()\n pygame.draw.rect(screen, grey, (0, 0, width, height))\n draw_view()\n\nrestart()\n\nwhile True:\n \"\"\"Main loop of the system.\n Gathers an event, and processes it each iteration.\n Moves the player if the player has chosen to move.\n Updates the screen.\n \"\"\"\n clock.tick(12) # Every second 12 frames will happen\n\n event = pygame.event.poll() # Gets an event from the event queue\n move_dir = None\n\n if event.type == pygame.QUIT: # If the event is a quit event\n pygame.quit() # Close the game\n sys.exit()\n elif event.type == KEYDOWN: # If the event is a button press\n if event.key == K_UP:\n move_dir = up\n elif event.key == K_RIGHT:\n move_dir = right\n elif event.key == K_DOWN:\n move_dir = down\n elif event.key == K_LEFT:\n move_dir = left\n elif event.key == K_r:\n restart()\n elif event.key == K_s:\n draw_maze()\n draw_view()\n elif event.key == K_q:\n pygame.event.post(pygame.event.Event(QUIT)) # Add a quit event to the top of the queue\n\n if player == end: continue # If the player has reached the end of the maze we do not want them to be able to move, end the loop iteration here\n\n if move_dir is not None: # If the player has chosen to move\n if maze[player + move_dir] == hall: # If the player is moving into an open space\n player += move_dir # Move the player\n moves += 1\n draw_view()\n\n pygame.display.flip()\n","sub_path":"maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"580883566","text":"import RPi.GPIO as gp\n\nLEDPin = 11\nbuttonPin = 12\nLEDstate = False\n\ndef setup():\n gp.setmode(gp.BOARD)\n gp.setup(LEDPin, gp.OUT)\n gp.setup(buttonPin, gp.IN, pull_up_down = gp.PUD_UP)\n\n\ndef buttonEvent(channel):\n global LEDstate\n print(f'buttonEvent GPIO {channel}')\n LEDstate = not LEDstate\n if LEDstate:\n print('LED turned on')\n else:\n print('LED turned off')\n gp.output(LEDPin, LEDstate)\n\ndef loop():\n # button detect\n gp.add_event_detect(buttonPin, gp.FALLING, callback = buttonEvent,\n bouncetime = 300)\n while True:\n pass\n\ndef finish():\n gp.cleanup()\n\nif __name__ == '__main__':\n print('program is starting')\n setup()\n try:\n loop()\n except KeyboardInterrupt:\n finish()\n\n","sub_path":"GPIO/tableLamp.py","file_name":"tableLamp.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"13211287","text":"# Django\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import IntegrityError, transaction\nfrom django.contrib.auth import authenticate, login, logout\n\n# Rest\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\n# Modelos\nfrom apps.Usuario.models import Usuario\nfrom django.contrib.auth.models import User\nfrom apps.Adopciones.models import Adopcion\nfrom apps.Adopciones.models import ComentarioAdopcion\nfrom apps.Rescate.models import Rescate\nfrom apps.Rescate.models import ComentarioRescate\nfrom apps.Extravio.models import Extravio\nfrom apps.Extravio.models import ComentarioExtravio\n# Serializadores\nfrom apps.Usuario.serializers import UsuarioSerializer\nfrom apps.Usuario.serializers import UserSerializer\nfrom apps.Adopciones.serializers import AdopcionesSerializer\nfrom apps.Adopciones.serializers import ComentarioAdopcionSerializer\nfrom apps.Rescate.serializers import ComentarioRescateSerializer\nfrom apps.Rescate.serializers import RescatesSerializer\nfrom apps.Extravio.serializers import ExtraviosSerializer\nfrom apps.Extravio.serializers import ComentarioExtravioSerializer\nfrom apps.Usuario.serializers import UserAllSerializer\n\n# Utilidades\nimport re\n\n# Create your views here.\n# ==============================================================================\n# Subclase de HTTPRESPONSE: Una RespuestHTTP que renderiza su contenido como JSON\n# ==============================================================================\nclass JSONResponse(HttpResponse):\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n@csrf_exempt\n@transaction.atomic\ndef registro(request):\n\tif request.method == 'POST':\n\t\tnombre= request.POST['nombre']\n\t\tusername = request.POST['username']\n\t\testado = request.POST['estado']\n\t\tpassword1 = request.POST['password1']\n\t\tpassword2 = request.POST['password2']\n\t\timagen = request.FILES['foto']\n\t\tif password1 == password2:\n\t\t\tuserData = {\n\t\t\t\t'username': username,\n\t\t\t\t'password': password1\n\t\t\t}\n\t\t\tserializerUser = UserSerializer(data=userData)\n\t\t\t\n\t\t\tif serializerUser.is_valid():\n\t\t\t\tusuarioData = {\n\t\t\t\t\t'nombre': nombre,\n\t\t\t\t\t'estado': estado,\n\t\t\t\t\t'foto': imagen\n\t\t\t\t}\n\t\t\t\tserializerUsuario = UsuarioSerializer(data=usuarioData)\n\n\t\t\t\tif serializerUsuario.is_valid():\n\t\t\t\t\ttry:\n\t\t\t\t\t\tuser = User.objects.create_user(\n\t\t username=username, \n\t\t password=password1\n\t\t )\n\t\t\t\t\texcept IntegrityError:\n\t\t\t\t\t\treturn JSONResponse({\n\t\t\t\t\t\t\t'userExists': _('!Este correo ya esta registrado¡')\n\t\t\t\t\t\t}, status=400)\n\n\t\t\t\t\tuser.save()\n\n\t\t\t\t\tusuario = Usuario.objects.create(user=user, nombre=nombre, estado=estado, foto=imagen)\n\t\t\t\t\tusuario.save()\n\t\t\t\t\treturn JSONResponse({}, status=200)\n\n\t\t\t\treturn JSONResponse(serializerUsuario.errors, status=400)\n\n\t\t\treturn JSONResponse(serializerUser.errors, status=400)\n\t\telse:\n\t\t\treturn JSONResponse({\n\t\t\t\t\t'password': _('¡Las contraseñas no coinciden!')\n\t\t\t\t}, status=400)\n\n@csrf_exempt\ndef inicio_sesion(request):\n\tif request.method == 'POST':\n\t\tusername = request.POST['username']\n\t\tpassword = request.POST['password']\n\t\tregex = r'[a-z0-9._%+-]+@[a-z0-9.-]+[\\\\.][a-z]{2,}$'\n\t\tif re.match(regex, username):\n\t\t\tuser = authenticate(request, username=username, password=password)\n\t\t\tif user:\n\t\t\t login(request, user)\n\t\t\t usuario = Usuario.objects.get(user=user)\n\t\t\t userSerial = UserSerializer(user)\n\t\t\t usuarioSerial = UsuarioSerializer(usuario)\n\t\t\t return JSONResponse(\n\t\t\t \tdata={\n\t\t\t \t\t'success': {\n\t\t\t\t \t\t'user': userSerial.data,\n\t\t\t\t \t\t'usuario': usuarioSerial.data\n\t\t\t \t\t}\n\t\t\t \t},\n\t\t\t \tstatus=200\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\treturn JSONResponse(\n\t\t\t\t\tdata={\n\t\t\t\t\t'error': '¡Usuario o contraseña incorrectos!'\n\t\t\t\t\t}, status=400\n\t\t\t\t)\n\t\telse:\n\t\t\treturn JSONResponse(\n\t\t\t\tdata={\n\t\t\t\t\t'error': '¡Ingrese un correo valido!.\\n Ej: puppy@mail.com'\n\t\t\t\t},\n\t\t\t\tstatus=400\n\t\t\t)\n\n@csrf_exempt\ndef perfil(request, username):\n\tif request.method == 'GET':\n\t\tusername = username\n\t\tuser = User.objects.get(username=username)\n\t\tusuario = Usuario.objects.get(user=user)\n\t\tuserSerial = UserSerializer(user)\n\t\tusuarioSerial = UsuarioSerializer(usuario)\n\t\tdata = {\n\t\t\t'user': userSerial.data,\n\t\t\t'usuario': usuarioSerial.data\n\t\t}\n\t\treturn JSONResponse(data, status=200)\n\n@csrf_exempt\ndef cantidad_publicaciones(request, username):\n\tif request.method == 'GET':\n\t\tuser = User.objects.get(username=username)\n\t\tusuario = Usuario.objects.get(user=user)\n\t\tcontador = 0\n\t\trescates = Rescate.objects.filter(usuario=usuario)\n\t\tfor rescate in rescates:\n\t\t\tcontador += 1\n\t\textravios = Extravio.objects.filter(usuario=usuario)\n\t\tfor extravio in extravios:\n\t\t\tcontador += 1\n\t\tadopciones = Adopcion.objects.filter(usuario=usuario)\n\t\tfor adopcion in adopciones:\n\t\t\tcontador += 1\n\t\tdata = {\n\t\t\t'success': {\n\t\t\t\t'totalPublicaciones': contador\n\t\t\t}\n\t\t}\n\t\treturn JSONResponse(data, status=200)\n\n@csrf_exempt\ndef cantidad_comentarios(request, username):\n\tif request.method == 'GET':\n\t\tuser = User.objects.get(username=username)\n\t\tusuario = Usuario.objects.get(user=user)\n\t\trescates = ComentarioRescate.objects.filter(usuario=usuario)\n\t\tcontador = 0\n\t\tfor rescate in rescates:\n\t\t\tcontador += 1\n\t\textravios = ComentarioExtravio.objects.filter(usuario=usuario)\n\t\tfor extravio in extravios:\n\t\t\tcontador += 1\n\t\tadopciones = ComentarioAdopcion.objects.filter(usuario=usuario)\n\t\tfor adopcion in adopciones:\n\t\t\tcontador += 1\n\t\tdata = {\n\t\t\t'success': {\n\t\t\t\t'totalComentarios': contador\n\t\t\t}\n\t\t}\n\t\treturn JSONResponse(data, status=200)\n\n@csrf_exempt\ndef dias_activo(request, username):\n\tif request.method == 'GET':\n\t\tuser = User.objects.get(username=username)\n\t\tuserSerialized = UserAllSerializer(user)\n\t\tdata = {\n\t\t\t'success': {\n\t\t\t\t'user': userSerialized.data\n\t\t\t}\n\t\t}\n\t\treturn JSONResponse(data, status=200)\n\n@csrf_exempt\ndef publicaciones_usuario(request, username):\n\tif request.method == 'GET':\n\t\tuser = User.objects.get(username=username)\n\t\tusuario = Usuario.objects.get(user=user)\n\t\tadopciones = Adopcion.objects.filter(usuario=usuario.id)\n\t\tadopcionesSerialized = AdopcionesSerializer(adopciones, many=True)\n\t\tcantidadComAdopcion = []\n\t\tfor adopcion in adopciones:\n\t\t\tcomentariosAdopcion = ComentarioAdopcion.objects.filter(adopcion=adopcion.id) \n\t\t\tcomentariosSerialized = ComentarioAdopcionSerializer(comentariosAdopcion, many=True)\n\t\t\tcantidadComAdopcion.append(len(comentariosSerialized.data))\n\t\trescates = Rescate.objects.filter(usuario=usuario.id)\n\t\trescatesSerialized = RescatesSerializer(rescates, many=True)\n\t\tcantidadComRescate = []\n\t\tfor rescate in rescates:\n\t\t\tcomentariosRescate = ComentarioRescate.objects.filter(rescate=rescate.id) \n\t\t\tcomentariosResSerialized = ComentarioRescateSerializer(comentariosRescate, many=True)\n\t\t\tcantidadComRescate.append(len(comentariosResSerialized.data))\n\t\textravios = Extravio.objects.filter(usuario=usuario.id)\n\t\textraviosSerialized = ExtraviosSerializer(extravios, many=True)\n\t\tcantidadComExtravio = []\n\t\tfor extravio in extravios:\n\t\t\tcomentariosExtravio = ComentarioExtravio.objects.filter(extravio=extravio.id) \n\t\t\tcomentariosExtSerialized = ComentarioExtravioSerializer(comentariosExtravio, many=True)\n\t\t\tcantidadComExtravio.append(len(comentariosExtSerialized.data))\n\t\tdata = {\n\t\t\t'success': {\n\t\t\t\t'adopciones': adopcionesSerialized.data,\n\t\t\t\t'rescates': rescatesSerialized.data,\n\t\t\t\t'extravios': extraviosSerialized.data,\n\t\t\t\t'comentAdopciones': cantidadComAdopcion,\n\t\t\t\t'comentRescates': cantidadComRescate,\n\t\t\t\t'comentExtravios': cantidadComExtravio,\n\t\t\t}\n\t\t}\n\t\treturn JSONResponse(data, status=200)\n\n@csrf_exempt\ndef logout_view(request, username):\n\tuser = User.objects.get(username=username)\n\tlogout(request)\n\tdata = {\n\t\t'success': True\n\t}\n\treturn JSONResponse(data, status=200)\n\n","sub_path":"apps/Usuario/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"235392061","text":"import uiScriptLocale\nimport item\nimport app\n\nCOSTUME_START_INDEX = item.COSTUME_SLOT_START\n\nwindow = {\n\t\"name\" : \"CostumeWindow\",\n\t\"x\" : SCREEN_WIDTH - 175 - 140,\n\t\"y\" : SCREEN_HEIGHT - 37 - 565,\n\t\"style\" : (\"movable\", \"float\",),\n\t\"width\" : 140,\n\t\"height\" : 180,\n\n\t\"children\" :\n\t[\n\t\t{\n\t\t\t\"name\" : \"board\",\n\t\t\t\"type\" : \"board\",\n\t\t\t\"style\" : (\"attach\",),\n\t\t\t\"x\" : 0,\n\t\t\t\"y\" : 0,\n\t\t\t\"width\" : 140,\n\t\t\t\"height\" : 180,\n\t\t\t\n\t\t\t\"children\" :\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"TitleBar\",\n\t\t\t\t\t\"type\" : \"titlebar\",\n\t\t\t\t\t\"style\" : (\"attach\",),\n\t\t\t\t\t\"x\" : 6,\n\t\t\t\t\t\"y\" : 6,\n\t\t\t\t\t\"width\" : 130,\n\t\t\t\t\t\"color\" : \"yellow\",\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t[\n\t\t\t\t\t\t{ \"name\":\"TitleName\", \"type\":\"text\", \"x\":60, \"y\":3, \"text\":uiScriptLocale.COSTUME_WINDOW_TITLE, \"text_horizontal_align\":\"center\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"Costume_Base\",\n\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\"x\" : 13,\n\t\t\t\t\t\"y\" : 38,\n\t\t\t\t\t\n\t\t\t\t\t\"image\" : uiScriptLocale.LOCALE_UISCRIPT_PATH + \"costume/costume_bg.jpg\",\t\t\t\t\t\n\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t[\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"CostumeSlot\",\n\t\t\t\t\t\t\t\"type\" : \"slot\",\n\t\t\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\t\t\"width\" : 127,\n\t\t\t\t\t\t\t\"height\" : 145,\n\t\t\t\t\t\t\t\"slot\" : [\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.COSTUME_SLOT_BODY, \"x\":62, \"y\":45, \"width\":32, \"height\":64},#몸\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.COSTUME_SLOT_HAIR, \"x\":62, \"y\": 9, \"width\":32, \"height\":32},#머리\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.EQUIPMENT_RING1, \"x\":13, \"y\":178, \"width\":32, \"height\":32},\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.EQUIPMENT_RING2, \"x\":62, \"y\":178, \"width\":32, \"height\":32},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t],\n}\n\nif ENABLE_COSTUME_MOUNT:\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"slot\"] += [\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.COSTUME_SLOT_MOUNT, \"x\":13, \"y\":126, \"width\":32, \"height\":32},]\n\nif ENABLE_ACCE_SYSTEM: # @@@correction024\n\twindow[\"height\"] += 50\n\twindow[\"children\"][0][\"height\"] += 50\n\twindow[\"children\"][0][\"children\"][1][\"image\"] = uiScriptLocale.LOCALE_UISCRIPT_PATH + \"costume/new_costume_bg.jpg\"\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"slot\"] += [\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.COSTUME_SLOT_ACCE, \"x\":62, \"y\":126, \"width\":32, \"height\":32},]\n\nif ENABLE_WEAPON_COSTUME_SYSTEM: # @@@correction038\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"slot\"] += [\n\t\t\t\t\t\t\t\t\t\t{\"index\":item.COSTUME_SLOT_WEAPON, \"x\":13, \"y\":13, \"width\":32, \"height\":96},]\n\n# if ENABLE_COSTUME_EFFECT: # @@@correction039\n\twindow[\"height\"] += 47\n\twindow[\"children\"][0][\"height\"] += 47\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"height\"] += 130\n\twindow[\"children\"][0][\"children\"][1][\"image\"] = uiScriptLocale.LOCALE_UISCRIPT_PATH + \"costume/new_costume_bg_with_ring.jpg\"\n\t# window[\"children\"][0][\"children\"][1][\"children\"][0][\"slot\"] += [\n\t\t\t\t\t\t\t\t\t\t# {\"index\":item.COSTUME_SLOT_EFFECT_WEAPON, \"x\":13, \"y\":178, \"width\":32, \"height\":32},\n\t\t\t\t\t\t\t\t\t\t# {\"index\":item.COSTUME_SLOT_EFFECT_BODY, \"x\":62, \"y\":178, \"width\":32, \"height\":32},]\n","sub_path":"Client/Pack/root/uiscript/costumewindow.py","file_name":"costumewindow.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"637806015","text":"from kivy.uix.widget import Widget\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.uix.button import Button\nfrom kivy.app import App\nfrom kivy.properties import ListProperty\nfrom random import choice\n\nfrom session import Session\n\nclass SessionSelectorScreen (Screen):\n\tdicesets = {}\n\tdef selected(self):\n\t\tsession = Session(self.dicesets[self.ids.title.text],name=\"session\")\n\t\tself.manager.add_widget(session)\n\t\tself.manager.current = 'session'\n\t\n\tdef load(self,dicesets):\n\t\tfor ds in dicesets:\n\t\t\tself.dicesets[ds.name] = ds\n\t\t\tsb = SetButton(text=ds.name)\n\t\t\tsb.change = self.change_set\n\t\t\tself.ids.set_selector.add_widget(sb)\n\t\tself.change_set(self.dicesets.keys()[0])\n\t\n\tdef change_set(self,name):\n\t\tself.ids.title.text = name\n\t\tself.ids.desc.text = self.dicesets[name].desc\n\nclass SetButton (Button):\n\tdef on_press(self):\n\t\tself.change(self.text)\n","sub_path":"sessionselectorscreen.py","file_name":"sessionselectorscreen.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"435538114","text":"from flask import session, request, render_template, jsonify, redirect\nfrom app import app\nfrom helpers.mongo import get_user, get_songs, auth, update_song, get_song, get_users, get_locations, get_song_by_id\nfrom helpers.utils import ip_to_location\n\n@app.route('/')\ndef index_view():\n return render_template('index.html')\n\n@app.route('/api/get_random')\ndef get_random():\n ip = request.remote_addr\n auth(ip)\n output, info = get_song(ip)\n success = 0 if output != -1 else 1\n return jsonify(\n code=success,\n response=output,\n info=info\n )\n\n@app.route(\"/api/song\")\ndef get_song_with_id():\n song_id = request.args.get(\"songId\")\n output = get_song_by_id(song_id)\n return jsonify(info=output)\n\n\n@app.route('/api/update', methods=['POST',])\ndef update():\n ip = request.remote_addr\n auth(ip)\n content = request.json\n _id = None\n if 'songId' in content.keys():\n _id = content['songId']\n # try:\n update_song(ip, content['measure'], _id)\n code = 0\n # except:\n # code = 1\n # finally:\n return jsonify(\n code=code\n )\n\n\n@app.route('/profile')\ndef profile():\n ip = request.remote_addr\n auth(ip)\n user = get_user(ip)\n result = zip(user[\"contributed\"].keys(), user['contributed'].values(),\n [i for i in range(1, len(user['contributed']) + 1)])\n return render_template('profile.html', contributed=result)\n\n@app.route('/api/tracker', methods=['POST',])\ndef track():\n ip = request.remote_addr\n auth(ip)\n loc = ip_to_location(ip)\n content = request.json\n return jsonify(self=loc, locations=get_locations(request.json['songId']))\n","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"45877937","text":"import json\nimport urllib.parse\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass OverdriveApi:\n\n def __init__(self, subdomain):\n self.subdomain = subdomain\n self._session = requests.Session()\n\n def base_url(self):\n return 'https://%s.overdrive.com' % self.subdomain\n\n def get_item_url(self, item_id):\n return urllib.parse.urljoin(self.base_url(), 'media/%s' % item_id)\n\n def _extract_page_config(self, content):\n soup = BeautifulSoup(content, 'lxml')\n for script_tag in soup.find_all('script'):\n if 'window.OverDrive.mediaItems' in script_tag.text:\n for line in script_tag.text.split('\\n'):\n if 'window.OverDrive.mediaItems' in line.strip():\n data = line.strip().partition('=')[2].rstrip(';')\n return next(iter(json.loads(data).values()))\n break\n else:\n raise Exception(\"Could not exctract page config\")\n\n def item_details(self, item_id):\n r = self._session.get(self.get_item_url(item_id))\n r.raise_for_status()\n item_data = self._extract_page_config(r.content)\n return {\n 'available': item_data.get('availableCopies', 0),\n 'copies': item_data.get('ownedCopies', 0),\n 'waiting_per_copy': None if item_data['isAvailable'] else item_data.get('holdsRatio', 0)\n }\n","sub_path":"verybook/apis/overdrive.py","file_name":"overdrive.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"118801707","text":"#!/usr/bin/env python\n\n# Script developed by Vincenz Frenzel\n# --- Changelog ---\n# Goal: Input by bebop camera and stereo camera and state machine and merged_odometry. Depending on state machine, use algorithms to detect gates on the image. Afterwards, position gates on a global map based on the odometry as gate orientation matrices are relative to camera orientation. Output position and orientation of next gate\n# Status: 06/19: Uses cheap stereo camera left video stream to identify gate position and orientation. Does not incorporate any odometry and publishes gate position at (1,0,0) with 3 Hz. Coordainte transformation missing. CV algorithm might need to be improved if there is a performance issue\n# 07/06: Publishes gate position as seen from the camera (tvec: translation from camera, rvec: rotation from camera, and applicable bebop odometry\n# 11/03: Commented code\n\nimport rospy\nfrom geometry_msgs.msg import Pose\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import String, Empty\nfrom sensor_msgs.msg import Image, CameraInfo\nimport cv2\nimport numpy as np\nfrom cv_bridge import CvBridge\nimport time\nimport math\nfrom bebop_auto.msg import Gate_Detection_Msg\nfrom std_msgs.msg import Float64MultiArray, Float32MultiArray, Bool, Float32\nimport matplotlib.pyplot as plt\n\nimport signal\nimport sys\n\n\ndef signal_handler(_, __):\n sys.exit(0)\n\n\n# intersect two line bundles to one single intersection point\ndef isect_lines_bundle(lines1, lines2, start, end):\n # start and end points of all lines\n x1 = start[0, lines1]\n y1 = start[1, lines1]\n x2 = end[0, lines1]\n y2 = end[1, lines1]\n x3 = start[0, lines2]\n y3 = start[1, lines2]\n x4 = end[0, lines2]\n y4 = end[1, lines2]\n\n # create matrices from lists to enable fast numpy operations\n x1 = np.repeat(np.matrix(x1, dtype='float'), len(lines2), axis=0)\n y1 = np.repeat(np.matrix(y1, dtype='float'), len(lines2), axis=0)\n x2 = np.repeat(np.matrix(x2, dtype='float'), len(lines2), axis=0)\n y2 = np.repeat(np.matrix(y2, dtype='float'), len(lines2), axis=0)\n x3 = np.transpose(np.repeat(np.matrix(x3, dtype='float'), len(lines1), axis=0))\n y3 = np.transpose(np.repeat(np.matrix(y3, dtype='float'), len(lines1), axis=0))\n x4 = np.transpose(np.repeat(np.matrix(x4, dtype='float'), len(lines1), axis=0))\n y4 = np.transpose(np.repeat(np.matrix(y4, dtype='float'), len(lines1), axis=0))\n\n # basic idea: g1=p1+t*(p2-p1)\n # g2=p3+s*(p4-p3) and solve for s\n s = (np.multiply(x2 - x1, y3 - y1) - np.multiply(x3 - x1, y2 - y1)) / (np.multiply(x4 - x3, y2 - y1) - np.multiply(\n x2 - x1, y4 - y3))\n\n x = x3 + np.multiply(s, x4 - x3)\n y = y3 + np.multiply(s, y4 - y3)\n\n # calculate mean of all intersection not taking into account invalid entries\n return np.ma.masked_invalid(x).mean(), np.ma.masked_invalid(y).mean()\n\n\n# mask an hsv image with a specific color\ndef mask_image(hsv, color):\n # make this function compatible also for pointer detection -> color information required\n if color == \"orange\":\n # lower_color = np.array([85, 60, 80]) # orange matlab jungle\n # upper_color = np.array([130, 255, 255]) # orange matlab jungle\n\n # lower_color = np.array([80, 20, 240]) # orange matlab dynamic\n # upper_color = np.array([130, 255, 255]) # orange matlab dynamic\n\n # lower_color = np.array([87, 55, 100]) # orange dynamic cypress\n # upper_color = np.array([117, 255, 255]) # orange dynamic cypress\n\n # lower_color = np.array([87, 145, 90]) # orange static cypress\n # upper_color = np.array([117, 255, 255]) # orange static cypress\n #\n # lower_color = np.array([87, 125, 50]) # orange armory\n # upper_color = np.array([145, 255, 255]) # orange armory\n\n # lower_color = np.array([106, 120, 90]) # orange kim hallway\n # upper_color = np.array([117, 255, 255]) # orange kim hallway\n #\n # lower_color = np.array([110, 135, 90]) # orange grad office 3D\n # upper_color = np.array([120, 255, 255]) # orange grad office 3D\n\n # lower_color = np.array([105, 115, 60]) # orange outdoor\n # upper_color = np.array([130, 255, 255]) # orange outdoor\n #\n lower_color = orange_low\n upper_color = orange_high\n\n publisher = publisher_image_threshold_orange\n else:\n # lower_color = np.array([0, 0, 150]) # green matlab pointer\n # upper_color = np.array([60, 255, 255]) # green matlab pointer\n\n # lower_color = np.array([20, 55, 100]) # green cypress pointer\n # upper_color = np.array([35, 255, 255]) # green cypress pointer\n\n # lower_color = np.array([0, 170, 60]) # green armory\n # upper_color = np.array([45, 255, 255]) # green armory\n\n lower_color = np.array([25, 70, 30]) # green Madrid\n upper_color = np.array([70, 255, 255]) # green Madrid\n\n publisher = publisher_image_threshold_dynamic\n\n # mask image\n mask = cv2.inRange(hsv, lower_color, upper_color)\n\n # different tries of improving runtime (line thinning, sobel edge detector, laplacian edge detetor, ...)\n # with runtime measuring\n\n # t0 = time.time()\n # try thinning all colored pixels from above (runs at around 5Hz)\n # thin = cv2.ximgproc.thinning(mask, mask, cv2.ximgproc.THINNING_ZHANGSUEN)\n\n # try a sobel edge detector (runs at around 20 Hz)\n # sobelx64f = cv2.Sobel(mask, cv2.CV_64F, 1, 0, ksize=3)\n # sobely64f = cv2.Sobel(mask, cv2.CV_64F, 0, 1, ksize=3)\n # abs_sobel64f = np.absolute(sobelx64f) + np.absolute(sobely64f)\n # sobel_8u = np.uint8(abs_sobel64f)\n\n # using a laplacian is very fast, around 100 Hz\n # laplacian = cv2.Laplacian(mask, cv2.CV_8U)\n\n # t1 = time.time()\n # total = t1 - t0\n # print(total)\n\n # Bitwise-AND mask and original image only for fun\n # global image_pub_dev1\n\n # output_im = bridge.cv2_to_imgmsg(mask, encoding=\"8UC1\")\n # image_pub_dev1.publish(output_im)\n\n # show = cv2.resize(res,(1280,720))\n # cv2.imshow(\"show\",show)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # exit()\n\n # output masked image. fast if only mask is returned, more informative but much slower if mask is applied onto rgb\n # and then returned. therefore uncomment the first three lines, comment our the following two\n global bridge\n # rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n # res = cv2.bitwise_and(rgb, rgb, mask=mask)\n # output_im = bridge.cv2_to_imgmsg(res, encoding=\"rgb8\")\n output_im = cv2.resize(mask, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(output_im, encoding=\"8UC1\")\n publisher.publish(output_im)\n\n # display image\n # cv2.imshow(\"test\",res)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # exit()\n\n return mask\n\n\n# callback of a new image\ndef stereo_callback(data):\n global bridge\n global latest_pose\n global rvec\n global tvec\n\n # set a debug mode where this runs without pose and can also run special detection if required\n debug_on = False\n if debug_on:\n global gate_detection_dynamic_on\n global gate_detection_jungle_on\n this_pose = Pose()\n # gate_detection_jungle_on = True\n gate_detection_dynamic_on = True\n else:\n if latest_pose is None:\n print(\"No position\")\n return\n this_pose = latest_pose\n this_time = time.time()\n\n # convert image msg to matrix\n rgb = bridge.imgmsg_to_cv2(data, desired_encoding=data.encoding)\n\n # convert image to HSV\n # original image is BGR but conversion here is RGB so red color does not wrap around, saves runtime\n hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)\n\n # masking image\n mask = mask_image(hsv, \"orange\")\n\n # probabilistic hough transform\n min_line_length = 720/4\n max_line_gap = 30\n\n # hough lines, returns start and end points of lines. lines are sorted by num of votes, but that number is unknown\n # image, precision r, precision theta, number of votes, minLineLength to consider, maxLineGap to overjump\n lines = cv2.HoughLinesP(mask, 5, np.pi / 90, 300, minLineLength=min_line_length, maxLineGap=max_line_gap)\n\n # print DEBUG onto image\n if debug_on:\n cv2.putText(rgb, \"DEBUG\", (10, 85), cv2.FONT_HERSHEY_SIMPLEX, 3.5, (0, 0, 255), 10, cv2.LINE_AA)\n\n # if there are less than 2 lines, exit\n # before exit: publish empty result and publish current rgb image\n if lines is None or len(lines) < 2:\n rospy.loginfo(\"no lines\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n # lines have been found\n # angles = []\n\n # shorten list of lines to only use good matches\n if len(lines) > 40:\n # if more than 40: use best 40 normally, use best 80 for special jungle detection (two gates need to be found)\n if gate_detection_jungle_on:\n lines = lines[:80]\n else:\n lines = lines[:40]\n\n # display lines and end points in rgb image, color dots by number of votes\n # votes = np.array(list(reversed(range(len(lines))))) + 1\n # for counter, line in enumerate(lines):\n # for x1, y1, x2, y2 in line:\n # # angles.append(math.atan2(y2 - y1, x2 - x1) * 180 / np.pi) # between -90 and 90\n # cv2.circle(rgb, (x1, y1), 5, (votes[counter]*255.0/len(lines), votes[counter]*255.0/len(lines),\n # votes[counter]*255.0/len(lines)), 2)\n # cv2.circle(rgb, (x2, y2), 5, (votes[counter]*255.0/len(lines), votes[counter]*255.0/len(lines),\n # votes[counter]*255.0/len(lines)), 2)\n # # cv2.line(rgb, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n # plot histogram of angles. usually angles are not calculated though\n # plt.clf()\n # hist = np.histogram(angles, 90, [-90.0, 90.0])\n #\n # ax = plt.axes()\n # ax.xaxis.set_major_locator(ticker.MultipleLocator(5))\n # ax.yaxis.set_minor_locator(ticker.MultipleLocator(100))\n # plt.plot(hist[1][1:], hist[0], 'bo-')\n # plt.axis([-90, 90, 0, 10])\n # # x_ticks = np.arange(-90, 90, 5)\n # # y_ticks = np.arange(-1500, 1500, 100)\n # # ax.set_xticks(x_ticks)\n # # ax.set_yticks(y_ticks)\n # plt.grid(which='both')\n\n # cluster start and end points\n # how big are clusters (pixels)\n dist_thresh = 50\n\n # array of lines\n lines = np.array(lines)\n # squeeze empty dimensions\n lines = np.squeeze(lines)\n # get corners instead of lines\n corners = np.transpose(lines)\n # seperate start and end points\n start = corners[:2, :]\n end = corners[2:, :]\n # append start and end points to each other\n start_end = np.concatenate((start, end), axis=1)\n # create fake number for votes to weigh good lines better\n votes = np.array(list(reversed(range(len(lines)))))+1\n # concatenate votes so it's as long as start+end list\n votes = np.concatenate((votes, votes))\n # set up variables for first clustering\n x_ms_1 = np.array([]) # list of x coords of cluster centers\n y_ms_1 = np.array([]) # list of y\n vote_ms_1 = np.array([]) # list of number of votes\n\n # draw all start and end points\n # for i in range(np.shape(start_end)[1]):\n # cv2.circle(rgb, (int(start_end[0][i]), int(start_end[1][i])), 5, (0, 0, 255), 2)\n\n # start clustering\n # nothing is clustered yet -> zeros\n clusters_1 = np.zeros(np.shape(start_end)[1])\n # number of current cluster\n cluster = 0\n # while not every point is in a cluster: keep clustering\n while not clusters_1.all():\n # start with cluster number 1\n cluster = cluster+1\n # get first unclustered index\n s = np.where(clusters_1 == 0)[0][0]\n # get position and votes and set as average for cluster\n x_m = start_end[0][s]\n y_m = start_end[1][s]\n vote_m = votes[s]\n # set this point as clustered\n clusters_1[s] = cluster\n # find points belonging to this cluster until no more were found (and go_around becomes false)\n go_around = True\n\n while go_around:\n go_around = False # assume there will not be another point\n for idx in np.where(clusters_1 == 0)[0]:\n # go through all unclustered points and calculate distance to cluster center\n x = start_end[0][idx]\n y = start_end[1][idx]\n vote = votes[idx]\n distance = math.sqrt((x-x_m)**2+(y-y_m)**2)\n # print distance\n # check distance between point and cluster mean\n if distance < dist_thresh:\n # enable go around\n go_around = True\n # recalculate average and votes\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n # set point as clustered\n clusters_1[idx] = cluster\n\n # no more points were found. add average to a list of clusters\n x_ms_1 = np.append(x_ms_1, x_m)\n y_ms_1 = np.append(y_ms_1, y_m)\n vote_ms_1 = np.append(vote_ms_1, vote_m)\n\n # weigh cluster votes, so that it is better the higher in the image the cluster is (build gate from top to bottom)\n # 1000 only used to make numbers smaller\n # commented out: also use horizontal position (weigh clusters in center higher)\n idx = vote_ms_1 * (800-y_ms_1) / 1000 # * (400-abs(x_ms_1-1280/2))/100000\n\n # no cluster was created -> exit\n if cluster == 0:\n rospy.loginfo(\"empty sequence 1\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n # draw all clusters with their weighted votes\n # for index in range(len(vote_ms_1)):\n # cv2.circle(rgb, (int(x_ms_1[index]), int(y_ms_1[index])), dist_thresh, (255, 255, 255), 2)\n # cv2.putText(rgb, str(int(idx[index])), (int(x_ms_1[index]), int(y_ms_1[index])), cv2.FONT_HERSHEY_SIMPLEX, 1,\n # (255, 255, 255), 2, cv2.LINE_AA)\n\n # find strongest corner\n max_cluster = np.argmax(idx)+1\n\n # set up list of all corner points, these will actually not be used for solvePnP algorithm\n corner_points = np.zeros((5, 2))\n # add point to gate corner\n corner_points[0, :] = [x_ms_1[max_cluster - 1], y_ms_1[max_cluster - 1]]\n\n # draw corner\n # cv2.circle(rgb, (int(corner_points[0, 0]), int(corner_points[0, 1])), dist_thresh, (255, 0, 0), 2)\n # cv2.circle(rgb, (int(corner_points[0, 0]), int(corner_points[0, 1])), 2, (255, 0, 0), 2)\n\n # find all lines originating from this first cluster\n to_cluster_id = np.where(clusters_1 == max_cluster)[0]\n to_cluster_id1 = to_cluster_id[to_cluster_id < len(lines)] # lines that started in cluster\n to_cluster_id2 = to_cluster_id[to_cluster_id >= len(lines)] - len(lines) # lines that ended in cluster\n lines_cluster_1 = np.concatenate((to_cluster_id1, to_cluster_id2)) # append both\n\n # draw the lines that were found and will be reclustered\n # for line in to_cluster_id1:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 255), 2)\n # for line in to_cluster_id2:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 255), 2)\n\n # use endpoints of the lines that started in cluster\n to_cluster1 = end[:, to_cluster_id1]\n # and startpoints of lines that ended in cluster\n to_cluster2 = start[:, to_cluster_id2]\n # append the two\n to_cluster = np.concatenate((to_cluster1, to_cluster2), axis=1)\n # find their votes\n votes_2 = np.concatenate((votes[to_cluster_id1], votes[to_cluster_id2]))\n\n # see above\n clusters_2 = np.zeros(np.shape(to_cluster)[1])\n cluster = 0\n x_ms_2 = np.array([])\n y_ms_2 = np.array([])\n vote_ms_2 = np.array([])\n\n while not clusters_2.all():\n cluster = cluster+1\n s = np.where(clusters_2 == 0)[0][0]\n x_m = to_cluster[0][s]\n y_m = to_cluster[1][s]\n vote_m = votes_2[s]\n clusters_2[s] = cluster\n\n for idx in np.where(clusters_2 == 0)[0]:\n x = to_cluster[0][idx]\n y = to_cluster[1][idx]\n vote = votes_2[idx]\n distance = math.sqrt((x-x_m)**2+(y-y_m)**2)\n # print distance\n if distance < dist_thresh:\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n clusters_2[idx] = cluster\n\n x_ms_2 = np.append(x_ms_2, x_m)\n y_ms_2 = np.append(y_ms_2, y_m)\n vote_ms_2 = np.append(vote_ms_2, vote_m)\n\n # not two clusters were created from the points -> exit or run jungle special detection if it was enabled\n if cluster < 2:\n if gate_detection_jungle_on:\n gate_detection_jungle(vote_ms_1, y_ms_1, x_ms_1, lines, clusters_1, start, end, votes, dist_thresh, rgb,\n data, this_pose) # run jungle detection with all available data\n else: # exit\n rospy.loginfo(\"empty sequence 2\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n # find two strongest clusters\n maximum_ids = vote_ms_2.argsort()[-2:][::-1]\n\n # these two clusters have to be matched to the original clusters of #1 as only there we know which lines contributes\n # therefore calculate distance of cluster 2.1 to all others and find minimum\n x_diff = x_ms_1 - x_ms_2[maximum_ids[0]]\n y_diff = y_ms_1 - y_ms_2[maximum_ids[0]]\n diff = x_diff * x_diff + y_diff * y_diff\n # a special algorithm can also take into account how strong the cluster is. In special cases, not the clostest\n # cluster is the one we are looking for but a further one that is much stronger (but disabled)\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id1 = np.argmax(temp_vote)\n # find minimum\n close_id1 = np.argmin(diff)\n\n # see above but for 2.2 to all others\n x_diff = x_ms_1 - x_ms_2[maximum_ids[1]]\n y_diff = y_ms_1 - y_ms_2[maximum_ids[1]]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id2 = np.argmax(temp_vote)\n close_id2 = np.argmin(diff)\n\n # add to list although the corners will never be used\n corner_points[1, :] = [x_ms_1[close_id1], y_ms_1[close_id1]]\n corner_points[2, :] = [x_ms_1[close_id2], y_ms_1[close_id2]]\n\n # draw these two points\n # cv2.circle(rgb, (int(corner_points[1, 0]), int(corner_points[1, 1])), dist_thresh, (0, 255, 0), 2)\n # cv2.circle(rgb, (int(corner_points[2, 0]), int(corner_points[2, 1])), dist_thresh, (0, 255, 0), 2)\n # cv2.circle(rgb, (int(corner_points[1, 0]), int(corner_points[1, 1])), 2, (0, 255, 0), 2)\n # cv2.circle(rgb, (int(corner_points[2, 0]), int(corner_points[2, 1])), 2, (0, 255, 0), 2)\n\n # find lines originating from these two median points and recluster its endpoints into two separate clusters\n close_id1 = close_id1 + 1 # to equal cluster number\n close_id2 = close_id2 + 1 # to equal cluster number\n\n # find lines in closest clusters\n lines_cluster_2a_long = np.where(clusters_1 == close_id1)[0]\n lines_cluster_2b_long = np.where(clusters_1 == close_id2)[0]\n\n # do the start and end point thing again (subtract number of lines from all points in second part of start_end_list\n to_cluster_id1_a = lines_cluster_2a_long[lines_cluster_2a_long < len(lines)]\n to_cluster_id2_a = lines_cluster_2a_long[lines_cluster_2a_long >= len(lines)] - len(lines)\n to_cluster_id1_b = lines_cluster_2b_long[lines_cluster_2b_long < len(lines)]\n to_cluster_id2_b = lines_cluster_2b_long[lines_cluster_2b_long >= len(lines)] - len(lines)\n\n # concatenate\n lines_cluster_2a = np.concatenate((to_cluster_id1_a, to_cluster_id2_a))\n lines_cluster_2b = np.concatenate((to_cluster_id1_b, to_cluster_id2_b))\n\n # find which lines were used in last clustering\n rm1a = np.in1d(to_cluster_id1_a, to_cluster_id1) + np.in1d(to_cluster_id1_a, to_cluster_id2)\n rm2a = np.in1d(to_cluster_id2_a, to_cluster_id1) + np.in1d(to_cluster_id2_a, to_cluster_id2)\n rm1b = np.in1d(to_cluster_id1_b, to_cluster_id1) + np.in1d(to_cluster_id1_b, to_cluster_id2)\n rm2b = np.in1d(to_cluster_id2_b, to_cluster_id1) + np.in1d(to_cluster_id2_b, to_cluster_id2)\n\n # remove them from this clustering as they don't go to point 4 but back to point 1\n to_cluster_id1_a = np.delete(to_cluster_id1_a, np.where(rm1a))\n to_cluster_id2_a = np.delete(to_cluster_id2_a, np.where(rm2a))\n to_cluster_id1_b = np.delete(to_cluster_id1_b, np.where(rm1b))\n to_cluster_id2_b = np.delete(to_cluster_id2_b, np.where(rm2b))\n\n # draw all lines that will be considered now\n # for line in to_cluster_id1_a:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 0), 2)\n # for line in to_cluster_id2_a:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 0), 2)\n #\n # for line in to_cluster_id1_b:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 0), 2)\n # for line in to_cluster_id2_b:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 0), 2)\n\n # do two seperate clusterings now\n # cluster a\n to_cluster1 = end[:, to_cluster_id1_a]\n to_cluster2 = start[:, to_cluster_id2_a]\n to_cluster = np.concatenate((to_cluster1, to_cluster2), axis=1)\n\n votes_3a = np.concatenate((votes[to_cluster_id1_a], votes[to_cluster_id2_a]))\n #\n # for i in range(np.shape(to_cluster)[1]):\n # cv2.circle(rgb, (int(to_cluster[0][i]), int(to_cluster[1][i])), 2, (255, 0, 0), 2)\n\n clusters_3a = np.zeros(np.shape(to_cluster)[1])\n cluster = 0\n x_ms_3a = np.array([])\n y_ms_3a = np.array([])\n vote_ms_3a = np.array([])\n\n while not clusters_3a.all():\n cluster = cluster + 1\n s = np.where(clusters_3a == 0)[0][0]\n x_m = to_cluster[0][s]\n y_m = to_cluster[1][s]\n vote_m = votes_3a[s]\n clusters_3a[s] = cluster\n\n for idx in np.where(clusters_3a == 0)[0]:\n x = to_cluster[0][idx]\n y = to_cluster[1][idx]\n vote = votes_3a[idx]\n distance = math.sqrt((x - x_m) ** 2 + (y - y_m) ** 2)\n # print distance\n if distance < dist_thresh:\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n clusters_3a[idx] = cluster\n\n x_ms_3a = np.append(x_ms_3a, x_m)\n y_ms_3a = np.append(y_ms_3a, y_m)\n vote_ms_3a = np.append(vote_ms_3a, vote_m)\n\n if cluster == 0:\n if gate_detection_jungle_on:\n gate_detection_jungle(vote_ms_1, y_ms_1, x_ms_1, lines, clusters_1, start, end, votes, dist_thresh, rgb,\n data, this_pose)\n else:\n rospy.loginfo(\"empty sequence 3a\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n maximum_id_3a = np.argmax(vote_ms_3a)\n\n # find closest original cluster\n x_diff = x_ms_1 - x_ms_3a[maximum_id_3a]\n y_diff = y_ms_1 - y_ms_3a[maximum_id_3a]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id_3a = np.argmax(temp_vote)\n close_id_3a = np.argmin(diff)\n\n corner_points[3, :] = [x_ms_1[close_id_3a], y_ms_1[close_id_3a]]\n\n # cv2.circle(rgb, (int(corner_points[3, 0]), int(corner_points[3, 1])), dist_thresh, (0, 255, 255), 2)\n # cv2.circle(rgb, (int(corner_points[3, 0]), int(corner_points[3, 1])), 2, (0, 255, 255), 2)\n\n # find all lines going from 2.1 to 3a\n # because in the end, algorithm will not use the found corners but the found lines\n close_id_3a = close_id_3a + 1 # to equal cluster number\n lines_cluster_3a_long = np.where(clusters_1 == close_id_3a)[0]\n lines_cluster_3a_short1 = lines_cluster_3a_long[lines_cluster_3a_long < len(lines)]\n lines_cluster_3a_short2 = lines_cluster_3a_long[lines_cluster_3a_long >= len(lines)] - len(lines)\n lines_cluster_3a = np.concatenate((lines_cluster_3a_short1, lines_cluster_3a_short2))\n\n # cluster b\n to_cluster1 = end[:, to_cluster_id1_b]\n to_cluster2 = start[:, to_cluster_id2_b]\n to_cluster = np.concatenate((to_cluster1, to_cluster2), axis=1)\n\n votes_3b = np.concatenate((votes[to_cluster_id1_b], votes[to_cluster_id2_b]))\n #\n # for i in range(np.shape(to_cluster)[1]):\n # cv2.circle(rgb, (int(to_cluster[0][i]), int(to_cluster[1][i])), 2, (255, 0, 0), 2)\n\n clusters_3b = np.zeros(np.shape(to_cluster)[1])\n cluster = 0\n x_ms_3b = np.array([])\n y_ms_3b = np.array([])\n vote_ms_3b = np.array([])\n\n while not clusters_3b.all():\n cluster = cluster + 1\n s = np.where(clusters_3b == 0)[0][0]\n x_m = to_cluster[0][s]\n y_m = to_cluster[1][s]\n vote_m = votes_3b[s]\n clusters_3b[s] = cluster\n\n for idx in np.where(clusters_3b == 0)[0]:\n x = to_cluster[0][idx]\n y = to_cluster[1][idx]\n vote = votes_3b[idx]\n distance = math.sqrt((x - x_m) ** 2 + (y - y_m) ** 2)\n # print distance\n if distance < dist_thresh:\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n clusters_3b[idx] = cluster\n\n x_ms_3b = np.append(x_ms_3b, x_m)\n y_ms_3b = np.append(y_ms_3b, y_m)\n vote_ms_3b = np.append(vote_ms_3b, vote_m)\n\n if cluster == 0:\n if gate_detection_jungle_on:\n gate_detection_jungle(vote_ms_1, y_ms_1, x_ms_1, lines, clusters_1, start, end, votes, dist_thresh, rgb,\n data, this_pose)\n else:\n rospy.loginfo(\"empty sequence 3b\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n maximum_id_3b = np.argmax(vote_ms_3b)\n\n # find closest original cluster\n x_diff = x_ms_1 - x_ms_3b[maximum_id_3b]\n y_diff = y_ms_1 - y_ms_3b[maximum_id_3b]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id_3b = np.argmax(temp_vote)\n close_id_3b = np.argmin(diff)\n\n corner_points[4, :] = [x_ms_1[close_id_3b], y_ms_1[close_id_3b]]\n\n # cv2.circle(rgb, (int(corner_points[4, 0]), int(corner_points[4, 1])), dist_thresh, (0, 0, 255), 2)\n # cv2.circle(rgb, (int(corner_points[4, 0]), int(corner_points[4, 1])), 2, (0, 0, 255), 2)\n\n # find all lines going from 2.2 to 3b\n # because in the end, algorithm will not use the found corners but the found lines\n close_id_3b = close_id_3b + 1 # to equal cluster number\n lines_cluster_3b_long = np.where(clusters_1 == close_id_3b)[0]\n lines_cluster_3b_short1 = lines_cluster_3b_long[lines_cluster_3b_long < len(lines)]\n lines_cluster_3b_short2 = lines_cluster_3b_long[lines_cluster_3b_long >= len(lines)] - len(lines)\n lines_cluster_3b = np.concatenate((lines_cluster_3b_short1, lines_cluster_3b_short2))\n\n # define all lines that were found by algorithm respresenting all 4 sides of gate\n # bascially by intersecting the found line bunches with each other\n lines1 = lines_cluster_1[np.in1d(lines_cluster_1, lines_cluster_2a)]\n lines2 = lines_cluster_1[np.in1d(lines_cluster_1, lines_cluster_2b)]\n lines3 = lines_cluster_2a[np.in1d(lines_cluster_2a, lines_cluster_3a)]\n lines4 = lines_cluster_2b[np.in1d(lines_cluster_2b, lines_cluster_3b)]\n\n # draw lines\n # for line in lines1:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 255, 0), 2)\n # for line in lines2:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 0), 2)\n # for line in lines3:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 255), 2)\n # for line in lines4:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 255, 0), 2)\n\n # make sure 4 line buches have been found, otherwise exit (if jungle special detection is not active)\n if not (lines1.any() and lines2.any() and lines3.any() and lines4.any()):\n if gate_detection_jungle_on:\n gate_detection_jungle(vote_ms_1, y_ms_1, x_ms_1, lines, clusters_1, start, end, votes, dist_thresh, rgb,\n data, this_pose)\n else:\n rospy.loginfo(\"not four lines\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n # intersect the relevant line bunches with each other to find intersection location. These are much more accurate\n # than the corners that have been found so far because these corners are only random start and end points of\n # lines and not their actual intersection\n (x1, y1) = isect_lines_bundle(lines1, lines2, start, end)\n (x2, y2) = isect_lines_bundle(lines1, lines3, start, end)\n (x3, y3) = isect_lines_bundle(lines2, lines4, start, end)\n (x4, y4) = isect_lines_bundle(lines3, lines4, start, end)\n\n # draw all these intersection points\n cv2.circle(rgb, (int(x1), int(y1)), dist_thresh, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x2), int(y2)), dist_thresh, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x3), int(y3)), dist_thresh, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x4), int(y4)), dist_thresh, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x1), int(y1)), 3, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x2), int(y2)), 3, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x3), int(y3)), 3, (0, 255, 255), 2)\n cv2.circle(rgb, (int(x4), int(y4)), 3, (0, 255, 255), 2)\n\n # redefine corner points\n corner_points = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])\n\n # Assume no lens distortion\n dist_coeffs = np.zeros((4, 1))\n\n # apply gate size\n square_side = gate_size\n\n # define 3D model points.\n model_points = np.array([\n (+square_side / 2, +square_side / 2, 0.0),\n (+square_side / 2, -square_side / 2, 0.0),\n (-square_side / 2, +square_side / 2, 0.0),\n (-square_side / 2, -square_side / 2, 0.0)])\n\n # solve Pnp algorithm\n (success, rvec, tvec) = cv2.solvePnP(model_points, corner_points, camera_matrix,\n dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE)\n\n # reduce the dimensions of the result\n rvec = np.squeeze(rvec)\n tvec = np.squeeze(tvec)\n # print \"Rotation Vector:\\n {0}\".format(rvec)\n # print \"Translation Vector:\\n {0}\".format(tvec)\n\n # publish results to gate detection message\n msg = Gate_Detection_Msg()\n msg.tvec = tvec\n msg.rvec = rvec\n msg.bebop_pose = this_pose\n publisher_result.publish(msg)\n rospy.loginfo(\"detected gate\")\n\n rospy.loginfo(\"corner_points\")\n rospy.loginfo(corner_points)\n\n # calculate a line that sticks out of the gate plane\n (center_point_2D_base, _) = cv2.projectPoints(np.array([(.0, .0, 0)]), rvec, tvec, camera_matrix, dist_coeffs)\n (center_point_2D_back, _) = cv2.projectPoints(np.array([(.0, .0, square_side)]), rvec, tvec, camera_matrix,\n dist_coeffs)\n (center_point_2D_frnt, _) = cv2.projectPoints(np.array([(.0, .0, -square_side)]), rvec, tvec, camera_matrix,\n dist_coeffs)\n\n # calculate the points that need to be drawn (backwards PnP basically)\n p1 = (int(center_point_2D_back[0][0][0]), int(center_point_2D_back[0][0][1]))\n p2 = (int(center_point_2D_frnt[0][0][0]), int(center_point_2D_frnt[0][0][1]))\n p3 = (int(center_point_2D_base[0][0][0]), int(center_point_2D_base[0][0][1]))\n\n # if these points make sense, draw them (check is turned off, was required earlier)\n if True or max(p1) < 10000 and max(p2) < 10000 and min(p1) > 0 and min(p2) > 0:\n cv2.line(rgb, p1, p3, (0, 255, 255), 10)\n cv2.line(rgb, p2, p3, (0, 255, 255), 10)\n # draw the center of the gate\n if True or max(p3) < 10000 and min(p3) > 0:\n cv2.circle(rgb, p3, 10, (255, 0, 0), -1)\n\n # do special hand detection\n if gate_detection_dynamic_on:\n\n # use same hsv as before but apply green mask\n mask = mask_image(hsv, \"green\")\n\n # probabilistic hough transform with slightly different parameters\n minlinelength = 70\n maxlinegap = 10\n\n lines = cv2.HoughLinesP(mask, 5, np.pi / 180, 500, minLineLength=minlinelength, maxLineGap=maxlinegap)\n\n # exit if there are no lines found\n if lines is None:\n rospy.loginfo(\"no dynamic lines\")\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n # lines have been found\n # calculate angles of all lines and store their max and mins to create a box around the lines\n angles = []\n # create indexes to weigh good lines higher\n indexes = np.array(list(reversed(range(len(lines)))))+1\n\n gate = p3\n borders = [5000, 0, 5000, 0]\n for counter, line in enumerate(lines):\n for x1, y1, x2, y2 in line:\n angles.append(math.atan2(-(x2 - x1), -(y2 - y1)) + math.pi) # between 0 and pi\n # cv2.line(rgb, (x1, y1), (x2, y2), (0, 0, 255), 2)\n borders[0] = min(borders[0], x1, x2)\n borders[1] = max(borders[1], x1, x2)\n borders[2] = min(borders[2], y1, y2)\n borders[3] = max(borders[3], y1, y2)\n\n angles = np.array(angles)\n # unwrap all these angles\n angles = np.unwrap(angles*2)/2\n\n # average over all lines to get the precise value taking into accound line weights\n angle_m = np.sum(indexes * angles) / np.sum(indexes)\n angle_m = angle_m % math.pi\n\n # the above created angle is in a domain [0,pi] but now needs to be transformed into [0,2pi]. the direction of\n # the lines was lost during hough transformation.\n\n # therefore: find out where angle is approximately\n # 0 degree is upwards position\n # if angle is close to 90 degrees, the hand can be either to the right or the left (so could be 270)\n if abs(angle_m - math.pi/2) < min(abs(angle_m), abs(math.pi-angle_m)): # 90 deg, find out if left or right\n # calculate the pixel distance of the gate to the min and max of the box in x dir that was calculate above\n dist_to_min = abs(borders[0] - gate[0])\n dist_to_max = abs(borders[1] - gate[0])\n if dist_to_min > dist_to_max: # pointer is on the left (90 degrees, so don't do anything)\n pass\n else: # pointer is right (270 degrees, so add 180)\n angle_m = angle_m + math.pi\n else: # 0 or 180 deg, find out if top or bottom\n # distance to min and max in y direction of the box\n dist_to_min = abs(borders[2] - gate[1])\n dist_to_max = abs(borders[3] - gate[1])\n if dist_to_min > dist_to_max: # pointer is up (0), so only add 180 if angle is larger than 90\n if angle_m > math.pi/2:\n angle_m = angle_m + math.pi\n else: # pointer is down (180), so only add 180 if angle is smaller than 90\n if angle_m < math.pi/2:\n angle_m = angle_m + math.pi\n\n # draw dynamic line\n cv2.line(rgb, (gate[0], gate[1]), (\n gate[0] + int(-250 * math.sin(angle_m)), gate[1] + int(-250 * math.cos(angle_m))),\n (0, 0, 255), 6)\n\n # print angle text\n # cv2.putText(rgb, str(angle_m * 180 / math.pi), (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2,\n # cv2.LINE_AA)\n\n # publish finding as [time, angle]\n rospy.loginfo(\"detected pointer\")\n rospy.loginfo(\"angle_m\")\n rospy.loginfo(angle_m)\n msg = Float64MultiArray()\n msg.data = [this_time, angle_m]\n publisher_dynamic.publish(msg)\n\n # if dynamic is not on, but jungle is on, run jungle detection\n elif gate_detection_jungle_on:\n gate_detection_jungle(vote_ms_1, y_ms_1, x_ms_1, lines, clusters_1, start, end, votes, dist_thresh, rgb, data,\n this_pose)\n\n # publish image (no error)\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n\n # plt.pause(0.0001) # pause required so plotting with pyplt works\n # time.sleep(3)\n\n\ndef gate_detection_jungle(vote_ms_1, y_ms_1, x_ms_1, lines, clusters_1, start, end, votes, dist_thresh, rgb, data,\n this_pose):\n # altered for jungle to find second gate. This code is exactly the same as for the first gate, only that\n # not the strongest corner is used but a different oneis used as start.\n\n # use same weighing of clusters\n idx = vote_ms_1 * (800-y_ms_1) / 1000 # * (400-abs(x_ms_1-1280/2))/100000\n max_hor_id = np.argmax(idx) # this is the strongest cluster\n # cut away all clusters in the lower half of the screen and reset their votes to -2\n idx[y_ms_1 > 360] = -2\n # cut away all clusters near and above the maximum horiontal line\n idx[y_ms_1 < y_ms_1[max_hor_id]+50] = -1\n\n #\n # for index in range(len(vote_ms_1)):\n # cv2.circle(rgb, (int(x_ms_1[index]), int(y_ms_1[index])), dist_thresh, (255, 255, 255), 2)\n # cv2.putText(rgb, str(int(idx[index])), (int(x_ms_1[index]), int(y_ms_1[index])), cv2.FONT_HERSHEY_SIMPLEX,\n# 1, (255, 255, 255), 2, cv2.LINE_AA)\n\n # now the remaining strongest corner belongs to the 2nd strongest gate in the frame. From here, everything is the\n # same besides the color of drawing the final gate into the image. For comments, see above\n max_cluster = np.argmax(idx) + 1\n\n corner_points = np.zeros((5, 2))\n corner_points[0, :] = [x_ms_1[max_cluster - 1], y_ms_1[max_cluster - 1]]\n\n # cv2.circle(rgb, (int(corner_points[0, 0]), int(corner_points[0, 1])), dist_thresh, (255, 0, 0), 2)\n # cv2.circle(rgb, (int(corner_points[0, 0]), int(corner_points[0, 1])), 2, (255, 0, 0), 2)\n\n # find lines originating from this cluster and recluster its endpoints\n to_cluster_id = np.where(clusters_1 == max_cluster)[0]\n to_cluster_id1 = to_cluster_id[to_cluster_id < len(lines)]\n to_cluster_id2 = to_cluster_id[to_cluster_id >= len(lines)] - len(lines)\n lines_cluster_1 = np.concatenate((to_cluster_id1, to_cluster_id2))\n\n #\n # for line in to_cluster_id1:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 255), 2)\n # for line in to_cluster_id2:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 255), 2)\n\n to_cluster1 = end[:, to_cluster_id1]\n to_cluster2 = start[:, to_cluster_id2]\n to_cluster = np.concatenate((to_cluster1, to_cluster2), axis=1)\n votes_2 = np.concatenate((votes[to_cluster_id1], votes[to_cluster_id2]))\n\n clusters_2 = np.zeros(np.shape(to_cluster)[1])\n cluster = 0\n x_ms_2 = np.array([])\n y_ms_2 = np.array([])\n vote_ms_2 = np.array([])\n\n while not clusters_2.all():\n cluster = cluster + 1\n s = np.where(clusters_2 == 0)[0][0]\n x_m = to_cluster[0][s]\n y_m = to_cluster[1][s]\n vote_m = votes_2[s]\n clusters_2[s] = cluster\n\n for idx in np.where(clusters_2 == 0)[0]:\n x = to_cluster[0][idx]\n y = to_cluster[1][idx]\n vote = votes_2[idx]\n distance = math.sqrt((x - x_m) ** 2 + (y - y_m) ** 2)\n # print distance\n if distance < dist_thresh:\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n clusters_2[idx] = cluster\n\n x_ms_2 = np.append(x_ms_2, x_m)\n y_ms_2 = np.append(y_ms_2, y_m)\n vote_ms_2 = np.append(vote_ms_2, vote_m)\n\n if cluster < 2:\n rospy.loginfo(\"empty sequence 2\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n maximum_ids = vote_ms_2.argsort()[-2:][::-1]\n\n # find closest original clusters\n x_diff = x_ms_1 - x_ms_2[maximum_ids[0]]\n y_diff = y_ms_1 - y_ms_2[maximum_ids[0]]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id1 = np.argmax(temp_vote)\n close_id1 = np.argmin(diff)\n\n x_diff = x_ms_1 - x_ms_2[maximum_ids[1]]\n y_diff = y_ms_1 - y_ms_2[maximum_ids[1]]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id2 = np.argmax(temp_vote)\n close_id2 = np.argmin(diff)\n\n corner_points[1, :] = [x_ms_1[close_id1], y_ms_1[close_id1]]\n corner_points[2, :] = [x_ms_1[close_id2], y_ms_1[close_id2]]\n\n # cv2.circle(rgb, (int(corner_points[1, 0]), int(corner_points[1, 1])), dist_thresh, (0, 255, 0), 2)\n # cv2.circle(rgb, (int(corner_points[2, 0]), int(corner_points[2, 1])), dist_thresh, (0, 255, 0), 2)\n # cv2.circle(rgb, (int(corner_points[1, 0]), int(corner_points[1, 1])), 2, (0, 255, 0), 2)\n # cv2.circle(rgb, (int(corner_points[2, 0]), int(corner_points[2, 1])), 2, (0, 255, 0), 2)\n\n # find lines originating from two median points and recluster its endpoints into two clusters\n close_id1 = close_id1 + 1 # to equal cluster number\n close_id2 = close_id2 + 1 # to equal cluster number\n\n lines_cluster_2a_long = np.where(clusters_1 == close_id1)[0]\n lines_cluster_2b_long = np.where(clusters_1 == close_id2)[0]\n\n to_cluster_id1_a = lines_cluster_2a_long[lines_cluster_2a_long < len(lines)]\n to_cluster_id2_a = lines_cluster_2a_long[lines_cluster_2a_long >= len(lines)] - len(lines)\n to_cluster_id1_b = lines_cluster_2b_long[lines_cluster_2b_long < len(lines)]\n to_cluster_id2_b = lines_cluster_2b_long[lines_cluster_2b_long >= len(lines)] - len(lines)\n\n lines_cluster_2a = np.concatenate((to_cluster_id1_a, to_cluster_id2_a))\n lines_cluster_2b = np.concatenate((to_cluster_id1_b, to_cluster_id2_b))\n\n rm1a = np.in1d(to_cluster_id1_a, to_cluster_id1) + np.in1d(to_cluster_id1_a, to_cluster_id2)\n rm2a = np.in1d(to_cluster_id2_a, to_cluster_id1) + np.in1d(to_cluster_id2_a, to_cluster_id2)\n rm1b = np.in1d(to_cluster_id1_b, to_cluster_id1) + np.in1d(to_cluster_id1_b, to_cluster_id2)\n rm2b = np.in1d(to_cluster_id2_b, to_cluster_id1) + np.in1d(to_cluster_id2_b, to_cluster_id2)\n\n to_cluster_id1_a = np.delete(to_cluster_id1_a, np.where(rm1a))\n to_cluster_id2_a = np.delete(to_cluster_id2_a, np.where(rm2a))\n to_cluster_id1_b = np.delete(to_cluster_id1_b, np.where(rm1b))\n to_cluster_id2_b = np.delete(to_cluster_id2_b, np.where(rm2b))\n\n # for line in to_cluster_id1_a:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 0), 2)\n # for line in to_cluster_id2_a:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 0, 0), 2)\n #\n # for line in to_cluster_id1_b:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 0), 2)\n # for line in to_cluster_id2_b:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 0), 2)\n\n # cluster a\n to_cluster1 = end[:, to_cluster_id1_a]\n to_cluster2 = start[:, to_cluster_id2_a]\n to_cluster = np.concatenate((to_cluster1, to_cluster2), axis=1)\n\n votes_3a = np.concatenate((votes[to_cluster_id1_a], votes[to_cluster_id2_a]))\n #\n # for i in range(np.shape(to_cluster)[1]):\n # cv2.circle(rgb, (int(to_cluster[0][i]), int(to_cluster[1][i])), 2, (255, 0, 0), 2)\n\n clusters_3a = np.zeros(np.shape(to_cluster)[1])\n cluster = 0\n x_ms_3a = np.array([])\n y_ms_3a = np.array([])\n vote_ms_3a = np.array([])\n\n while not clusters_3a.all():\n cluster = cluster + 1\n s = np.where(clusters_3a == 0)[0][0]\n x_m = to_cluster[0][s]\n y_m = to_cluster[1][s]\n vote_m = votes_3a[s]\n clusters_3a[s] = cluster\n\n for idx in np.where(clusters_3a == 0)[0]:\n x = to_cluster[0][idx]\n y = to_cluster[1][idx]\n vote = votes_3a[idx]\n distance = math.sqrt((x - x_m) ** 2 + (y - y_m) ** 2)\n # print distance\n if distance < dist_thresh:\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n clusters_3a[idx] = cluster\n\n x_ms_3a = np.append(x_ms_3a, x_m)\n y_ms_3a = np.append(y_ms_3a, y_m)\n vote_ms_3a = np.append(vote_ms_3a, vote_m)\n\n if cluster == 0:\n rospy.loginfo(\"empty sequence 3a\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n maximum_id_3a = np.argmax(vote_ms_3a)\n\n # find closest original cluster\n x_diff = x_ms_1 - x_ms_3a[maximum_id_3a]\n y_diff = y_ms_1 - y_ms_3a[maximum_id_3a]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id_3a = np.argmax(temp_vote)\n close_id_3a = np.argmin(diff)\n\n corner_points[3, :] = [x_ms_1[close_id_3a], y_ms_1[close_id_3a]]\n\n # cv2.circle(rgb, (int(corner_points[3, 0]), int(corner_points[3, 1])), dist_thresh, (0, 255, 255), 2)\n # cv2.circle(rgb, (int(corner_points[3, 0]), int(corner_points[3, 1])), 2, (0, 255, 255), 2)\n\n # find lines going to two endpoints\n close_id_3a = close_id_3a + 1 # to equal cluster number\n lines_cluster_3a_long = np.where(clusters_1 == close_id_3a)[0]\n lines_cluster_3a_short1 = lines_cluster_3a_long[lines_cluster_3a_long < len(lines)]\n lines_cluster_3a_short2 = lines_cluster_3a_long[lines_cluster_3a_long >= len(lines)] - len(lines)\n lines_cluster_3a = np.concatenate((lines_cluster_3a_short1, lines_cluster_3a_short2))\n\n # cluster b\n to_cluster1 = end[:, to_cluster_id1_b]\n to_cluster2 = start[:, to_cluster_id2_b]\n to_cluster = np.concatenate((to_cluster1, to_cluster2), axis=1)\n\n votes_3b = np.concatenate((votes[to_cluster_id1_b], votes[to_cluster_id2_b]))\n #\n # for i in range(np.shape(to_cluster)[1]):\n # cv2.circle(rgb, (int(to_cluster[0][i]), int(to_cluster[1][i])), 2, (255, 0, 0), 2)\n\n clusters_3b = np.zeros(np.shape(to_cluster)[1])\n cluster = 0\n x_ms_3b = np.array([])\n y_ms_3b = np.array([])\n vote_ms_3b = np.array([])\n\n while not clusters_3b.all():\n cluster = cluster + 1\n s = np.where(clusters_3b == 0)[0][0]\n x_m = to_cluster[0][s]\n y_m = to_cluster[1][s]\n vote_m = votes_3b[s]\n clusters_3b[s] = cluster\n\n for idx in np.where(clusters_3b == 0)[0]:\n x = to_cluster[0][idx]\n y = to_cluster[1][idx]\n vote = votes_3b[idx]\n distance = math.sqrt((x - x_m) ** 2 + (y - y_m) ** 2)\n # print distance\n if distance < dist_thresh:\n x_m = (x_m * vote_m + x * vote) / (vote_m + vote)\n y_m = (y_m * vote_m + y * vote) / (vote_m + vote)\n vote_m = vote_m + vote\n clusters_3b[idx] = cluster\n\n x_ms_3b = np.append(x_ms_3b, x_m)\n y_ms_3b = np.append(y_ms_3b, y_m)\n vote_ms_3b = np.append(vote_ms_3b, vote_m)\n\n if cluster == 0:\n rospy.loginfo(\"empty sequence 3b\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n maximum_id_3b = np.argmax(vote_ms_3b)\n\n # find closest original cluster\n x_diff = x_ms_1 - x_ms_3b[maximum_id_3b]\n y_diff = y_ms_1 - y_ms_3b[maximum_id_3b]\n diff = x_diff * x_diff + y_diff * y_diff\n # temp_vote = vote_ms_1.copy()\n # for index in range(len(temp_vote)):\n # if diff[index] > relocate_factor * relocate_factor * dist_thresh * dist_thresh:\n # temp_vote[index] = 0\n # close_id_3b = np.argmax(temp_vote)\n close_id_3b = np.argmin(diff)\n\n corner_points[4, :] = [x_ms_1[close_id_3b], y_ms_1[close_id_3b]]\n\n # cv2.circle(rgb, (int(corner_points[4, 0]), int(corner_points[4, 1])), dist_thresh, (0, 0, 255), 2)\n # cv2.circle(rgb, (int(corner_points[4, 0]), int(corner_points[4, 1])), 2, (0, 0, 255), 2)\n\n # find lines going to two endpoints\n close_id_3b = close_id_3b + 1 # to equal cluster number\n lines_cluster_3b_long = np.where(clusters_1 == close_id_3b)[0]\n lines_cluster_3b_short1 = lines_cluster_3b_long[lines_cluster_3b_long < len(lines)]\n lines_cluster_3b_short2 = lines_cluster_3b_long[lines_cluster_3b_long >= len(lines)] - len(lines)\n lines_cluster_3b = np.concatenate((lines_cluster_3b_short1, lines_cluster_3b_short2))\n\n # intersect all lines that go together\n lines1 = lines_cluster_1[np.in1d(lines_cluster_1, lines_cluster_2a)]\n lines2 = lines_cluster_1[np.in1d(lines_cluster_1, lines_cluster_2b)]\n lines3 = lines_cluster_2a[np.in1d(lines_cluster_2a, lines_cluster_3a)]\n lines4 = lines_cluster_2b[np.in1d(lines_cluster_2b, lines_cluster_3b)]\n\n # for line in lines1:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (0, 255, 0), 2)\n # for line in lines2:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 0), 2)\n # for line in lines3:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 0, 255), 2)\n # for line in lines4:\n # cv2.line(rgb, (start[0][line], start[1][line]), (end[0][line], end[1][line]), (255, 255, 0), 2)\n\n if not (lines1.any() and lines2.any() and lines3.any() and lines4.any()):\n rospy.loginfo(\"not four lines\")\n publisher_result.publish(Gate_Detection_Msg())\n rgb = cv2.resize(rgb, (0, 0), fx=output_scale, fy=output_scale)\n output_im = bridge.cv2_to_imgmsg(rgb, encoding=data.encoding)\n publisher_image_gate.publish(output_im)\n return\n\n (x1, y1) = isect_lines_bundle(lines1, lines2, start, end)\n (x2, y2) = isect_lines_bundle(lines1, lines3, start, end)\n (x3, y3) = isect_lines_bundle(lines2, lines4, start, end)\n (x4, y4) = isect_lines_bundle(lines3, lines4, start, end)\n\n cv2.circle(rgb, (int(x1), int(y1)), dist_thresh, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x2), int(y2)), dist_thresh, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x3), int(y3)), dist_thresh, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x4), int(y4)), dist_thresh, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x1), int(y1)), 3, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x2), int(y2)), 3, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x3), int(y3)), 3, (255, 255, 255), 2)\n cv2.circle(rgb, (int(x4), int(y4)), 3, (255, 255, 255), 2)\n\n corner_points = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])\n\n # Assume no lens distortion\n dist_coeffs = np.zeros((4, 1))\n\n square_side = gate_size\n\n # 3D model points\n model_points = np.array([\n (+square_side / 2, +square_side / 2, 0.0),\n (+square_side / 2, -square_side / 2, 0.0),\n (-square_side / 2, +square_side / 2, 0.0),\n (-square_side / 2, -square_side / 2, 0.0)])\n (success, rvec, tvec) = cv2.solvePnP(model_points, corner_points, camera_matrix,\n dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE)\n\n rvec = np.squeeze(rvec)\n tvec = np.squeeze(tvec)\n # print \"Rotation Vector:\\n {0}\".format(rvec)\n # print \"Translation Vector:\\n {0}\".format(tvec)\n\n # publish results\n msg = Gate_Detection_Msg()\n msg.tvec = tvec\n msg.rvec = rvec\n msg.bebop_pose = this_pose\n publisher_result.publish(msg)\n rospy.loginfo(\"detected gate\")\n\n rospy.loginfo(\"corner_points\")\n rospy.loginfo(corner_points)\n\n # draw a line sticking out of the plane\n (center_point_2D_base, _) = cv2.projectPoints(np.array([(.0, .0, 0)]), rvec, tvec, camera_matrix, dist_coeffs)\n (center_point_2D_back, _) = cv2.projectPoints(np.array([(.0, .0, square_side)]), rvec, tvec, camera_matrix,\n dist_coeffs)\n (center_point_2D_frnt, _) = cv2.projectPoints(np.array([(.0, .0, -square_side)]), rvec, tvec, camera_matrix,\n dist_coeffs)\n\n p1 = (int(center_point_2D_back[0][0][0]), int(center_point_2D_back[0][0][1]))\n p2 = (int(center_point_2D_frnt[0][0][0]), int(center_point_2D_frnt[0][0][1]))\n p3 = (int(center_point_2D_base[0][0][0]), int(center_point_2D_base[0][0][1]))\n\n if True or max(p1) < 10000 and max(p2) < 10000 and min(p1) > 0 and min(p2) > 0:\n cv2.line(rgb, p1, p3, (255, 255, 255), 10)\n cv2.line(rgb, p2, p3, (255, 255, 255), 10)\n if True or max(p3) < 10000 and min(p3) > 0:\n cv2.circle(rgb, p3, 10, (0, 0, 0), -1)\n\n\ndef pose_callback(data):\n # update odometry\n global latest_pose\n latest_pose = data.pose.pose\n\n\ndef camera_info_update(data):\n # update camera matrix\n global camera_matrix\n camera_matrix = np.resize(np.asarray(data.K), [3, 3])\n\n\ndef callback_dynamic_detection_changed(data):\n # update special detection dynamic\n global gate_detection_dynamic_on\n gate_detection_dynamic_on = data.data\n\n\ndef callback_jungle_detection_changed(data):\n # update special detection jungle\n global gate_detection_jungle_on\n gate_detection_jungle_on = data.data\n\n\ndef callback_gate_size_changed(data):\n # update gate size\n global gate_size\n gate_size = data.data\n\n\ndef emergency_shutdown(_):\n # shutdown for faster emergency intervention. After this signal, the node terminates itself so manual control can be\n # obtained\n rospy.loginfo(\"emergency shutdown\")\n rospy.signal_shutdown(\"emergency shutdown\")\n\n\ndef callback_orange_values(data):\n # update gate color thresholds\n global orange_low\n global orange_high\n orange_low = np.array(data.data[:3])\n orange_high = np.array(data.data[3:])\n\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, signal_handler)\n\n # initialize node\n rospy.init_node('gate_detection', anonymous=False)\n\n # variables\n camera_matrix = None # np.array([[669.86121, 0.0, 629.62378], [0.0, 669.86121, 384.62851], [0.0, 0.0, 1.0]])\n latest_pose = None # latest odometry\n gate_detection_dynamic_on = False # special gate detection bool (dynamic)\n gate_detection_jungle_on = False # special gate detection bool (jungle)\n gate_size = 1.4 # initial gate size\n output_scale = 0.1 # factor to scale all images with before broadcasting to save bandwidth\n orange_low = np.array([100, 130, 50]) # some original orange values\n orange_high = np.array([130, 255, 255])\n # a factor currently not used for finding nearest cluster but allowing relocation if further clusters are much\n # stonger\n # relocate_factor = 1.5\n\n # initialize bridge to transform ROS images to CV matrices\n bridge = CvBridge()\n\n # subscribers\n rospy.Subscriber(\"/zed/rgb/camera_info\", CameraInfo, camera_info_update)\n rospy.Subscriber(\"/zed/rgb/image_rect_color\", Image, stereo_callback)\n rospy.Subscriber(\"/bebop/odom\", Odometry, pose_callback)\n rospy.Subscriber(\"/auto/dynamic_detection_on\", Bool, callback_dynamic_detection_changed)\n rospy.Subscriber(\"/auto/jungle_detection_on\", Bool, callback_jungle_detection_changed)\n rospy.Subscriber(\"/auto/gate_size\", Float32, callback_gate_size_changed)\n rospy.Subscriber(\"/auto/emergency_shutdown\", Empty, emergency_shutdown)\n rospy.Subscriber(\"/auto/gate_color\", Float32MultiArray, callback_orange_values)\n\n # publishers\n publisher_image_threshold_orange = rospy.Publisher(\"/auto/gate_detection_threshold_orange\", Image, queue_size=1)\n publisher_image_threshold_dynamic = rospy.Publisher(\"/auto/gate_detection_threshold_dynamic\", Image, queue_size=1)\n publisher_image_gate = rospy.Publisher(\"/auto/gate_detection_gate\", Image, queue_size=1)\n publisher_result = rospy.Publisher(\"/auto/gate_detection_result\", Gate_Detection_Msg, queue_size=1)\n publisher_dynamic = rospy.Publisher(\"/auto/gate_detection_result_dynamic\", Float64MultiArray, queue_size=1)\n\n rospy.loginfo(\"running\")\n rospy.spin()\n","sub_path":"scripts/gate_detection.py","file_name":"gate_detection.py","file_ext":"py","file_size_in_byte":59561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"532652152","text":"#!/usr/bin/python\nimport multiprocessing\nfrom multiprocessing import Queue, Pool\nimport os\nimport time\nimport re\nimport csv\nimport argparse\n\n\nq = Queue()\n\ndef powerDownContainer (command):\n os.system(command)\n\ndef powerDownContainers ( vch_Ips):\n\n dockerStopCommands = []\n for vchIp in vch_Ips:\n deleteCommand = \"docker -H \" + vchIp + \":2376 --tls stop $(docker -H \" + vchIp + \":2376 --tls ps -a -q)\"\n print (deleteCommand)\n dockerStopCommands.append ( deleteCommand )\n\n p = multiprocessing.Pool(len(dockerStopCommands))\n p.map( powerDownContainer , dockerStopCommands )\n\ndef create_VCH(cmd ):\n\n vchInfo =[]\n ts=time.time()\n vch=cmd.split()[-1:] #extracting VCH name from the script\n print(vch[0])\n vchInfo.append(vch[0])\n vchInfo.append(ts)\n\n start_time=time.time()\n outpu=str(os.system(cmd+\">/dev/null\"))\n elapsed_time=time.time() - start_time\n\n vchInfo.append(elapsed_time)\n q.put(vchInfo)\n\ndef delete_VCH(cmd):\n\n vchInfo =[]\n ts=time.time()\n vch=cmd.split()[-1:]\n print(vch[0])\n vchInfo.append(vch[0])\n vchInfo.append(ts)\n\n start_time=time.time()\n outpu=str(os.system(cmd+\" > /dev/null\"))\n elapsed_time=time.time() - start_time\n\n vchInfo.append(elapsed_time)\n q.put(vchInfo)\n \n\ndef createParallelVCHS( file_name ):\n\n \n with open(file_name) as f:\n createCommands = [line.rstrip('\\n') for line in f]\n\n num_lines = len(createCommands)\n p = multiprocessing.Pool(num_lines)\n p.map(create_VCH, createCommands )\n p.close()\n p.join()\n vch_time = []\n while not q.empty():\n vch_time.append(q.get())\n return vch_time \n\ndef createSequentialVCHS ( file_name ):\n\n f = open( file_name )\n createCommands = [line.rstrip('\\n') for line in f]\n \n vch_time = [] \n for comm in createCommands:\n vchInfo =[]\n ts=time.time()\n vch= comm.split()[-1:] #extracting VCH name from the script\n #print(vch[0])\n vchInfo.append(vch[0])\n vchInfo.append(ts)\n\n start_time=time.time()\n outpu=str(os.system(comm +\">/dev/null\"))\n elapsed_time=time.time() - start_time\n\n vchInfo.append(elapsed_time)\n vch_time.append(vchInfo)\n\n return (vch_time)\n \ndef deleteParallelVCHS( file_name ):\n\n \n f = open ( file_name )\n vchNames = [line.rstrip('\\n').split()[-1:] for line in f]\n \n if file_name != \"50VchDeploy.txt\" and file_name != \"10VCHDeploy.txt\" and file_name != \"1VCHDeploy.txt\":\n f.seek(0,0)\n start = 'network-ip '\n end = '/23'\n vchIps = [line.rstrip('\\n').split(start)[1].split(end)[0] for line in f]\n print (vchIps)\n f.close()\n powerDownContainers ( vchIps)\n \n deleteCommand = \"./vic-machine-linux delete -t administrator@vsphere.local:Admin!23@w2hs2-vrops08.eng.vmware.com/Datacenter -r \\\n Cluster/Resources --thumbprint 24:16:40:23:D8:F9:D4:9D:16:65:10:E3:E5:D6:2B:0F:10:26:4C:FA --timeout 40m -n \"\n\n deleteCommands = []\n for vch in vchNames:\n deleteCommands.append( deleteCommand + vch[0] ) \n\n num_lines = len(deleteCommands)\n\n p = multiprocessing.Pool(num_lines)\n p.map(delete_VCH, deleteCommands )\n p.close()\n p.join()\n\n vch_time = []\n while not q.empty():\n vch_time.append(q.get())\n\n return (vch_time)\n\ndef deleteSequentialVCHS ( file_name ):\n\n f = open( file_name )\n vchNames = [line.rstrip('\\n').split()[-1:] for line in f]\n f.seek(0,0)\n start = 'network-ip '\n end = '/23'\n vchIps = [line.rstrip('\\n').split(start)[1].split(end)[0] for line in f]\n f.close()\n powerDownContainers ( vchIps )\n\n deleteCommand = \"./vic-machine-linux delete -t administrator@vsphere.local:Admin!23@w2hs2-vrops08.eng.vmware.com/Datacenter -r \\\n Cluster/Resources --thumbprint 24:16:40:23:D8:F9:D4:9D:16:65:10:E3:E5:D6:2B:0F:10:26:4C:FA --timeout 40m -n \"\n \n vch_time = []\n for vch in vchNames:\n vchName = vch[0]\n command = deleteCommand + vchName \n vchInfo =[]\n ts=time.time()\n vchInfo.append(vchName )\n vchInfo.append(ts)\n\n start_time=time.time()\n outpu=str(os.system(command + \" >/dev/null\"))\n elapsed_time=time.time() - start_time\n\n vchInfo.append(elapsed_time)\n vch_time.append(vchInfo)\n\n return ( vch_time )\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Create or delete VCH.')\n parser.add_argument(\"-f\", \"--filename\", help=\"input file\", required=True)\n parser.add_argument(\"-a\", \"--action\", help= \"create or delete \", required=True)\n parser.add_argument(\"-e\", \"--execution\", help= \"parallel or sequential\", required=True)\n\n args = vars ( parser.parse_args())\n\n fname = args[\"filename\"]\n action = args[\"action\"]\n execution = args [\"execution\"]\n filetime = str(time.strftime('%l-%M%p-%b%d-%Y')).strip()\n \n if \"create\" in action and \"parallel\" in execution:\n\n outputfname= filetime + \"-\" + fname.split('.')[0] + \"-parallel-create.csv\" \n vch_time = createParallelVCHS (fname)\n\n elif \"create\" in action and \"sequential\" in execution:\n \n vch_time = createSequentialVCHS ( file_name )\n outputfname= filetime + \"-\" + fname.split('.')[0] + \"-sequential-create.csv\"\n\n elif \"delete\" in action and \"sequential\" in execution:\n\n vch_time = deleteSequentialVCHS (fname)\n outputfname= filetime + \"-\" + fname.split('.')[0] + \"-sequential-delete.csv\"\n\n elif \"delete\" in action and \"parallel\" in execution:\n\n vch_time = deleteParallelVCHS (fname)\n outputfname= filetime + \"-\" + fname.split('.')[0] + \"-parallel-delete.csv\"\n\n\n with open(\"/home/vmlib/VIC/OPTIME/operationTimeCSV/\" + outputfname , 'w' ) as wfile:\n writer = csv.writer(wfile)\n header=['VCH_Name','UTC','time']\n writer.writerow(header)\n writer.writerows(vch_time)\n\nif __name__ == \"__main__\":\n\n main()","sub_path":"VicOnJenkins/NSXV/execVCH_proc.py","file_name":"execVCH_proc.py","file_ext":"py","file_size_in_byte":5957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"249430792","text":"from zope.interface import Interface, Attribute\nfrom zope.configuration import fields\nfrom zope import schema\n\nclass IRegion(Interface):\n \"\"\"Represents a region definition for a template.\"\"\"\n\n name = schema.TextLine(\n title=u\"Name of region.\",\n required=True)\n \n xpath = schema.TextLine(\n title=u\"X-path expression for this region\",\n required=True)\n\n title = schema.TextLine(\n title=u\"Title\",\n required=False)\n\n mode = schema.Choice(\n (u\"replace\", u\"append\", u\"prepend\", u\"before\", u\"after\"),\n default=u\"replace\",\n required=False)\n \n provider = schema.TextLine(\n title=u\"Content provider\",\n description=u\"Name of the content provider component to render this region.\",\n required=False)\n\nclass ILayout(Interface):\n \"\"\"A layout is a template with region definitions.\"\"\"\n\n name = schema.TextLine(\n title=u\"Title\")\n \n template = fields.Path(\n title=u\"Template\")\n\n regions = schema.Set(\n title=u\"Regions that are defined in this layout.\",\n value_type=schema.Object(schema=IRegion),\n required=False)\n\n def parse():\n \"\"\"Parse template using lxml's HTML parser class. Transforms\n are applied before the tree is returned.\"\"\"\n\nclass IContentProviderFactory(Interface):\n def __call__(context, request, view):\n \"\"\"Return content provider.\"\"\"\n","sub_path":"z3c.layout/trunk/src/z3c/layout/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"324809419","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom model import Net\nfrom data_loader import get_dataloader\n\nfrom tqdm import tqdm\n\n\n# gpu対応\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# データローダーの定義\ntrain_loader = get_dataloader(dataset='mnist', datatype='train')\ntest_loader = get_dataloader(dataset='mnist', datatype='test')\n\nnet = Net().to(device)\n\n# 最適化の目的関数の定義\nobject_func = nn.CrossEntropyLoss()\n\n# 最適化手法の選択\noptimizer = optim.Adam(net.parameters(), lr=0.001)\n\n\n#--- TRAIN ---#\nepoch_n = 10\nverbose = True\nverbose_step = 100\n\n\nfor epoch in tqdm(range(epoch_n)):\n # 損失(表示用)\n running_loss = 0.0\n for i, (X_train, y_train) in enumerate(train_loader):\n X_train, y_train = X_train.to(device), y_train.to(device)\n # 勾配初期化\n optimizer.zero_grad()\n # forward\n outputs = net(X_train)\n # 損失計算\n loss = object_func(outputs, y_train)\n # ↑ここまでで計算グラフの構築が行われ、勾配に使う情報が設定される\n # 勾配計算\n loss.backward()\n # パラメータ更新\n optimizer.step()\n # lossの更新\n running_loss += loss.item()\n\n if verbose and ((i + 1) % verbose_step == 0):\n print(f'epoch:{epoch + 1}, batch:{i + 1}, '\n + f'loss: {running_loss / verbose_step}')\n running_loss = 0.0\n\n\n#--- TEST ---#\n\ncorrect_n = 0\ntotal_n = 0\n\n# 予測時には勾配更新をしない\nwith torch.no_grad():\n for (X_test, y_test) in test_loader:\n X_test, y_test = X_test.to(device), y_test.to(device)\n outputs = net(X_test) # 更に、nn.functional.softmax() すると確率が得られる\n # torch.max() -> return (最大値, そのindex)\n _, predicted = torch.max(outputs.data, dim=1)\n total_n += y_test.size(0)\n correct_n += (predicted == y_test).sum().item()\nprint(f'Accuracy for test data: {100 * float(correct_n/total_n)}')\n","sub_path":"PyTorch_base/train_and_val.py","file_name":"train_and_val.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"43136364","text":"#%%\nimport pandas as pd\nimport os\n\n# %%\ncwd = os.getcwd()\ndata_path = os.path.join(cwd, 'dataset')\ndata_path = os.path.join(data_path, 'train.csv')\nprint(data_path)\n\n# %%\ndf = pd.read_csv(data_path)\ndf.head()\n\n# %%\ndf.describe()\n\n# %%\ndf.info()\n\n# %%\n# %matplotlib inline\n#from matplotlib import pyplot as plt\n#df.hist(bins=50, figsize=(20,15))\n#plt.show()\n\n# %%\n# Split training and testing data.\nfrom sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(df, test_size=0.05, random_state=42)\n\n#%%\ntrain_set, val_set = train_test_split(train_set, test_size=0.1, random_state=42)\n\n\n# %%\nprint(len(train_set))\nprint(len(val_set))\nprint(len(test_set))\n\n# %%\ntrain_set.head()\n\n# %%\n# Create age category.\nm = {'child':0, 'adult':1}\ntrain_set['Age_Cat'] = pd.cut(train_set['Age'], bins=[0,15,max(train_set['Age']+1)],\nlabels=['child','adult']).map(m).fillna(1).astype(int)\ntest_set['Age_Cat'] = pd.cut(test_set['Age'], bins=[0,15,max(test_set['Age']+1)],\nlabels=['child','adult']).map(m).fillna(1).astype(int)\nval_set['Age_Cat'] = pd.cut(val_set['Age'], bins=[0,15,max(val_set['Age']+1)],\nlabels=['child','adult']).map(m).fillna(1).astype(int)\n\n# %%\n# Convert male female to 0s and 1s\nm = {'male':0,'female':1}\ntrain_set['Sex'] = train_set['Sex'].map(m)\ntest_set['Sex'] = test_set['Sex'].map(m)\nval_set['Sex'] = val_set['Sex'].map(m)\n\n#%%\n# Create family size\ntrain_set['Family_Size'] = train_set['Parch'] + train_set['SibSp'] + 1\n\n#%%\ntest_set['Family_Size'] = test_set['Parch'] + test_set['SibSp'] + 1\nval_set['Family_Size'] = val_set['Parch'] + val_set['SibSp'] + 1\n\n# %%\n# Extract miss, mr etc from name and map them to numbers.\nname = train_set['Name']\n\n#%%\ntrain_set['Title'] = train_set['Name'].map(lambda name:name.split(',')[1].split('.')[0].strip())\ntest_set['Title'] = test_set['Name'].map(lambda name:name.split(',')[1].split('.')[0].strip())\nval_set['Title'] = val_set['Name'].map(lambda name:name.split(',')[1].split('.')[0].strip())\n\n# %%\nfeatures = ['Family_Size', 'Pclass','Sex','Age','Parch','Age_Cat', 'Title','Embarked']\nX_train = train_set[features]\nY_train = train_set['Survived']\n\n# %%\nX_val = val_set[features]\nY_val = val_set['Survived']\n\n# %%\nX_test = test_set[features]\nY_test = test_set['Survived']\n\n# %%\nX_train.head()\n\n#%%\nemb_map = {\n 'S': 0,\n 'Q': 1,\n 'C': 2\n}\n\ntitle_map = {\n 'Miss':0, \n 'Mlle':5, \n 'Mr':1, \n 'Mrs':2, \n 'Master':3, \n 'Dr':5, \n 'Lady':5, \n 'Capt':5,\n 'Major':5, \n 'Mme':5, \n 'Rev':5, \n 'Sir':5, \n 'Jonkheer':5, \n 'Col':5, \n 'Ms':4\n}\n\nX_train['Title'] = X_train['Title'].map(title_map)\nX_train['Embarked'] = X_train['Embarked'].map(emb_map)\nX_train.head()\n\n#%%\nX_test['Title'] = X_test['Title'].map(title_map)\nX_val['Embarked'] = X_val['Embarked'].map(emb_map)\n\n#%%\nX_val['Title'] = X_val['Title'].map(title_map)\nX_test['Embarked'] = X_test['Embarked'].map(emb_map)\n\n# %%\ndef normalize(X):\n mean = X.mean()\n print(mean)\n\n X = X.fillna(mean)\n \n std = X.std()\n print(std)\n \n X = (X - mean)/std\n return X\n\n# %%\nnorm_X_train = normalize(X_train)\n\n#%%\nnorm_X_val = normalize(X_val)\n\n# %%\nimport numpy as np\nnorm_X_train = np.array(norm_X_train)\nnorm_X_val = np.array(norm_X_val)\n\n# %%\nprint(norm_X_train.shape)\nprint(norm_X_val.shape)\n\n# %%\nprint(Y_train.shape)\nprint(Y_val.shape)\n\n# %%\nfrom model import TitanicModel\nmdl = TitanicModel()\nmodel = mdl.train_with_keras_model(norm_X_train,Y_train,norm_X_val,Y_val,50,64,0.01)\n\n# %%\npreds = model.predict(X_test)\nprint(preds)","sub_path":"Titanic - Machine Learning from Disaster/notebook.py","file_name":"notebook.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"363614796","text":"import logging\n\nimport requests\n\n\nclass JiraController(object):\n def __init__(self, jira_auth, jira_project):\n logging.basicConfig(level=logging.INFO)\n\n self.jira_auth = jira_auth\n self.jira_project = jira_project\n\n def get_tickets(self, release_version):\n \"\"\"\n Gets the finished tickets statistics\n \"\"\"\n response = []\n params = self.get_params(release_version)\n\n finished_tickets = self.make_jira_request(params)\n\n for ticket in finished_tickets['issues']:\n response.append({\n \"key\": ticket['key'],\n \"desc\": ticket['fields']['summary']\n })\n\n return response\n\n def make_jira_request(self, params):\n headers = {\n 'contentType': 'application/json',\n 'Authorization': self.jira_auth\n }\n\n response = requests.get('https://wikia-inc.atlassian.net/rest/api/2/search',\n params={\n 'jql': 'project=\"{project}\" AND \"Preview branch\" ~ \"{release}\"'.format(\n project=params['project_name'], release=params['release_version'])\n },\n headers=headers\n ).json()\n\n logging.info(\n \"\\nFetching data for {project} for {release}\".format(project=params['project_name'],\n release=params['release_version'])\n )\n\n return response\n\n def get_params(self, release_version):\n params = {\n 'project_name': self.jira_project,\n 'release_version': release_version\n }\n\n return params\n","sub_path":"jira.py","file_name":"jira.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"554210479","text":"import sys\nsys.path.append(\"../\")\n\nimport argparse\nfrom joblib import Parallel, delayed\nimport numpy as np\nimport datetime\nimport pickle\nimport os\nimport learning_algorithm as la\nimport source_task_creation as stc\nimport simulation_classes as sc\nfrom model_estimation_rkhs import ModelEstimatorRKHS\nfrom source_estimator import SourceEstimator\nfrom discrete_model_estimation import Models\nimport gym\nimport envs\n\n\ndef main(id):\n\n # General env properties\n env_tgt = gym.make('cartpolec-v0')\n env_src = gym.make('cartpolec-v0')\n param_space_size = 4\n state_space_size = 4\n env_param_space_size = 3\n episode_length = 200\n gaussian_transition = True\n\n env_param = sc.EnvParam(env_tgt, param_space_size, state_space_size, env_param_space_size, episode_length, gaussian_transition)\n\n mean_initial_param = np.random.normal(np.zeros(param_space_size), 0.01)\n variance_initial_param = 0\n variance_action = 0.1\n\n simulation_param = sc.SimulationParam(mean_initial_param, variance_initial_param, variance_action, arguments.batch_size,\n arguments.iterations, arguments.gamma, None, arguments.learning_rate, arguments.ess_min,\n \"Yes\" if arguments.adaptive else \"No\", arguments.n_min, use_adam=arguments.use_adam)\n\n # Source tasks\n pis = [[-0.04058811, 0.06820783, 0.09962419, -0.01481458],\n [-0.04327763, 0.01926409, 0.10651812, 0.07304843],\n [-0.04660533, -0.08301117, 0.14598312, 0.31524803],\n [-0.04488895, -0.04959011, 0.20856307, 0.52564195],\n [-0.02085553, 0.11530108, 0.24525215, 0.58338479],\n [-0.03072567, 0.15546779, 0.27241488, 0.65833969],\n [-0.05493752, 0.11100809, 0.30213226, 0.73134919],\n [-0.02389198, 0.18004238, 0.30697023, 0.72447482],\n [-0.0702051, 0.17653729, 0.32254312, 0.72004621],\n [-0.09675066, 0.16063462, 0.32343255, 0.73801456]]\n\n m = np.random.uniform(0.8, 1.2, arguments.n_source_models)\n l = np.random.uniform(0.4, 0.6, arguments.n_source_models)\n envs = [[m[i], l[i], 0.09] for i in range(m.shape[0])]\n\n policy_params = []\n env_params = []\n num_policy = len(pis)\n for e in envs:\n for p in pis:\n policy_params.append(p)\n env_params.append(e)\n\n policy_params = np.array(policy_params)\n env_params = np.array(env_params)\n\n source_envs = []\n for param in np.array(envs):\n source_envs.append(gym.make('cartpolec-v0'))\n source_envs[-1].setParams(param)\n n_config_cv = policy_params.shape[0]\n n_source = [arguments.n_source_samples*len(pis) for _ in envs]\n\n data = stc.sourceTaskCreationSpec(env_src, episode_length, arguments.n_source_samples, arguments.gamma, variance_action,\n policy_params, env_params, param_space_size, state_space_size, env_param_space_size)\n\n # Envs for discrete model estimation\n possible_env_params = [[1.0, 0.5, 0.09],\n [0.8, 0.3, 0.09],\n [1.2, 0.7, 0.09],\n [1.1, 0.6, 0.09],\n [0.9, 0.4, 0.09],\n [0.9, 0.6, 0.09],\n [1.1, 0.4, 0.09],\n [1.5, 1.0, 0.09]]\n\n possible_envs = []\n for param in np.array(possible_env_params):\n possible_envs.append(gym.make('cartpolec-v0'))\n possible_envs[-1].setParams(param)\n\n stats = {}\n for estimator in estimators:\n stats[estimator] = []\n\n for estimator in estimators:\n\n print(estimator)\n\n model_estimation = 0\n off_policy = 0\n discrete_estimation = 0\n model = None\n env_src_models = None\n\n # Create a new dataset object\n source_dataset = sc.SourceDataset(*data, n_config_cv)\n source_dataset.policy_per_model = num_policy\n if estimator in [\"GPOMDP\", \"REINFORCE\", \"REINFORCE-BASELINE\"]:\n name = estimator\n else:\n off_policy = 1\n name = estimator[:-3]\n\n if estimator.endswith(\"SR\"):\n # Create a fake dataset for the sample-reuse algorithm\n data_sr = stc.sourceTaskCreationSpec(env_src, episode_length, 1, arguments.gamma, variance_action,\n np.array([[0, 0, 0, 0]]), np.array([[1.0, 0.5, 0.09]]), param_space_size,\n state_space_size, env_param_space_size)\n source_dataset = sc.SourceDataset(*data_sr, 1)\n elif estimator.endswith(\"DI\"):\n model_estimation = 1\n discrete_estimation = 1\n model = Models(possible_envs)\n elif estimator.endswith(\"GP\") or estimator.endswith(\"ES\") or estimator.endswith(\"MI\") or estimator.endswith(\"NS\"):\n model_estimation = 1\n model = ModelEstimatorRKHS(kernel_rho=1, kernel_lambda=[1, 1, 1, 1, 1], sigma_env=env_tgt.sigma_env,\n sigma_pi=np.sqrt(variance_action), T=arguments.rkhs_horizon, R=arguments.rkhs_samples,\n lambda_=0.0, source_envs=source_envs, n_source=n_source,\n max_gp=arguments.max_gp_samples, state_dim=4, linear_kernel=False,\n balance_coeff=arguments.balance_coeff, alpha_gp=1e-5,\n target_env=env_tgt if arguments.print_mse else None, id=id)\n if estimator.endswith(\"GP\"):\n model.use_gp = True\n elif estimator.endswith(\"MI\"):\n model.use_gp_generate_mixture = True\n\n if estimator.endswith(\"NS\"):\n n_models = int(source_dataset.episodes_per_config.shape[0]/source_dataset.policy_per_model)\n transition_models = []\n for i in range(n_models):\n model_estimator = ModelEstimatorRKHS(kernel_rho=1, kernel_lambda=[1, 1, 1, 1, 1], sigma_env=env_tgt.sigma_env,\n sigma_pi=np.sqrt(variance_action), T=arguments.rkhs_horizon, R=arguments.rkhs_samples,\n lambda_=0.0, source_envs=source_envs, n_source=n_source,\n max_gp=arguments.max_gp_samples_src, state_dim=4, linear_kernel=False,\n balance_coeff=arguments.balance_coeff, alpha_gp=1e-5,\n target_env=env_tgt if arguments.print_mse else None, id=id)\n transition_models.append(model_estimator)\n env_src_models = SourceEstimator(source_dataset, transition_models)\n result = la.learnPolicy(env_param, simulation_param, source_dataset, name, off_policy=off_policy,\n model_estimation=model_estimation, dicrete_estimation=discrete_estimation,\n model_estimator=model, verbose=not arguments.quiet, dump_model=arguments.dump_estimated_model,\n iteration_dump=arguments.iteration_dump, source_estimator=env_src_models if estimator.endswith(\"NS\") else None)\n\n stats[estimator].append(result)\n\n return stats\n\n\ndef run(id, seed):\n\n # Set the random seed\n np.random.seed(seed)\n\n print(\"Starting run {0}\".format(id))\n\n results = main(id)\n\n print(\"Done run {0}\".format(id))\n\n # Log the results\n with open(\"{0}/{1}.pkl\".format(folder, id), 'wb') as output:\n pickle.dump(results, output)\n\n return results\n\n\n# Command line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--iterations\", default=5, type=int)\nparser.add_argument(\"--learning_rate\", default=1e-3, type=float)\nparser.add_argument(\"--gamma\", default=0.99, type=float)\nparser.add_argument(\"--batch_size\", default=10, type=int)\nparser.add_argument(\"--ess_min\", default=20, type=int)\nparser.add_argument(\"--n_min\", default=3, type=int)\nparser.add_argument(\"--adaptive\", default=False, action='store_true')\nparser.add_argument(\"--use_adam\", default=False, action='store_true')\nparser.add_argument(\"--n_source_samples\", default=10, type=int)\nparser.add_argument(\"--n_source_models\", default=2, type=int)\nparser.add_argument(\"--max_gp_samples\", default=250, type=int)\nparser.add_argument(\"--max_gp_samples_src\", default=1000, type=int)\nparser.add_argument(\"--rkhs_samples\", default=20, type=int)\nparser.add_argument(\"--rkhs_horizon\", default=20, type=int)\nparser.add_argument(\"--dump_estimated_model\", default=False, action='store_true')\nparser.add_argument(\"--source_task_unknown\", default=False, action='store_true')\nparser.add_argument(\"--iteration_dump\", default=5, type=int)\nparser.add_argument(\"--balance_coeff\", default=False, action='store_true')\nparser.add_argument(\"--print_mse\", default=False, action='store_true')\nparser.add_argument(\"--n_jobs\", default=1, type=int)\nparser.add_argument(\"--n_runs\", default=6, type=int)\nparser.add_argument(\"--quiet\", default=False, action='store_true')\n\n# Read arguments\narguments = parser.parse_args()\n\nestimators = [\"GPOMDP\",\n \"PD-MIS-NS\",\n \"PD-MIS-ID\",\n \"PD-MIS-ES\",\n \"PD-MIS-GP\",\n \"PD-MIS-DI\"]\n\n# Base folder where to log\nfolder = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\nos.mkdir(folder)\n\n# Save arguments\nwith open(\"{0}/params.txt\".format(folder), 'w') as f:\n for key, value in vars(arguments).items():\n f.write(\"{0}: {1}\\n\".format(key, value))\n\n# Seeds for each run\nseeds = [np.random.randint(1000000) for _ in range(arguments.n_runs)]\n\nif arguments.n_jobs == 1:\n results = [run(id, seed) for id, seed in zip(range(arguments.n_runs), seeds)]\nelse:\n results = Parallel(n_jobs=arguments.n_jobs, backend='loky')(delayed(run)(id, seed) for id, seed in zip(range(arguments.n_runs), seeds))\n\nwith open('{0}/results1.pkl'.format(folder), 'wb') as output:\n pickle.dump(results, output)\n\n################################################\n\nprint(folder)\n","sub_path":"scripts/run_cartpole_models.py","file_name":"run_cartpole_models.py","file_ext":"py","file_size_in_byte":10203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"321043652","text":"from django import forms\n\nfrom .models import Profile\nfrom django.contrib.auth.models import User\nfrom addresses.models import Address\nfrom events.models import PhysicalEvent\nfrom profiles.models import Profile\n\n\nclass SignupForm(forms.Form):\n is_main_organiser = forms.BooleanField(required = False)\n\n def signup(self, request, user):\n main = self.cleaned_data['is_main_organiser']\n new_profile = Profile.objects.create(user = user, is_main_organiser = main, user_owner = user)\n new_profile.save()\n\nclass BaseUserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = (\n 'username',\n 'first_name',\n 'last_name',\n 'email',\n )\n\nclass RegisterUserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = (\n 'username',\n 'first_name',\n 'last_name',\n 'email',\n )\n\nclass ProfileForm(forms.ModelForm):\n \n\n class Meta:\n model = Profile\n fields = (\n 'bio',\n 'phone_number',\n 'street_name',\n 'street_number',\n 'city',\n 'country',\n 'facebook_link',\n 'twitter_link',\n )\n\nclass OrganisationForm(forms.ModelForm):\n\n class Meta:\n model = Profile\n fields = (\n 'bio',\n 'phone_number',\n 'street_name',\n 'street_number',\n 'city',\n 'country',\n 'ico',\n 'dic',\n 'account_number',\n 'facebook_link',\n 'twitter_link',\n\n )\n\nclass SpeakerForm(forms.ModelForm):\n def __init__(self, user, *args, **kwargs):\n self.user = user\n user_owner = Profile.objects.get(user = user)\n print (user_owner.user_owner)\n super(SpeakerForm, self).__init__(*args, **kwargs)\n self.fields['events'].queryset = PhysicalEvent.events.filter(event_owner=user, is_active = True) | PhysicalEvent.events.filter(event_owner=user_owner.user_owner, is_active = True)\n self.fields['facebook_link'].widget.attrs['placeholder'] = 'Add facebook link in format https://www.facebook.com'\n self.fields['twitter_link'].widget.attrs['placeholder'] = 'Add facebook link in format https://www.twitter.com'\n\n class Meta:\n model = Profile\n fields = (\n 'bio',\n 'phone_number',\n 'street_name',\n 'street_number',\n 'city',\n 'country',\n 'events',\n 'confirmed',\n 'facebook_link',\n 'twitter_link',\n 'is_published',\n )\n","sub_path":"profiles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"185863143","text":"import string\n\nlyric = 'The night begin to shine, the night begin to shine'\nwords = lyric.split()\nprint(words)\n\ndef function_Count(filename):\n with open(filename,'r') as text:\n words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]\n words_index = set(words)\n counts_dict = {index:words.count(index) for index in words_index}\n for word in sorted(counts_dict,key=lambda x: counts_dict[x],reverse=True):\n print('{}-{} times'.format(word, counts_dict[word]))\n #print(words)\n # for word in words:\n # print('{}-{} times'.format(word,words.count(word)))\n\n\nfunction_Count('F:/code/python/Walden.txt')","sub_path":"tongji.py","file_name":"tongji.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"83152169","text":"import requests\n\nurl = 'https://viacep.com.br/ws/'\ncep = '30140071'\nformato = '/xml/'\n\nr = requests.get(url + cep + formato)\n\nif (r.status_code == 200):\n print()\n print('XML : \\n', r.text)\n print()\nelse:\n print('Não houve sucesso na requisição.')\n","sub_path":"exercise-get/exercicio01.py","file_name":"exercicio01.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"60186640","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nC/C++ Documentation Generator\nCopyright (C) 2012 Matthias Bolte <matthias@tinkerforge.com>\nCopyright (C) 2011 Olaf Lüke <olaf@tinkerforge.com>\n\ngenerator_c_doc.py: Generator for C/C++ documentation\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License \nas published by the Free Software Foundation; either version 2 \nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public\nLicense along with this program; if not, write to the\nFree Software Foundation, Inc., 59 Temple Place - Suite 330,\nBoston, MA 02111-1307, USA.\n\"\"\"\n\nimport sys\nimport os\nimport shutil\nimport subprocess\nimport glob\nimport re\n\nsys.path.append(os.path.split(os.getcwd())[0])\nimport common\n\ndevice = None\n\ndef get_c_type(py_type):\n if py_type == 'string':\n return 'char'\n if py_type in ( 'int8', 'int16', 'int32' , 'int64', \\\n 'uint8', 'uint16', 'uint32', 'uint64'):\n return \"{0}_t\".format(py_type)\n return py_type\n\ndef format_doc(packet):\n text = common.select_lang(packet.get_doc()[1])\n parameter = {\n 'en': 'parameter',\n 'de': 'Parameter'\n }\n parameters = {\n 'en': 'parameters',\n 'de': 'Parameter'\n }\n\n for other_packet in device.get_packets():\n name_false = ':func:`{0}`'.format(other_packet.get_camel_case_name())\n if other_packet.get_type() == 'callback':\n name_upper = other_packet.get_upper_case_name()\n pre_upper = device.get_upper_case_name()\n name_right = ':c:data:`{0}_CALLBACK_{1}`'.format(pre_upper,\n name_upper)\n else:\n name_right = ':c:func:`{0}_{1}`'.format(device.get_underscore_name(),\n other_packet.get_underscore_name())\n text = text.replace(name_false, name_right)\n\n text = text.replace(\":word:`parameter`\", common.select_lang(parameter))\n text = text.replace(\":word:`parameters`\", common.select_lang(parameters))\n\n text = common.handle_rst_if(text, device)\n text = common.handle_since_firmware(text, device, packet)\n\n return common.shift_right(text, 1)\n\ndef make_parameter_list(packet):\n param = ''\n for element in packet.get_elements():\n c_type = get_c_type(element[1])\n name = element[0]\n pointer = ''\n arr = ''\n if element[3] == 'out':\n pointer = '*'\n name = \"ret_{0}\".format(name)\n if element[2] > 1:\n arr = '[{0}]'.format(element[2])\n pointer = ''\n \n param += ', {0} {1}{2}{3}'.format(c_type, pointer, name, arr)\n return param\n\ndef make_examples():\n def title_from_file(f):\n f = f.replace('example_', '')\n f = f.replace('.c', '')\n s = ''\n for l in f.split('_'):\n s += l[0].upper() + l[1:] + ' '\n return s[:-1]\n\n return common.make_rst_examples(title_from_file, device, common.path_binding,\n 'c', 'example_', '.c', 'C')\n\ndef make_methods(typ):\n version_method = {\n 'en': \"\"\"\n.. c:function:: int {0}_get_version({1} *{0}, uint8_t ret_api_version[3])\n\n Returns API version [major, minor, revision] used for this device.\n\"\"\",\n 'de': \"\"\"\n.. c:function:: int {0}_get_version({1} *{0}, uint8_t ret_api_version[3])\n\n Gibt die API Version (major, minor, revision) die benutzt\n wird zurück.\n\"\"\"\n }\n\n methods = ''\n func_start = '.. c:function:: int '\n for packet in device.get_packets('function'):\n if packet.get_doc()[0] != typ:\n continue\n name = '{0}_{1}'.format(device.get_underscore_name(), packet.get_underscore_name())\n plist = make_parameter_list(packet)\n params = '{0} *{1}{2}'.format(device.get_camel_case_name(), device.get_underscore_name(), plist)\n desc = format_doc(packet)\n func = '{0}{1}({2})\\n{3}'.format(func_start, name, params, desc)\n methods += func + '\\n'\n\n if typ == 'af':\n methods += common.select_lang(version_method).format(device.get_underscore_name(),\n device.get_camel_case_name())\n\n return methods\n\ndef make_callbacks():\n param_format = {\n 'en': \"\"\"\n .. code-block:: c\n\n void callback({0})\n\"\"\",\n 'de': \"\"\"\n .. code-block:: c\n\n void callback({0})\n\"\"\"\n }\n\n cbs = ''\n func_start = '.. c:var:: '\n for packet in device.get_packets('callback'):\n plist = make_parameter_list(packet)[2:].replace('*ret_', '')\n if not plist:\n plist = 'void'\n params = common.select_lang(param_format).format(plist)\n desc = format_doc(packet)\n name = '{0}_{1}'.format(device.get_upper_case_name(),\n packet.get_upper_case_name())\n\n func = '{0}{1}_CALLBACK_{2}\\n{3}\\n{4}'.format(func_start,\n device.get_upper_case_name(),\n packet.get_upper_case_name(),\n params,\n desc)\n cbs += func + '\\n'\n\n return cbs\n\ndef make_api():\n create_str = {\n 'en': \"\"\"\n.. c:function:: void {0}_create({1} *{0}, const char *uid, IPConnection *ipcon)\n\n Creates an object with the unique device ID *uid*:\n\n .. code-block:: c\n\n {1} {0};\n {0}_create(&{0}, \"YOUR_DEVICE_UID\", &ipcon);\n\n This object can then be used after the IP connection is connected \n (see examples :ref:`above <{0}_{2}_c_examples>`).\n\"\"\",\n 'de': \"\"\"\n.. c:function:: void {0}_create({1} *{0}, const char *uid, IPConnection *ipcon)\n\n Erzeugt ein Objekt mit der eindeutigen Geräte ID *uid*:\n\n .. code-block:: c\n\n {1} {0};\n {0}_create(&{0}, \"YOUR_DEVICE_UID\", &ipcon);\n\n Dieses Objekt kann benutzt werden, nachdem die IP Connection verbunden ist\n (siehe Beispiele :ref:`oben <{0}_{2}_c_examples>`).\n\"\"\"\n }\n\n register_str = {\n 'en': \"\"\"\n.. c:function:: void {0}_register_callback({1} *{0}, uint8_t id, void *callback, void *user_data)\n\n Registers a callback with ID *id* to the function *callback*. The *user_data*\n will be given as a parameter of the callback. \n \n The available IDs with corresponding function signatures are listed \n :ref:`below <{0}_{2}_c_callbacks>`.\n\"\"\",\n 'de': \"\"\"\n.. c:function:: void {0}_register_callback({1} *{0}, uint8_t id, void *callback, void *user_data)\n\n Registriert einen Callback mit der ID *id* mit der Funktion *callback*.\n Der Parameter *user_data* wird bei jedem Callback wieder mit übergeben.\n \n Die verfügbaren IDs mit den zugehörigen Funktionssignaturen sind \n :ref:`unten <{0}_{2}_c_callbacks>` zu finden.\n\"\"\"\n }\n\n c_str = {\n 'en': \"\"\"\n.. _{0}_{3}_c_callbacks:\n\nCallbacks\n^^^^^^^^^\n\n*Callbacks* can be registered with *callback IDs* to receive\ntime critical or recurring data from the device. The registration is done\nwith the :c:func:`{0}_register_callback` function. The parameters consist of\nthe device object, the callback ID and the callback function:\n\n .. code-block:: c\n\n void my_callback(int p, void *user_data) {{\n printf(\"parameter: %d\\\\n\", p);\n }}\n\n {0}_register_callback(&{0}, {1}_CALLBACK_EXAMPLE, (void*)my_callback, NULL);\n\nThe available constants with corresponding callback function signatures \nare described below.\n\n.. note::\n Using callbacks for recurring events is *always* preferred\n compared to using getters. It will use less USB bandwidth and the latency\n will be a lot better, since there is no round trip time.\n\n{2}\n\"\"\",\n 'de': \"\"\"\n.. _{0}_{3}_c_callbacks:\n\nCallbacks\n^^^^^^^^^\n\n*Callbacks* können mit *callback IDs* registriert werden um zeitkritische\noder wiederkehrende Daten vom Gerät zu erhalten. Die Registrierung kann\nmit der Funktion :c:func:`{0}_register_callback` durchgeführt werden. Die\nParameter bestehen aus dem Geräteobjekt, der Callback ID und der Callbackfunktion:\n\n .. code-block:: c\n\n void my_callback(int p, void *user_data) {{\n printf(\"parameter: %d\\\\n\", p);\n }}\n\n {0}_register_callback(&{0}, {1}_CALLBACK_EXAMPLE, (void*)my_callback, NULL);\n\nDie verfügbaren Konstanten mit den zugehörigen Callback Funktionssignaturen\nwerden weiter unten beschrieben.\n\n.. note::\n Callbacks für wiederkehrende Ereignisse zu verwenden ist \n *immer* zu bevorzugen gegenüber der Verwendung von Abfragen.\n Es wird weniger USB-Bandbreite benutzt und die Latenz ist\n erheblich geringer, da es keine Paketumlaufzeit gibt.\n\n{2}\n\"\"\"\n }\n\n api = {\n 'en': \"\"\"\n{0}\nAPI\n---\n\nEvery function of the C/C++ bindings returns an integer which describes an\nerror code. Data returned from the device, when a getter is called,\nis handled via call by reference. These parameters are labeled with the\n``ret_`` prefix.\n\nPossible error codes are:\n\n* E_OK = 0\n* E_TIMEOUT = -1\n* E_NO_STREAM_SOCKET = -2\n* E_HOSTNAME_INVALID = -3\n* E_NO_CONNECT = -4\n* E_NO_THREAD = -5\n* E_NOT_ADDED = -6\n\nas defined in :file:`ip_connection.h`.\n\nAll functions listed below are thread-safe.\n\n{1}\n\n{2}\n\"\"\",\n 'de': \"\"\"\n{0}\nAPI\n---\n\nJede Funktion der C/C++ Bindings gibt einen Integer zurück, welcher einen\nFehlercode beschreibt. Vom Gerät zurückgegebene Daten werden, wenn eine\nAbfrage aufgerufen wurde, über Referenzparameter gehandhabt. Diese Parameter\nsind mit dem ``ret_`` Präfix gekennzeichnet.\n\nMögliche Fehlercodes sind:\n\n* E_OK = 0\n* E_TIMEOUT = -1\n* E_NO_STREAM_SOCKET = -2\n* E_HOSTNAME_INVALID = -3\n* E_NO_CONNECT = -4\n* E_NO_THREAD = -5\n* E_NOT_ADDED = -6\n\nwie in :file:`ip_connection.h` definiert.\n\nAlle folgend aufgelisteten Funktionen sind Thread-sicher.\n\n{1}\n\n{2}\n\"\"\"\n }\n\n cre = common.select_lang(create_str).format(device.get_underscore_name(),\n device.get_camel_case_name(),\n device.get_category().lower())\n reg = common.select_lang(register_str).format(device.get_underscore_name(),\n device.get_camel_case_name(),\n device.get_category().lower())\n bf = make_methods('bf')\n af = make_methods('af')\n ccf = make_methods('ccf')\n c = make_callbacks()\n api_str = ''\n if bf:\n api_str += common.select_lang(common.bf_str).format(cre, bf)\n if af:\n api_str += common.select_lang(common.af_str).format(af)\n if c:\n api_str += common.select_lang(common.ccf_str).format(reg, ccf)\n api_str += common.select_lang(c_str).format(device.get_underscore_name(),\n device.get_upper_case_name(),\n c,\n device.get_category().lower())\n\n ref = '.. _{0}_{1}_c_api:\\n'.format(device.get_underscore_name(),\n device.get_category().lower())\n\n api_desc = ''\n if 'api' in device.com:\n api_desc = common.select_lang(device.com['api'])\n\n return common.select_lang(api).format(ref, api_desc, api_str)\n\ndef make_files(com_new, directory):\n global device\n device = common.Device(com_new)\n file_name = '{0}_{1}_C'.format(device.get_camel_case_name(), device.get_category())\n title = {\n 'en': 'C/C++ bindings',\n 'de': 'C/C++ Bindings'\n }\n directory = os.path.join(directory, 'doc', common.lang)\n f = file('{0}/{1}.rst'.format(directory, file_name), \"w\")\n f.write(common.make_rst_header(device, 'c', 'C/C++'))\n f.write(common.make_rst_summary(device, common.select_lang(title)))\n f.write(make_examples())\n f.write(make_api())\n\nif __name__ == \"__main__\":\n for lang in ['en', 'de']:\n common.generate(os.getcwd(), lang, make_files, common.prepare_doc, True)\n","sub_path":"c/generate_c_doc.py","file_name":"generate_c_doc.py","file_ext":"py","file_size_in_byte":12159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"386599306","text":"import tkinter\n\ndef check():\n if cval.get() == True:\n print(\"Checked\")\n else:\n print(\"Not checked\")\n\nroot = tkinter.Tk()\nroot.title(\"Check button\")\nroot.geometry(\"400x200\")\ncval = tkinter.BooleanVar()\ncval.set(False)\ncbtn = tkinter.Checkbutton(text=\"check button\", variable=cval, command=check)\ncbtn.pack()\nroot.mainloop()","sub_path":"chap7/check_box.py","file_name":"check_box.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"629369375","text":"\"\"\"Generic utility functions\n\"\"\"\nimport logging\nimport time\nfrom logging.handlers import RotatingFileHandler\n\nlogging.raiseExceptions = False\n\n\ndef retry(n_try, sleep=1, *exception_types):\n \"\"\"Retry a function several times\n \n Args:\n n_try: Number of trials\n sleep: Delay in seconds. Default=1\n exception_types: Types of exeptions\n \"\"\"\n\n def try_fn(func, *args, **kwargs):\n for n in range(n_try):\n if n == n_try - 1: # this is the last trial\n return func(*args, **kwargs)\n try:\n return func(*args, **kwargs)\n except exception_types or Exception as e:\n logger = create_logger(\"retry\")\n logger.warn(\n \"Trial {n} failed with exception: {e}.\\n\"\n \"Trying again after a {sleep} second sleep\".format(n=n, e=str(e), sleep=sleep)\n )\n time.sleep(sleep)\n\n return try_fn\n\n\ndef create_logger(\n name,\n level=\"info\",\n fmt=\"%(asctime)s %(levelname)s %(name)s: %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n add_console_handler=True,\n add_file_handler=False,\n logfile=\"/tmp/tmp.log\",\n):\n \"\"\"Create a formatted logger\n \n Args:\n fmt: Format of the log message\n datefmt: Datetime format of the log message\n Examples:\n logger = create_logger(__name__, level=\"info\")\n logger.info(\"Hello world\")\n \"\"\"\n\n level = {\"debug\": logging.DEBUG, \"info\": logging.INFO, \"warn\": logging.WARN, \"error\": logging.ERROR}[level]\n\n logger = logging.getLogger(name)\n logger.setLevel(level)\n\n if add_console_handler: # Print on console\n ch = logging.StreamHandler()\n ch.setLevel(level)\n chformatter = logging.Formatter(fmt=fmt, datefmt=datefmt)\n ch.setFormatter(chformatter)\n logger.addHandler(ch)\n\n if add_file_handler: # Print in a log file\n if \"s3://\" in logfile:\n # put the log file to local first\n logfile = \"/tmp/tmp.log\"\n th = RotatingFileHandler(logfile, mode=\"a\", maxBytes=1_000_000, backupCount=5, encoding=\"utf-8\")\n thformatter = logging.Formatter(fmt=fmt, datefmt=datefmt)\n th.setFormatter(thformatter)\n\n logger.addHandler(th)\n\n return logger\n","sub_path":"pypchutils/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"391835972","text":"############################################################\n#\n# BuildingRules Project \n# Politecnico di Milano\n# Author: Alessandro A. Nacci\n#\n# This code is confidential\n# Milan, March 2014\n#\n############################################################\n\nimport sys\nimport json\nimport datetime\nimport time\nfrom app.backend.commons.errors import *\nfrom app.backend.commons.database import Database\n\nclass Feedback:\n\tdef __init__(self, id = None, authorUuid = None, alternativeContact = None, score = None, message = None, feedbackTimestamp = None):\n\n\t\t\tself.id = id\n\t\t\tself.authorUuid = authorUuid\n\t\t\tself.alternativeContact = alternativeContact\n\t\t\tself.score = score\n\t\t\tself.message = message\n\t\t\tself.feedbackTimestamp = feedbackTimestamp\n\n\tdef __replaceSqlQueryToken(self, queryTemplate):\n\t\tif self.id \t\t\t\t\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@id@@\", str(self.id))\n\t\tif self.authorUuid\t\t\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@author_uuid@@\", str(self.authorUuid))\t\t\n\t\tif self.alternativeContact\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@alternative_contact@@\", str(self.alternativeContact))\n\t\tif self.score\t\t\t\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@score@@\", str(self.score))\n\t\tif self.message \t\t\t!= None\t: \tqueryTemplate = queryTemplate.replace(\"@@message@@\", str(self.message))\n\t\tif self.feedbackTimestamp\t!= None\t:\tqueryTemplate = queryTemplate.replace(\"@@feedback_timestamp@@\", self.feedbackTimestamp.strftime('%Y-%m-%d %H:%M:%S'))\n\n\t\treturn queryTemplate\n\n\tdef store(self):\n\n\t\tif not self.feedbackTimestamp:\n\t\t\tself.feedbackTimestamp = datetime.datetime.now() \n\n\n\t\tdatabase = Database()\n\t\tdatabase.open()\n\n\t\tquery = \"SELECT COUNT(id) FROM feedbacks WHERE id = '@@id@@';\"\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tqueryResult = database.executeReadQuery(query)\n\n\t\tif int(queryResult[0][0]) > 0:\n\t\t\tquery = \"UPDATE feedbacks SET author_uuid = '@@author_uuid@@', alternative_contact = '@@alternative_contact@@', score = '@@score@@', message = '@@message@@', feedback_timestamp = '@@feedback_timestamp@@' WHERE id = '@@id@@';\"\n\t\telse:\n\t\t\tquery = \"INSERT INTO feedbacks (author_uuid, alternative_contact, score, message, feedback_timestamp) VALUES ('@@author_uuid@@', '@@alternative_contact@@', '@@score@@', '@@message@@', '@@feedback_timestamp@@');\"\t\n\t\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tdatabase.executeWriteQuery(query)\n\t\tself.id = int(database.getLastInsertedId()) if not self.id else self.id\n\t\tdatabase.close()\n\n\n\tdef retrieve(self):\n\n\t\tif self.id:\n\t\t\tquery = \"SELECT * FROM feedbacks WHERE id = '@@id@@';\"\n\t\telse:\n\t\t\traise MissingInputDataError(\"Impossibile to query any feedback with missing parameters\")\n\n\t\tdatabase = Database()\n\t\tdatabase.open()\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tqueryResult = database.executeReadQuery(query)\n\n\t\tif len(queryResult) > 0:\n\t\t\tself.id = queryResult[0][0]\n\t\t\tself.authorUuid = queryResult[0][1]\n\t\t\tself.alternativeContact = queryResult[0][2]\n\t\t\tself.score = queryResult[0][3]\n\t\t\tself.message = queryResult[0][4]\n\t\t\tself.feedbackTimestamp = queryResult[0][5]\n\t\telse:\n\t\t\tdatabase.close()\n\t\t\traise MturkNotFoundError(\"Impossibile to find any feedback with the provided values\")\n\n\t\tdatabase.close()\n\n\tdef delete(self):\n\n\t\tdatabase = Database()\n\t\tdatabase.open()\n\n\t\tquery = \"DELETE FROM feedbacks WHERE id = '@@id@@';\"\n\t\tquery = self.__replaceSqlQueryToken(query)\n\t\tdatabase.executeWriteQuery(query)\n\n\t\tdatabase.close()\n\n\tdef getDict(self):\n\t\t\n\t\tresponse = {}\n\n\t\tresponse[\"id\"] = self.id\n\t\tresponse[\"authorUuid\"] = self.authorUuid\n\t\tresponse[\"alternativeContact\"] = self.alternativeContact\n\t\tresponse[\"score\"] = self.score\n\t\tresponse[\"message\"] = self.message\n\t\tresponse[\"feedbackTimestamp\"] = self.feedbackTimestamp.strftime('%Y-%m-%d %H:%M:%S') if self.feedbackTimestamp else None\n\n\t\treturn response\t\n\n\n\tdef __str__(self):\n\t\treturn \"Feedback \" + str(json.dumps(self.getDict(), separators=(',',':')))","sub_path":"backend/app/backend/model/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"106007610","text":"import cv2\nfrom PIL import Image\nfrom Tello import Tello\n\ndef action():\n print(\"start action\")\n t=Tello()\n print(\"tello initialized\")\n print(t.connect())\n \n t.streamon()\n t.takeoff()\n counter=0\n img=[]\n \n \n while True:\n if(counter==10000):\n t.land()\n try:\n \n frame_read=t.get_frame_read()\n a= frame_read.frame\n \n im = Image.fromarray(a)\n im.save(\"your_file_\"+str(counter)+\".jpeg\")\n t.rotate_clockwise(10)\n except:\n e = sys.exc_info()[0]\n write_to_page( \"<p>Error: %s</p>\" % e )\n counter=counter+1\n cv2.destroyAllWindows() \n #video.release() \n out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)\n for i in range(len(img)):\n out.write(img_array[i])\n out.release()\n ","sub_path":"sequnce.py","file_name":"sequnce.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"155834398","text":"import argparse\nimport json\nimport pandas as pd\nimport os\nimport csv\nfrom utils.config import *\n\n# This file compares results in a csv file\n\nparser = argparse.ArgumentParser(prog=\"compare_results.py\",\n description=\"Visualize results from training\")\nparser.add_argument(\"-r\", \"--result\", nargs='+', help=\"path to result json\", required=True)\nparser.add_argument(\"-c\", \"--compare\", help=\"path to compare result\", required=False)\nparser.add_argument(\"-a\", \"--argument\", help=\"argument to compare\", required=False)\narguments = parser.parse_args()\n\n\ndef append_csv(source, to, mode='a', header=''):\n \"\"\"\n append existing csv file to csv file\n :param source: source file\n :param to: file to append\n :param mode: mode to open file\n :param header: header of file\n :return:\n \"\"\"\n with open(to, mode) as f:\n writer = csv.writer(f)\n writer.writerow([header])\n reader = csv.reader(open(source))\n for row in reader:\n writer.writerow(row)\n\n\ndef generate_single_csv(origin, path, sort=True):\n \"\"\"\n generate a single csv file\n :param origin: data for file\n :param path: path to store file\n :param sort: defines if header should be sorted\n :return:\n \"\"\"\n df = pd.DataFrame(origin)\n if sort:\n df = df.reindex(sorted(df.columns, key=lambda x: int(x) if x is not 'inactive' else x), axis=1)\n df.to_csv(path)\n\n\ndef result_to_csv_table():\n \"\"\"\n save results in csv file\n \"\"\"\n r = arguments.result[0]\n store_result_path = results_folder + r.rsplit('/', 1)[1].rsplit('.', 1)[0] + '/'\n print(store_result_path)\n if not os.path.exists(store_result_path):\n os.mkdir(store_result_path)\n result = json.load(open(r))\n\n # show training results\n generate_single_csv(add_key_to_dict(result['active']['training'], 'inactive',result['inactive']['training']),\n store_result_path + 'training.csv')\n # show test results\n generate_single_csv(add_key_to_dict(result['active']['test'], 'inactive', result['inactive']['test']),\n store_result_path + 'test.csv')\n # show arguments\n generate_single_csv({'arguments': result['arguments']}, store_result_path + 'arguments.csv', sort=False)\n # generate combined csv\n append_csv(store_result_path + 'training.csv', store_result_path + 'visualization.csv', 'w+', 'Training metrics')\n append_csv(store_result_path + 'test.csv', store_result_path + 'visualization.csv', header='Test metrics')\n append_csv(store_result_path + 'arguments.csv', store_result_path + 'visualization.csv')\n\n\ndef compare_arguments_for_path(result, compare, tag):\n \"\"\"\n compare arguments of different results to define stor name\n :param result: results dict\n :param compare: results to compare\n :param tag: tag of store\n :return:\n \"\"\"\n store_path = results_folder + tag\n for a in result['arguments']:\n if not result['arguments'][a] == compare['arguments'][a]:\n store_path += '_' + a.capitalize() + '-' + str(result['arguments'][a]).capitalize() + '-' + str(\n compare['arguments'][a]).capitalize()\n store_path += '/'\n return store_path\n\n\ndef combine_dicts(result, compare, appendix_res='_res', appendix_comp='_comp'):\n \"\"\"\n combine two result dicts\n :param result: result dict\n :param compare: result dict to compare\n :param appendix_res: appendix of header values for result dict\n :param appendix_comp: appendix of header values for compare dict\n :return: combine dict\n \"\"\"\n for key in list(result.keys()):\n result[key + appendix_res] = result.pop(key)\n for key in list(compare.keys()):\n result[key + appendix_comp] = compare[key]\n return result\n\n\ndef add_key_to_dict(dic, addition_label, addition):\n \"\"\"\n add single key to existing dict\n :param dic: dict\n :param addition_label: additinal label\n :param addition: additional data\n :return: dict\n \"\"\"\n dic[addition_label] = addition\n return dic\n\n\ndef compare_results():\n \"\"\"\n compare results in csv file\n :return:\n \"\"\"\n result = json.load(open(arguments.result))\n compare = json.load(open(arguments.compare))\n store_path = compare_arguments_for_path(result, compare, 'compare')\n\n if not os.path.exists(store_path):\n os.mkdir(store_path)\n\n training = combine_dicts(add_key_to_dict(result['active']['training'], 'inactive', result['inactive']['training']),\n add_key_to_dict(compare['active']['training'], 'inactive', compare['inactive']['training']))\n generate_single_csv(training, store_path + 'training.csv', sort=False)\n\n test = combine_dicts(add_key_to_dict(result['active']['test'], 'inactive', result['inactive']['test']),\n add_key_to_dict(compare['active']['test'], 'inactive', compare['inactive']['test']))\n generate_single_csv(test, store_path + 'test.csv')\n\n generate_single_csv({'result': result['arguments'], 'compare': compare['arguments']}, store_path + 'arguments.csv',\n sort=False)\n # generate combined csv\n append_csv(store_path + 'training.csv', store_path + 'visualization.csv', 'w+', 'Training metrics')\n append_csv(store_path + 'test.csv', store_path + 'visualization.csv', header='Test metrics')\n append_csv(store_path + 'arguments.csv', store_path + 'visualization.csv')\n\n\ndef combine_schema_dicts(mode):\n \"\"\"\n combine dicts with different schemes\n :param mode: metrics to combine\n :return: combined dict\n \"\"\"\n metrics_dict = {}\n for res in arguments.result:\n result = json.load(open(res))\n schema = result['arguments'][arguments.argument]\n metrics_dict['inactive_' + schema] = result['inactive'][mode]\n max_it = max(int(k) for k in result['active'][mode].keys())\n metrics_dict[schema] = result['active'][mode][str(max_it)]\n return metrics_dict\n\n\ndef compare_specific_argument():\n \"\"\"\n compare one sepcific argument in csv file\n \"\"\"\n store_path = results_folder + 'compare_' + arguments.argument + '/'\n if not os.path.exists(store_path):\n os.mkdir(store_path)\n metrics_training = combine_schema_dicts('training')\n generate_single_csv(metrics_training, store_path + 'training.csv', sort=False)\n metrics_test = combine_schema_dicts('test')\n generate_single_csv(metrics_test, store_path + 'test.csv', sort=False)\n\n arguments_dict = {}\n for res in arguments.result:\n result = json.load(open(res))\n arguments_dict[result['arguments'][arguments.argument]] = result['arguments']\n generate_single_csv(arguments_dict, store_path + 'arguments.csv', sort=False)\n\n # generate combined csv\n append_csv(store_path + 'training.csv', store_path + 'visualization.csv', 'w+', 'Training metrics')\n append_csv(store_path + 'test.csv', store_path + 'visualization.csv', header='Test metrics')\n append_csv(store_path + 'arguments.csv', store_path + 'visualization.csv')\n\n\nif __name__ == '__main__':\n if arguments.argument is not None:\n compare_specific_argument()\n elif arguments.compare is None:\n result_to_csv_table()\n else:\n compare_results()\n","sub_path":"visualisation/compare_results.py","file_name":"compare_results.py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"282340367","text":"\"\"\"\nThis file fixes portability issues for ctypes\n\"\"\"\nfrom __future__ import absolute_import\nimport ctypes\nfrom numba import types\nfrom . import templates\n\nCTYPES_MAP = {\n None: types.none,\n ctypes.c_int8: types.int8,\n ctypes.c_int16: types.int16,\n ctypes.c_int32: types.int32,\n ctypes.c_int64: types.int64,\n\n ctypes.c_uint8: types.uint8,\n ctypes.c_uint16: types.uint16,\n ctypes.c_uint32: types.uint32,\n ctypes.c_uint64: types.uint64,\n\n ctypes.c_float: types.float32,\n ctypes.c_double: types.float64,\n\n ctypes.c_void_p: types.voidptr,\n}\n\n\ndef convert_ctypes(ctypeobj):\n try:\n return CTYPES_MAP[ctypeobj]\n except KeyError:\n raise TypeError(\"unhandled ctypes type: %s\" % ctypeobj)\n\n\ndef is_ctypes_funcptr(obj):\n try:\n # Is it something of which we can get the address\n ctypes.cast(obj, ctypes.c_void_p)\n except ctypes.ArgumentError:\n return False\n else:\n # Does it define argtypes and restype\n return hasattr(obj, 'argtypes') and hasattr(obj, 'restype')\n\n\ndef make_function_type(cfnptr):\n cargs = [convert_ctypes(a)\n for a in cfnptr.argtypes]\n cret = convert_ctypes(cfnptr.restype)\n\n cases = [templates.signature(cret, *cargs)]\n template = templates.make_concrete_template(\"CFuncPtr\", cfnptr, cases)\n\n pointer = ctypes.cast(cfnptr, ctypes.c_void_p).value\n return types.FunctionPointer(template, pointer)\n","sub_path":"numba/typing/ctypes_utils.py","file_name":"ctypes_utils.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"476602062","text":"import numpy as np\nimport pandas as pd\nimport os\nimport math\n\ndef plot_request_answer(*dateList, **district):\n '''get request, answer, gap numbers of specified date\n\n Notes:\n if the dictionary district is not specified,\n\n else,\n\n\n Args:\n dateList(list):\n\n district(dictionary):\n\n Return: None\n\n '''\n\n # column names\n orderNames = ['order_id', 'driver_id', 'passenger_id', 'start_district_hash', 'dest_district_hash', 'Price', 'Time']\n\n if not district:\n\n filedir = 'season_1/training_data/order_data/order_data_' + dateList[0]\n\n orderDf = pd.read_csv(filedir, sep='\\t', header=None, names=orderNames, index_col='Time', parse_dates=True)\n\n for startDistrict in orderDf.groupby('start_district_hash'):\n # print startDistrict[0]\n startDistrictDf = startDistrict[1]\n # add a column to specify time_period index\n timeIndex = (startDistrictDf.index.hour * 60 + startDistrictDf.index.minute) / 10\n timeIndex += 1\n startDistrictDf['time_period'] = timeIndex\n\n # group by time_period column and count records (if driver_id == NaN, the record will not be counted )\n requestAnswerDf = startDistrictDf.groupby('time_period').count()\n\n # requestAnswerDf[['driver_id', 'order_id']].plot()\n requestAnswerDf['gap'] = requestAnswerDf['order_id'] - requestAnswerDf['driver_id']\n\n requestAnswerDf[['order_id','driver_id']].plot()\n\n else:\n for date in dateList:\n filedir = 'season_1/training_data/order_data/order_data_' + date\n orderDf = pd.read_csv(filedir, sep='\\t', header=None, names=orderNames, index_col='Time', parse_dates=True)\n\n # specify the start_district\n orderHashDf = orderDf[orderDf['start_district_hash'] == self.numberToHash[district['districtNum']]]\n timeIndex = (orderHashDf.index.hour * 60 + orderHashDf.index.minute) / 10\n timeIndex += 1\n orderHashDf['time_period'] = timeIndex\n\n requestAnswerDf = orderHashDf.groupby('time_period').count()\n\n requestAnswerDf['gap'] = requestAnswerDf['order_id'] - requestAnswerDf['driver_id']\n\n requestAnswerDf[['order_id','driver_id']].plot()\n","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"610357855","text":"import numpy as np\n\n\ndef main():\n with open(\"/Users/sangmin/Downloads/wssa\", 'rb') as f:\n byte = f.read(16+4+8+5+28+18+80 )\n next_byte = f.read(88)\n #print(byte)\n print(next_byte)\n #print(byte.split())\n print(next_byte.split())\n # Headder 180\n # Headlen 2887\n # curpops 171\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"ssw2txt/phsp_read.py","file_name":"phsp_read.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"86106432","text":"\"\"\"ch10 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom myapp import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('home/', views.home),\n path('login/', views.login),\n path('logout/', views.logout),\n path('userinfo/', views.userinfo),\n path('vote_item/', views.vote_item),\n path('test/', views.test),\n path('voting/<int:poll_id>/', views.voting, name='voting-url'),\n path('voting/<int:poll_id>/<int:item_id>/', views.voting, name='voting-url'),\n path('govote/', views.govote),\n \n # django allauth\n path('account/', include('allauth.urls')),\n # registration.backends.default.urls\n]\n\n\n","sub_path":"ch10/ch10/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"58419560","text":"from argparse import ArgumentParser\nfrom re import findall\nfrom sys import exit\nfrom urllib.request import Request, urlopen\nfrom urllib.error import URLError, HTTPError\n\n\ndef get_rss(url: str) -> str:\n try:\n response = urlopen(Request(url))\n except HTTPError as e:\n print('[-] Error code: ', e.code)\n exit(1)\n except URLError as e:\n print('[-] Reason: ', e.reason)\n exit(1)\n else:\n rss_str = findall(r'channel-external-id=\"(.*?)\"', response.read().decode('utf-8').strip())[1]\n\n return 'https://www.youtube.com/feeds/videos.xml?channel_id=' + rss_str\n\nif __name__ == '__main__':\n parser = ArgumentParser(description='Fetches the RSS feed url of a given youtube channel.')\n parser.add_argument('url', help='The full youtube channel url.')\n print('[+] RSS Url: ', get_rss(parser.parse_args().url))\n","sub_path":"Youtube-Rss/Youtube-Rss.py","file_name":"Youtube-Rss.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"343423250","text":"# import sys\n# import re\nimport time\nimport requests\nfrom lxml import etree\nfrom lxml import html\nfrom unidecode import unidecode\nfrom itertools import chain\n\nimport os\nif 'API_KEY' in os.environ:\n API_KEY = os.environ.get('API_KEY')\n pass\nelse:\n from CapProj.settings_secret import API_KEY\n\n#What does this do?\n# try:\n# from urllib.request import urlopen\n# except ImportError:\n# from urllib2 import urlopen\n\n\"\"\"\nThis coded was taken from\nTitipata's pubmed_parser (https://github.com/titipata/pubmed_parser) and only slightly modified for my needs.\nTitipat Achakulvisut, Daniel E. Acuna (2015) \"Pubmed Parser\" http://github.com/titipata/pubmed_parser. http://doi.org/10.5281/zenodo.159504\n\"\"\"\n\nclass Pubmed:\n def stringify_children(node):\n \"\"\"\n Filters and removes possible Nones in texts and tails\n ref: http://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml\n \"\"\"\n parts = ([node.text] +\n list(chain(*([c.text, c.tail] for c in node.getchildren()))) +\n [node.tail])\n return ''.join(filter(None, parts))\n\n def load_xml(pmid, sleep=None):\n \"\"\"\n Load XML file from given pmid from eutils site\n return a dictionary for given pmid and xml string from the site\n sleep: how much time we want to wait until requesting new xml\n \"\"\"\n link = \"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&id=%s\" % str(pmid) + \"&api_key=\" + API_KEY\n print(link)\n page = requests.get(link)\n tree = html.fromstring(page.content)\n if sleep is not None:\n time.sleep(sleep)\n return tree\n\n\n def parse_pubmed_web_tree(tree):\n \"\"\"\n Giving tree, return simple parsed information from the tree\n \"\"\"\n\n if tree.xpath('//articletitle') is not None:\n title = ' '.join([title.text for title in tree.xpath('//articletitle')])\n else:\n title = ''\n\n abstract_tree = tree.xpath('//abstract/abstracttext')\n abstract = ' '.join([Pubmed.stringify_children(a).strip() for a in abstract_tree])\n\n if tree.xpath('//article//title') is not None:\n journal = ';'.join([t.text.strip() for t in tree.xpath('//article//title')])\n else:\n journal = ''\n\n pubdate = tree.xpath('//pubmeddata//history//pubmedpubdate[@pubstatus=\"medline\"]')\n if len(pubdate) >= 1 and pubdate[0].find('year') is not None:\n year = pubdate[0].find('year').text\n else:\n year = ''\n\n affiliations = list()\n if tree.xpath('//affiliationinfo/affiliation') is not None:\n for affil in tree.xpath('//affiliationinfo/affiliation'):\n affiliations.append(affil.text)\n affiliations_text = '; '.join(affiliations)\n\n authors_tree = tree.xpath('//authorlist/author')\n authors = list()\n if authors_tree is not None:\n for a in authors_tree:\n firstname = a.find('forename').text if a.find('forename') is not None else ''\n lastname = a.find('lastname').text if a.find('forename') is not None else ''\n fullname = (firstname + ' ' + lastname).strip()\n if fullname == '':\n fullname = a.find('collectivename').text if a.find('collectivename') is not None else ''\n authors.append(fullname)\n authors_text = '; '.join(authors)\n else:\n authors_text = ''\n\n dict_out = {'title': title,\n 'journal': journal,\n 'affiliation': affiliations_text,\n 'authors': authors_text,\n 'year': year,\n 'abstract': abstract}\n return dict_out\n\n\n def parse_xml_web(pmid, sleep=None, save_xml=False):\n \"\"\"\n Give pmid, load and parse xml from Pubmed eutils\n if save_xml is True, save xml output in dictionary\n \"\"\"\n tree = Pubmed.load_xml(pmid, sleep=sleep)\n dict_out = Pubmed.parse_pubmed_web_tree(tree)\n dict_out['pmid'] = str(pmid)\n if save_xml:\n dict_out['xml'] = etree.tostring(tree)\n return dict_out\n","sub_path":"CapApp/pubmed.py","file_name":"pubmed.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"566715739","text":"\"\"\"\n244. Shortest Word Distance II\n\n\nDesign a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.\n\nExample:\nAssume that words = [\"practice\", \"makes\", \"perfect\", \"coding\", \"makes\"].\n\nInput: word1 = “coding”, word2 = “practice”\nOutput: 3\nInput: word1 = \"makes\", word2 = \"coding\"\nOutput: 1\nNote:\nYou may assume that word1 does not equal to word2, and word1 and word2 are both in the list.\n\n\n\"\"\"\n\n# list compression, pre-processing\n\n\nclass WordDistance:\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n self.map = {}\n for i, word in enumerate(words):\n if word not in self.map:\n self.map[word] = [i]\n else:\n self.map[word].append(i)\n\n def shortest(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n l1 = self.map[word1]\n l2 = self.map[word2]\n return min([abs(x - y) for x in l1 for y in l2])\n\n# Your WordDistance object will be instantiated and called as such:\n# obj = WordDistance(words)\n# param_1 = obj.shortest(word1,word2)\n\n\n\n\n# slight improvement O(n)\nclass WordDistance:\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n self.map = {}\n for i, word in enumerate(words):\n if word not in self.map:\n self.map[word] = [i]\n else:\n self.map[word].append(i)\n\n def shortest(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n l1 = self.map[word1]\n l2 = self.map[word2]\n idx1, idx2 = 0, 0\n res = float('inf')\n while idx1 < len(l1) and idx2 < len(l2):\n res = min(res, abs(l2[idx2] - l1[idx1]))\n if l1[idx1] < l2[idx2]:\n idx1 += 1\n else:\n idx2 += 1\n return res\n\n# Your WordDistance object will be instantiated and called as such:\n# obj = WordDistance(words)\n# param_1 = obj.shortest(word1,word2)\n\n\n# 2020/05/03, hashtable + binary search\n# O(NlgN), not good\n\n'''\nRuntime: 104 ms, faster than 54.09% of Python3 online submissions for Shortest Word Distance II.\nMemory Usage: 21.3 MB, less than 50.00% of Python3 online submissions for Shortest Word Distance II.\n'''\n\nclass WordDistance:\n\n def __init__(self, words: List[str]):\n self.m = collections.defaultdict(list)\n for i, word in enumerate(words):\n self.m[word].append(i)\n\n def shortest(self, word1: str, word2: str) -> int:\n l1, l2 = self.m[word1], self.m[word2]\n res = float(\"inf\")\n for i in l1:\n d = self.search(l2, i)\n res = min(d, res)\n return res\n\n def search(self, nums, target):\n l, r = 0, len(nums) - 1\n while l + 1 < r:\n m = (l + r) >> 1\n if target < nums[m]:\n r = m\n else:\n l = m\n c1, c2 = abs(nums[l] - target), abs(nums[r] - target)\n return c1 if c1 < c2 else c2\n\n# 2020/05/03, two pointers in same direction\n\n'''\nRuntime: 100 ms, faster than 76.52% of Python3 online submissions for Shortest Word Distance II.\nMemory Usage: 21.1 MB, less than 50.00% of Python3 online submissions for Shortest Word Distance II.\n'''\n\n\nclass WordDistance:\n\n def __init__(self, words: List[str]):\n self.m = collections.defaultdict(list)\n for i, word in enumerate(words):\n self.m[word].append(i)\n\n def shortest(self, word1: str, word2: str) -> int:\n l1, l2 = self.m[word1], self.m[word2]\n res = float(\"inf\")\n i1, i2 = 0, 0\n while i1 < len(l1) and i2 < len(l2):\n res = min(res, abs(l2[i2] - l1[i1]))\n if l1[i1] < l2[i2]:\n i1 += 1\n else:\n i2 += 1\n return res","sub_path":"0244. Shortest Word Distance II.py","file_name":"0244. Shortest Word Distance II.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"571163391","text":"#call largest_component.py before this script!\nimport sys\nimport multiprocessing\nfrom joblib import Parallel, delayed\nimport pandas as pd\nimport SimpleITK as sitk\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nfrom scipy.ndimage import morphology\nsys.path.append(\"..\") # Adds higher directory to python modules path.\nsys.path.append(\"../..\") # Adds higher directory to python modules path.\nsys.path.append(\"../measures/\") # Adds higher directory to python modules path.\nfrom measures.measures import DSC_MSD_HD95\n\n# from read_data import _read_data\nvali=1\nif vali==1:\n out_dir = 'result_vali/'\nelse:\n out_dir = 'result/'\n # out_dir = 'result2/'\ntest_path='/srv/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2018-08-15/00_Seperate_training_2nddataset/13331_0.75_4-cross-noRand-train2test2--8/'\ntest_path='/srv/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2018-08-15/00_Seperate_training_1stdataset/13331_0.75_4-cross-noRand-train1-107/'\ntest_path='/srv/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2018-08-15/cross_validation/13331_0.75_4-cross-NoRand-tumor25-004/'\ntest_path='/srv/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2018-08-15/00_Seperate_training_2nddataset/13331_0.75_4-cross-noRand-train2test2--6/'\ntest_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-04172020_140/' #Dunet\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-04252020_220/'=\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-07052020_000/'\n\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-07102020_140/'=\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-07142020_020/'=\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-04302020_090/'\n# test_path='/srv/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2018-08-15/00_Seperate_training_1stdataset/13331_0.75_4-cross-noRand-train1-104/'\n\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-08052020_140/'\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-08132020_10590/'\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-08132020_120/'\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-08242020_1950240/'\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-08242020_1950240/'\ntest_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-08272020_161/' #fold1\ntest_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-09042020_152/' #fold2\n# test_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-05082020_090/' #distance map\ntest_path='/exports/lkeb-hpc/syousefi/2-lkeb-17-dl01/syousefi/TestCode/EsophagusProject/Code/Log_2019_09_23/Dataset3/33533_0.75_4-train1-07032020_170/'\neps=10e-6\ndef surfd(input1, input2, sampling=1, connectivity=1):\n input_1 = np.atleast_1d(input1.astype(np.bool))\n input_2 = np.atleast_1d(input2.astype(np.bool))\n\n conn = morphology.generate_binary_structure(input_1.ndim, connectivity)\n\n S = (input_1.astype(np.int)) - (morphology.binary_erosion(input_1, conn).astype(np.int))\n Sprime = input_2.astype(np.int) - morphology.binary_erosion(input_2, conn).astype(np.int)\n\n dta = morphology.distance_transform_edt(~S, sampling)\n dtb = morphology.distance_transform_edt(~Sprime, sampling)\n\n sds = np.concatenate([np.ravel(dta[Sprime != 0]), np.ravel(dtb[S != 0])])\n\n return sds\ndef read_names( tag='_result.mha'):\n\n gtv_names = [join(test_path+out_dir, g) for g in [f for f in listdir(test_path + out_dir) if ~isfile(join(test_path, f)) \\\n and not join(test_path, f).endswith('_fuzzy_result.mha')] if g.endswith(tag)]\n gtv_names=np.sort(gtv_names)\n return gtv_names\ndef tp_tn_fp_fn(logits, labels):\n y_pred = np.asarray(logits).astype(np.bool)\n y_true = np.asarray(labels).astype(np.bool)\n im1 = y_pred.flatten()\n im2 = y_true.flatten()\n TP_t = len(np.where((im1 == True) & (im2 == True))[0])\n TN_t = len(np.where((im1 == False) & (im2 == False))[0])\n FP_t = len(np.where((im1 == True) & (im2 == False))[0])\n FN_t = len(np.where((im1 == False) & (im2 == True))[0])\n\n TP_b = len(np.where((im1 == False) & (im2 == False))[0])\n TN_b = len(np.where((im1 == True) & (im2 == True))[0])\n FP_b = len(np.where((im1 == False) & (im2 == True))[0])\n FN_b = len(np.where((im1 == True) & (im2 == False))[0])\n\n TP=np.array((TP_t,TP_b))\n\n TN = np.array((TN_t,TN_b))\n\n FP = np.array((FP_t,FP_b))\n\n FN = np.array((FN_t,FN_b))\n\n return TP,TN,FP,FN\ndef Precision(TP,TN,FP,FN):\n precision=TP/(TP+FP+ eps)\n return precision\n\ndef Recall(TP,TN,FP,FN):\n recall=TP/(TP+FN+ eps)\n return recall\ndef f1_measure(TP,TN,FP,FN):\n precision=Precision(TP,TN,FP,FN)\n recall=Recall(TP,TN,FP,FN)\n f1 = 2 * (precision * recall) / (precision + recall + eps) # f0:background, f1: tumor\n # print(f1)\n return f1\n\ndef get_largest_component(predicted_image_path,out_image_name) :\n # read the input image\n maskImg = sitk.ReadImage(predicted_image_path)\n maskImg = sitk.Cast(maskImg, sitk.sitkUInt8)\n\n # initialize the connected component filter\n ccFilter = sitk.ConnectedComponentImageFilter()\n # apply the filter to the input image\n labelImg = ccFilter.Execute(maskImg)\n # get the number of labels (connected components)\n numberOfLabels = ccFilter.GetObjectCount()\n # print('numberOfLabels: %d'%numberOfLabels)\n # extract the data array from the itk object\n labelArray = sitk.GetArrayFromImage(labelImg)\n # count the voxels belong to different components\n labelSizes = np.bincount(labelArray.flatten())\n # get the largest connected component\n\n if len(labelSizes[1:])!=0:\n largestLabel = np.argmax(labelSizes[1:]) + 1\n # convert the data array to itk object\n outImg = sitk.GetImageFromArray((labelArray == largestLabel).astype(np.uint8))\n # output image should have same metadata as input mask image\n outImg.CopyInformation(maskImg)\n voxel_size = maskImg.GetSpacing()\n origin = maskImg.GetOrigin()\n direction = maskImg.GetDirection()\n outImg.SetDirection(direction=direction)\n outImg.SetOrigin(origin=origin)\n outImg.SetSpacing(spacing=voxel_size)\n else:\n outImg=maskImg\n\n # write the image to the disk\n sitk.WriteImage(outImg, out_image_name)\n\ndef overlapped_component(predicted_image_path,overlapped_name) :\n # read the input image\n maskImg = sitk.ReadImage(predicted_image_path)\n outImg =maskImg\n maskImg = sitk.Cast(maskImg, sitk.sitkUInt8)\n gtvImg = sitk.GetArrayFromImage(sitk.ReadImage(predicted_image_path.split('_result.mha')[0]+'_gtv.mha'))\n # torsoImg = sitk.GetArrayFromImage(sitk.ReadImage(predicted_image_path.split('_result.mha')[0]+'_T.mha'))\n # initialize the connected component filter\n ccFilter = sitk.ConnectedComponentImageFilter()\n # apply the filter to the input image\n labelImg = ccFilter.Execute(maskImg)\n # get the number of labels (connected components)\n numberOfLabels = ccFilter.GetObjectCount()\n # print('numberOfLabels: %d'%numberOfLabels)\n if numberOfLabels>1:\n # extract the data array from the itk object\n labelArray = sitk.GetArrayFromImage(labelImg)\n # count the voxels belong to different components\n labelSizes = np.bincount(labelArray.flatten())\n # get the largest connected component\n\n if len(labelSizes[1:])!=0:\n indx = np.where((labelArray * gtvImg))\n if len(indx[0]):\n largestLabel = np.unique(labelArray[indx])[0]\n # overlayLabel=\n # convert the data array to itk object\n outImg = sitk.GetImageFromArray((labelArray == largestLabel).astype(np.uint8))\n # output image should have same metadata as input mask image\n outImg.CopyInformation(maskImg)\n voxel_size = maskImg.GetSpacing()\n origin = maskImg.GetOrigin()\n direction = maskImg.GetDirection()\n outImg.SetDirection(direction=direction)\n outImg.SetOrigin(origin=origin)\n outImg.SetSpacing(spacing=voxel_size)\n else:\n outImg=maskImg\n\n # write the image to the disk\n sitk.WriteImage(outImg, overlapped_name)\n return sitk.GetArrayFromImage(outImg)\ndef compute_tp_tn_fp_fn(result,Gtv,\n overlapped_name ,result_lc,\n ):\n print(result.split('/')[-1])\n sitk_res=sitk.ReadImage(result)\n res = sitk.GetArrayFromImage(sitk_res)\n sitk_res_lc=sitk.ReadImage(result_lc)\n res_lc = sitk.GetArrayFromImage(sitk_res_lc)\n sitk_gtv=sitk.ReadImage(Gtv)\n gtv = sitk.GetArrayFromImage(sitk_gtv)\n\n dice, msd, hd_percentile, jaccard, vol_similarity= DSC_MSD_HD95(sitk_gtv,sitk_res)\n dice_lc, msd_lc, hd_percentile_lc, jaccard_lc, vol_similarity_lc= DSC_MSD_HD95(sitk_gtv,sitk_res_lc)\n\n # hausdorff_distance_image_filter = sitk.HausdorffDistanceImageFilter()\n # hausdorff_distance_image_filter.Execute(gtv, res)\n # hausdorff_distance_image_filter.Execute(gtv, res)\n\n overlapped=sitk.GetArrayFromImage(sitk.ReadImage(overlapped_name))\n\n\n if len(np.where(gtv)[0]) == 0 or len(np.where(overlapped)[0]) == 0:\n x = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n else:\n top_prep_dis=max(np.where(gtv)[0])-max(np.where(overlapped)[0])\n bottom_prep_dis=min(np.where(gtv)[0])-min(np.where(overlapped)[0])\n\n\n\n [TP, TN, FP, FN] = tp_tn_fp_fn(res, gtv)\n f1 = f1_measure(TP, TN, FP, FN)\n\n\n\n dsc_res.append(f1[0])\n\n [TP, TN, FP, FN] = tp_tn_fp_fn(res_lc, gtv)\n f1_lc = f1_measure(TP, TN, FP, FN)\n\n\n top_prep_dis_lc=max(np.where(gtv)[0])-max(np.where(overlapped)[0])\n bottom_prep_dis_lc=min(np.where(gtv)[0])-min(np.where(overlapped)[0])\n\n # srfd = surfd(res_lc, gtv, [3, 1, 1])\n # msd = srfd.mean()\n # hd = srfd.max()\n # rms = np.sqrt((srfd ** 2).mean())\n\n dsc_res_lc.append(f1_lc[0])\n x=np.array([TP[0],TP[1],\n TN[0],\n TN[1], FP[0],\n FP[1], FN[0],\n FN[1],f1[0],f1_lc[0],\n top_prep_dis,bottom_prep_dis,\n top_prep_dis_lc,bottom_prep_dis_lc,\n jaccard, msd, hd_percentile,\n jaccard_lc,msd_lc,hd_percentile_lc\n ])\n # if not len(dsc):\n # dsc=x\n # else:\n # dsc=np.vstack((dsc,x))\n # name_list.append(result[i].split('/')[-1].split('_result.mha')[0])\n\n\n # print('hd:%f,msd:%f' % (hd, msd))\n print('%s: f1:%f ' % (result.split('/')[-1], f1[0] ))\n return result.split('/')[-1].split('_result.mha')[0],x\n\n\n\nif __name__=='__main__':\n\n result=read_names()\n result=np.sort(result)\n result_lc=read_names('_result_lc.mha')\n result_lc=np.sort(result_lc)\n Gtv=read_names('_gtv.mha')\n Gtv=np.sort(Gtv)\n dsc_res=[]\n dsc_res_lc=[]\n dsc=[]\n name_list=[]\n\n num_cores = 16#multiprocessing.cpu_count()\n print('===============================')\n print('===============================')\n print('num_cores:')\n print(num_cores)\n print('===============================')\n print('===============================')\n\n Parallel(n_jobs=num_cores)(\n delayed(get_largest_component)(predicted_image_path=result[i],\n out_image_name=result[i].split('_result.mha')[0]+'_result_lc.mha',\n )\n for i in range(len(result)))#\n print('end get_largest_component')\n print('===============================')\n print('===============================')\n\n Parallel(n_jobs=num_cores)(\n delayed(overlapped_component)(predicted_image_path=result[i],\n overlapped_name=result[i].split('_result.mha')[0]+'_result_ov.mha'\n )\n for i in range(len(result)))#\n print('end overlapped_component')\n print('===============================')\n print('===============================')\n res=Parallel(n_jobs=num_cores)(\n delayed(compute_tp_tn_fp_fn)(result=result[i],\n result_lc=result[i].split('_result.mha')[0]+'_result_lc.mha',\n Gtv=Gtv[i],\n overlapped_name=result[i].split('_result.mha')[0]+'_result_ov.mha'\n )\n for i in range(len(result)))#\n\n dsc=[]\n name_list=[]\n tp_list=[]\n tn_list=[]\n fp_list=[]\n fn_list=[]\n for i in range(len(res)):\n if np.sum(res[i][1])==0:\n continue\n name_list.append(res[i][0])\n if not len(dsc):\n dsc=res[i][1]\n else:\n dsc=np.vstack((dsc,res[i][1]))\n\n\n # Create a Pandas dataframe from some data.\n\n df = pd.DataFrame(dsc,\n index=name_list,\n columns=pd.Index(['TP_tumor','TP_back',\n 'TN_tumor','TN_back',\n 'FP_tumor', 'FP_back',\n 'FN_tumor', 'FN_back',\n 'DCS-LC', 'DCS+LC',\n 'top_prep_dis','bottom_prep_dis',\n 'top_prep_dis_lc', 'bottom_prep_dis_lc',\n 'jaccard','msd','95hd',\n 'jaccard_lc','msd_lc','95hd_lc'\n ],\n name='Genus')).round(2)\n\n\n # Create a Pandas Excel writer using XlsxWriter as the engine.\n writer = pd.ExcelWriter(test_path+out_dir+'/all_dice2.xlsx',\n engine='xlsxwriter')\n\n # Convert the dataframe to an XlsxWriter Excel object.\n df.to_excel(writer, sheet_name='Sheet1')\n\n # Close the Pandas Excel writer and output the Excel file.\n writer.save()\n\n df.plot(kind='bar',figsize=(10,4))\n\n ax = plt.gca()\n pos = []\n for bar in ax.patches:\n pos.append(bar.get_x()+bar.get_width()/2.)\n\n\n ax.set_xticks(pos,minor=True)\n lab = []\n for i in range(len(pos)):\n l = df.columns.values[i//len(df.index.values)]\n lab.append(l)\n\n ax.set_xticklabels(lab,minor=True)\n ax.tick_params(axis='x', which='major', pad=15, size=0)\n plt.setp(ax.get_xticklabels(), rotation=0)\n\n plt.margins(.05)\n plt.ylim([0,1])\n plt.grid()\n\n plt.savefig(test_path+out_dir+'dsc_bar2.png')\n\n # plt.figure()\n # ax = plt.gca()\n fig, ax1 = plt.subplots(figsize=(10, 6))\n bp = plt.boxplot(dsc, notch=0, sym='+', vert=1, whis=1.5, showmeans=True)\n ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',\n alpha=0.5)\n # bp=plt.boxplot(dsc, 0, 'rs')\n ax.set_xticklabels(['-CS', '+CS'])\n plt.ylim([0,1])\n plt.grid()\n plt.savefig(test_path+out_dir+'dsc_bp2.png')\n # plt.show()","sub_path":"functions/plot/boxplot_results.py","file_name":"boxplot_results.py","file_ext":"py","file_size_in_byte":16234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"275070972","text":"#!/usr/bin/python\n\n# ~~~~~============== HOW TO RUN ==============~~~~~\n# 1) Configure things in CONFIGURATION section\n# 2) Change permissions: chmod +x bot.py\n# 3) Run in loop: while true; do ./bot.py; sleep 1; done\n\nfrom __future__ import print_function\n\nimport sys\nimport socket\nimport json\nimport functions\nimport time\n\n# ~~~~~============== CONFIGURATION ==============~~~~~\n# replace REPLACEME with your team name!\nteam_name=\"BIGMONEY\"\n# This variable dictates whether or not the bot is connecting to the prod\n# or test exchange. Be careful with this switch!\ntest_mode = True\n\n# This setting changes which test exchange is connected to.\n# 0 is prod-like\n# 1 is slower\n# 2 is empty\ntest_exchange_index=0\nprod_exchange_hostname=\"production\"\n\nport=25000 + (test_exchange_index if test_mode else 0)\nexchange_hostname = \"test-exch-\" + team_name if test_mode else prod_exchange_hostname\n\n# ALGORITHM\nprevious_buy_price = 1000\nprevious_sell_price = 1001\norder_id = 0\nbought = False\n\n# ~~~~~============== NETWORKING CODE ==============~~~~~\ndef connect():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((exchange_hostname, port))\n return s.makefile('rw', 1)\n\ndef write_to_exchange(exchange, obj):\n json.dump(obj, exchange)\n exchange.write(\"\\n\")\n\ndef read_from_exchange(exchange):\n x = None \n while not x:\n x = exchange.readline()\n try:\n return json.loads(x)\n except Exception:\n print(\"Bad message:\", x)\n raise\n# ~~~~~============== MAIN LOOP ==============~~~~~\ndef xlf_strat(exchange, fair_xlf, buy_price, sell_price, order_id, capacity):\n # try:\n if buy_price != None and buy_price[-1][0] < fair_xlf and capacity < 10:\n write_to_exchange(exchange, {\"type\": \"add\", \"order_id\": order_id, \"symbol\": \"XLF\", \"dir\": \"BUY\", \"price\": buy_price[-1][0], \"size\": min(buy_price[-1][1], 10 - capacity)})\n print(f\"Bought {buy_price[-1][1]} units at {buy_price[-1][0]}\")\n\n return capacity + min(buy_price[-1][0], 10 - capacity)\n \n elif sell_price != None and sell_price[-1] != None and sell_price[-1][0] > fair_xlf and capacity > 0:\n write_to_exchange(exchange, {\"type\": \"add\", \"order_id\": order_id, \"symbol\": \"XLF\", \"dir\": \"SELL\", \"price\": sell_price[-1][0], \"size\": min(sell_price[-1][1], capacity)})\n print(f\"Sold {sell_price[-1][1]} units at {sell_price[-1][0]}\")\n return capacity - min(sell_price[-1][1], capacity)\n #except:\n # print(\"error - xlf_strat\")\n # print(f\"{fair_xlf} - {buy_price[-1][0]} - {sell_price[-1][0]}\")\n\n\n\ndef main():\n exchange = connect()\n write_to_exchange(exchange, {\"type\": \"hello\", \"team\": team_name.upper()})\n hello_from_exchange = read_from_exchange(exchange)\n print(\"The exchange replied:\", hello_from_exchange, file=sys.stderr)\n\n # A common mistake people make is to call write_to_exchange() > 1\n # time for every read_from_exchange() response.\n # Since many write messages generate marketdata, this will cause an\n # exponential explosion in pending messages. Please, don't do that!\n\n fair_bond = 1000\n fair_gs = None\n fair_ms = None\n fair_wfc = None\n\n order_id = 0\n capacity = 0\n\n while True:\n cur_state = read_from_exchange(exchange)\n if cur_state[\"type\"] == 'close':\n break\n # print(cur_state)\n if cur_state['type'] == 'book' and cur_state['symbol'] == 'GS':\n buy_price = cur_state['buy']\n sell_price = cur_state['sell']\n # try: \n if buy_price != [] and sell_price != []:\n fair_gs = (buy_price[0][0] + sell_price[0][0]) / 2\n # except:\n # print(\"error\")\n\n elif cur_state['type'] == 'book' and cur_state['symbol'] == 'MS':\n buy_price = cur_state['buy']\n sell_price = cur_state['sell']\n if buy_price != [] and sell_price != []:\n fair_ms = (buy_price[0][0] + sell_price[0][0]) / 2\n # except:\n # print(\"error\")\n\n elif cur_state['type'] == 'book' and cur_state['symbol'] == 'WFC':\n buy_price = cur_state['buy']\n sell_price = cur_state['sell']\n # try:\n if buy_price != [] and sell_price != []:\n fair_wfc = (buy_price[0][0] + sell_price[0][0]) / 2\n # except:\n # print(\"error\")\n\n elif cur_state['type'] == 'book' and cur_state['symbol'] == 'XLF' and fair_gs is not None and fair_ms is not None and fair_wfc is not None:\n \n fair_xlf_est = 0.3 * fair_bond + 0.2 * fair_gs + 0.3 * fair_ms + 0.2 * fair_wfc\n buy_price = cur_state['buy']\n sell_price = cur_state['sell']\n if buy_price != [] and sell_price != []:\n capacity = xlf_strat(exchange, fair_xlf_est, buy_price, sell_price, order_id, capacity)\n order_id += 1\n \n elif cur_state['type'] == 'ack' or cur_state['type'] == 'reject':\n # print(cur_state)\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bot3.py","file_name":"bot3.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"500267529","text":"\"\"\"\n 创建颜色类,创建颜色列表\n 通过内置函数实现以下功能:\n 获取颜色最深(r+g+b)的\n 查找Color(1,0,1)的数量\n 查找Color(1,0,1)的索引 列表.index\n\"\"\"\n\n\nclass Color:\n def __init__(self, r, g, b):\n self.r = r\n self.g = g\n self.b = b\n\n def __gt__(self, other):\n return self.r + self.g + self.b > other.r + other.g + other.b\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n\nlist_color = [\n Color(0.1, 0.8, 0.2),\n Color(1, 0, 0.5),\n Color(1, 0, 1),\n Color(0, 1, 1),\n]\n\nmax_value = max(list_color)\nprint(max_value.__dict__)\n\ncount = list_color.count(Color(1, 0, 1))\nprint(count)\n\nindex = list_color.index(Color(1, 0, 1))\nprint(index)\n","sub_path":"fancy_month01/day11_fancy/day11_teacher/exercise04.py","file_name":"exercise04.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"103856371","text":"import bpy\nfrom .particle import apply_force\nfrom .particle import particle_system\nfrom .particle import solver\nfrom .particle import custom_prop\nfrom .particle import utils\nfrom .particle import constraint\nfrom .particle import collision\nfrom bpy.props import BoolProperty, EnumProperty\nfrom mathutils import Vector, Matrix\nimport subprocess\nimport os\n\n\n# Install dependency in blender environment\ndef check_deps(deps_list):\n py_exec = bpy.app.binary_path_python\n for deps in deps_list:\n if not os.path.exists(os.path.join(str(py_exec)[:-14] + 'lib', deps)):\n print('Installing dependency')\n # ensure pip is installed\n subprocess.call([str(py_exec), \"-m\", \"ensurepip\", \"--user\"])\n # update pip\n subprocess.call([str(py_exec), \"-m\", \"pip\", \"install\", \"--upgrade\", \"pip\"])\n # install packages\n subprocess.call([str(py_exec), \"-m\", \"pip\", \"install\", f\"--target={str(py_exec)[:-14]}\" + \"lib\", deps])\n\n\ncheck_deps(deps_list=[\"scipy\", \"numpy\"])\n\nbl_info = {\n \"name\": \"Particle Simulation Addon\",\n \"author\": \"Edge\",\n \"version\": (1, 0, 0),\n \"blender\": (2, 83, 5),\n \"description\": \"particle simulation\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"support\": 'TESTING',\n \"category\": \"Particle\",\n}\n\nclass DeleteParticleSystemOperator(bpy.types.Operator):\n bl_idname = \"delete_system.particle\"\n bl_label = \"delete current custom particle system\"\n bl_description = \"delete current custom particle system\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.delete_instance()\n current_collection = bpy.data.collections.get(\"Custom Particle System\")\n if current_collection != None:\n bpy.ops.object.select_all(action='DESELECT')\n for ob in current_collection.objects:\n ob.select_set(True)\n bpy.ops.object.delete()\n bpy.data.collections.remove(current_collection)\n\n return {'FINISHED'}\n\nclass ApplyConstantForceOperator(bpy.types.Operator):\n bl_idname = \"apply_constant_force.particle\"\n bl_label = \"apply constant force on particle system\"\n bl_description = \"select object and apply constant force on it\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n # p_system.add_force(apply_force.ConstantForce(context.scene.constant_force_vector))\n p_system.add_force(apply_force.ConstantForce())\n return {'FINISHED'}\n\nclass ApplyDampingForceOperator(bpy.types.Operator):\n bl_idname = \"apply_damping_force.particle\"\n bl_label = \"apply damping force on particle system\"\n bl_description = \"select object and apply damping force on it\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.add_force(apply_force.DampingForce())\n return {'FINISHED'}\n\nclass ApplySpringForceOperator(bpy.types.Operator):\n bl_idname = \"apply_spring_force.particle\"\n bl_label = \"apply spring force on particle system\"\n bl_description = \"select object and apply spring force on it\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n spring_force = apply_force.SpringForce()\n p_system.add_force(spring_force)\n return {'FINISHED'}\n\nclass CalculateFrameOperator(bpy.types.Operator):\n bl_idname = \"particle.calculate_frame\"\n bl_label = \"Calculate frame on blender particle system\"\n bl_description = \"Calculate frame on blender particle system\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.update_to_object(context, calculate_frame=True)\n return {'FINISHED'}\n\nclass AddParticleOperator(bpy.types.Operator):\n bl_idname = \"add.particle\"\n bl_label = \"Add particle to custom particle system\"\n bl_description = \"add particle custom particle system\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n if len(p_system.particle_list) == 0:\n p_system.add_particle()\n else:\n latest_location = p_system.particle_list[-1].location\n p_system.add_particle(latest_location + Vector((2.0, 0.0, 0.0)))\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.update_to_object(context)\n return {'FINISHED'}\n\nclass RemoveParticleOperator(bpy.types.Operator):\n bl_idname = \"remove.particle\"\n bl_label = \"Remove particle to custom particle system\"\n bl_description = \"remove particle custom particle system\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.remove_particle(int(context.scene.select_particle_idx))\n p_system.update_to_object(context)\n return {'FINISHED'}\n\nclass SyncParticleInitOperator(bpy.types.Operator):\n bl_idname = \"particle.sync_init\"\n bl_label = \"Sync particle initial state\"\n bl_description = \"sync particle initial state\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n particle_idx = int(context.scene.select_particle_idx)\n new_location = p_system.init_particle_list[particle_idx].location\n new_mass = p_system.init_particle_list[particle_idx].mass\n particle_ob = bpy.data.objects.get(str(particle_idx))\n bpy.ops.object.select_all(action='DESELECT')\n particle_ob.select = True\n context.view_layer.objects.active = particle_ob\n particle_ob.location = Vector(new_location)\n particle_ob.scale = Vector(\n (new_mass, new_mass, new_mass))\n return {'FINISHED'}\n\nclass ApplySolverOperator(bpy.types.Operator):\n bl_idname = \"apply.solver\"\n bl_label = \"Apply solver to custom particle system\"\n bl_description = \"apply solver custom particle system\"\n\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n solver_name = context.scene.solver_name\n if solver_name == \"FOREULER\":\n p_system.solver = solver.ForwardEulerSolver()\n elif solver_name == \"2RK\":\n p_system.solver = solver.SecondOrderRKSolver()\n elif solver_name == \"4RK\":\n p_system.solver = solver.FourthOrderRKSolver()\n elif solver_name == \"VERLET\":\n p_system.solver = solver.VerletSolver()\n elif solver_name == \"LEAPFROG\":\n p_system.solver = solver.LeapfrogSolver()\n elif solver_name == \"BACKEULER\":\n p_system.solver = solver.BackwardEulerSolver()\n return {'FINISHED'}\n\nclass MassSpringSystemOperator(bpy.types.Operator):\n bl_idname = \"particle_system.mass_spring_system\"\n bl_label = \"Create mass spring system\"\n bl_description = \"create mass spring system\"\n\n def execute(self, context):\n mass_spring_system = particle_system.MassSpringSystem()\n return {'FINISHED'}\n\nclass ClothMassSpringSystemOperator(bpy.types.Operator):\n bl_idname = \"particle_system.cloth_mass_spring_system\"\n bl_label = \"Create cloth mass spring system\"\n bl_description = \"create cloth mass spring system\"\n\n def execute(self, context):\n mass_spring_system = particle_system.MassSpringSystem(advance=True)\n return {'FINISHED'}\n\nclass RemoveForceOperator(bpy.types.Operator):\n bl_idname = \"force.remove\"\n bl_label = \"Remove force\"\n bl_description = \"remove force\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n force_idx = int(context.scene.force_name)\n p_system.force_list.pop(force_idx)\n return {'FINISHED'}\n\nclass RemoveConstraintOperator(bpy.types.Operator):\n bl_idname = \"constraint.remove\"\n bl_label = \"Remove constraint\"\n bl_description = \"remove constraint\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n constraint_idx = int(context.scene.constraint_name)\n p_system.constraint_list.pop(constraint_idx)\n return {'FINISHED'}\n\n\nclass AddWallCollisionOperator(bpy.types.Operator):\n bl_idname = \"collision.wall\"\n bl_label = \"Add wall collision\"\n bl_description = \"add wall collision\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n current_collection = bpy.data.collections.get(\"Collision\")\n if current_collection == None:\n current_collection = utils.create_collection(context.scene.collection, \"Collision\")\n plane_ob = utils.create_plane(current_collection, 'Wall collision', Vector((0.0, 0.0, -4.0)))\n wall_collision = collision.WallCollision(plane_ob)\n p_system.add_collision(wall_collision)\n return {'FINISHED'}\n\nclass AddParticleCollisionOperator(bpy.types.Operator):\n bl_idname = \"collision.particle\"\n bl_label = \"Add particle collision\"\n bl_description = \"add particle collision\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.add_collision(collision.ParticleCollision())\n return {'FINISHED'}\n\nclass AddAngularConstraintOperator(bpy.types.Operator):\n bl_idname = \"constraint.angular\"\n bl_label = \"Add angular constraint\"\n bl_description = \"add angular constraint\"\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n axis_particle_idx = int(bpy.context.scene.axis_particle_idx)\n pair_particle_1_idx = int(bpy.context.scene.pair_particle_1_idx)\n pair_particle_2_idx = int(bpy.context.scene.pair_particle_2_idx)\n angular_constraint = constraint.AngularConstraint()\n angular_constraint.axis_particle_idx = axis_particle_idx\n angular_constraint.pair_particle_idx = pair_particle_1_idx, pair_particle_2_idx\n p_system.add_constraint(angular_constraint)\n return {'FINISHED'}\n\n\nclass SaveInitParticleSystemOperator(bpy.types.Operator):\n bl_idname = \"particle_system.save_init\"\n bl_label = \"Save init particle system\"\n bl_description = \"save init particle system\"\n\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\n\n def execute(self, context):\n particle_system.ParticleSystem.save_init_system(self.filepath)\n return {'FINISHED'}\n\n def invoke(self, context, event): # See comments at end [1]\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass LoadInitParticleSystemOperator(bpy.types.Operator):\n bl_idname = \"particle_system.load_init\"\n bl_label = \"Load init particle system\"\n bl_description = \"load init particle system\"\n\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\n\n def execute(self, context):\n particle_system.ParticleSystem.load_init_system(self.filepath)\n return {'FINISHED'}\n\n def invoke(self, context, event): # See comments at end [1]\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass SaveParticleSystemAnimationOperator(bpy.types.Operator):\n bl_idname = \"particle_system.save_animation\"\n bl_label = \"Save particle system animation\"\n bl_description = \"save particle system animation\"\n\n directory = bpy.props.StringProperty(subtype=\"DIR_PATH\")\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.save_animation(self.directory)\n return {'FINISHED'}\n\n def invoke(self, context, event): # See comments at end [1]\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass LoadParticleSystemAnimationOperator(bpy.types.Operator):\n bl_idname = \"particle_system.load_animation\"\n bl_label = \"Load particle system animation\"\n bl_description = \"load particle system animation\"\n\n directory = bpy.props.StringProperty(subtype=\"DIR_PATH\")\n\n def execute(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n p_system.load_animation(self.directory)\n return {'FINISHED'}\n\n def invoke(self, context, event): # See comments at end [1]\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass ParticleSimulationPanel(bpy.types.Panel):\n bl_idname = \"PARTICLE_PT_SIMULATION\"\n bl_label = \"particle simulation panel\"\n bl_category = \"Particle System\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n\n def draw(self, context):\n layout = self.layout\n # scene = context.scene\n\n # FIXME solver update while loading init\n row = layout.row()\n row.prop(context.scene, \"solver_name\", text=\"Solver\")\n row.operator('apply.solver', text=\"Apply\")\n row.separator()\n\n row = layout.row()\n row.operator('delete_system.particle', text=\"Delete particle system\")\n row = layout.row()\n row.label(text='Init particle system')\n row.operator('particle_system.save_init', text=\"Save\")\n row.operator('particle_system.load_init', text=\"Load\")\n row = layout.row()\n row.label(text='Particle system animation')\n row.operator('particle_system.save_animation', text=\"Save animation\")\n row.operator('particle_system.load_animation', text=\"Load animation\")\n\n row = layout.row()\n row.operator('particle.calculate_frame', text=\"Calculate animation\")\n row = layout.row()\n row.operator('particle_system.mass_spring_system', text=\"Mass spring system\")\n row.operator('particle_system.cloth_mass_spring_system', text=\"Cloth system\")\n\nclass ParticleManagePanel(bpy.types.Panel):\n bl_parent_id = \"PARTICLE_PT_SIMULATION\"\n bl_label = \"Particle management\"\n bl_category = \"Particle System\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n\n def draw(self, context):\n layout = self.layout\n # scene = context.scene\n\n row = layout.row()\n row.operator('add.particle', text=\"add particle\")\n row = layout.row()\n row.separator()\n row.prop(context.scene, 'select_particle_idx', text=\"Particle\")\n if context.scene.select_particle_idx != \"None\":\n p_system = particle_system.ParticleSystem.get_instance()\n particle_idx = int(context.scene.select_particle_idx)\n if particle_idx < len(p_system.init_particle_list):\n p_system.draw(context, layout, particle_idx)\n row.operator('remove.particle', text=\"remove particle\")\n\n\nclass ForceManagePanel(bpy.types.Panel):\n bl_parent_id = \"PARTICLE_PT_SIMULATION\"\n bl_label = \"Force management\"\n bl_category = \"Particle System\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n\n def draw(self, context):\n layout = self.layout\n # scene = context.scene\n\n row = layout.row()\n row.operator('apply_constant_force.particle', text=\"Add constant force\")\n row = layout.row()\n row.operator('apply_damping_force.particle', text=\"Add damping force\")\n row = layout.row()\n row.prop(context.scene, 'spring_particle_idx', text=\"spring particle\")\n row.operator('apply_spring_force.particle', text=\"Add spring force\")\n row = layout.row()\n row.separator()\n row.prop(context.scene, 'force_name', text=\"force list\")\n if context.scene.force_name != \"None\":\n p_system = particle_system.ParticleSystem.get_instance()\n force_idx = int(context.scene.force_name)\n if force_idx < len(p_system.force_list):\n p_system.force_list[force_idx].draw(context, layout)\n row.operator('force.remove', text=\"remove current force\")\n\nclass CollisionManagePanel(bpy.types.Panel):\n bl_parent_id = \"PARTICLE_PT_SIMULATION\"\n bl_label = \"Collision management\"\n bl_category = \"Particle System\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n\n def draw(self, context):\n layout = self.layout\n # scene = context.scene\n\n row = layout.row()\n row.operator('collision.wall', text=\"Wall collision\")\n row.operator('collision.particle', text=\"Particle collision\")\n\nclass ConstraintManagePanel(bpy.types.Panel):\n bl_parent_id = \"PARTICLE_PT_SIMULATION\"\n bl_label = \"Constraint management\"\n bl_category = \"Particle System\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n\n def draw(self, context):\n layout = self.layout\n # scene = context.scene\n\n row = layout.row()\n row.prop(context.scene, 'pair_particle_1_idx', text=\"Pair particle 1\")\n row.prop(context.scene, 'axis_particle_idx', text=\"Axis particle\")\n row.prop(context.scene, 'pair_particle_2_idx', text=\"Pair particle 2\")\n row.operator('constraint.angular', text=\"Angular constraint\")\n\n row = layout.row()\n row.separator()\n row.prop(context.scene, 'constraint_name', text=\"Constraint\")\n if context.scene.constraint_name != \"None\":\n p_system = particle_system.ParticleSystem.get_instance()\n constraint_idx = int(context.scene.constraint_name)\n if constraint_idx < len(p_system.constraint_list):\n p_system.constraint_list[constraint_idx].draw(context, layout)\n row.operator('constraint.remove', text=\"remove current constraint\")\n\n\ndef particle_item_callback(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n enum_prop_list = []\n for i, force in enumerate(p_system.init_particle_list):\n enum_prop_list.append((str(i), str(i), str(i)))\n if len(enum_prop_list) == 0:\n enum_prop_list.append((\"None\", \"None\", \"None\"))\n return enum_prop_list\n\ndef force_item_callback(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n enum_prop_list = []\n for i, force in enumerate(p_system.force_list):\n enum_prop_list.append((str(i), str(i) + \" \" + type(force).__name__, str(i) + \" \" + type(force).__name__))\n if len(enum_prop_list) == 0:\n enum_prop_list.append((\"None\", \"None\", \"None\"))\n return enum_prop_list\n\ndef constraint_item_callback(self, context):\n p_system = particle_system.ParticleSystem.get_instance()\n enum_prop_list = []\n for i, constraint in enumerate(p_system.constraint_list):\n enum_prop_list.append((str(i), str(i) + \" \" + type(constraint).__name__, str(i) + \" \" + type(constraint).__name__))\n if len(enum_prop_list) == 0:\n enum_prop_list.append((\"None\", \"None\", \"None\"))\n return enum_prop_list\n\ndef solver_item_callback(self, context):\n return (\n ('FOREULER', 'Forward Euler', \"Forward euler solver\"),\n ('2RK', '2nd order RK', \"2nd order runge kutta solver\"),\n ('4RK', '4th order RK', \"4th order runge kutta solver\"),\n ('VERLET', 'Verlet', \"Verlet solver\"),\n ('LEAPFROG', 'Leapfrog', \"Leapfrog solver\"),\n ('BACKEULER', 'Backward Euler', \"Backward euler solver\"),\n )\n\ndef obj_location_callback(ob):\n # Do something here\n print('Object \"{}\" changed its location to: {}: '.format(\n ob.name, ob.location)\n )\n\ndef register():\n bpy.utils.register_class(DeleteParticleSystemOperator)\n bpy.utils.register_class(ParticleSimulationPanel)\n bpy.utils.register_class(ParticleManagePanel)\n bpy.utils.register_class(ForceManagePanel)\n bpy.utils.register_class(CollisionManagePanel)\n bpy.utils.register_class(ConstraintManagePanel)\n bpy.utils.register_class(ApplyConstantForceOperator)\n bpy.utils.register_class(ApplyDampingForceOperator)\n bpy.utils.register_class(ApplySpringForceOperator)\n bpy.utils.register_class(CalculateFrameOperator)\n bpy.utils.register_class(AddParticleOperator)\n bpy.utils.register_class(RemoveParticleOperator)\n bpy.utils.register_class(SyncParticleInitOperator)\n bpy.utils.register_class(ApplySolverOperator)\n bpy.utils.register_class(MassSpringSystemOperator)\n bpy.utils.register_class(RemoveForceOperator)\n bpy.utils.register_class(RemoveConstraintOperator)\n bpy.utils.register_class(ClothMassSpringSystemOperator)\n bpy.utils.register_class(AddWallCollisionOperator)\n bpy.utils.register_class(AddParticleCollisionOperator)\n bpy.utils.register_class(AddAngularConstraintOperator)\n bpy.utils.register_class(SaveInitParticleSystemOperator)\n bpy.utils.register_class(LoadInitParticleSystemOperator)\n bpy.utils.register_class(SaveParticleSystemAnimationOperator)\n bpy.utils.register_class(LoadParticleSystemAnimationOperator)\n\n bpy.utils.register_class(custom_prop.ParticleProp)\n bpy.utils.register_class(custom_prop.ConstantForceProp)\n bpy.utils.register_class(custom_prop.DampingForceProp)\n bpy.utils.register_class(custom_prop.SpringForceProp)\n bpy.utils.register_class(custom_prop.AngularConstraintProp)\n\n bpy.types.Scene.spring_particle_idx = bpy.props.EnumProperty(name=\"spring_particle_idx\", items=particle_item_callback)\n bpy.types.Scene.solver_name = bpy.props.EnumProperty(name=\"solver_name\", items=solver_item_callback)\n bpy.types.Scene.particle_property = bpy.props.PointerProperty(type=custom_prop.ParticleProp)\n bpy.types.Scene.constant_force_vector = bpy.props.PointerProperty(type=custom_prop.ConstantForceProp)\n bpy.types.Scene.damping_constant = bpy.props.PointerProperty(type=custom_prop.DampingForceProp)\n bpy.types.Scene.spring_force = bpy.props.PointerProperty(type=custom_prop.SpringForceProp)\n bpy.types.Scene.angular_constraint = bpy.props.PointerProperty(type=custom_prop.AngularConstraintProp)\n bpy.types.Scene.axis_particle_idx = bpy.props.EnumProperty(name=\"axis_particle_idx\", items=particle_item_callback)\n bpy.types.Scene.pair_particle_1_idx = bpy.props.EnumProperty(name=\"pair_particle_1_idx\", items=particle_item_callback)\n bpy.types.Scene.pair_particle_2_idx = bpy.props.EnumProperty(name=\"pair_particle_2_idx\", items=particle_item_callback)\n bpy.types.Scene.select_particle_idx = bpy.props.EnumProperty(name=\"select_particle_idx\", items=particle_item_callback)\n bpy.types.Scene.force_name = bpy.props.EnumProperty(name=\"force_name\", items=force_item_callback)\n bpy.types.Scene.constraint_name = bpy.props.EnumProperty(name=\"constraint_name\", items=constraint_item_callback)\n\ndef unregister():\n bpy.utils.unregister_class(DeleteParticleSystemOperator)\n bpy.utils.unregister_class(ParticleSimulationPanel)\n bpy.utils.unregister_class(ParticleManagePanel)\n bpy.utils.unregister_class(ForceManagePanel)\n bpy.utils.unregister_class(CollisionManagePanel)\n bpy.utils.unregister_class(ConstraintManagePanel)\n bpy.utils.unregister_class(ApplyConstantForceOperator)\n bpy.utils.unregister_class(ApplyDampingForceOperator)\n bpy.utils.unregister_class(ApplySpringForceOperator)\n bpy.utils.unregister_class(CalculateFrameOperator)\n bpy.utils.unregister_class(AddParticleOperator)\n bpy.utils.unregister_class(RemoveParticleOperator)\n bpy.utils.unregister_class(SyncParticleInitOperator)\n bpy.utils.unregister_class(ApplySolverOperator)\n bpy.utils.unregister_class(MassSpringSystemOperator)\n bpy.utils.unregister_class(RemoveForceOperator)\n bpy.utils.unregister_class(RemoveConstraintOperator)\n bpy.utils.unregister_class(ClothMassSpringSystemOperator)\n bpy.utils.unregister_class(AddWallCollisionOperator)\n bpy.utils.unregister_class(AddParticleCollisionOperator)\n bpy.utils.unregister_class(AddAngularConstraintOperator)\n bpy.utils.unregister_class(SaveInitParticleSystemOperator)\n bpy.utils.unregister_class(LoadInitParticleSystemOperator)\n bpy.utils.unregister_class(SaveParticleSystemAnimationOperator)\n bpy.utils.unregister_class(LoadParticleSystemAnimationOperator)\n\n\n bpy.utils.unregister_class(custom_prop.ParticleProp)\n bpy.utils.unregister_class(custom_prop.ConstantForceProp)\n bpy.utils.unregister_class(custom_prop.DampingForceProp)\n bpy.utils.unregister_class(custom_prop.SpringForceProp)\n bpy.utils.unregister_class(custom_prop.AngularConstraintProp)\n\n del bpy.types.Scene.solver_name\n del bpy.types.Scene.particle_property\n del bpy.types.Scene.constant_force_vector\n del bpy.types.Scene.damping_constant\n del bpy.types.Scene.spring_force\n del bpy.types.Scene.angular_constraint\n del bpy.types.Scene.axis_particle_idx\n del bpy.types.Scene.pair_particle_1_idx\n del bpy.types.Scene.pair_particle_2_idx\n del bpy.types.Scene.angular_constraint\n del bpy.types.Scene.angular_constraint\n del bpy.types.Scene.select_particle_idx\n del bpy.types.Scene.force_name\n del bpy.types.Scene.constraint_name\n\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":24702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"78281715","text":"#!/usr/bin/env python3\n\nclass DisjointSet:\n\n def __init__(self, init_arr):\n self._parents = {}\n self._parents_uncompressed = {}\n if init_arr:\n for item in init_arr:\n self._parents[item] = item\n self._parents_uncompressed[item] = item\n\n def find(self, elem):\n if elem not in self._parents:\n return None\n path = []\n while self._parents[elem] != elem:\n path.append(elem)\n elem = self._parents[elem]\n # path compression\n for e in path[1:]:\n self._parents[e] = elem\n return elem\n\n def find_path(self, elem):\n if elem not in self._parents_uncompressed:\n return []\n path = []\n while self._parents_uncompressed[elem] != elem:\n path.append(elem)\n elem = self._parents_uncompressed[elem]\n path.append(elem)\n return path\n\n def union(self, elem1, elem2):\n if elem1 == elem2:\n return\n # TODO: more advanced algorithm ?\n elem1 = self.find(elem1)\n elem2 = self.find(elem2)\n assert elem1 is not None and elem2 is not None\n self._parents[elem2] = elem1\n self._parents_uncompressed[elem2] = elem1\n\n def get_roots(self):\n roots = []\n for key in self._parents:\n value = self._parents[key]\n if value == key:\n roots.append(key)\n return roots\n\n def get_cluster(self):\n cluster = dict()\n for v in self._parents:\n r = self.find(v)\n if r not in cluster:\n cluster[r] = [v]\n else:\n cluster[r].append(v)\n return cluster\n\nif __name__ == '__main__':\n import argparse\n import numpy as np\n import h5py\n from scipy.io import loadmat,savemat\n from progressbar import progressbar\n\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('n', help='number of vertices', type=int)\n parser.add_argument('efile', help='edge file')\n args = parser.parse_args()\n if args.efile.endswith('.txt'):\n pairs = np.loadtxt(args.efile, dtype=np.int32, delimiter=\",\")\n elif args.efile.endswith('.mat'):\n pairs = loadmat(args.efile)['E']\n elif args.efile.endswith('.hdf5'):\n pairs = h5py.File(args.efile, 'r')['E'][:]\n else:\n print(\"Unknown format for file {}\".format(args.efile))\n exit()\n OPENSPACE_NODE = -3\n vset = [i for i in range(args.n)] + [OPENSPACE_NODE]\n djs = DisjointSet(vset)\n print(pairs.shape)\n # pairs = np.unique(pairs, axis=0)\n for e in progressbar(pairs):\n [r,c] = e[0], e[1]\n djs.union(r, c)\n '''\n if djs.find(0) == djs.find(1):\n print(\"Early terminate: 0 and 1 connected\")\n break\n '''\n print(djs.get_roots())\n cluster = djs.get_cluster()\n print(cluster)\n print(\"Root of 0 {} Size {}\".format(djs.find(0), len(cluster[djs.find(0)])))\n print(\"Path from 0 {}\".format(djs.find_path(0)))\n print(\"Root of 1 {} Size {}\".format(djs.find(1), len(cluster[djs.find(1)])))\n print(\"Path from 1 {}\".format(djs.find_path(1)))\n","sub_path":"src/GP/disjoint_set.py","file_name":"disjoint_set.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"136202708","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2020-2023 Ramon van der Winkel.\n# All rights reserved.\n# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.\n\nfrom django.urls import reverse\nfrom django.db.models import Q\nfrom django.views.generic import ListView\nfrom django.contrib.auth.mixins import UserPassesTestMixin\nfrom Account.models import Account\nfrom Functie.definities import Rollen\nfrom Functie.models import Functie\nfrom Functie.rol import rol_get_huidige_functie, rol_get_beschrijving\nfrom Plein.menu import menu_dynamics\n\n\nTEMPLATE_OVERZICHT = 'functie/overzicht.dtl'\n\n\nclass LijstBeheerdersView(UserPassesTestMixin, ListView):\n\n \"\"\" Via deze view worden de huidige beheerders getoond\n met Wijzig knoppen waar de gebruiker dit mag, aan de hand van de huidige rol\n\n Wordt ook gebruikt om de HWL relevante bestuurders te tonen\n \"\"\"\n\n # class variables shared by all instances\n template_name = TEMPLATE_OVERZICHT\n raise_exception = True # genereer PermissionDenied als test_func False terug geeft\n permission_denied_message = 'Geen toegang'\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.rol_nu, self.functie_nu = None, None\n\n def test_func(self):\n \"\"\" called by the UserPassesTestMixin to verify the user has permissions to use this view \"\"\"\n # alle competitie beheerders + HWL\n self.rol_nu, self.functie_nu = rol_get_huidige_functie(self.request)\n return self.rol_nu in (Rollen.ROL_BB, Rollen.ROL_MO, Rollen.ROL_MWZ, Rollen.ROL_MWW, Rollen.ROL_SUP,\n Rollen.ROL_BKO, Rollen.ROL_RKO, Rollen.ROL_RCL,\n Rollen.ROL_SEC, Rollen.ROL_HWL, Rollen.ROL_WL,\n Rollen.ROL_CS)\n\n @staticmethod\n def _sorteer_functies(objs):\n \"\"\" Sorteer de functies zodat:\n MWZ < MO < MWW < SUP < rest\n 18 < 25\n BKO < RKO < RCL\n op volgorde van rayon- of regionummer (oplopend)\n \"\"\"\n sort_level = {'MWZ': 1, 'MO': 2, 'CS': 3, 'MWW': 4, 'SUP': 5, 'BKO': 6, 'RKO': 7, 'RCL': 8}\n tup2obj = dict()\n sort_me = list()\n for obj in objs:\n if obj.rol == 'RKO':\n deel = obj.rayon.rayon_nr\n elif obj.rol == 'RCL':\n deel = obj.regio.regio_nr\n else:\n deel = 0\n\n tup = (obj.comp_type, sort_level[obj.rol], deel)\n sort_me.append(tup)\n tup2obj[tup] = obj\n # for\n sort_me.sort()\n objs = [tup2obj[tup] for tup in sort_me]\n return objs\n\n def _zet_wijzig_urls(self, objs):\n \"\"\" Voeg een wijzig_url veld toe aan elk Functie object\n \"\"\"\n # de huidige rol bepaalt welke functies gewijzigd mogen worden\n rko_rayon_nr = None\n wijzigbare_functie = self.functie_nu\n wijzigbare_functie_rollen = ()\n wijzigbare_email_rollen = ()\n\n if self.rol_nu == Rollen.ROL_BB:\n wijzigbare_functie_rollen = ('BKO', 'CS', 'MWW', 'MO', 'MWZ')\n wijzigbare_email_rollen = ('BKO', 'CS', 'MWW', 'MO', 'MWZ')\n\n elif self.rol_nu == Rollen.ROL_BKO:\n wijzigbare_functie_rollen = ('RKO',)\n wijzigbare_email_rollen = ('RKO',)\n\n elif self.rol_nu == Rollen.ROL_RKO:\n wijzigbare_functie_rollen = ('RCL',)\n wijzigbare_email_rollen = ('RCL',)\n rko_rayon_nr = self.functie_nu.rayon.rayon_nr\n\n for obj in objs:\n obj.wijzig_url = None\n obj.email_url = None\n\n if obj.rol in wijzigbare_functie_rollen:\n obj.wijzig_url = reverse('Functie:wijzig-beheerders', kwargs={'functie_pk': obj.pk})\n\n # competitie beheerders: alleen van hun eigen competitie type (Indoor / 25m1pijl)\n if self.rol_nu in (Rollen.ROL_BKO, Rollen.ROL_RKO, Rollen.ROL_RCL):\n if obj.comp_type != self.functie_nu.comp_type:\n obj.wijzig_url = None\n\n # verdere begrenzing RKO: alleen 'zijn' Regio's\n if self.rol_nu == Rollen.ROL_RKO and obj.rol == \"RCL\" and obj.regio.rayon.rayon_nr != rko_rayon_nr:\n obj.wijzig_url = None\n\n if obj == wijzigbare_functie or obj.rol in wijzigbare_email_rollen:\n obj.email_url = reverse('Functie:wijzig-email', kwargs={'functie_pk': obj.pk})\n\n # competitie beheerders: alleen van hun eigen competitie type (Indoor / 25m1pijl)\n if self.rol_nu in (Rollen.ROL_BKO, Rollen.ROL_RKO, Rollen.ROL_RCL):\n if obj.comp_type != self.functie_nu.comp_type:\n obj.email_url = None\n\n # verdere begrenzing RKO: alleen 'zijn' Regio's\n if self.rol_nu == Rollen.ROL_RKO and obj.rol == \"RCL\" and obj.regio.rayon.rayon_nr != rko_rayon_nr:\n obj.email_url = None\n # for\n\n @staticmethod\n def _zet_accounts(objs):\n \"\"\" als we de template door functie.accounts.all() laten lopen dan resulteert\n elke lookup in een database query voor het volledige account record.\n Hier doen we het iets efficienter.\n \"\"\"\n for obj in objs:\n obj.beheerders = [account.volledige_naam() for account in obj.accounts.all()]\n # for\n\n def get_queryset(self):\n \"\"\" called by the template system to get the queryset or list of objects for the template \"\"\"\n\n # maak een lijst van de functies\n if self.rol_nu == Rollen.ROL_HWL:\n # toon alleen de hierarchy vanuit deze vereniging omhoog\n functie_hwl = self.functie_nu\n objs = (Functie.objects\n .filter(Q(rol='RCL', regio=functie_hwl.vereniging.regio) |\n Q(rol='RKO', rayon=functie_hwl.vereniging.regio.rayon) |\n Q(rol='BKO'))\n .select_related('rayon',\n 'regio',\n 'regio__rayon')\n .prefetch_related('accounts'))\n else:\n objs = (Functie.objects\n .filter(rol__in=('BKO', 'RKO', 'RCL', 'MWZ', 'MWW', 'SUP', 'MO', 'CS'))\n .select_related('rayon',\n 'regio',\n 'regio__rayon')\n .prefetch_related('accounts'))\n\n objs = self._sorteer_functies(objs)\n\n # zet de wijzig-urls, waar toegestaan\n self._zet_wijzig_urls(objs)\n self._zet_accounts(objs)\n return objs\n\n def get_context_data(self, **kwargs):\n \"\"\" called by the template system to get the context data for the template \"\"\"\n context = super().get_context_data(**kwargs)\n\n context['huidige_rol'] = rol_get_beschrijving(self.request)\n\n if self.rol_nu == Rollen.ROL_HWL:\n context['rol_is_hwl'] = True\n\n if self.rol_nu in (Rollen.ROL_BB, Rollen.ROL_SUP):\n context['accounts_it'] = (Account\n .objects\n .filter(is_staff=True)\n .order_by('username'))\n\n context['accounts_bb'] = (Account\n .objects\n .filter(is_BB=True)\n .order_by('username'))\n\n if self.rol_nu in (Rollen.ROL_BB, Rollen.ROL_MWZ, Rollen.ROL_BKO, Rollen.ROL_RKO, Rollen.ROL_RCL):\n context['url_sec_hwl'] = reverse('Functie:sec-hwl-lid_nrs')\n\n context['kruimels'] = (\n (reverse('Competitie:kies'), 'Bondscompetities'),\n (None, 'Beheerders'),\n )\n\n menu_dynamics(self.request, context)\n return context\n\n# end of file\n","sub_path":"Functie/view_beheerders.py","file_name":"view_beheerders.py","file_ext":"py","file_size_in_byte":7878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"629987540","text":"\"\"\"\nthis script is used to develop better GUI\nwhich might be involved with tkinter\nfor now just run game.py should be enough\n\"\"\"\nimport game\n\nCONST_FOOD = \"F\" # cat food\nCONST_CAT = \"C\" # cat\nCONST_MOUSE = \"M\" # mouse\nCONST_EMPTY = \"-\" # empty\nCONST_OBSTACLE = \"X\" # obstacle\nCONST_DOG = \"D\" # dog\nMAX_INT = 2 ** 31 - 1\n# 6 possible direction for a singe move\nDIRECTIONS = {\n 1: [(-1, -1), (-1, 0), (0, -1), (0, 1), (1, -1), (1, 0)], # if row_num % 2 == 1\n 0: [(-1, 0), (-1, 1), (0, -1), (0, 1), (1, 0), (1, 1)] # if row_num % 2 == 0\n}\n\n\nif __name__ == \"__main__\":\n size = 11\n n_food = 0\n n_mouse = 3\n n_dog = 0\n # if dog_move_interval == MAX_INT, means dog should be keep stationary\n dog_move_interval = MAX_INT\n my_game = game.Game(size, n_food, n_mouse, n_dog, dog_move_interval) # 8x8 grid, 2 food, 3 mice, 1 dog, 2 interval\n my_game.play_game()\n","sub_path":"circleCatGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"151159710","text":"# float('inf') float('-inf')\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # # answer = prices and prices[0]\n # answer = [float('inf'),0]\n # for i in prices:\n # answer[1] = max(answer[1], i - answer[0])\n # answer[0] = min(i, answer[0])\n # return answer[1]\n \n def div(begin, end):\n if begin+1 == end or begin == end: return max(0,prices[end]-prices[begin])\n half = (begin+end)//2\n c = max(prices[half+1:end+1])-min(prices[begin:half+1])\n c = max(c, 0)\n a = div(half+1,end)\n b = div(begin,half)\n return max(a,b,c)\n return len(prices) and div(0,len(prices)-1)\n\nif __name__ == '__main__':\n sol = Solution()\n print(sol.maxProfit([7, 1, 5, 3, 6, 4]))\n print(sol.maxProfit([7, 6, 4, 3, 1]))\n print(sol.maxProfit([]))\n","sub_path":"Algorithms/Best Time to Buy and Sell Stock/Best Time to Buy and Sell Stock.py","file_name":"Best Time to Buy and Sell Stock.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"435754000","text":"list1=[1,2,3,4,5,7,8]\r\nlist2= [\"a\",\"b\",\"c\",\"d\",\"e\"]\r\nres = {}\r\nfor key in list1:\r\n for value in list2:\r\n res[key] = (value)\r\n list2.remove(value)\r\n break\r\n\r\n\r\nprint (\"dictionary output is : \" + str(res))","sub_path":"assignment 6.py","file_name":"assignment 6.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"406403292","text":"import logging\n\n# Create a custom logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# Create handlers\nc_handler = logging.StreamHandler()\nc_handler.setLevel(logging.DEBUG)\n\n# Create formatters and add it to handlers\nc_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')\nc_handler.setFormatter(c_format)\n\n# Add handlers to the logger\nlogger.addHandler(c_handler)\n","sub_path":"console_logging.py","file_name":"console_logging.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"439626275","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Python 3.x\n\n__author__ = \"Gumble <abcdoyle888@gmail.com>\"\n__version__ = \"2.22\"\n\n'''\nExtract images downloaded by Buka.\n\nSupports .buka, .bup.view, .jpg.view formats.\nTo use: buka.py input [output]\nFor help: buka.py -h\nAPI: import buka\nMain features:\n * BukaFile Reads the buka file.\n * ComicInfo Get comic information from chaporder.dat.\n * DirMan Manages directories for converting and renaming.\n * buildfromdb Build a dict of BukaFile objects from buka_store.sql\n'''\n\nimport sys\nif sys.version_info[0] < 3:\n\tprint('requires Python 3. try:\\n python3 ' + sys.argv[0])\n\tsys.exit(1)\n\nimport os\nimport shutil\nimport argparse\nimport time\nimport json\nimport struct\nimport sqlite3\nimport logging, logging.config\nimport traceback\nimport threadpool\nfrom io import StringIO\nfrom collections import OrderedDict\nfrom subprocess import Popen, PIPE\nfrom platform import machine\nfrom multiprocessing import cpu_count\n\ntry:\n\t# requires Pillow with WebP support\n\tfrom PIL import Image\n\timport PIL.WebPImagePlugin\n\tSUPPORTPIL = True\nexcept ImportError:\n\tSUPPORTPIL = False\n\nNT_SLEEP_SEC = 7\nlogstr = StringIO()\n\nclass BadBukaFile(Exception):\n\tpass\n\nclass ArgumentParserWait(argparse.ArgumentParser):\n\t'''For Windows: makes the cmd window delay.'''\n\tdef exit(self, status=0, message=None):\n\t\tif message:\n\t\t\tself._print_message(message, sys.stderr)\n\t\tif os.name == 'nt':\n\t\t\tsys.stderr.write(\"使用方法不正确。请将文件夹拖至软件图标使用。\")\n\t\t\tsys.stderr.flush()\n\t\t\ttime.sleep(NT_SLEEP_SEC)\n\t\tsys.exit(status)\n\nclass tTree():\n\t'''\n\tThe tTree format for directories.\n\t\n\ttTree[('foo', 'bar', 'baz')] = 42\n\twhich auto creates:\n\ttTree[('foo', 'bar')] = None\n\ttTree[('foo', )] = None\n\t'''\n\tdef __init__(self):\n\t\tself.d = {}\n\t\n\tdef __len__(self):\n\t\treturn len(self.d)\n\t\n\tdef __getitem__(self, key):\n\t\treturn self.d[tuple(key)]\n\t\n\tdef __setitem__(self, key, value):\n\t\tkey = tuple(key)\n\t\tif key not in self.d:\n\t\t\tfor i in range(1, len(key)):\n\t\t\t\tif key[:i] not in self.d:\n\t\t\t\t\tself.d[key[:i]] = None\n\t\tself.d[key] = value\n\t\n\tdef __delitem__(self, key):\n\t\tdel self.d[tuple(key)]\n\n\tdef __iter__(self):\n\t\treturn iter(self.d)\n\t\n\tdef __contains__(self, item):\n\t\treturn tuple(item) in self.d\n\t\n\tdef keys(self):\n\t\treturn self.d.keys()\n\t\n\tdef get(self, key, default=None):\n\t\tkey = tuple(key)\n\t\tif key in self.d:\n\t\t\treturn self.d[key]\n\t\telse:\n\t\t\treturn default\n\t\n\tdef __repr__(self):\n\t\treturn repr(self.d)\n\nclass BukaFile:\n\t'''Reads the buka file.'''\n\tdef __init__(self, filename):\n\t\tself.filename = filename\n\t\tf = self.fp = open(filename, 'rb')\n\t\tbuff = f.read(128)\n\t\tif buff[0:4] != b'buka':\n\t\t\traise BadBukaFile('not a buka file')\n\t\tself.comicid = struct.unpack('<I', buff[12:16])[0]\n\t\tself.chapid = struct.unpack('<I', buff[16:20])[0]\n\t\tpos = buff.find(b'\\x00', 20)\n\t\tself.comicname = buff[20:pos].decode(encoding='utf-8', errors='ignore')\n\t\tpos += 1\n\t\tendhead = pos + struct.unpack('<I', buff[pos:pos + 4])[0] - 1\n\t\tpos += 4\n\t\tf.seek(pos)\n\t\tbuff = f.read(endhead-pos+1)\n\t\tself.files = OrderedDict() # {}\n\t\tpos = 0\n\t\twhile pos + 8 < len(buff):\n\t\t\tpointer, size = struct.unpack('<II', buff[pos:pos + 8])\n\t\t\tpos += 8\n\t\t\tend = buff.find(b'\\x00', pos)\n\t\t\tname = buff[pos:end].decode(encoding='utf-8', errors='ignore')\n\t\t\tpos = end + 1\n\t\t\tself.files[name] = (pointer, size)\n\t\tif 'chaporder.dat' in self.files:\n\t\t\tself.fp.seek(self.files['chaporder.dat'][0])\n\t\t\tself._chaporderdat = self.fp.read(self.files['chaporder.dat'][1])\n\t\t\tself.chapinfo = ComicInfo(json.loads(self._chaporderdat.decode('utf-8')), self.comicid)\n\t\telse:\n\t\t\tself._chaporderdat, self.chapinfo = None, None\n\t\t\t\n\t\n\tdef __len__(self):\n\t\treturn len(self.files)\n\t\n\tdef __getitem__(self, key):\n\t\tif key in self.files:\n\t\t\tif key == 'chaporder.dat' and self._chaporderdat:\n\t\t\t\treturn self._chaporderdat\n\t\t\tindex = self.files[key]\n\t\t\tself.fp.seek(index[0])\n\t\t\treturn self.fp.read(index[1])\n\t\telse:\n\t\t\traise KeyError(key)\n\t\n\tdef __iter__(self):\n\t\treturn iter(self.files)\n\t\n\tdef __contains__(self, item):\n\t\treturn item in self.files\n\t\n\tdef keys(self):\n\t\treturn self.files.keys()\n\t\n\tdef getfile(self, key, offset=0):\n\t\t'''offset is for bup files.'''\n\t\tif key == 'chaporder.dat' and self._chaporderdat:\n\t\t\treturn self._chaporderdat\n\t\tindex = self.files[key]\n\t\tself.fp.seek(index[0] + offset)\n\t\treturn self.fp.read(index[1] - offset)\n\t\n\tdef extract(self, key, path):\n\t\twith open(path, 'wb') as w:\n\t\t\tindex = self.files[key]\n\t\t\tself.fp.seek(index[0])\n\t\t\tw.write(self.fp.read(index[1]))\n\t\n\tdef extractall(self, path):\n\t\tif not os.path.exists(path):\n\t\t\tos.makedirs(path)\n\t\tfor key in self.files:\n\t\t\tself.extract(key, os.path.join(path, key))\n\t\n\tdef __repr__(self):\n\t\treturn \"<BukaFile comicid=%r comicname=%r chapid=%r>\" % \\\n\t\t\t(self.comicid, self.comicname, self.chapid)\n\t\n\tdef close(self):\n\t\tself.fp.close()\n\t\n\tdef __del__(self):\n\t\tself.fp.close()\n\nclass ComicInfo:\n\t'''\n\tGet comic information from chaporder.dat.\n\t\n\tThis class represents the items in chaporder.dat,\n\tand provides convenient access to chapters.\n\t'''\n\tdef __init__(self, chaporder, comicid=None):\n\t\tself.chaporder = chaporder\n\t\tself.comicname = chaporder['name']\n\t\tself.chap = {}\n\t\tfor d in chaporder['links']:\n\t\t\tself.chap[int(d['cid'])] = d\n\t\tif comicid:\n\t\t\tself.comicid = comicid\n\t\telse:\n\t\t\ttry:\n\t\t\t\tself.comicid = int(chaporder['logo'].split('/')[-1].split('-')[0])\n\t\t\texcept ValueError:\n\t\t\t\tlogging.debug(\"can't get comicid from url: %s\", chaporder['logo'])\n\t\t\t\tself.comicid = None\n\t\n\tdef renamef(self, cid):\n\t\tif cid in self.chap:\n\t\t\tif self.chap[cid]['title']:\n\t\t\t\treturn self.chap[cid]['title']\n\t\t\telse:\n\t\t\t\tif self.chap[cid]['type'] == '0':\n\t\t\t\t\treturn '第' + self.chap[cid]['idx'].zfill(2) + '卷'\n\t\t\t\telif self.chap[cid]['type'] == '1':\n\t\t\t\t\treturn '第' + self.chap[cid]['idx'].zfill(3) + '话'\n\t\t\t\telif self.chap[cid]['type'] == '2':\n\t\t\t\t\treturn '番外' + self.chap[cid]['idx'].zfill(2)\n\t\t\t\telse:\n\t\t\t\t\treturn self.chap[cid]['idx'].zfill(3)\n\t\telse:\n\t\t\treturn str(cid)\n\t\n\tdef __getitem__(self, key):\n\t\tif key in self.chaporder:\n\t\t\treturn self.chaporder[key]\n\t\telse:\n\t\t\traise KeyError(key)\n\t\n\tdef __contains__(self, item):\n\t\treturn item in self.chaporder\n\n\tdef __repr__(self):\n\t\treturn \"<ComicInfo comicid=%r comicname=%r>\" % (self.comicid, self.comicname)\n\nclass DirMan:\n\t'''\n\tManages directories for converting and renaming.\n\t\n\tThis class mainly maintains three items:\n\t* self.nodes - represents the directory tree and what it contains.\n\t* self.comicdict - maintains the dictionary of known comic entries.\n\t* self.dwebpman - puts decode requests\n\t'''\n\tdef __init__(self, dirpath, dwebpman, comicdict={}):\n\t\tself.dirpath = dirpath\n\t\tself.nodes = tTree()\n\t\tself.dwebpman = dwebpman\n\t\tself.comicdict = comicdict\n\t\n\tdef __repr__(self):\n\t\treturn \"<DirMan dirpath=%r>\" % self.dirpath\n\t\n\tdef cutname(self, filename):\n\t\t'''\n\t\tCuts the filename to be relative to the base directory name\n\t\tto avoid renaming outer directories.\n\t\t'''\n\t\treturn os.path.relpath(filename, os.path.dirname(self.dirpath))\n\t\n\tdef updatecomicdict(self, comicinfo):\n\t\tif comicinfo.comicid in self.comicdict:\n\t\t\tself.comicdict[comicinfo.comicid].chaporder.update(comicinfo.chaporder)\n\t\t\tself.comicdict[comicinfo.comicid].chap.update(comicinfo.chap)\n\t\telse:\n\t\t\tself.comicdict[comicinfo.comicid] = comicinfo\n\t\n\tdef detectndecode(self):\n\t\t'''\n\t\tDetects what the directory contains, attach it to its contents,\n\t\tand decode bup/webp images.\n\t\t'''\n\t\t# ifndef = lambda x,y: x if x else y\n\t\t# ==> x or y\n\t\tremovefiles = []\n\t\tfor root, subFolders, files in os.walk(self.dirpath):\n\t\t\tdtype = None\n\t\t\t#frombup = set()\n\t\t\tif 'chaporder.dat' in files:\n\t\t\t\tfilename = os.path.join(root, 'chaporder.dat')\n\t\t\t\tchaporder = ComicInfo(json.load(open(filename, 'r')))\n\t\t\t\ttry:\n\t\t\t\t\ttempid = int(os.path.basename(root))\n\t\t\t\t\tif tempid == chaporder.comicid:\n\t\t\t\t\t\tdtype = dtype or ('comic', chaporder.comicname)\n\t\t\t\t\telif tempid in chaporder.chap:\n\t\t\t\t\t\tdtype = dtype or ('chap', chaporder.comicname, chaporder.renamef(tempid))\n\t\t\t\t\telif chaporder.comicid is None:\n\t\t\t\t\t\tdtype = dtype or ('comic', chaporder.comicname)\n\t\t\t\t\t\tchaporder.comicid = tempid\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\t\t\t\tself.updatecomicdict(chaporder)\n\t\t\tfor name in files:\n\t\t\t\tfilename = os.path.join(root, name)\n\t\t\t\tif detectfile(filename) == 'buka' and not subFolders and (name == 'pack.dat' or len(files)<4):\n\t\t\t\t\t# only a buka (and a chaporder) (and an index2)\n\t\t\t\t\tlogging.info('正在提取 ' + self.cutname(filename))\n\t\t\t\t\tbuka = BukaFile(filename)\n\t\t\t\t\tif buka.chapinfo:\n\t\t\t\t\t\tchaporder = buka.chapinfo\n\t\t\t\t\t\tself.updatecomicdict(chaporder)\n\t\t\t\t\t\tdtype = dtype or ('chap', buka.comicname, chaporder.renamef(int(os.path.basename(root))))\n\t\t\t\t\telif buka.comicid in self.comicdict:\n\t\t\t\t\t\tdtype = dtype or ('chap', buka.comicname, self.comicdict[buka.comicid].renamef(buka.chapid))\n\t\t\t\t\textractndecode(buka, root, self.dwebpman)\n\t\t\t\t\tbuka.close()\n\t\t\t\t\tremovefiles.append(filename)\n\t\t\t\telif detectfile(filename) == 'buka':\n\t\t\t\t\tlogging.info('正在提取 ' + self.cutname(filename))\n\t\t\t\t\tbuka = BukaFile(filename)\n\t\t\t\t\tsp = splitpath(self.cutname(os.path.join(root, os.path.splitext(name)[0])))\n\t\t\t\t\tif buka.chapinfo:\n\t\t\t\t\t\tchaporder = buka.chapinfo\n\t\t\t\t\t\tself.updatecomicdict(chaporder)\n\t\t\t\t\t\tself.nodes[sp] = ('chap', buka.comicname, chaporder.renamef(buka.chapid))\n\t\t\t\t\telif buka.comicid in self.comicdict:\n\t\t\t\t\t\tself.nodes[sp] = ('chap', buka.comicname, self.comicdict[buka.comicid].renamef(buka.chapid))\n\t\t\t\t\textractndecode(buka, os.path.join(root, os.path.splitext(name)[0]), self.dwebpman)\n\t\t\t\t\ttry:\n\t\t\t\t\t\ttempid = int(os.path.basename(root))\n\t\t\t\t\t\tif tempid == buka.comicid:\n\t\t\t\t\t\t\tdtype = dtype or ('comic', buka.comicname)\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tpass\n\t\t\t\t\tbuka.close()\n\t\t\t\t\tremovefiles.append(filename)\n\t\t\t\telif detectfile(filename) == 'bup':\n\t\t\t\t\tlogging.info('加入队列 ' + self.cutname(filename))\n\t\t\t\t\twith open(filename, 'rb') as f, open(os.path.splitext(filename)[0] + '.webp', 'wb') as w:\n\t\t\t\t\t\tf.seek(64)\n\t\t\t\t\t\tshutil.copyfileobj(f, w)\n\t\t\t\t\t#frombup.add(os.path.splitext(filename)[0] + '.webp')\n\t\t\t\t\tself.dwebpman.add(os.path.splitext(filename)[0], self.cutname(filename))\n\t\t\t\t\tremovefiles.append(filename)\n\t\t\t\t\t#decodewebp(os.path.splitext(filename)[0])\n\t\t\t\t# No way! don't let webp's confuse the program.\n\t\t\t\t#elif detectfile(filename) == 'webp':\n\t\t\t\t\t#if os.path.isfile(os.path.splitext(filename)[0]+'.bup') or filename in frombup:\n\t\t\t\t\t\t#continue\n\t\t\t\t\t#logging.info('加入队列 ' + self.cutname(filename))\n\t\t\t\t\t#self.dwebpman.add(os.path.splitext(filename)[0], self.cutname(filename))\n\t\t\t\t\t##decodewebp(os.path.splitext(filename)[0])\n\t\t\t\telif name == 'buka_store.sql':\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcdict = buildfromdb(filename)\n\t\t\t\t\t\tfor key in cdict:\n\t\t\t\t\t\t\tself.updatecomicdict(cdict[key])\n\t\t\t\t\texcept Exception:\n\t\t\t\t\t\tlogging.error('不是有效的数据库: ' + self.cutname(filename))\n\t\t\t\t#else:\n\t\t\t\t\t#dtype = 'unk'\n\t\t\t#for name in subFolders:\n\t\t\t\t#pass\n\t\t\tsp = splitpath(self.cutname(root))\n\t\t\tif not dtype:\n\t\t\t\ttry:\n\t\t\t\t\ttempid = int(os.path.basename(root))\n\t\t\t\t\tif tempid in self.comicdict:\n\t\t\t\t\t\tdtype = ('comic', self.comicdict[tempid].comicname)\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\ttempid2 = int(os.path.basename(os.path.dirname(root)))\n\t\t\t\t\t\t\tif tempid2 in self.comicdict:\n\t\t\t\t\t\t\t\tif tempid in self.comicdict[tempid2].chap:\n\t\t\t\t\t\t\t\t\tdtype = ('chap', self.comicdict[tempid2].comicname, self.comicdict[tempid2].renamef(tempid))\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\tpass\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\t\t\tself.nodes[sp] = dtype\n\t\t# just for the low speed of Windows\n\t\tfor filename in removefiles:\n\t\t\ttryremove(filename)\n\t\n\tdef renamedirs(self):\n\t\t'''Does the renaming.'''\n\t\tls = sorted(self.nodes.keys(), key=len, reverse=True)\n\t\tfor i in ls:\n\t\t\tthis = self.nodes.get(i)\n\t\t\tparent = self.nodes.get(i[:-1])\n\t\t\tif this:\n\t\t\t\torigpath = os.path.join(os.path.dirname(self.dirpath), *i)\n\t\t\t\tbasepath = os.path.join(os.path.dirname(self.dirpath), *i[:-1])\n\t\t\t\tif this[0] == 'comic':\n\t\t\t\t\tmovedir(origpath, os.path.join(basepath, this[1]))\n\t\t\t\telif parent:\n\t\t\t\t\tif this[1] == parent[1]:\n\t\t\t\t\t\tmovedir(origpath, os.path.join(basepath, this[2]))\n\t\t\t\telse:\n\t\t\t\t\tmovedir(origpath, os.path.join(basepath, this[1] + '-' + this[2]))\n\t\ndef movedir(src, dst):\n\t'''Avoid conflicts when moving into an exist directory.'''\n\tif src == dst:\n\t\tpass\n\telif os.path.isdir(src) and os.path.isdir(dst):\n\t\tfor item in os.listdir(src):\n\t\t\tmovedir(os.path.join(src, item), os.path.join(dst, item))\n\t\tos.rmdir(src)\n\telse:\n\t\tshutil.move(src, dst)\n\ndef tryremove(filename):\n\t'''\n\tTries to remove a file until it's not locked.\n\t\n\tIt's just for the low speed of Windows.\n\tThe exceptions are caused by the file lock is not released by System(4)\n\t'''\n\tfor att in range(10):\n\t\ttry:\n\t\t\tos.remove(filename)\n\t\t\tbreak\n\t\texcept PermissionError as ex:\n\t\t\tlogging.debug(\"Delete failed, trying... \" + str(att+1))\n\t\t\tif att == 9:\n\t\t\t\tlogging.error(\"删除文件失败超过重试次数。\")\n\t\t\t\traise ex\n\t\t\ttime.sleep(0.2 * att)\n\ndef splitpath(path):\n\t'''\n\tSplits a path to a list.\n\t>>> p = splitpath('a/b/c/d/')\n\t# p = ['a', 'b', 'c', 'd']\n\t>>> p = splitpath('/a/b/c/d')\n\t# p = ['/', 'a', 'b', 'c', 'd']\n\t'''\n\tfolders = []\n\tpath = path.rstrip(r'\\\\').rstrip(r'/')\n\twhile 1:\n\t\tpath,folder = os.path.split(path)\n\t\tif folder != \"\":\n\t\t\tfolders.append(folder)\n\t\telse:\n\t\t\tif path != \"\":\n\t\t\t\tfolders.append(path)\n\t\t\tbreak\n\tfolders.reverse()\n\treturn folders\n\ndef extractndecode(bukafile, path, dwebpman):\n\t'''Extracts buka files and puts decode requests.'''\n\tif not os.path.exists(path):\n\t\tos.makedirs(path)\n\tfor key in bukafile.files:\n\t\tif os.path.splitext(key)[1] == '.bup':\n\t\t\twith open(os.path.join(path, os.path.splitext(key)[0] + '.webp'), 'wb') as f:\n\t\t\t\tf.write(bukafile.getfile(key,64))\n\t\t\t# decodewebp(os.path.join(path, os.path.splitext(key)[0]))\n\t\t\tdwebpman.add(os.path.join(path, os.path.splitext(key)[0]), os.path.join(os.path.basename(path), key))\n\t\telif key == 'logo':\n\t\t\twith open(os.path.join(path, key + '.jpg'), 'wb') as f:\n\t\t\t\tf.write(bukafile[key])\n\t\telse:\n\t\t\twith open(os.path.join(path, key), 'wb') as f:\n\t\t\t\tf.write(bukafile[key])\n\ndef buildfromdb(dbname):\n\t'''\n\tBuild a dict of BukaFile objects from buka_store.sql file in iOS devices.\n\tuse json.dump(<dictname>[id].chaporder) to generate chaporder.dat from db.\n\t'''\n\tdb = sqlite3.connect(dbname)\n\tc = db.cursor()\n\tinitd = {'author': '', #mangainfo/author\n\t\t\t 'discount': '0', 'favor': 0,\n\t\t\t 'finish': '0', #ismangaend/isend\n\t\t\t 'intro': '',\n\t\t\t 'lastup': '', #mangainfo/recentupdatename\n\t\t\t 'lastupcid': '', #Trim and lookup chapterinfo/fulltitle\n\t\t\t 'lastuptime': '', #mangainfo/recentupdatetime\n\t\t\t 'lastuptimeex': '', #mangainfo/recentupdatetime + ' 00:00:00'\n\t\t\t 'links': [], #From chapterinfo\n\t\t\t 'logo': '', #mangainfo/logopath\n\t\t\t 'logos': '', #mangainfo/logopath.split('-')[0]+'-s.jpg'\n\t\t\t 'name': '', #mangainfo/title\n\t\t\t 'popular': 9999999, 'populars': '10000000+', 'rate': '20',\n\t\t\t 'readmode': 50331648, 'readmode2': '0',\n\t\t\t 'recomctrlparam': '101696', 'recomctrltype': '1',\n\t\t\t 'recomdelay': '2000', 'recomenter': '', 'recomwords': '',\n\t\t\t 'res': [],\n\t\t\t #'res': [{'cid': '0', #downloadview/cid\n\t\t\t\t#'csize': '4942', 'restype': '1'}]\n\t\t\t 'resupno': '0', 'ret': 0, 'upno': '0'}\n\td = {}\n\tc.execute('select * from mangainfo')\n\twhile 1:\n\t\tlst = c.fetchone()\n\t\tif not lst:\n\t\t\tbreak\n\t\td[lst[0]] = initd.copy()\n\t\td[lst[0]]['name'] = lst[1]\n\t\td[lst[0]]['logo'] = lst[2]\n\t\td[lst[0]]['logos'] = lst[2].split('-')[0] + '-s.jpg'\n\t\td[lst[0]]['lastup'] = lst[3]\n\t\td[lst[0]]['lastuptime'] = lst[4]\n\t\td[lst[0]]['lastuptimeex'] = lst[4] + ' 00:00:00'\n\t\td[lst[0]]['author'] = lst[5]\n\tc.execute('select * from ismangaend')\n\twhile 1:\n\t\tlst = c.fetchone()\n\t\tif not lst:\n\t\t\tbreak\n\t\td[lst[0]]['finish'] = str(lst[1])\n\tc.execute('select * from chapterinfo')\n\twhile 1:\n\t\tlst = c.fetchone()\n\t\tif not lst:\n\t\t\tbreak\n\t\tif not d[lst[0]]['links']:\n\t\t\td[lst[0]]['links'] = []\n\t\tif not d[lst[0]]['res']:\n\t\t\td[lst[0]]['res'] = []\n\t\tif lst[3]:\n\t\t\tcomictitle = ''\n\t\t\tif lst[3][-1] == '卷':\n\t\t\t\tcomictype = '0'\n\t\t\telif lst[3][-1] == '话':\n\t\t\t\tcomictype = '1'\n\t\t\telse:\n\t\t\t\tcomictype = '2'\n\t\t\t\tcomictitle = lst[3]\n\t\telse:\n\t\t\tcomictype = '2'\n\t\t\tcomictitle = lst[2]\n\t\td[lst[0]]['links'].append({'cid': str(lst[1]), #chapterinfo/cid\n\t\t\t\t\t\t'idx': str(lst[4]), #chapterinfo/idx\n\t\t\t\t\t\t'ressupport': '7', 'size': '0',\n\t\t\t\t\t\t'title': comictitle, 'type': comictype})\n\t\td[lst[0]]['res'].append({'cid': str(lst[1]), 'csize': '1', 'restype': '1'})\n\t\tif not d[lst[0]]['lastupcid']:\n\t\t\tif d[lst[0]]['lastup'].strip() in lst[3]:\n\t\t\t\td[lst[0]]['lastupcid'] = str(lst[1])\n\t\t\telif d[lst[0]]['lastup'].strip() in lst[2]:\n\t\t\t\td[lst[0]]['lastupcid'] = str(lst[1])\n\tdb.close()\n\treturn dict(map(lambda k: (k, ComicInfo(d[k], k)), d))\n\ndef detectfile(filename):\n\t'''Tests file format.'''\n\tif not os.path.exists(filename):\n\t\treturn None\n\tif os.path.isdir(filename):\n\t\treturn 'dir'\n\tif os.path.basename(filename) == 'index2.dat':\n\t\treturn 'index2'\n\telif os.path.basename(filename) == 'chaporder.dat':\n\t\treturn 'chaporder'\n\text = os.path.splitext(filename)[1]\n\tif ext == '.buka':\n\t\treturn 'buka'\n\telif ext == '.bup':\n\t\treturn 'bup'\n\telif ext == '.view':\n\t\text2 = os.path.splitext(os.path.splitext(filename)[0])[1]\n\t\tif ext2 == '.jpg':\n\t\t\treturn 'jpg'\n\t\telif ext2 == '.bup':\n\t\t\treturn 'bup'\n\t\telif ext2 == '.png':\n\t\t\treturn 'png'\n\twith open(filename, 'rb') as f:\n\t\th = f.read(32)\n\tif h[6:10] in (b'JFIF', b'Exif'):\n\t\treturn 'jpg'\n\telif h.startswith(b'\\211PNG\\r\\n\\032\\n'):\n\t\treturn 'png'\n\telif h[:4] == b\"buka\":\n\t\treturn 'buka'\n\telif h[:4] == b\"AKUB\" or h[12:16] == b\"AKUB\":\n\t\treturn 'index2'\n\telif h[:4] == b\"bup\\x00\":\n\t\treturn 'bup'\n\telif h.startswith(b'SQLite format 3'):\n\t\treturn 'sqlite3'\n\telif h[:4] == b\"RIFF\" and h[8:16] == b\"WEBPVP8 \":\n\t\treturn 'webp'\n\telse:\n\t\treturn False\n\ndef copytree(src, dst, symlinks=False, ignore=None):\n\tif not os.path.exists(dst):\n\t\tos.makedirs(dst)\n\tfor item in os.listdir(src):\n\t\ts = os.path.join(src, item)\n\t\td = os.path.join(dst, item)\n\t\tif os.path.isdir(s):\n\t\t\tcopytree(s, d, symlinks, ignore)\n\t\telif detectfile(s) in ('index2','chaporder','buka','bup','jpg','png','sqlite3'): # whitelist ,'webp'\n\t\t\tif os.path.splitext(s)[1] == '.view':\n\t\t\t\td = os.path.splitext(d)[0]\n\t\t\tif not os.path.isfile(d) or os.stat(src).st_mtime - os.stat(dst).st_mtime > 1:\n\t\t\t\tshutil.copy2(s, d)\n\tif not os.listdir(dst):\n\t\tos.rmdir(dst)\n\nclass DwebpMan:\n\t'''\n\tUse a pool of dwebp's to decode webps.\n\t'''\n\tdef __init__(self, dwebppath, process):\n\t\tprogramdir = os.path.dirname(os.path.abspath(sys.argv[0]))\n\t\tself.fail = False\n\t\tif '64' in machine():\n\t\t\tbit = '64'\n\t\telse:\n\t\t\tbit = '32'\n\t\tlogging.debug('os.machine() = %s', machine())\n\t\tif dwebppath:\n\t\t\tself.dwebp = dwebppath\n\t\telif os.name == 'nt':\n\t\t\tself.dwebp = os.path.join(programdir, 'dwebp_' + bit + '.exe')\n\t\telse:\n\t\t\tself.dwebp = os.path.join(programdir, 'dwebp_' + bit)\n\t\t\n\t\tnul = open(os.devnull, 'w')\n\t\ttry:\n\t\t\tp = Popen(self.dwebp, stdout=nul, stderr=nul).wait()\n\t\t\tself.supportwebp = True\n\t\texcept Exception as ex:\n\t\t\tif os.name == 'posix':\n\t\t\t\ttry:\n\t\t\t\t\tp = Popen('dwebp', stdout=nul, stderr=nul).wait()\n\t\t\t\t\tself.supportwebp = True\n\t\t\t\t\tself.dwebp = 'dwebp'\n\t\t\t\t\tlogging.info(\"used dwebp installed in the system.\")\n\t\t\t\texcept Exception as ex:\n\t\t\t\t\tlogging.error(\"dwebp 不可用,仅支持普通文件格式。\")\n\t\t\t\t\tlogging.debug(\"dwebp test: \" + repr(ex))\n\t\t\t\t\tself.supportwebp = False\n\t\t\telse:\n\t\t\t\tlogging.error(\"dwebp 不可用,仅支持普通文件格式。\")\n\t\t\t\tlogging.debug(\"dwebp test: \" + repr(ex))\n\t\t\t\tself.supportwebp = False\n\t\tnul.close()\n\t\tlogging.debug(\"dwebp = \" + self.dwebp)\n\t\tif self.supportwebp:\n\t\t\tself.pool = threadpool.NoOrderedRequestManager(process,self.decodewebp,self.checklog,self.handle_thread_exception)\n\t\telse:\n\t\t\tself.pool = None\n\t\n\tdef __repr__(self):\n\t\treturn \"<DwebpMan supportwebp=%r dwebp=%r>\" % (self.supportwebp, self.dwebp)\n\n\tdef add(self, basepath, displayname):\n\t\t'''Ignores if not supported.'''\n\t\tif self.pool:\n\t\t\tself.pool.putRequest([basepath, displayname])\n\n\tdef wait(self):\n\t\tself.pool.wait()\n\n\tdef checklog(self, request, result):\n\t\tif 'cannot' in result[1]:\n\t\t\tlogging.error(\"dwebp 错误[%d]: %s\", result[0], result[1])\n\t\telse:\n\t\t\tlogging.info(\"完成转换 %s\", request.args[1])\n\t\t\tlogging.debug(\"dwebp OK[%d]: %s\", result[0], result[1])\n\n\tdef handle_thread_exception(self, request, exc_info):\n\t\t\"\"\"Logging exception handler callback function.\"\"\"\n\t\tself.fail = True\n\t\tlogging.getLogger().error(str(request))\n\t\ttraceback.print_exception(*exc_info, file=logstr)\n\n\tdef decodewebp(self, basepath, displayname):\n\t\tproc = Popen([self.dwebp, basepath + \".webp\", \"-o\", basepath + \".png\"], stdout=PIPE, stderr=PIPE, cwd=os.getcwd())\n\t\tstdout, stderr = proc.communicate()\n\t\t#if stdout:\n\t\t\t#stdout = stdout.decode(errors='ignore')\n\t\t\t#logging.info(\"dwebp: \" + stdout)\n\t\tif stderr:\n\t\t\tstderr = stderr.decode(errors='ignore')\n\t\ttryremove(basepath + \".webp\")\n\t\treturn (proc.returncode, stderr)\n\nclass DwebpPILMan:\n\t\"\"\"\n\tUse threads of PIL.Image instead of dwebp to decode webps.\n\t\n\tNote: For now, this class is available for decoding, and the it's faster.\n\t BUT, use this for decoding hundreds of images will cause CPython\n\t memory leaks. gc / del / close() don't work. Using multiprocessing\n\t is a waste though.\n\t So, don't use it for a large number of images.\n\t If you can fix it, contact the __author__.\n\t\"\"\"\n\tdef __init__(self, process):\n\t\tself.supportwebp = True\n\t\tself.fail = False\n\t\tself.pool = threadpool.NoOrderedRequestManager(process,self.decodewebp,self.checklog,self.handle_thread_exception)\n\n\tdef add(self, basepath, displayname):\n\t\tself.pool.putRequest([basepath, displayname])\n\n\tdef wait(self):\n\t\tself.pool.wait()\n\n\tdef checklog(self, request, result):\n\t\tif result:\n\t\t\tlogging.info(\"完成转换 %s\", request.args[1])\n\t\telse:\n\t\t\tlogging.error(\"解码错误: %s\", request.args[1])\n\n\tdef handle_thread_exception(self, request, exc_info):\n\t\t\"\"\"Logging exception handler callback function.\"\"\"\n\t\tself.fail = True\n\t\tlogging.getLogger().error(str(request))\n\t\ttraceback.print_exception(*exc_info, file=logstr)\n\t\n\tdef decodewebp(self, basepath, displayname):\n\t\tim = Image.open(basepath + \".webp\")\n\t\tim.save(basepath + '.jpg', quality=90)\n\t\tim.close()\n\t\tdel im\n\t\ttryremove(basepath + \".webp\")\n\t\treturn True\n\ndef logexit(err=True):\n\tlogging.shutdown()\n\tif err:\n\t\ttry:\n\t\t\twith open(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),'bukaex.log'), 'a') as f:\n\t\t\t\tf.write(logstr.getvalue())\n\t\texcept Exception:\n\t\t\twith open('bukaex.log', 'a') as f:\n\t\t\t\tf.write(logstr.getvalue())\n\t\tprint('如果不是使用方法错误,请发送错误报告 bukaex.log 给作者 ' + __author__)\n\tif os.name == 'nt':\n\t\ttime.sleep(NT_SLEEP_SEC)\n\tsys.exit(int(err))\n\ndef main():\n\tLOG_CONFIG = {'version':1,\n\t\t\t'formatters':{'strlog':{'format':'*** %(levelname)s\t%(funcName)s\\n%(message)s'},\n\t\t\t\t\t\t'stderr':{'format':'%(levelname)-7s %(message)s'}},\n\t\t\t'handlers':{'console':{'class':'logging.StreamHandler',\n\t\t\t\t\t\t\t\t\t'formatter':'stderr',\n\t\t\t\t\t\t\t\t\t'level':'INFO',\n\t\t\t\t\t\t\t\t\t'stream':sys.stderr},\n\t\t\t\t\t\t'strlogger':{'class':'logging.StreamHandler',\n\t\t\t\t\t\t\t\t 'formatter':'strlog',\n\t\t\t\t\t\t\t\t 'level':'DEBUG',\n\t\t\t\t\t\t\t\t 'stream':logstr}},\n\t\t\t'root':{'handlers':('console', 'strlogger'), 'level':'DEBUG'}}\n\tlogging.config.dictConfig(LOG_CONFIG)\n\ttry:\n\t\tcpus = cpu_count() if cpu_count() else 2\n\texcept NotImplementedError:\n\t\tcpus = 1\n\n\tlogging.info('%s version %s' % (os.path.basename(sys.argv[0]), __version__))\n\tparser = ArgumentParserWait(description=\"Converts comics downloaded by Buka.\")\n\tparser.add_argument(\"-p\", \"--process\", help=\"The max number of running dwebp's. (Default = CPU count)\", default=cpus, type=int, metavar='NUM')\n\t# parser.add_argument(\"-s\", \"--same-dir\", action='store_true', help=\"Change the default output dir to <input>/../output. Ignored when specifies <output>\")\n\tparser.add_argument(\"-c\", \"--current-dir\", action='store_true', help=\"Change the default output dir to ./output. Ignored when specifies <output>\")\n\tparser.add_argument(\"-l\", \"--log\", action='store_true', help=\"Force logging to file.\")\n\tparser.add_argument(\"--pil\", action='store_true', help=\"Perfer PIL/Pillow for decoding, faster, and may cause memory leaks.\")\n\t# parser.add_argument(\"--dwebp\", nargs='?', help=\"Perfer dwebp for decoding, and/or locate your own dwebp WebP decoder.\", default=None, const=True)\n\tparser.add_argument(\"--dwebp\", help=\"Locate your own dwebp WebP decoder.\", default=None)\n\tparser.add_argument(\"-d\", \"--db\", help=\"Locate the 'buka_store.sql' file in iOS devices, which provides infomation for renaming.\", default=None, metavar='buka_store.sql')\n\tparser.add_argument(\"input\", help=\"The .buka file or the folder containing files downloaded by Buka, which is usually located in (Android) /sdcard/ibuka/down\")\n\tparser.add_argument(\"output\", nargs='?', help=\"The output folder. (Default = ./output)\", default=None)\n\targs = parser.parse_args()\n\tlogging.debug(repr(args))\n\n\tprogramdir = os.path.dirname(os.path.abspath(sys.argv[0]))\n\tfn_buka = args.input\n\tif args.output:\n\t\ttarget = args.output\n\telif args.current_dir:\n\t\ttarget = 'output'\n\telse:\n\t\ttarget = os.path.join(os.path.dirname(fn_buka),'output')\n\ttarget = os.path.abspath(target)\n\tlogging.info('输出至 ' + target)\n\tif not os.path.exists(target):\n\t\tos.makedirs(target)\n\tdbdict = {}\n\tif args.db:\n\t\ttry:\n\t\t\tdbdict = buildfromdb(args.db)\n\t\texcept Exception:\n\t\t\tlogging.error('指定的数据库文件不是有效的 iOS 设备中的 buka_store.sql 数据库文件。提取过程将继续。')\n\t\n\tlogging.info(\"检查环境...\")\n\tlogging.debug(repr(os.uname()))\n\t# if args.dwebp == True:\n\t\t# dwebpman = DwebpMan(None, args.process)\n\tif args.dwebp:\n\t\tdwebpman = DwebpMan(args.dwebp, args.process)\n\telif SUPPORTPIL and args.pil:\n\t\tdwebpman = DwebpPILMan(args.process)\n\telse:\n\t\tdwebpman = DwebpMan(args.dwebp, args.process)\n\tlogging.debug(\"dwebpman = \" + repr(dwebpman))\n\n\tif os.path.isdir(target):\n\t\tif detectfile(fn_buka) == \"buka\":\n\t\t\tif not os.path.isfile(fn_buka):\n\t\t\t\tlogging.critical('没有此文件: ' + fn_buka)\n\t\t\t\tif not os.listdir(target):\n\t\t\t\t\tos.rmdir(target)\n\t\t\t\tlogexit()\n\t\t\tlogging.info('正在提取 ' + fn_buka)\n\t\t\tbuka = BukaFile(fn_buka)\n\t\t\textractndecode(buka, target, dwebpman)\n\t\t\tif dwebpman.supportwebp:\n\t\t\t\tdwebpman.wait()\n\t\t\tif buka.chapinfo:\n\t\t\t\tmovedir(target, os.path.join(os.path.dirname(target), buka.comicname + '-' + buka.chapinfo.renamef(buka.chapid)))\n\t\t\telse:\n\t\t\t\t# cannot get chapter name\n\t\t\t\tmovedir(target, os.path.join(os.path.dirname(target), buka.comicname + '-' + buka.chapid))\n\t\t\tbuka.close()\n\t\telif os.path.isdir(fn_buka):\n\t\t\tlogging.info('正在复制...')\n\t\t\tcopytree(fn_buka, target)\n\t\t\tdm = DirMan(target, dwebpman, dbdict)\n\t\t\tdm.detectndecode()\n\t\t\tif dwebpman.supportwebp:\n\t\t\t\tlogging.info(\"等待所有转换进程/线程...\")\n\t\t\t\tdwebpman.wait()\n\t\t\tlogging.info(\"完成转换。\")\n\t\t\tlogging.info(\"正在重命名...\")\n\t\t\tdm.renamedirs()\n\t\telse:\n\t\t\tlogging.critical(\"输入必须为 buka 文件或一个文件夹。\")\n\t\t\tif not os.listdir(target):\n\t\t\t\tos.rmdir(target)\n\t\t\tlogexit()\n\t\tif dwebpman.fail:\n\t\t\tlogexit()\n\t\tlogging.info('完成。')\n\t\tif not dwebpman.supportwebp:\n\t\t\tlogging.warning('警告: .bup 格式文件无法转换,保留为 webp 格式。')\n\t\t\tlogexit()\n\t\tif args.log:\n\t\t\tlogexit()\n\telse:\n\t\tlogging.critical(\"错误: 输出文件夹路径为一个文件。\")\n\t\tlogexit()\n\nif __name__ == '__main__':\n\ttry:\n\t\tmain()\n\texcept SystemExit:\n\t\tpass\n\texcept Exception:\n\t\tlogging.exception('错误: 主线程异常退出。')\n\t\tlogexit()\n","sub_path":"buka.py","file_name":"buka.py","file_ext":"py","file_size_in_byte":27410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"615601332","text":"import numpy as np\r\n\r\nclass HandleData(object):\r\n\r\n def __init__(self,batch_size,num_examples,num_ex_per_angle,num_angle):\r\n self.num_examples=num_examples\r\n self.num_ex_per_angle=num_ex_per_angle\r\n self.num_angle = num_angle\r\n self.current_point = 0\r\n self.data_set = np.zeros((self.num_examples,4),dtype=np.float32)\r\n self.label_set = np.zeros((self.num_examples,self.num_angle),dtype=np.float32)\r\n\r\n def onehot_encode(self,number):\r\n encoded_no = np.zeros(self.num_angle, dtype=np.float32)\r\n if number < self.num_angle:\r\n encoded_no[number] = 1\r\n return encoded_no\r\n\r\n def next_batch(self,batch_size):\r\n # print(\"start : \" + str(self.current_point))\r\n if self.current_point == self.num_examples:\r\n self.current_point = 0\r\n start = self.current_point\r\n end = start + batch_size\r\n return_data = self.data_set[start:end]\r\n return_label = self.label_set[start:end]\r\n self.current_point=end\r\n # print(return_data)\r\n # print(\"end : \" + str(self.current_point))\r\n return return_data,return_label\r\n\r\n def get_synthatic_data(self):\r\n _1 = np.random.randint(low=1, high=10, size=self.num_ex_per_angle)\r\n _2 = np.random.randint(low=15, high=25, size=self.num_ex_per_angle)\r\n _3 = np.random.randint(low=30, high=40, size=self.num_ex_per_angle)\r\n\r\n l_0 = np.array([_3,_2,_1,_2], np.float32)\r\n l_1 = np.array([_2,_2,_1,_1], np.float32)\r\n l_2 = np.array([_2,_3,_2,_1], np.float32)\r\n l_3 = np.array([_1,_2,_2,_1], np.float32)\r\n l_4 = np.array([_1,_2,_3,_2], np.float32)\r\n l_5 = np.array([_1,_1,_2,_2], np.float32)\r\n l_6 = np.array([_2,_1,_2,_3], np.float32)\r\n l_7 = np.array([_2,_1,_1,_2], np.float32)\r\n\r\n data_matrix = np.array([l_0, l_1, l_2, l_3, l_4, l_5, l_6, l_7], np.float32)\r\n tmp = np.zeros((self.num_angle, self.num_ex_per_angle, 4), dtype=np.float32)\r\n for j in range(0,self.num_angle):\r\n for i in range(0, self.num_ex_per_angle):\r\n tmp[j][i][0] = data_matrix[j][0][i]\r\n tmp[j][i][1] = data_matrix[j][1][i]\r\n tmp[j][i][2] = data_matrix[j][2][i]\r\n tmp[j][i][3] = data_matrix[j][3][i]\r\n\r\n # l_sel = np.random.randint(low=0, high=self.num_angle, size=1)[0]\r\n # index_sel = np.random.randint(low=0, high=self.num_ex_per_angle, size=1)[0]\r\n\r\n # data_set = np.zeros((self.num_examples,4),dtype=np.float32)\r\n # label_set = np.zeros((self.num_examples,self.num_angle),dtype=np.float32)\r\n\r\n for i in range(0,self.num_angle):\r\n for j in range(0, self.num_ex_per_angle):\r\n \"add one hot\"\r\n \"add data\"\r\n self.label_set[i * self.num_ex_per_angle + j] = self.onehot_encode(i)\r\n self.data_set[i * self.num_ex_per_angle + j] = tmp[i][j]\r\n return self.data_set ,self.label_set\r\n# print(onehot_encode(0).shape)\r\n# print(label_set)\r\n# print(data_set)\r\n# print(data_set.shape)\r\n# print(label_set.shape)\r\n\r\n# print(getSynthaticData()['data'])\r\n\r\n# data = HandleData(batch_size=10,num_examples=800,num_ex_per_angle=100,num_angle=8)\r\n# a,b = data.get_synthatic_data()\r\n# _a,_b = data.next_batch(50)\r\n# print(_a)\r\n# print(data.current_point)\r\n# _a,_b = data.next_batch(51)\r\n# print(_a)\r\n# print(data.current_point)","sub_path":"data_generate.py","file_name":"data_generate.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"362194326","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n# 时间复杂度:O(n²)\n# 空间复杂度:O(1)\n# 稳定性:稳定\n\n\ndef select_sort(lists):\n\n n = len(lists)\n for j in range(0,n-1):\n min_key = j\n for i in range(j+1, n):\n if lists[min_key] > lists[i]:\n min_key = i\n lists[min_key], lists[j] = lists[j], lists[min_key]\n\n\ndef main():\n\n lists = [22, 34, 1, 2332, 33, 333, 112]\n print(lists)\n select_sort(lists)\n print(lists)\n\n\nif __name__ == \"__main__\":\n\n main()\n\n","sub_path":"sortAlgorithm/select_sort.py","file_name":"select_sort.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"340382031","text":"'''\nWrite a program, which takes a year as input and returns message if this is a leap year or note.\n Please handle the exceptions which may arise is a user will enter non-numeric symbols.\n\n Additional task – to show the closest leap year in case if entered year is not leap\n\n Optional task - Add a possibility to print all the leap years within given range\n\n'''\n\n\nquestion = input(\"Do you want to know a leap of single year or a range of years? \\n\"\n \" Print : \\n\"\n \" 1 - Single year \\n\"\n \" 2 - Range of years \\n\")\n\nif question == \"2\":\n leaps = []\n start = input(\"Write start of the range\")\n end = input(\"Write end of the range\")\n for i in range(int(start),int(end) +1):\n if (i % 4 == 0) & (i % 100 != 0) | (i % 400 == 0):\n leaps.append(i)\n print(leaps)\n\nif question == \"1\":\n try:\n answer = int(input(\"Please input a year \"))\n except ValueError:\n print(\"You need to input a number\")\n answer = input(\"Please input a year \")\n\n if (answer % 4 == 0) & (answer % 100 != 0) | (answer % 400 == 0):\n print(str(answer) + \" year is leap!!\")\n else:\n print(str(answer) + \" isn`t leap(((\")\n for i in range(3):\n for y in (answer + i,answer - i) :\n if (y % 4 == 0) & (y % 100 != 0) | (y % 400 == 0):\n print(\"The closest leap year is \" + str(y))","sub_path":"Lab_Works_3/lab_work3_4/3_4.py","file_name":"3_4.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"513372054","text":"from __future__ import annotations\n\nimport pytest\n\nINPUT = '''\\\n939\n7,13,x,x,59,x,31,19'''\n\n\ndef load(input_string: str) -> list:\n lines = input_string.splitlines()\n return lines\n\n\ndef compute(input_string: str):\n lines = load(input_string)\n arrival_time = int(lines[0])\n bus_times = lines[1].split(',')\n pickup_time = {}\n for bus in bus_times:\n if bus == \"x\":\n continue\n bus = int(bus)\n t = bus - (arrival_time % bus)\n pickup_time[str(t)] = bus\n lowest = min([int(x) for x in pickup_time])\n return lowest * pickup_time[str(lowest)]\n\n\n\n@pytest.mark.parametrize(\"expected\", [295])\ndef test_results(expected):\n assert expected == compute(INPUT)\n\n\nif __name__ == '__main__':\n i = open(file='input.txt').read()\n print(compute(i))\n","sub_path":"Day13/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"407122269","text":"import cv2\r\nimport keras\r\nfrom keras.applications.imagenet_utils import preprocess_input\r\nfrom keras.backend.tensorflow_backend import set_session\r\nfrom keras.models import Model\r\nfrom keras.preprocessing import image\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.misc import imread\r\nimport tensorflow as tf\r\nimport random\r\nimport os\r\n\r\nfrom ssd import SSD300\r\nfrom ssd_utils import BBoxUtility\r\n\r\n# matplotlib表示画像の拡大 大した意味なし\r\nplt.rcParams['figure.figsize'] = (8, 8)\r\n# 画像を見やすいようにするかみたいな ここではしない設定\r\nplt.rcParams['image.interpolation'] = 'nearest'\r\n\r\n# npの行列の指数表示の禁止 大した意味なし\r\nnp.set_printoptions(suppress=True)\r\n\r\n# tensorflowの設定クラス\r\nconfig = tf.ConfigProto()\r\n# GPUのメモリの何%を使うか否か あまり関係ない\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.45\r\nset_session(tf.Session(config=config))\r\n\r\n#voc_classes = ['Aeroplane', 'Bicycle', 'Bird', 'Boat', 'Bottle',\r\nvoc_classes = ['barcode', 'tag', 'Bird', 'Boat', 'Bottle',\r\n 'Bus', 'Car', 'Cat', 'Chair', 'Cow', 'Diningtable',\r\n 'Dog', 'Horse','Motorbike', 'Person', 'Pottedplant',\r\n 'Sheep', 'Sofa', 'Train', 'Tvmonitor']\r\nNUM_CLASSES = len(voc_classes) + 1\r\n# (300, 300)では自動的に画像を(300, 300)に拡大・縮小している\r\ninput_shape=(300, 300, 3)\r\nmodel = SSD300(input_shape, num_classes=NUM_CLASSES)\r\n#model.load_weights('weights_SSD300.hdf5', by_name=True)\r\nmodel.load_weights('./checkpoints/third_weights_barcode.09-1.46.hdf5', by_name=True)\r\nmodel.compile('sgd','mse')\r\nbbox_util = BBoxUtility(NUM_CLASSES)\r\n\r\n\r\nfor path in os.listdir('pics'):\r\n inputs = []\r\n images = []\r\n img_path = './pics/' + path\r\n img = image.load_img(img_path, target_size=(300, 300))\r\n img = image.img_to_array(img)\r\n #rand = random.randint(1,10**10)\r\n #pre_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\r\n #cv2.imwrite('pre_pics/'+str(rand)+'.jpg',pre_img)\r\n images.append(imread(img_path))\r\n inputs.append(img.copy())\r\n # preprocess_input()は平均値を引いてRGB→BGRにしているだけ\r\n # 0-1にしているわけではないから注意\r\n inputs = preprocess_input(np.array(inputs))\r\n\r\n # verbose=1はログを出す設定\r\n preds = model.predict(inputs, batch_size=1, verbose=1)\r\n #print(preds[0][4500])\r\n results = bbox_util.detection_out(preds)\r\n\r\n for i, img in enumerate(images):\r\n # Parse the outputs.\r\n det_label = results[i][:, 0]\r\n # おそらく予測確率\r\n det_conf = results[i][:, 1]\r\n det_xmin = results[i][:, 2]\r\n det_ymin = results[i][:, 3]\r\n det_xmax = results[i][:, 4]\r\n det_ymax = results[i][:, 5]\r\n\r\n top_indices = [i for i, conf in enumerate(det_conf) if conf >= 0.6]\r\n\r\n top_conf = det_conf[top_indices]\r\n top_label_indices = det_label[top_indices].tolist()\r\n top_xmin = det_xmin[top_indices]\r\n top_ymin = det_ymin[top_indices]\r\n top_xmax = det_xmax[top_indices]\r\n top_ymax = det_ymax[top_indices]\r\n\r\n colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()\r\n\r\n plt.imshow(img / 255.)\r\n # 矩形の座標軸(?)\r\n currentAxis = plt.gca()\r\n\r\n\r\n for i in range(top_conf.shape[0]):\r\n xmin = int(round(top_xmin[i] * img.shape[1]))\r\n ymin = int(round(top_ymin[i] * img.shape[0]))\r\n xmax = int(round(top_xmax[i] * img.shape[1]))\r\n ymax = int(round(top_ymax[i] * img.shape[0]))\r\n score = top_conf[i]\r\n label = int(top_label_indices[i])\r\n label_name = voc_classes[label - 1]\r\n display_txt = '{:0.2f}, {}'.format(score, label_name)\r\n coords = (xmin, ymin), xmax-xmin+1, ymax-ymin+1\r\n color = colors[label]\r\n currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))\r\n currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5})\r\n\r\n # barcodeのみの切り取り\r\n if label == 1:\r\n print(coords)\r\n # area = [xmin, ymin, xmax, ymax]\r\n area = [coords[0][0], coords[0][1], coords[0][0] + coords[1], coords[0][1] + coords[2]]\r\n print(area)\r\n im = cv2.imread(img_path, 1)\r\n dst = im[area[1]: area[3], area[0]: area[2]]\r\n rand = random.randint(1,1000)\r\n filepath = 'PASCAL_VOC/barcode/cut_images/' + path + str(rand) + '.jpg'\r\n cv2.imwrite(filepath, dst)\r\n print(path, 'の切り取り完了')\r\n\r\n #plt.show()\r\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"428223843","text":"# Load TensorFlow\nimport tensorflow as tf\n\n# Set up the converter\nconverter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)\nconverter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\n\n# Perform conversion and output file\ntflite_quant_model = converter.convert()\noutput_dir.write_bytes(tflite_quant_model)","sub_path":"scripts/quantize_lite.py","file_name":"quantize_lite.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"86362726","text":"from solutions.day11_SortColors import sortColors\n\ndef test_day11_01():\n test_input = [2,0,2,1,1,0]\n test_output = [0,0,1,1,2,2]\n sortColors(test_input)\n assert test_input == test_output\n\ndef test_day11_02():\n test_input = [1,1,1,1,1,1]\n test_output = [1,1,1,1,1,1]\n sortColors(test_input)\n assert test_input == test_output\n\ndef test_day11_03():\n test_input = [2,2,2,0,0,0]\n test_output = [0,0,0,2,2,2]\n sortColors(test_input)\n assert test_input == test_output\n","sub_path":"june2020/tests/test_day11_SortColors.py","file_name":"test_day11_SortColors.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"282944064","text":"\"\"\"Contains opsin models and default parameters\"\"\"\nfrom __future__ import annotations\nfrom typing import Callable, Tuple\nimport warnings\n\nfrom attrs import define, field, asdict, fields_dict\nfrom brian2 import (\n Synapses,\n Function,\n NeuronGroup,\n Unit,\n BrianObjectException,\n get_unit,\n Equations,\n implementation,\n check_units,\n)\nfrom nptyping import NDArray\nfrom brian2.units import (\n mm,\n mm2,\n nmeter,\n Quantity,\n second,\n ms,\n second,\n psiemens,\n nsiemens,\n mV,\n volt,\n amp,\n mM,\n)\nfrom brian2.units.allunits import radian\nimport numpy as np\nfrom scipy.interpolate import CubicSpline\n\nfrom cleo.base import InterfaceDevice\nfrom cleo.coords import assign_coords\nfrom cleo.opto.registry import lor_for_sim\nfrom cleo.utilities import wavelength_to_rgb\n\n\ndef linear_interpolator(lambdas_nm, epsilons, lambda_new_nm):\n return np.interp(lambda_new_nm, lambdas_nm, epsilons)\n\n\ndef cubic_interpolator(lambdas_nm, epsilons, lambda_new_nm):\n return CubicSpline(lambdas_nm, epsilons)(lambda_new_nm)\n\n\n@define(eq=False)\nclass Opsin(InterfaceDevice):\n \"\"\"Base class for opsin model.\n\n We approximate dynamics under multiple wavelengths using a weighted sum\n of photon fluxes, where the :math:`\\\\varepsilon` factor indicates the activation\n relative to the peak-sensitivy wavelength for an equivalent number of photons\n (see Mager et al, 2018). This weighted sum is an approximation of a nonlinear\n peak-non-peak wavelength relation; see notebooks/multi_wavelength_model.ipynb\n for details.\"\"\"\n\n model: str = field(init=False)\n \"\"\"Basic Brian model equations string.\n \n Should contain a `rho_rel` term reflecting relative expression \n levels. Will likely also contain special NeuronGroup-dependent\n symbols such as V_VAR_NAME to be replaced on injection in \n :meth:`~OpsinModel.modify_model_and_params_for_ng`.\"\"\"\n\n per_ng_unit_replacements: list[Tuple[str, str]] = field(\n factory=list, init=False, repr=False\n )\n \"\"\"List of (UNIT_NAME, neuron_group_specific_unit_name) tuples to be substituted\n in the model string on injection and before checking required variables.\"\"\"\n\n required_vars: list[Tuple[str, Unit]] = field(factory=list, init=False, repr=False)\n \"\"\"Default names of state variables required in the neuron group,\n along with units, e.g., [('Iopto', amp)].\n \n It is assumed that non-default values can be passed in on injection\n as a keyword argument ``[default_name]_var_name=[non_default_name]``\n and that these are found in the model string as \n ``[DEFAULT_NAME]_VAR_NAME`` before replacement.\"\"\"\n\n light_agg_ngs: dict[str, NeuronGroup] = field(factory=dict, init=False, repr=False)\n \"\"\"{target_ng.name: light_agg_ng} dict of light aggregator neuron groups.\"\"\"\n\n opto_syns: dict[NeuronGroup, Synapses] = field(factory=dict, init=False, repr=False)\n \"\"\"Stores the synapse objects implementing the opsin model,\n with NeuronGroup keys and Synapse values.\"\"\"\n\n action_spectrum: list[tuple[float, float]] = field(\n factory=lambda: [(-1e10, 1), (1e10, 1)]\n )\n \"\"\"List of (wavelength, epsilon) tuples representing the action spectrum.\"\"\"\n\n action_spectrum_interpolator: Callable = field(\n default=cubic_interpolator, repr=False\n )\n \"\"\"Function of signature (lambdas_nm, epsilons, lambda_new_nm) that interpolates\n the action spectrum data and returns :math:`\\\\varepsilon \\\\in [0,1]` for the new\n wavelength.\"\"\"\n\n extra_namespace: dict = field(factory=dict, repr=False)\n \"\"\"Additional items (beyond parameters) to be added to the opto synapse namespace\"\"\"\n\n def connect_to_neuron_group(self, neuron_group: NeuronGroup, **kwparams) -> None:\n \"\"\"Transfect neuron group with opsin.\n\n Parameters\n ----------\n neuron_group : NeuronGroup\n The neuron group to stimulate with the given opsin and light source\n\n Keyword args\n ------------\n p_expression : float\n Probability (0 <= p <= 1) that a given neuron in the group\n will express the opsin. 1 by default.\n rho_rel : float\n The expression level, relative to the standard model fit,\n of the opsin. 1 by default. For heterogeneous expression,\n this would have to be modified in the opsin synapse post-injection,\n e.g., ``opto.opto_syns[\"neuron_group_name\"].rho_rel = ...``\n Iopto_var_name : str\n The name of the variable in the neuron group model representing\n current from the opsin\n v_var_name : str\n The name of the variable in the neuron group model representing\n membrane potential\n \"\"\"\n if neuron_group.name in self.light_agg_ngs:\n assert neuron_group.name in self.opto_syns\n raise ValueError(\n f\"Opsin {self.name} already connected to neuron group {neuron_group.name}\"\n )\n\n # get modified opsin model string (i.e., with names/units specified)\n mod_opsin_model, mod_opsin_params = self.modify_model_and_params_for_ng(\n neuron_group, kwparams\n )\n\n # handle p_expression\n p_expression = kwparams.get(\"p_expression\", 1)\n i_expression_bool = np.random.rand(neuron_group.N) < p_expression\n i_expression = np.where(i_expression_bool)[0]\n if len(i_expression) == 0:\n return\n\n # create light aggregator neurons\n light_agg_ng = NeuronGroup(\n len(i_expression),\n model=\"\"\"\n phi : 1/second/meter**2\n Irr : watt/meter**2\n \"\"\",\n name=f\"light_agg_{self.name}_{neuron_group.name}\",\n )\n assign_coords(\n light_agg_ng,\n neuron_group.x[i_expression] / mm,\n neuron_group.y[i_expression] / mm,\n neuron_group.z[i_expression] / mm,\n unit=mm,\n )\n\n # create opsin synapses\n opto_syn = Synapses(\n light_agg_ng,\n neuron_group,\n model=mod_opsin_model,\n namespace=mod_opsin_params,\n name=f\"opto_syn_{self.name}_{neuron_group.name}\",\n )\n opto_syn.namespace.update(self.extra_namespace)\n opto_syn.connect(i=range(len(i_expression)), j=i_expression)\n self.init_opto_syn_vars(opto_syn)\n # relative channel density\n opto_syn.rho_rel = kwparams.get(\"rho_rel\", 1)\n\n # store at the end, after all checks have passed\n self.light_agg_ngs[neuron_group.name] = light_agg_ng\n self.brian_objects.add(light_agg_ng)\n self.opto_syns[neuron_group.name] = opto_syn\n self.brian_objects.add(opto_syn)\n\n lor = lor_for_sim(self.sim)\n lor.register_opsin(self, neuron_group)\n\n def modify_model_and_params_for_ng(\n self, neuron_group: NeuronGroup, injct_params: dict\n ) -> Tuple[Equations, dict]:\n \"\"\"Adapt model for given neuron group on injection\n\n This enables the specification of variable names\n differently for each neuron group, allowing for custom names\n and avoiding conflicts.\n\n Parameters\n ----------\n neuron_group : NeuronGroup\n NeuronGroup this opsin model is being connected to\n injct_params : dict\n kwargs passed in on injection, could contain variable\n names to plug into the model\n\n Keyword Args\n ------------\n model : str, optional\n Model to start with, by default that defined for the class.\n This allows for prior string manipulations before it can be\n parsed as an `Equations` object.\n\n Returns\n -------\n Equations, dict\n A tuple containing an Equations object\n and a parameter dictionary, constructed from :attr:`~model`\n and :attr:`~params`, respectively, with modified names for use\n in :attr:`~cleo.opto.OptogeneticIntervention.opto_syns`\n \"\"\"\n model = self.model\n\n # perform unit substitutions\n for unit_name, neuron_group_unit_name in self.per_ng_unit_replacements:\n model = model.replace(unit_name, neuron_group_unit_name)\n\n # check required variables/units and replace placeholder names\n for default_name, unit in self.required_vars:\n var_name = injct_params.get(f\"{default_name}_var_name\", default_name)\n if var_name not in neuron_group.variables or not neuron_group.variables[\n var_name\n ].unit.has_same_dimensions(unit):\n raise BrianObjectException(\n (\n f\"{var_name} : {unit.name} needed in the model of NeuronGroup \"\n f\"{neuron_group.name} to connect Opsin {self.name}.\"\n ),\n neuron_group,\n )\n # opsin synapse model needs modified names\n to_replace = f\"{default_name}_var_name\".upper()\n model = model.replace(to_replace, var_name)\n\n # Synapse variable and parameter names cannot be the same as any\n # neuron group variable name\n return self._fix_name_conflicts(model, neuron_group)\n\n @property\n def params(self) -> dict:\n \"\"\"Returns a dictionary of parameters for the model\"\"\"\n params = asdict(self, recurse=False)\n # remove generic fields that are not parameters\n for field in fields_dict(Opsin):\n params.pop(field)\n # remove private attributes\n for key in list(params.keys()):\n if key.startswith(\"_\"):\n params.pop(key)\n return params\n\n def _fix_name_conflicts(\n self, modified_model: str, neuron_group: NeuronGroup\n ) -> Tuple[Equations, dict]:\n modified_params = self.params.copy()\n rename = lambda x: f\"{x}_syn\"\n\n # get variables to rename\n opsin_eqs = Equations(modified_model)\n substitutions = {}\n for var in opsin_eqs.names:\n if var in neuron_group.variables:\n substitutions[var] = rename(var)\n\n # and parameters\n for param in self.params.keys():\n if param in neuron_group.variables:\n substitutions[param] = rename(param)\n modified_params[rename(param)] = modified_params[param]\n del modified_params[param]\n\n mod_opsin_eqs = opsin_eqs.substitute(**substitutions)\n return mod_opsin_eqs, modified_params\n\n def reset(self, **kwargs):\n for opto_syn in self.opto_syns.values():\n self.init_opto_syn_vars(opto_syn)\n\n def init_opto_syn_vars(self, opto_syn: Synapses) -> None:\n \"\"\"Initializes appropriate variables in Synapses implementing the model\n\n Can also be used to reset the variables.\n\n Parameters\n ----------\n opto_syn : Synapses\n The synapses object implementing this model\n \"\"\"\n pass\n\n def epsilon(self, lambda_new) -> float:\n \"\"\"Returns the epsilon value for a given lambda (in nm)\n representing the relative sensitivity of the opsin to that wavelength.\"\"\"\n action_spectrum = np.array(self.action_spectrum)\n lambdas = action_spectrum[:, 0]\n epsilons = action_spectrum[:, 1]\n if lambda_new < min(lambdas) or lambda_new > max(lambdas):\n warnings.warn(\n f\"λ = {lambda_new} nm is outside the range of the action spectrum data\"\n f\" for {self.name}. Assuming ε = 0.\"\n )\n return 0\n return self.action_spectrum_interpolator(lambdas, epsilons, lambda_new)\n\n\ndef plot_action_spectra(*opsins: Opsin):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n for opsin in opsins:\n action_spectrum = np.array(opsin.action_spectrum)\n lambdas = action_spectrum[:, 0]\n epsilons = action_spectrum[:, 1]\n lambdas_new = np.linspace(min(lambdas), max(lambdas), 100)\n epsilons_new = opsin.action_spectrum_interpolator(\n lambdas, epsilons, lambdas_new\n )\n c_points = [wavelength_to_rgb(l) for l in lambdas]\n c_line = wavelength_to_rgb(lambdas_new[np.argmax(epsilons_new)])\n ax.plot(lambdas_new, epsilons_new, c=c_line, label=opsin.name)\n ax.scatter(lambdas, epsilons, marker=\"o\", s=50, color=c_points)\n title = \"Action spectra\" if len(opsins) > 1 else f\"Action spectrum\"\n ax.set(xlabel=\"λ (nm)\", ylabel=\"ε\", title=title)\n fig.legend()\n return fig, ax\n\n\n@define(eq=False)\nclass MarkovOpsin(Opsin):\n \"\"\"Base class for Markov state models à la Evans et al., 2016\"\"\"\n\n required_vars: list[Tuple[str, Unit]] = field(\n factory=lambda: [(\"Iopto\", amp), (\"v\", volt)],\n init=False,\n )\n\n\n@implementation(\n \"cython\",\n \"\"\"\n cdef double f_unless_x0(double f, double x, double f_when_x0):\n if x == 0:\n return f_when_x0\n else:\n return f\n \"\"\",\n)\n@check_units(f=1, x=volt, f_when_0=1, result=1)\ndef f_unless_x0(f, x, f_when_x0):\n f[x == 0] = f_when_x0\n return f\n\n\n@define(eq=False)\nclass FourStateOpsin(MarkovOpsin):\n \"\"\"4-state model from PyRhO (Evans et al. 2016).\n\n rho_rel is channel density relative to standard model fit;\n modifying it post-injection allows for heterogeneous opsin expression.\n\n IOPTO_VAR_NAME and V_VAR_NAME are substituted on injection.\n\n Defaults are for ChR2.\n \"\"\"\n\n g0: Quantity = 114000 * psiemens\n gamma: Quantity = 0.00742\n phim: Quantity = 2.33e17 / mm2 / second # *photon, not in Brian2\n k1: Quantity = 4.15 / ms\n k2: Quantity = 0.868 / ms\n p: Quantity = 0.833\n Gf0: Quantity = 0.0373 / ms\n kf: Quantity = 0.0581 / ms\n Gb0: Quantity = 0.0161 / ms\n kb: Quantity = 0.063 / ms\n q: Quantity = 1.94\n Gd1: Quantity = 0.105 / ms\n Gd2: Quantity = 0.0138 / ms\n Gr0: Quantity = 0.00033 / ms\n E: Quantity = 0 * mV\n v0: Quantity = 43 * mV\n v1: Quantity = 17.1 * mV\n model: str = field(\n init=False,\n default=\"\"\"\n dC1/dt = Gd1*O1 + Gr0*C2 - Ga1*C1 : 1 (clock-driven)\n dO1/dt = Ga1*C1 + Gb*O2 - (Gd1+Gf)*O1 : 1 (clock-driven)\n dO2/dt = Ga2*C2 + Gf*O1 - (Gd2+Gb)*O2 : 1 (clock-driven)\n C2 = 1 - C1 - O1 - O2 : 1\n\n Theta = int(phi_pre > 0*phi_pre) : 1\n Hp = Theta * phi_pre**p/(phi_pre**p + phim**p) : 1\n Ga1 = k1*Hp : hertz\n Ga2 = k2*Hp : hertz\n Hq = Theta * phi_pre**q/(phi_pre**q + phim**q) : 1\n Gf = kf*Hq + Gf0 : hertz\n Gb = kb*Hq + Gb0 : hertz\n\n fphi = O1 + gamma*O2 : 1\n # TODO: get this voltage dependence right \n # v1/v0 when v-E == 0 via l'Hopital's rule\n # fv = (1 - exp(-(V_VAR_NAME_post-E)/v0)) / -2 : 1\n fv = f_unless_x0(\n (1 - exp(-(V_VAR_NAME_post-E)/v0)) / ((V_VAR_NAME_post-E)/v1),\n V_VAR_NAME_post - E,\n v1/v0\n ) : 1\n\n IOPTO_VAR_NAME_post = -g0*fphi*fv*(V_VAR_NAME_post-E)*rho_rel : ampere (summed)\n rho_rel : 1\"\"\",\n )\n\n extra_namespace: dict[str, Any] = field(\n init=False, factory=lambda: {\"f_unless_x0\": f_unless_x0}\n )\n\n def init_opto_syn_vars(self, opto_syn: Synapses) -> None:\n for varname, value in {\"C1\": 1, \"O1\": 0, \"O2\": 0}.items():\n setattr(opto_syn, varname, value)\n\n\n@define(eq=False)\nclass BansalFourStateOpsin(MarkovOpsin):\n \"\"\"4-state model from Bansal et al. 2020.\n\n The difference from the PyRhO model is that there is no voltage dependence.\n\n rho_rel is channel density relative to standard model fit;\n modifying it post-injection allows for heterogeneous opsin expression.\n\n IOPTO_VAR_NAME and V_VAR_NAME are substituted on injection.\n \"\"\"\n\n Gd1: Quantity = 0.066 / ms\n Gd2: Quantity = 0.01 / ms\n Gr0: Quantity = 3.33e-4 / ms\n g0: Quantity = 3.2 * nsiemens\n phim: Quantity = 1e16 / mm2 / second # *photon, not in Brian2\n k1: Quantity = 0.4 / ms\n k2: Quantity = 0.12 / ms\n Gf0: Quantity = 0.018 / ms\n Gb0: Quantity = 0.008 / ms\n kf: Quantity = 0.01 / ms\n kb: Quantity = 0.008 / ms\n gamma: Quantity = 0.05\n p: Quantity = 1\n q: Quantity = 1\n E: Quantity = 0 * mV\n\n model: str = field(\n init=False,\n default=\"\"\"\n dC1/dt = Gd1*O1 + Gr0*C2 - Ga1*C1 : 1 (clock-driven)\n dO1/dt = Ga1*C1 + Gb*O2 - (Gd1+Gf)*O1 : 1 (clock-driven)\n dO2/dt = Ga2*C2 + Gf*O1 - (Gd2+Gb)*O2 : 1 (clock-driven)\n C2 = 1 - C1 - O1 - O2 : 1\n\n Theta = int(phi_pre > 0*phi_pre) : 1\n Hp = Theta * phi_pre**p/(phi_pre**p + phim**p) : 1\n Ga1 = k1*Hp : hertz\n Ga2 = k2*Hp : hertz\n Hq = Theta * phi_pre**q/(phi_pre**q + phim**q) : 1\n Gf = kf*Hq + Gf0 : hertz\n Gb = kb*Hq + Gb0 : hertz\n\n fphi = O1 + gamma*O2 : 1\n\n IOPTO_VAR_NAME_post = -g0*fphi*(V_VAR_NAME_post-E)*rho_rel : ampere (summed)\n rho_rel : 1\"\"\",\n )\n\n def init_opto_syn_vars(self, opto_syn: Synapses) -> None:\n for varname, value in {\"C1\": 1, \"O1\": 0, \"O2\": 0}.items():\n setattr(opto_syn, varname, value)\n\n\n@define(eq=False)\nclass BansalThreeStatePump(MarkovOpsin):\n \"\"\"3-state model from `Bansal et al. 2020 <10.1016/j.neuroscience.2020.09.022>`_.\n\n rho_rel is channel density relative to standard model fit;\n modifying it post-injection allows for heterogeneous opsin expression.\n\n IOPTO_VAR_NAME and V_VAR_NAME are substituted on injection.\n \"\"\"\n\n Gd: Quantity = 0\n Gr: Quantity = 0\n ka: Quantity = 0\n p: Quantity = 0\n q: Quantity = 0\n phim: Quantity = 0\n E: Quantity = 0\n a: Quantity = 0\n b: Quantity = 0\n vartheta_max = 5 * mM\n kd = 16 * mM\n model: str = field(\n init=False,\n default=\"\"\"\n dP0/dt = Gr*P6 - Ga*P0 : 1 (clock-driven)\n dP4/dt = Ga*P0 - Gd*P4 : 1 (clock-driven)\n P6 = 1 - P0 - P4 : 1\n\n Theta = int(phi_pre > 0*phi_pre) : 1\n Hp = Theta * phi_pre**p/(phi_pre**p + phim**p) : 1\n Ga = ka*Hp : hertz\n\n fphi = P4 : 1\n dCl_in/dt = a*(I_i + b*I_Cl_leak) : molar\n Cl_out : molar\n E_Cl = -26.67*mV * log(Cl_out/Cl_in) : volt\n I_Cl_leak = g_Cl * (E_Cl0 - E_Cl)\n\n Psi = vartheta_max*Cl_out / (kd + Cl_out) / 4.43 : 1\n I_i = fphi*(V_VAR_NAME_post-E)*Psi*rho_rel\n\n IOPTO_VAR_NAME_post = -(I_i + I_Cl_leak) : ampere (summed)\n rho_rel : 1\"\"\",\n )\n\n extra_namespace: dict[str, Any] = field(\n init=False, factory=lambda: {\"E_Cl0\": -70 * mV, \"g_Cl\": 2.3 * msiemens / cm2}\n )\n\n def init_opto_syn_vars(self, opto_syn: Synapses) -> None:\n raise NotImplementedError(\"Still need to figure out [Cl-_out]\")\n opto_syn.P0 = 1\n opto_syn.P4 = 0\n opto_syn.P6 = 0\n opto_syn.Cl_out = 124 * mM\n opto_syn.Cl_in = np.exp(np.log(124) - 70 / 26.67) * mM\n\n\n@define(eq=False)\nclass ProportionalCurrentOpsin(Opsin):\n \"\"\"A simple model delivering current proportional to light intensity\"\"\"\n\n I_per_Irr: Quantity = field(kw_only=True)\n \"\"\" How much current (in amps or unitless, depending on neuron model)\n to deliver per mW/mm2.\n \"\"\"\n # would be IOPTO_UNIT but that throws off Equation parsing\n model: str = field(\n init=False,\n default=\"\"\"\n IOPTO_VAR_NAME_post = I_per_Irr / (mwatt / mm2) \n * Irr_pre * rho_rel : IOPTO_UNIT (summed)\n rho_rel : 1\n \"\"\",\n )\n\n required_vars: list[Tuple[str, Unit]] = field(factory=list, init=False)\n\n def __attrs_post_init__(self):\n if isinstance(self.I_per_Irr, Quantity):\n Iopto_unit = get_unit(self.I_per_Irr.dim)\n else:\n Iopto_unit = radian\n self.per_ng_unit_replacements = [(\"IOPTO_UNIT\", Iopto_unit.name)]\n self.required_vars = [(\"Iopto\", Iopto_unit)]\n","sub_path":"cleo/opto/opsins.py","file_name":"opsins.py","file_ext":"py","file_size_in_byte":19918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"339387745","text":"from random import randrange\nfrom math import inf\nfrom src.board import Board\n\n\nclass RandomAI:\n @staticmethod\n def move(board: Board, symbol: str) -> Board:\n \"\"\"\n Applies RandomAI's move.\n :param board: The current state of the board\n :param symbol: The symbol RandomAI should use\n :return: The updated board\n \"\"\"\n while True:\n comp_move: int = randrange(10)\n if comp_move in board.get_free_cells():\n board.set_cell(comp_move, symbol)\n break\n return board\n\n\nclass OptimalAI:\n # The cache for storing the results of expensive, recursive minimax calls.\n cache: dict = {}\n\n @staticmethod\n def minimax(board: Board, alpha: float, beta: float, depth: int, maximising: bool, own_symbol: str) -> float:\n \"\"\"\n Finds the best score possible for the maximiser or minimiser for the current board\n :param board: The current state of the board\n :param alpha: The best score so far for the maxmimiser\n :param beta: The best score so far for the minimiser\n :param depth: The depth the algorithm has reached down the game tree\n :param maximising: If the function should act like the maxmiiser or the minimiser\n :param own_symbol: The symbol the function should use for itself, and give the opposite to its opponent\n :return: The best score possible for the maximiser or minimiser\n \"\"\"\n opponent_symbol = \"X\" if own_symbol == \"O\" else \"O\"\n\n # Check if we've reached a terminal state. If so, return the state's score.\n # The score is divided by depth. This rewards quick wins and long losses.\n result = board.is_ended()\n if result == \"D\":\n return 0\n elif result == own_symbol:\n return 1 / depth\n elif result == opponent_symbol:\n return -1 / depth\n\n # Create an identifier string based on: the board, alpha, beta, and whether we are trying to maximise or not.\n state_hash: str = str([board.board, alpha, beta, maximising])\n\n # If the result for this state is in the cache, just return that, instead of recursing the subtree.\n if state_hash in OptimalAI.cache:\n return OptimalAI.cache[state_hash]\n\n final_score = inf * (-1) ** maximising\n\n for cell in board.get_free_cells():\n board.set_cell(cell, own_symbol if maximising else opponent_symbol)\n score: float = OptimalAI.minimax(board, alpha, beta, depth + 1, not maximising, own_symbol)\n board.undo()\n\n if maximising:\n final_score = max(final_score, score)\n alpha = max(alpha, score)\n # If the maximiser realises that the minimiser has a better choice than this subtree, break.\n if beta <= final_score:\n break\n else:\n final_score = min(final_score, score)\n beta = min(beta, score)\n # If the minimiser realises that the maximiser has a better choice than this subtree, break.\n if alpha >= final_score:\n break\n\n # Add our state and its corresponding score to the cache to avoid computing this result in the future.\n OptimalAI.cache[state_hash] = final_score\n return final_score\n\n @staticmethod\n def move(board: Board, symbol: str) -> Board:\n \"\"\"\n Applies OptimalAI's move.\n :param board: The current state of the board\n :param symbol: The symbol RandomAI should use\n :return: The updated board\n \"\"\"\n best_score = -inf\n best_index = None\n\n # Test each possible move, and evaluate its strength based on the minimax algorithm.\n for cell in board.get_free_cells():\n board.set_cell(cell, symbol)\n score = OptimalAI.minimax(board, -inf, inf, 1, False, symbol)\n board.undo()\n\n # If this move is better than the currently best move, replace it.\n if score > best_score:\n best_score = score\n best_index = cell\n\n board.set_cell(best_index, symbol)\n return board\n","sub_path":"src/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"466011266","text":"\nfrom buche import buche\nfrom ..util import Singleton\nfrom ..stx import top as about_top, is_builtin, is_global, Symbol, TMP\nimport json\nimport os\n\n\nclass NO_VALUE(Singleton):\n pass\n\n\nNO_VALUE = NO_VALUE() # type: ignore\n\n\n_css_path = f'{os.path.dirname(__file__)}/graph.css'\n_css = open(_css_path).read()\n\n\n# Roles\n# FN: unique, function used to compute node\n# IN(idx): unique, idxth input to computation for the node\n\n\nclass FN(Singleton):\n \"\"\"\n Edge label for the FN relation between two nodes.\n \"\"\"\n pass\n\n\nclass IN:\n \"\"\"\n Edge label for the IN(i) relation between two nodes.\n \"\"\"\n def __init__(self, index):\n self.index = index\n\n def __str__(self):\n return f'IN({self.index})'\n\n def __hash__(self):\n return hash(IN) ^ self.index\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and \\\n self.index == other.index\n\n\nclass OUT(Singleton):\n \"\"\"\n Edge label for the OUT relation between a graph and a node.\n \"\"\"\n pass\n\n\nFN = FN() # type: ignore\nOUT = OUT() # type: ignore\n\n\ndef commit(ops):\n for op, n1, n2, r in ops:\n n1.process_operation(op, n2, r)\n\n\nclass AbstractNode:\n def process_operation(self, op, node, role):\n method = getattr(self, f'process_operation_{op}')\n method(node, role)\n\n def commit(self, ops):\n commit(ops)\n\n def set_succ(self, role, node):\n \"\"\"\n Create an edge toward node with given role\n \"\"\"\n return commit(self.set_succ_operations(role, node))\n\n\nclass IRNode(AbstractNode):\n \"\"\"\n Node in the intermediate representation. It can represent:\n\n * A computation:\n - fn != None, inputs == list of inputs, value == NO_VALUE\n * A numeric/string/etc. constant\n - fn == None, value == the constant\n * A builtin function like add or multiply\n - fn == None, value == the Symbol for the builtin\n * A pointer to another Myia function\n - fn == None, value == an IRGraph\n * An input\n - fn == None, value == NO_VALUE\n\n Attributes:\n graph: Parent IRGraph for this node. This should be None for\n constant nodes.\n tag: Symbol representing the node name.\n fn: Points to an IRNode providing the function to call.\n inputs: List of IRNode arguments.\n users: Set of incoming edges. Each edge is a (role, node)\n tuple where role is FN or IN(i)\n value: Value taken by this node.\n inferred: TODO\n about: Tracks source code location and sequence of\n transformations and optimizations for this node.\n \"\"\"\n def __init__(self, graph, tag, value=NO_VALUE):\n # Graph the node belongs to\n self.graph = graph\n # Node name (Symbol instance)\n self.tag = tag\n # Outgoing edges\n self.fn = None\n self.inputs = []\n # Incoming edges as (role, node) tuples\n self.users = set()\n # Value this node will take, if it can be determined\n self.value = value\n # Information inferred about this node (type, shape, etc.)\n self.inferred = {}\n # Optimization/source code trace\n self.about = about_top()\n\n def is_input(self):\n return self.fn is None and self.value is NO_VALUE\n\n def is_computation(self):\n return self.fn is not None\n\n def is_constant(self):\n return self.value is not NO_VALUE\n\n def is_builtin(self):\n return is_builtin(self.value)\n\n def is_global(self):\n return is_global(self.value)\n\n def is_graph(self):\n return isinstance(self.value, IRGraph)\n\n def edges(self):\n \"\"\"\n List of nodes that this node depends on.\n \"\"\"\n succ = [(FN, self.fn)] + \\\n [(IN(i), inp) for i, inp in enumerate(self.inputs)]\n return {(r, s) for r, s in succ if s}\n\n def successors(self):\n succ = [self.fn] + list(self.inputs)\n return {s for s in succ if s}\n\n def predecessors(self):\n return {s for _, s in self.users}\n\n def sexp(self):\n \"\"\"\n If this node is an application, return:\n\n (n.fn, *n.inputs)\n\n Otherwise, return None.\n \"\"\"\n if self.fn is None:\n return None\n else:\n return (self.fn,) + tuple(self.inputs)\n\n def set_sexp(self, fn, inputs):\n \"\"\"\n Make this node an application of fn on the specified inputs.\n fn and the inputs must be IRNode instances.\n \"\"\"\n return commit(self.set_sexp_operations(fn, inputs))\n\n def redirect(self, new_node):\n \"\"\"\n Transfer every user of this node to new_node.\n \"\"\"\n return commit(self.redirect_operations(new_node,))\n\n def subsume(self, node):\n \"\"\"\n Transfer every user of the given node to this one.\n \"\"\"\n return node.redirect(self)\n\n # The following methods return a list of atomic \"operations\" to\n # execute in order to perform the task. Atomic operations are\n # ('link', from, to, role) and ('unlink', from, to, node)\n\n def set_succ_operations(self, role, node):\n assert isinstance(node, IRNode) or node is None\n if role is FN:\n unl = self.fn\n elif isinstance(role, IN):\n unl = self.inputs[role.index]\n else:\n raise KeyError(f'Invalid role: {role}')\n rval = []\n if unl:\n if unl == node:\n # Nothing to do because the new successor is the\n # same as the old one.\n return []\n else:\n rval.append(('unlink', self, unl, role))\n if node is not None:\n rval.append(('link', self, node, role))\n return rval\n\n def set_sexp_operations(self, fn, inputs):\n rval = self.set_succ_operations(FN, fn)\n if fn:\n for i, inp in enumerate(self.inputs):\n if inp is not None:\n rval.append(('unlink', self, inp, IN(i)))\n for i, inp in enumerate(inputs):\n if inp is not None:\n rval.append(('link', self, inp, IN(i)))\n return rval\n\n def redirect_operations(self, node):\n rval = []\n for role, n in set(self.users):\n rval += n.set_succ_operations(role, node)\n return rval\n\n def trim_inputs(self):\n while self.inputs and self.inputs[-1] is None:\n self.inputs.pop()\n\n def process_operation_link(self, node, role):\n if role is FN:\n assert self.fn is None\n self.fn = node\n elif isinstance(role, IN):\n idx = role.index\n nin = len(self.inputs)\n if nin <= idx:\n self.inputs += [None for _ in range(idx - nin + 1)]\n assert self.inputs[idx] is None\n self.inputs[idx] = node\n node.users.add((role, self))\n\n def process_operation_unlink(self, node, role):\n if role is FN:\n assert self.fn is node\n self.fn = None\n elif isinstance(role, IN):\n idx = role.index\n nin = len(self.inputs)\n assert self.inputs[idx] is node\n self.inputs[idx] = None\n self.trim_inputs()\n node.users.remove((role, self))\n\n def __getitem__(self, role):\n if role is FN:\n return self.fn\n elif isinstance(role, IN):\n return self.inputs[role.index]\n else:\n raise KeyError(f'Invalid role: {role}')\n\n def __setitem__(self, role, node):\n self.set_succ(role, node)\n\n def __hrepr__(self, H, hrepr):\n if self.value is NO_VALUE:\n return hrepr(self.tag)\n else:\n return hrepr(self.value)\n\n\nclass IRGraph(AbstractNode):\n \"\"\"\n Graph with inputs and an output. Represents a Myia function or\n a closure.\n\n Attributes:\n parent: The IRGraph for the parent function, if this graph\n represents a closure. Otherwise, None.\n tag: A Symbol representing the name of this graph.\n gen: A GenSym instance to generate new tags within this\n graph.\n inputs: A tuple of input IRNodes for this graph.\n output: The IRNode representing the output of this graph.\n \"\"\"\n def __init__(self, parent, tag, gen):\n self.parent = parent\n self.tag = tag\n self.inputs = []\n self._output = None\n self.gen = gen\n # Legacy\n self.lbda = None\n\n @property\n def output(self):\n return self._output\n\n @output.setter\n def output(self, out):\n if self._output:\n self.process_operation('unlink', self._output, OUT)\n self.process_operation('link', out, OUT)\n\n def set_succ_operations(self, role, node):\n if role is OUT:\n lnk = ('link', self, node, role)\n if self._output:\n return [('unlink', self, self._output, role), lnk]\n else:\n return [lnk]\n else:\n raise ValueError(f'Invalid outgoing edge type for IRGraph: {role}')\n\n def process_operation_link(self, node, role):\n if role is OUT:\n assert self._output is None\n self._output = node\n node.users.add((role, self))\n\n def process_operation_unlink(self, node, role):\n if role is OUT:\n assert self._output is node\n self._output = None\n node.users.remove((role, self))\n\n def dup(self, g=None, no_mangle=False):\n \"\"\"\n Duplicate this graph, optionally setting g as the parent of\n every node in the graph.\n\n Return the new graph (or g), a list of inputs, and the output\n node.\n \"\"\"\n set_io = g is None\n if not g:\n g = IRGraph(self.parent, self.tag, self.gen)\n mapping = {}\n for node in self.inputs + tuple(self.iternodes()):\n if no_mangle:\n mapping[node] = IRNode(g, node.tag, node.value)\n else:\n mapping[node] = IRNode(g, g.gen(node.tag, '+'), node.value)\n for n1, n2 in mapping.items():\n sexp = n1.sexp()\n if sexp:\n f, *args = sexp\n f2 = mapping.get(f, f)\n args2 = [mapping.get(a, a) for a in args]\n n2.set_sexp(f2, args2)\n output = mapping.get(self.output, self.output)\n inputs = tuple(mapping[i] for i in self.inputs)\n if set_io:\n g.output = output\n g.inputs = inputs\n return g, inputs, output\n\n def toposort(self):\n if not self.output.is_computation():\n return []\n pred = {}\n ready = {self.output}\n processed = set()\n results = []\n while ready:\n node = ready.pop()\n if not node.is_computation():\n continue\n if node in processed:\n raise Exception('Cannot toposort: cycle detected.')\n results.append(node)\n processed.add(node)\n for succ in node.successors():\n if succ not in pred:\n pred[succ] = {n for _, n in succ.users}\n d = pred[succ]\n d.remove(node)\n if len(d) == 0:\n ready.add(succ)\n pred[succ] = None\n results.reverse()\n return results\n\n def iternodes(self, boundary=False):\n # Basic BFS from output node\n to_visit = {self.output}\n seen = set()\n while to_visit:\n node = to_visit.pop()\n if not node or node in seen:\n continue\n if node.graph is not self:\n if boundary:\n yield node\n continue\n yield node\n seen.add(node)\n to_visit.add(node.fn)\n for inp in node.inputs:\n to_visit.add(inp)\n\n def iterboundary(self):\n return self.iternodes(True)\n\n def iterparents(self, stop=None):\n g = self\n while g and g is not stop:\n yield g\n g = g.parent\n\n @classmethod\n def __hrepr_resources__(cls, H):\n return H.bucheRequire(name='cytoscape')\n\n def __hrepr__(self, H, hrepr):\n rval = H.cytoscapeGraph(H.style(_css))\n options = {\n 'layout': {\n 'name': 'dagre',\n 'rankDir': 'TB'\n }\n }\n rval = rval(H.options(json.dumps(options)))\n\n opts = {\n 'duplicate_constants': hrepr.config.duplicate_constants,\n 'function_in_node': hrepr.config.function_in_node,\n 'follow_references': hrepr.config.follow_references\n }\n nodes_data, edges_data = GraphPrinter({self}, **opts).process()\n for elem in nodes_data + edges_data:\n rval = rval(H.element(json.dumps(elem)))\n return rval\n\n\nclass GraphPrinter:\n \"\"\"\n Helper class to print Myia graphs.\n\n Arguments:\n entry_points: A collection of graphs to print.\n duplicate_constants: If True, each use of a constant will\n be shown as a different node.\n function_in_node: If True, applications of a known function\n will display the function's name in the node like this:\n \"node_name:function_name\". If False, the function will\n be a separate constant node, with a \"F\" edge pointing to\n it.\n follow_references: If True, graphs encountered while walking\n the initial graphs will also be processed.\n \"\"\"\n def __init__(self,\n entry_points,\n duplicate_constants=True,\n function_in_node=True,\n follow_references=True):\n # Graphs left to process\n self.graphs = set(entry_points)\n self.duplicate_constants = duplicate_constants\n self.function_in_node = function_in_node\n self.follow_references = follow_references\n # Nodes left to process\n self.pool = set()\n # ID system for the nodes that will be sent to buche\n self.currid = 0\n self.ids = {}\n # Nodes and edges are accumulated in these lists\n self.nodes = []\n self.edges = []\n\n def next_id(self):\n self.currid += 1\n return f'X{self.currid}'\n\n def register(self, obj):\n if not self.should_dup(obj) and obj in self.ids:\n return False, self.ids[obj]\n id = self.next_id()\n self.ids[obj] = xzz = id\n return True, id\n\n def const_fn(self, node):\n cond = self.function_in_node \\\n and node.is_computation() \\\n and node.fn.is_constant()\n if cond:\n return node.fn.tag\n\n def should_dup(self, node):\n return isinstance(node, IRNode) \\\n and self.duplicate_constants \\\n and node.value is not NO_VALUE\n\n def add_graph(self, g):\n new, id = self.register(g)\n if new:\n self.nodes.append({'data': {'id': id, 'label': str(g.tag)},\n 'classes': 'function'})\n return id\n\n def label(self, node):\n if node.is_constant() and not node.is_graph():\n return str(node.value)\n rels = ''\n tag = node.tag\n while tag.relation:\n if tag.relation != '+':\n rels = rels + tag.relation\n tag = tag.label\n lbl = tag.label\n if '/out' in lbl or '/in' in lbl or lbl == TMP:\n lbl = \"•\"\n lbl = rels + lbl\n cfn = self.const_fn(node)\n if cfn:\n if lbl == \"•\":\n lbl = f'{cfn}'\n else:\n lbl = f'{lbl}←{cfn}'\n return lbl\n\n def add_node(self, node, g=None):\n\n new, id = self.register(node)\n if not new:\n return id\n\n if not g:\n g = node.graph\n\n if node.is_graph():\n if self.follow_references:\n self.graphs.add(node.value)\n\n if node.graph is None:\n cl = 'constant'\n elif node is g.output and node.is_computation():\n cl = 'output'\n elif node in g.inputs:\n cl = 'input'\n else:\n cl = 'intermediate'\n\n lbl = self.label(node)\n\n data = {'id': id, 'label': lbl}\n if g:\n data['parent'] = self.add_graph(g)\n self.nodes.append({'data': data, 'classes': cl})\n self.pool.add(node)\n return id\n\n def process_graph(self, g):\n for inp in g.inputs:\n self.add_node(inp)\n self.add_node(g.output)\n\n if not g.output.is_computation():\n oid = self.next_id()\n self.nodes.append({'data': {'id': oid,\n 'label': '',\n 'parent': self.add_graph(g)},\n 'classes': 'const_output'})\n self.edges.append({'data': {\n 'id': self.next_id(),\n 'label': '',\n 'source': self.ids[g.output],\n 'target': oid\n }})\n\n while self.pool:\n node = self.pool.pop()\n if self.const_fn(node):\n if self.follow_references \\\n and isinstance(node.fn.value, IRGraph):\n self.graphs.add(node.fn.value)\n edges = []\n else:\n edges = [(node, FN, node.fn)] \\\n if node.is_computation() \\\n else []\n edges += [(node, IN(i), inp)\n for i, inp in enumerate(node.inputs) or []]\n for edge in edges:\n src, role, dest = edge\n if role is FN:\n lbl = 'F'\n else:\n lbl = str(role.index)\n dest_id = self.add_node(dest, self.should_dup(dest) and g)\n data = {\n 'id': self.next_id(),\n 'label': lbl,\n 'source': dest_id,\n 'target': self.ids[src]\n }\n self.edges.append({'data': data})\n\n def process(self):\n while self.graphs:\n g = self.graphs.pop()\n self.process_graph(g)\n return self.nodes, self.edges\n","sub_path":"myia/ir/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":18343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"274586804","text":"'''file handling -1.file handing is very important for accessing other data.\r\n 2.there are three modes in file hanling as read , write and append.\r\n 3.in read you can red only\r\n 4.in write you can write a data but when you write new line old one gets deletd\r\n 5.append adds new data and keeps olds data as it is.\r\n 6.if you open a file but that file doesnt exist it creates a new file with that name but mode\r\n must be append.\r\n 7. we also can acess image using this\r\n ..for eg we are aceesed a demo file below'''\r\n#EG-\r\n\r\nf1 = open(\"abc.txt\",'a')\r\nf1.write(\"encryptt side support encrypted communication, an eavesdropper snooping ...\")\r\nf1 = open(\"abc.txt\",'r')\r\nfor data in f1:\r\n print(data)","sub_path":"all python code/file handing.py","file_name":"file handing.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"87750903","text":"import hashlib\nimport urllib\nimport urlparse\nimport datetime\nfrom django.db.models import F\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.views.decorators.csrf import csrf_exempt\nfrom querystring.models import Query\nfrom querystring.utils import SearchReferrerParser\n\n@csrf_exempt\ndef search_queries(request):\n if request.POST:\n post = request.POST\n if 'referrer' in post.keys():\n page_url = urlparse.urlsplit(request.META['HTTP_REFERER'])\n page_path = page_url.path\n\n referrer = post['referrer'].encode('utf-8')\n referrer = urllib.unquote(referrer)\n\n srp = SearchReferrerParser()\n results = srp.get_result(referrer)\n\n if results[2]:\n query_string = results[2]\n\n query_hash = hashlib.sha1(query_string.encode('utf-8')).hexdigest()\n\n cnt = Query.objects.filter(hash = query_hash).count()\n if cnt:\n Query.objects.filter(hash = query_hash).update(counter=F('counter') + 1, updated = datetime.datetime.now())\n else:\n Query.objects.create(hash = query_hash, text = query_string, url = page_path)\n\n return HttpResponse('ok')\n else:\n return HttpResponse('nose')\n\n return HttpResponseBadRequest\n","sub_path":"querystring/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"479319566","text":"#coding=utf8\n'''\n 请实现一个函数,参数为一个list,list中的元素都是整数,函数需要将List中的元素按从小到大排序,最终返回一个新的list\n'''\n# 请按下面算法的思路实现函数:\n# 创建一个新的列表newList\n\n# 先找出所有元素中最小的,append在newList里面\n# 再找出剩余的所有元素中最小的,append在newList里面\n# 依次类推,直到所有的元素都放到newList里面\n\n\ndef sort(alist):\n newList = []\n while len(alist) > 0:\n theMin = alist[0] #记录当前循环最小元素\n minIdx = 0 #记录当前最小元素的下标\n Idx = 0 #指向当前元素下标\n for one in alist:\n if theMin > one:\n theMin = one\n minIdx = Idx\n Idx += 1\n alist.pop(minIdx)\n newList.append(theMin)\n return newList\n\nprint (sort([2,3,5,6,1,77,3,8,7,1,3]))\n\n# print (sorted([2-服务端+客户端编写,3,5,6,1,77,3,8,7,1,3]))\n\n# def bubble(alist):\n# for j in range(len(alist)-1,0,1):\n# for i in range(0,j):\n# if alist[i] > alist[i+1]:\n# alist[i],alist[i + 1] = alist[i+1],alist[i]\n# return alist\n# alist = [2-服务端+客户端编写,1,5,6,77,3,8,7,4,3]\n# print bubble(alist)\n\n\n\n\n\n \n \n\n\n","sub_path":"code/untitled1/模拟测试脚本开发验证/python/4sort4.py","file_name":"4sort4.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"544754559","text":"#===----------------------------------------------------------------------===//\n#\n# The LLVM Compiler Infrastructure\n#\n# This file is dual licensed under the MIT and the University of Illinois Open\n# Source Licenses. See LICENSE.TXT for details.\n#\n#===----------------------------------------------------------------------===//\n\nimport importlib\nimport lit.util # pylint: disable=import-error,no-name-in-module\nimport locale\nimport os\nimport platform\nimport re\nimport sys\n\nclass DefaultTargetInfo(object):\n def __init__(self, full_config):\n self.full_config = full_config\n\n def platform(self):\n return sys.platform.lower().strip()\n\n def add_locale_features(self, features):\n self.full_config.lit_config.warning(\n \"No locales entry for target_system: %s\" % self.platform())\n\n def add_cxx_compile_flags(self, flags): pass\n def add_cxx_link_flags(self, flags): pass\n def configure_env(self, env): pass\n def allow_cxxabi_link(self): return True\n def add_sanitizer_features(self, sanitizer_type, features): pass\n def use_lit_shell_default(self): return False\n\n\ndef test_locale(loc):\n assert loc is not None\n default_locale = locale.setlocale(locale.LC_ALL)\n try:\n locale.setlocale(locale.LC_ALL, loc)\n return True\n except locale.Error:\n return False\n finally:\n locale.setlocale(locale.LC_ALL, default_locale)\n\n\ndef add_common_locales(features, lit_config):\n # A list of locales needed by the test-suite.\n # The list uses the canonical name for the locale used in the test-suite\n # TODO: On Linux ISO8859 *may* needs to hyphenated.\n locales = [\n 'en_US.UTF-8',\n 'fr_FR.UTF-8',\n 'ru_RU.UTF-8',\n 'zh_CN.UTF-8',\n 'fr_CA.ISO8859-1',\n 'cs_CZ.ISO8859-2'\n ]\n for loc in locales:\n if test_locale(loc):\n features.add('locale.{0}'.format(loc))\n else:\n lit_config.warning('The locale {0} is not supported by '\n 'your platform. Some tests will be '\n 'unsupported.'.format(loc))\n\n\nclass DarwinLocalTI(DefaultTargetInfo):\n def __init__(self, full_config):\n super(DarwinLocalTI, self).__init__(full_config)\n\n def is_host_macosx(self):\n name = lit.util.capture(['sw_vers', '-productName']).strip()\n return name == \"Mac OS X\"\n\n def get_macosx_version(self):\n assert self.is_host_macosx()\n version = lit.util.capture(['sw_vers', '-productVersion']).strip()\n version = re.sub(r'([0-9]+\\.[0-9]+)(\\..*)?', r'\\1', version)\n return version\n\n def get_sdk_version(self, name):\n assert self.is_host_macosx()\n cmd = ['xcrun', '--sdk', name, '--show-sdk-path']\n try:\n out = lit.util.capture(cmd).strip()\n except OSError:\n pass\n\n if not out:\n self.full_config.lit_config.fatal(\n \"cannot infer sdk version with: %r\" % cmd)\n\n return re.sub(r'.*/[^0-9]+([0-9.]+)\\.sdk', r'\\1', out)\n\n def get_platform(self):\n platform = self.full_config.get_lit_conf('platform')\n if platform:\n platform = re.sub(r'([^0-9]+)([0-9\\.]*)', r'\\1-\\2', platform)\n name, version = tuple(platform.split('-', 1))\n else:\n name = 'macosx'\n version = None\n\n if version:\n return (False, name, version)\n\n # Infer the version, either from the SDK or the system itself. For\n # macosx, ignore the SDK version; what matters is what's at\n # /usr/lib/libc++.dylib.\n if name == 'macosx':\n version = self.get_macosx_version()\n else:\n version = self.get_sdk_version(name)\n return (True, name, version)\n\n def add_locale_features(self, features):\n add_common_locales(features, self.full_config.lit_config)\n\n def add_cxx_compile_flags(self, flags):\n if self.full_config.use_deployment:\n _, name, _ = self.full_config.config.deployment\n cmd = ['xcrun', '--sdk', name, '--show-sdk-path']\n else:\n cmd = ['xcrun', '--show-sdk-path']\n try:\n out = lit.util.capture(cmd).strip()\n res = 0\n except OSError:\n res = -1\n if res == 0 and out:\n sdk_path = out\n self.full_config.lit_config.note('using SDKROOT: %r' % sdk_path)\n flags += [\"-isysroot\", sdk_path]\n\n def add_cxx_link_flags(self, flags):\n flags += ['-lSystem']\n\n def configure_env(self, env):\n library_paths = []\n # Configure the library path for libc++\n if self.full_config.use_system_cxx_lib:\n if (os.path.isdir(str(self.full_config.use_system_cxx_lib))):\n library_paths += [self.full_config.use_system_cxx_lib]\n pass\n elif self.full_config.cxx_runtime_root:\n library_paths += [self.full_config.cxx_runtime_root]\n # Configure the abi library path\n if self.full_config.abi_library_root:\n library_paths += [self.full_config.abi_library_root]\n if library_paths:\n env['DYLD_LIBRARY_PATH'] = ':'.join(library_paths)\n\n def allow_cxxabi_link(self):\n # FIXME: PR27405\n # libc++ *should* export all of the symbols found in libc++abi on OS X.\n # For this reason LibcxxConfiguration will not link libc++abi in OS X.\n # However __cxa_throw_bad_new_array_length doesn't get exported into\n # libc++ yet so we still need to explicitly link libc++abi when testing\n # libc++abi\n # See PR22654.\n if(self.full_config.get_lit_conf('name', '') == 'libc++abi'):\n return True\n # Don't link libc++abi explicitly on OS X because the symbols\n # should be available in libc++ directly.\n return False\n\n def add_sanitizer_features(self, sanitizer_type, features):\n if sanitizer_type == 'Undefined':\n features.add('sanitizer-new-delete')\n\n\nclass FreeBSDLocalTI(DefaultTargetInfo):\n def __init__(self, full_config):\n super(FreeBSDLocalTI, self).__init__(full_config)\n\n def add_locale_features(self, features):\n add_common_locales(features, self.full_config.lit_config)\n\n def add_cxx_link_flags(self, flags):\n flags += ['-lc', '-lm', '-lpthread', '-lgcc_s', '-lcxxrt']\n\n\nclass LinuxLocalTI(DefaultTargetInfo):\n def __init__(self, full_config):\n super(LinuxLocalTI, self).__init__(full_config)\n\n def platform(self):\n return 'linux'\n\n def platform_name(self):\n name, _, _ = platform.linux_distribution()\n name = name.lower().strip()\n return name # Permitted to be None\n\n def platform_ver(self):\n _, ver, _ = platform.linux_distribution()\n ver = ver.lower().strip()\n return ver # Permitted to be None.\n\n def add_locale_features(self, features):\n add_common_locales(features, self.full_config.lit_config)\n # Some linux distributions have different locale data than others.\n # Insert the distributions name and name-version into the available\n # features to allow tests to XFAIL on them.\n name = self.platform_name()\n ver = self.platform_ver()\n if name:\n features.add(name)\n if name and ver:\n features.add('%s-%s' % (name, ver))\n\n def add_cxx_compile_flags(self, flags):\n flags += ['-D__STDC_FORMAT_MACROS',\n '-D__STDC_LIMIT_MACROS',\n '-D__STDC_CONSTANT_MACROS']\n\n def add_cxx_link_flags(self, flags):\n enable_threads = ('libcpp-has-no-threads' not in\n self.full_config.config.available_features)\n llvm_unwinder = self.full_config.get_lit_bool('llvm_unwinder', False)\n shared_libcxx = self.full_config.get_lit_bool('enable_shared', True)\n flags += ['-lm']\n if not llvm_unwinder:\n flags += ['-lgcc_s', '-lgcc']\n if enable_threads:\n flags += ['-lpthread']\n if not shared_libcxx:\n flags += ['-lrt']\n flags += ['-lc']\n if llvm_unwinder:\n flags += ['-lunwind', '-ldl']\n else:\n flags += ['-lgcc_s']\n flags += ['-lgcc']\n use_libatomic = self.full_config.get_lit_bool('use_libatomic', False)\n if use_libatomic:\n flags += ['-latomic']\n san = self.full_config.get_lit_conf('use_sanitizer', '').strip()\n if san:\n # The libraries and their order are taken from the\n # linkSanitizerRuntimeDeps function in\n # clang/lib/Driver/Tools.cpp\n flags += ['-lpthread', '-lrt', '-lm', '-ldl']\n\n\nclass WindowsLocalTI(DefaultTargetInfo):\n def __init__(self, full_config):\n super(WindowsLocalTI, self).__init__(full_config)\n\n def add_locale_features(self, features):\n add_common_locales(features, self.full_config.lit_config)\n\n def use_lit_shell_default(self):\n # Default to the internal shell on Windows, as bash on Windows is\n # usually very slow.\n return True\n\n\ndef make_target_info(full_config):\n default = \"libcxx.test.target_info.LocalTI\"\n info_str = full_config.get_lit_conf('target_info', default)\n if info_str != default:\n mod_path, _, info = info_str.rpartition('.')\n mod = importlib.import_module(mod_path)\n target_info = getattr(mod, info)(full_config)\n full_config.lit_config.note(\"inferred target_info as: %r\" % info_str)\n return target_info\n target_system = platform.system()\n if target_system == 'Darwin': return DarwinLocalTI(full_config)\n if target_system == 'FreeBSD': return FreeBSDLocalTI(full_config)\n if target_system == 'Linux': return LinuxLocalTI(full_config)\n if target_system == 'Windows': return WindowsLocalTI(full_config)\n return DefaultTargetInfo(full_config)\n","sub_path":"libcxx/utils/libcxx/test/target_info.py","file_name":"target_info.py","file_ext":"py","file_size_in_byte":9953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"72534061","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/sflib/ps.py\n# Compiled at: 2009-01-08 03:15:58\n\"\"\"\nManage Processes and a ProcessList under Linux.\n\nfrom http://mail.python.org/pipermail/python-list/2006-June/386765.html\n\n >>> from sflib import ps\n >>> p = ps.ProcessList()\n >>> p.named(\"emacs\") # doctest: +SKIP\n [Process(pid = 20610), Process(pid = 6076), Process(pid = 6113), Process(pid = 6590), Process(pid = 857), Process(pid = 1394), Process(pid = 28974)]\n\n\"\"\"\nimport os, signal\n\nclass Process(object):\n \"\"\"Represents a process\"\"\"\n __module__ = __name__\n\n def __init__(self, pid):\n \"\"\"Make a new Process object\"\"\"\n self.proc = '/proc/%d' % pid\n (pid, command, state, parent_pid) = file(os.path.join(self.proc, 'stat')).read().strip().split()[:4]\n command = command[1:-1]\n self.pid = int(pid)\n self.command = command\n self.state = state\n self.parent_pid = int(parent_pid)\n self.parent = None\n self.children = []\n return\n\n def kill(self, sig=signal.SIGTERM):\n \"\"\"Kill this process with SIGTERM by default\"\"\"\n os.kill(self.pid, sig)\n\n def __repr__(self):\n return 'Process(pid = %r)' % self.pid\n\n def getcwd(self):\n \"\"\"Read the current directory of this process or None for can't\"\"\"\n try:\n return os.readlink(os.path.join(self.proc, 'cwd'))\n except OSError:\n return\n\n return\n\n\nclass ProcessList(object):\n \"\"\"Represents a list of processes\"\"\"\n __module__ = __name__\n\n def __init__(self):\n \"\"\"Read /proc and fill up the process lists\"\"\"\n self.by_pid = {}\n self.by_command = {}\n for f in os.listdir('/proc'):\n if f.isdigit():\n process = Process(int(f))\n self.by_pid[process.pid] = process\n self.by_command.setdefault(process.command, []).append(process)\n\n for process in self.by_pid.values():\n try:\n parent = self.by_pid[process.parent_pid]\n parent.children.append(process)\n process.parent = parent\n except KeyError:\n pass\n\n def named(self, name):\n \"\"\"Returns a list of processes with the given name\"\"\"\n return self.by_command.get(name, [])","sub_path":"pycfiles/sflib-1.0dev_BZR_r45_panta_elasticworld.org_20091021145839_1oceeh3stpvyl04t-py2.4/ps.py","file_name":"ps.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"161100791","text":"from telegram import ReplyKeyboardMarkup\r\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\r\nimport constants, base_work\r\nimport logging\r\nimport calendar\r\nimport time\r\nfrom datetime import date, timedelta\r\ndelete_b = add_b = licension = day_id = admin_add = delete_admin = False\r\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\r\n level=logging.INFO)\r\n\r\nupdater = Updater(token=constants.token)\r\n\r\ndispatcher = updater.dispatcher\r\n\r\njob_queue = updater.job_queue\r\n\r\n\r\ndef start(bot, update):\r\n message = update.message\r\n if message.chat.type == 'private' and message.chat.id in base_work.collect_All_id():\r\n bottons = [['Посмотреть слова', 'Удалить слова'], ['Добавить слово']]\r\n if message.chat.id in constants.main_admins:\r\n bottons1 = [['Выдать лицензию', 'Добавить админа'], ['Список Админов', 'Удалить Админа', 'Дополнительно'] ]\r\n else: bottons1 = []\r\n user_markup = ReplyKeyboardMarkup(bottons + bottons1)\r\n bot.send_message(message.chat.id, 'Здравствуй, админ!', reply_markup=user_markup)\r\n elif message.chat.type != 'group':\r\n bot.send_message(message.chat.id, str(message.chat.id))\r\n for i in constants.main_admins:\r\n try:\r\n bot.send_message(i, str(message.chat.id))\r\n except:\r\n pass\r\n elif message.chat.type == 'group' and message.from_user.id in base_work.collect_All_id():\r\n base_work.add_group(message.from_user.id, message.chat.title)\r\n else:\r\n print(message)\r\n bot.send_message(message.chat.id, constants.hello_text)\r\n\r\ndef answer(bot, update):\r\n global delete_b, add_b, licension, datet, day_id, admin_add, delete_admin\r\n message = update.message\r\n if message.chat.type == 'group':\r\n text1 = message.text.lower().split()\r\n text2 = base_work.collect_All_words()\r\n ai = []\r\n ai2 = []\r\n for i in text1:\r\n if i in text2:\r\n ai = base_work.all_about_all(i)\r\n for j in ai:\r\n if not j in ai2:\r\n bot.forward_message(chat_id=j, from_chat_id=message.chat.id, message_id=message.message_id)\r\n ai2 = ai\r\n ai = []\r\n\r\n elif message.text == 'Дополнительно' and message.chat.id in constants.main_admins:\r\n bottons = [['Все слова в базе данных', 'Группы/Слова', 'Лицензии'], ['Назад']]\r\n user_markup = ReplyKeyboardMarkup(bottons)\r\n bot.send_message(message.chat.id, 'Дополнительно', reply_markup=user_markup)\r\n elif message.text == 'Все слова в базе данных' and message.chat.id in constants.main_admins:\r\n all_words = base_work.collect_All_words()\r\n word = ''\r\n for i in all_words:\r\n word += i + '\\n'\r\n bot.send_message(message.chat.id, word)\r\n elif message.text == 'Посмотреть слова' and message.chat.id in base_work.collect_All_id():\r\n try:\r\n words = base_work.collect_words(message.chat.id)\r\n word = ''\r\n for i in words:\r\n word += i + '\\n'\r\n bot.send_message(message.chat.id, word)\r\n except:\r\n bot.send_message(message.chat.id, 'У вас нет пока что слов')\r\n elif message.text == 'Удалить слова' and message.chat.id in base_work.collect_All_id():\r\n bottons = [['Назад']]\r\n user_markup = ReplyKeyboardMarkup(bottons)\r\n bot.send_message(message.chat.id, 'Напишите слово, которое хотите удалить', reply_markup=user_markup)\r\n delete_b = True\r\n elif delete_b == True:\r\n delete_b = False\r\n if message.text == 'Назад':\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n else:\r\n base_work.delete_words(message.chat.id, message.text.lower())\r\n bot.send_message(message.chat.id, 'Слово \"'+ message.text+'\" удалено')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif message.text == 'Добавить слово' and message.chat.id in base_work.collect_All_id():\r\n bottons = [['Назад']]\r\n user_markup = ReplyKeyboardMarkup(bottons)\r\n bot.send_message(message.chat.id, 'Напишите слово, которое хотите добавить', reply_markup=user_markup)\r\n add_b = True\r\n elif add_b == True:\r\n add_b = False\r\n if message.text == 'Назад':\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n else:\r\n base_work.add_words(message.chat.id, message.text.lower())\r\n bot.send_message(message.chat.id, 'Слово \"' + message.text + '\" добавлено')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif message.text == 'Список Админов' and message.chat.id in constants.main_admins:\r\n ids = base_work.collect_All_id()\r\n word = ''\r\n for i in ids:\r\n word += str(i) + '\\n'\r\n bot.send_message(message.chat.id, word)\r\n elif message.text == 'Добавить админа' and message.chat.id in constants.main_admins:\r\n admin_add = True\r\n bottons = [['Назад']]\r\n user_markup = ReplyKeyboardMarkup(bottons)\r\n bot.send_message(message.chat.id, 'Напишите, id пользователя, чтобы добавить его в список админов', reply_markup=user_markup)\r\n elif admin_add == True:\r\n admin_add = False\r\n if message.text == 'Назад':\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n else:\r\n try:\r\n base_work.add_id(message.text)\r\n bot.send_message(message.chat.id, 'Админ добавлен, если хотите посмотреть список всех админов, нажмите \"Список Админов\"')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n except:\r\n bot.send_message(message.chat.id, 'Что-то пошло не так. Проверьте правильность написания id')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif message.text == 'Удалить Админа' and message.chat.id in constants.main_admins:\r\n delete_admin = True\r\n bottons = [['Назад']]\r\n user_markup = ReplyKeyboardMarkup(bottons)\r\n bot.send_message(message.chat.id, 'Напишите id админа', reply_markup=user_markup)\r\n elif delete_admin == True:\r\n delete_admin = False\r\n if message.text == 'Назад':\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n else:\r\n try:\r\n base_work.delete_id(int(message.text))\r\n bot.send_message(message.chat.id, 'Вы удалили админа')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n except:\r\n bot.send_message(message.chat.id,'Что-то пошло не так')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif message.text == 'Выдать лицензию' and message.chat.id in constants.main_admins:\r\n bot.send_message(message.chat.id, 'Напишите, на сколько вы хотите выдать лицензию,в формате:')\r\n bot.send_message(message.chat.id, '1 месяц' )\r\n bot.send_message(message.chat.id, '2 года')\r\n bottons = [['Навсегда'],['Назад']]\r\n user_markup = ReplyKeyboardMarkup(bottons)\r\n bot.send_message(message.chat.id, 'Или нажмите на кнопку \"Навсегда\"', reply_markup=user_markup)\r\n licension = True\r\n elif licension == True:\r\n licension = False\r\n if message.text == 'Назад':\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif message.text == 'Навсегда':\r\n datet = 0\r\n bot.send_message(message.chat.id, 'Выберите id')\r\n day_id = True\r\n else:\r\n text = message.text.split()\r\n today = date.today()\r\n if text[1] == 'месяц' or text[1] == 'месяца' or text[1] == 'месяцев':\r\n days = int(text[0])*31\r\n datet = today + timedelta(days=days)\r\n bot.send_message(message.chat.id, 'Выберите id')\r\n day_id = True\r\n elif text[1] == 'год' or text[1] == 'года' or text[1] == 'лет':\r\n days = int(text[0])*31*12\r\n datet = today + timedelta(days=days)\r\n bot.send_message(message.chat.id, 'Выберите id')\r\n day_id = True\r\n else:\r\n bot.send_message(message.chat.id, 'Проверьте правильность написания промежутка')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif day_id == True:\r\n day_id = False\r\n try:\r\n base_work.incert_date(int(message.text), datet)\r\n bot.send_message(message.chat.id, 'Изменения добавлены')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n except:\r\n bot.send_message(message.chat.id, 'Проверьте правильность написания id')\r\n update.message.text = 'Назад'\r\n answer(bot, update)\r\n elif message.text == 'Назад':\r\n bottons = [['Посмотреть слова', 'Удалить слова'], ['Добавить слово']]\r\n if message.chat.id in constants.main_admins:\r\n bottons1 = [['Выдать лицензию','Добавить админа'], ['Список Админов', 'Удалить Админа', 'Дополнительно'] ]\r\n else:\r\n bottons1 = []\r\n user_markup = ReplyKeyboardMarkup(bottons + bottons1)\r\n bot.send_message(message.chat.id, 'Чем еще могу помочь?', reply_markup=user_markup)\r\n elif message.text == 'Лицензии' and message.chat.id in constants.main_admins:\r\n lic = base_work.all_licience()\r\n bot.send_message(message.chat.id, 'Тут будет написано, до какого действует лицензия, в формате ID / Date')\r\n line = ''\r\n for i in lic:\r\n line += str(i[0]) + ' / '\r\n if i[1] == 0:\r\n line += 'Навсегда' + '\\n'\r\n else:\r\n line += str(i[1]) + '\\n'\r\n bot.send_message(message.chat.id, line)\r\n elif message.text == 'Группы/Слова' and message.chat.id in constants.main_admins:\r\n lic = base_work.all_groups()\r\n bot.send_message(message.chat.id, 'Тут будут выведены все группы и слова админов, в формате ID/ Group/ Words')\r\n line = ''\r\n for i in lic:\r\n line += str(i[0]) + ' / ' + str(i[1])[:-1] + ' / ' +str(i[2])+ '\\n'\r\n bot.send_message(message.chat.id, line)\r\n\r\n\r\n\r\ndef chek_time():\r\n pass\r\n\r\n\r\n\r\nstart_handler = CommandHandler('start', start)\r\nanswer_handler = MessageHandler(Filters.text, answer)\r\ndispatcher.add_handler(start_handler)\r\ndispatcher.add_handler(answer_handler)\r\nupdater.start_polling(clean=True, timeout=5 )","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"190435665","text":"from __future__ import absolute_import, division, print_function\n\nfrom Templates.Utils import *\n\nSTATE = {\n \"_pltype\": \"list\",\n # \"_do\":\n # - setdb MAIN_DB\n # - setvar _path,%STATE/*/$/@rodbank,apply=>&pathfind\n # - getvar _path,apply=>'my @value=split(/\\//,shift @_); splice(@value,2,1)';\n # - getvar _path,apply=>&pathlevel,arg=>3\n\n # \"_tr\":\n # \"_name\": \"_loop\"\n # \"_content\": \"\"%STATE\n\n # State_(_loop)\"\":\n # \"_pltype\": \"list\"\n # \"_do\":\n # - setdb MAIN_DB\n\n \"_content\": {\n\n \"id\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$id\n \"_value\": copy_value,\n }\n ]\n },\n \"title\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$title\n \"_value\": copy_value,\n }\n ]\n },\n \"power\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$power\n \"_value\": copy_value,\n }\n ]\n },\n \"flow\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$flow\n \"_value\": copy_value,\n }\n ]\n },\n \"bypass\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$bypass\n \"_value\": copy_value,\n }\n ]\n },\n \"xenon\": {\n \"_output\": [\n {\n \"_name\": \"xenopt\",\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$xenon\n \"_value\": copy_value,\n }\n ]\n },\n \"samopt\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$samar\n \"_value\": copy_value,\n }\n ]\n },\n \"rlx_xesm\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$rlx_xesm\n \"_value\": copy_value,\n }\n ]\n },\n \"rodbank\": {\n \"_output\": [\n {\n \"_name\": \"bank_labels\",\n \"_pltype\": \"array\",\n \"_type\": \"string\",\n # \"_do\":\n # - copyarray %STATE/$(_loop)/@rodbank,select=>even\n \"_value\": [copy_array, slice(0, None, 2)],\n },\n {\n \"_name\": \"bank_pos\",\n \"_pltype\": \"array\",\n \"_type\": \"int\",\n # \"_do\":\n # - copyarray %STATE/$(_loop)/@rodbank,select=>odd\n \"_value\": [copy_array, slice(1, None, 2)],\n }\n ]\n },\n \"boron\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$boron\n \"_value\": copy_value,\n }\n ]\n },\n \"b10\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"b10\":0\n \"_value\": [copy_value, 0],\n },\n {\n \"_name\": \"b10_depl\",\n \"_pltype\": \"parameter\",\n \"_type\": \"bool\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"b10\":1\n \"_value\": [copy_value, 1],\n }\n ]\n },\n \"tinlet\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - tocelsius %STATE/$(_loop)/@tinlet\n \"_value\": toCelsius,\n }\n ]\n },\n \"pressure\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$pressure,apply=>($_[0])*0.00689475729\n \"_value\": [copy_value_mult, 0, 0.00689475729],\n }\n ]\n },\n \"search\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$search\n \"_value\": copy_value,\n }\n ]\n },\n \"search_bank\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$search_bank\n \"_value\": copy_value,\n }\n ]\n },\n \"kcrit\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$kcrit\n \"_value\": copy_value,\n }\n ]\n },\n \"deplete\": {\n \"_output\": [\n {\n \"_pltype\": \"array\",\n \"_type\": \"double\",\n # \"_do\":\n # - copyarray %STATE/$(_loop)/@deplete,start=>1\n \"_value\": [copy_array, slice(1, None)],\n },\n {\n \"_name\": \"deplete_units\",\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/@\"deplete\":0\n \"_value\": [copy_value, 0],\n }\n ]\n },\n \"edit\": {\n \"_output\": [\n {\n \"_pltype\": \"array\",\n \"_type\": \"string\",\n # \"_do\":\n # - copyarray %STATE/$(_loop)/$edit\n \"_value\": copy_array,\n }\n ]\n },\n \"tfuel\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - tocelsius %STATE/$(_loop)/@tfuel,apply=>($_[0]+273.15)\n \"_value\": toKelvin,\n }\n ]\n },\n \"modden\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$modden\n \"_value\": copy_value,\n }\n ]\n },\n \"feedback\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$feedback\n \"_value\": copy_value,\n }\n ]\n },\n \"thexp\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$thexp\n \"_value\": copy_value,\n }\n ]\n },\n \"thexp_tfuel\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - tocelsius %STATE/$(_loop)/@thexp_tfuel,apply=>($_[0]+273.15)\n \"_value\": toKelvin,\n }\n ]\n },\n \"thexp_tclad\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - tocelsius %STATE/$(_loop)/@thexp_tclad,apply=>($_[0]+273.15)\n \"_value\": toKelvin,\n }\n ]\n },\n \"thexp_tmod\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - tocelsius %STATE/$(_loop)/@thexp_tmod,apply=>($_[0]+273.15)\n \"_value\": toKelvin,\n }\n ]\n },\n \"sym\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$sym\n \"_value\": copy_value,\n }\n ]\n },\n \"reset_sol\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"bool\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$reset_sol\n \"_value\": copy_value,\n }\n ]\n },\n \"op_date\": {\n \"_output\": [\n {\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$op_date\n \"_value\": copy_value,\n }\n ]\n },\n \"restart_shuffle\": {\n \"_output\": [\n {\n \"_name\": \"restart_shuffle_file\",\n \"_pltype\": \"array\",\n \"_type\": \"string\",\n # \"_do\":\n # - copyarray %STATE/$(_loop)/@restart_shuffle,select=>even\n \"_value\": [copy_array, slice(0, None, 2)],\n },\n {\n \"_name\": \"restart_shuffle_label\",\n \"_pltype\": \"array\",\n \"_type\": \"string\",\n # \"_do\":\n # - copyarray %STATE/$(_loop)/@restart_shuffle,select=>odd\n \"_value\": [copy_array, slice(1, None, 2)],\n }\n ]\n },\n \"restart_write\": {\n \"_output\": [\n {\n \"_name\": \"restart_write_file\",\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/@\"restart_write\":0\n \"_value\": [copy_value, 0],\n },\n {\n \"_name\": \"restart_write_label\",\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/@\"restart_write\":1\n \"_value\": [copy_value, 1],\n }\n ]\n },\n \"restart_read\": {\n \"_output\": [\n {\n \"_name\": \"restart_read_file\",\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/@\"restart_read\":0\n \"_value\": [copy_value, 0],\n },\n {\n \"_name\": \"restart_read_label\",\n \"_pltype\": \"parameter\",\n \"_type\": \"string\",\n # \"_do\":\n # - copy %STATE/$(_loop)/@\"restart_read\":1\n \"_value\": [copy_value, 1],\n }\n ]\n },\n \"shuffle_label\": {\n \"_output\": [\n {\n \"_pltype\": \"array\",\n \"_type\": \"string\",\n # \"_do\":\n # - coremapmap CORE/$size,CORE/@core_shape,%STATE/$(_loop)/@shuffle_label,CORE/$bc_sym,expand=>0,ignore=>'-'\n \"_value\": [core_map, \"ref:size:0\", \"ref:shape\"],\n }\n ]\n },\n \"tinlet_dist\": {\n \"_output\": [\n {\n \"_pltype\": \"array\",\n \"_type\": \"double\",\n # \"_do\":\n # - coremapmap CORE/$size,CORE/@core_shape,%STATE/$(_loop)/@tinlet_dist,CORE/$bc_sym\n \"_value\": [core_map, \"ref:size:0\", \"ref:shape\"],\n }\n ]\n },\n \"void_map\": {\n \"_output\": [\n {\n \"_pltype\": \"array\",\n \"_type\": \"double\",\n # \"_do\":\n # - coremapmap CORE/$size,CORE/@core_shape,%STATE/$(_loop)/@void,CORE/$bc_sym\n \"_value\": [core_map, \"ref:size:0\", \"ref:shape\"],\n }\n ]\n },\n \"flow_dist\": {\n \"_output\": [\n {\n \"_pltype\": \"array\",\n \"_type\": \"double\",\n # \"_do\":\n # - coremapmap CORE/$size,CORE/@core_shape,%STATE/$(_loop)/@flow_dist,CORE/$bc_sym\n \"_value\": [core_map, \"ref:size:0\", \"ref:shape\"],\n }\n ]\n },\n \"cool_chem\": {\n \"_output\": [\n {\n \"_name\": \"h_conc\",\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"cool_chem\":0\n \"_value\": [copy_value, 0],\n },\n {\n \"_name\": \"li_conc\",\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"cool_chem\":1\n \"_value\": [copy_value, 1],\n },\n {\n \"_name\": \"ni_sol\",\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"cool_chem\":2\n \"_value\": [copy_value, 2],\n },\n {\n \"_name\": \"ni_par\",\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"cool_chem\":3\n \"_value\": [copy_value, 3],\n },\n {\n \"_name\": \"fe_sol\",\n \"_pltype\": \"parameter\",\n \"_type\": \"double\",\n # \"_do\":\n # - copy %STATE/$(_loop)/$\"cool_chem\":4\n \"_value\": [copy_value, 4],\n }\n ]\n },\n }\n}\n","sub_path":"verain/python/Templates/STATE.py","file_name":"STATE.py","file_ext":"py","file_size_in_byte":11989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"647254537","text":"import sys\nfrom PySide2.QtWidgets import (QApplication, QWidget, QHBoxLayout, \nQFrame, QSplitter, QStyleFactory)\nfrom PySide2.QtCore import Qt # 数据类型; Qt布局方向\n\nclass Example(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n\n hbox = QHBoxLayout()\n\n topleft = QFrame(self)\n topleft.setFrameShape(QFrame.StyledPanel)\n # topleft.setFrameShape(QFrame.Shadow) # ? 报错\n \n topright = QFrame(self)\n topright.setFrameShape(QFrame.StyledPanel)\n\n bottom = QFrame(self)\n bottom.setFrameShape(QFrame.StyledPanel)\n\n splitter1 = QSplitter(Qt.Horizontal) # 横向增加部件\n splitter1.addWidget(topleft)\n splitter1.addWidget(topright)\n\n splitter2 = QSplitter(Qt.Vertical)\n splitter2.addWidget(splitter1)\n splitter2.addWidget(bottom)\n\n hbox.addWidget(splitter2)\n self.setLayout(hbox)\n\n self.setGeometry(300, 300, 600, 400)\n self.setWindowTitle(\"QSplitter\")\n self.show()\n\nif __name__ == \"__main__\":\n\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n","sub_path":"6_subassembly/08_QSplitter.py","file_name":"08_QSplitter.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"523180587","text":"import json\nimport time\nimport uuid\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom great_expectations.dataset import PandasDataset\n\nfrom feast import (\n Client,\n Entity,\n Feature,\n FeatureTable,\n FileSource,\n KafkaSource,\n ValueType,\n)\nfrom feast.contrib.validation.ge import apply_validation, create_validation_udf\nfrom feast.data_format import AvroFormat, ParquetFormat\nfrom feast.pyspark.abc import SparkJobStatus\nfrom feast.wait import wait_retry_backoff\nfrom tests.e2e.fixtures.statsd_stub import StatsDServer\nfrom tests.e2e.utils.kafka import check_consumer_exist, ingest_and_retrieve\n\n\ndef generate_train_data():\n df = pd.DataFrame(columns=[\"key\", \"num\", \"set\", \"event_timestamp\"])\n df[\"key\"] = np.random.choice(999999, size=100, replace=False)\n df[\"num\"] = np.random.randint(0, 100, 100)\n df[\"set\"] = np.random.choice([\"a\", \"b\", \"c\"], size=100)\n df[\"event_timestamp\"] = pd.to_datetime(int(time.time()), unit=\"s\")\n\n return df\n\n\ndef generate_test_data():\n df = pd.DataFrame(columns=[\"key\", \"num\", \"set\", \"event_timestamp\"])\n df[\"key\"] = np.random.choice(999999, size=100, replace=False)\n df[\"num\"] = np.random.randint(0, 150, 100)\n df[\"set\"] = np.random.choice([\"a\", \"b\", \"c\", \"d\"], size=100)\n df[\"event_timestamp\"] = pd.to_datetime(int(time.time()), unit=\"s\")\n\n return df\n\n\ndef create_schema(kafka_broker, topic_name, feature_table_name):\n entity = Entity(name=\"key\", description=\"Key\", value_type=ValueType.INT64)\n feature_table = FeatureTable(\n name=feature_table_name,\n entities=[\"key\"],\n features=[Feature(\"num\", ValueType.INT64), Feature(\"set\", ValueType.STRING)],\n batch_source=FileSource(\n event_timestamp_column=\"event_timestamp\",\n file_format=ParquetFormat(),\n file_url=\"/dev/null\",\n ),\n stream_source=KafkaSource(\n event_timestamp_column=\"event_timestamp\",\n bootstrap_servers=kafka_broker,\n message_format=AvroFormat(avro_schema()),\n topic=topic_name,\n ),\n )\n return entity, feature_table\n\n\ndef start_job(feast_client: Client, feature_table: FeatureTable, pytestconfig):\n if pytestconfig.getoption(\"scheduled_streaming_job\"):\n return\n\n job = feast_client.start_stream_to_online_ingestion(feature_table)\n wait_retry_backoff(\n lambda: (None, job.get_status() == SparkJobStatus.IN_PROGRESS), 120\n )\n return job\n\n\ndef stop_job(job, feast_client: Client, feature_table: FeatureTable):\n if job:\n job.cancel()\n else:\n feast_client.delete_feature_table(feature_table.name)\n\n\ndef test_validation_with_ge(feast_client: Client, kafka_server, pytestconfig):\n kafka_broker = f\"{kafka_server[0]}:{kafka_server[1]}\"\n topic_name = f\"avro-{uuid.uuid4()}\"\n\n entity, feature_table = create_schema(kafka_broker, topic_name, \"validation_ge\")\n feast_client.apply_entity(entity)\n feast_client.apply_feature_table(feature_table)\n\n train_data = generate_train_data()\n ge_ds = PandasDataset(train_data)\n ge_ds.expect_column_values_to_be_between(\"num\", 0, 100)\n ge_ds.expect_column_values_to_be_in_set(\"set\", [\"a\", \"b\", \"c\"])\n expectations = ge_ds.get_expectation_suite()\n\n udf = create_validation_udf(\"testUDF\", expectations, feature_table)\n apply_validation(feast_client, feature_table, udf, validation_window_secs=1)\n\n job = start_job(feast_client, feature_table, pytestconfig)\n\n wait_retry_backoff(\n lambda: (None, check_consumer_exist(kafka_broker, topic_name)), 300\n )\n\n test_data = generate_test_data()\n ge_ds = PandasDataset(test_data)\n validation_result = ge_ds.validate(expectations, result_format=\"COMPLETE\")\n invalid_idx = list(\n {\n idx\n for check in validation_result.results\n for idx in check.result[\"unexpected_index_list\"]\n }\n )\n\n entity_rows = [{\"key\": key} for key in test_data[\"key\"].tolist()]\n\n try:\n ingested = ingest_and_retrieve(\n feast_client,\n test_data,\n avro_schema_json=avro_schema(),\n topic_name=topic_name,\n kafka_broker=kafka_broker,\n entity_rows=entity_rows,\n feature_names=[\"validation_ge:num\", \"validation_ge:set\"],\n expected_ingested_count=test_data.shape[0] - len(invalid_idx),\n )\n finally:\n stop_job(job, feast_client, feature_table)\n\n test_data[\"num\"] = test_data[\"num\"].astype(np.float64)\n test_data[\"num\"].iloc[invalid_idx] = np.nan\n test_data[\"set\"].iloc[invalid_idx] = None\n\n pd.testing.assert_frame_equal(\n ingested[[\"key\", \"validation_ge:num\", \"validation_ge:set\"]],\n test_data[[\"key\", \"num\", \"set\"]].rename(\n columns={\"num\": \"validation_ge:num\", \"set\": \"validation_ge:set\"}\n ),\n )\n\n\n@pytest.mark.env(\"local\")\ndef test_validation_reports_metrics(\n feast_client: Client, kafka_server, statsd_server: StatsDServer, pytestconfig\n):\n kafka_broker = f\"{kafka_server[0]}:{kafka_server[1]}\"\n topic_name = f\"avro-{uuid.uuid4()}\"\n\n entity, feature_table = create_schema(\n kafka_broker, topic_name, \"validation_ge_metrics\"\n )\n feast_client.apply_entity(entity)\n feast_client.apply_feature_table(feature_table)\n\n train_data = generate_train_data()\n ge_ds = PandasDataset(train_data)\n ge_ds.expect_column_values_to_be_between(\"num\", 0, 100)\n ge_ds.expect_column_values_to_be_in_set(\"set\", [\"a\", \"b\", \"c\"])\n expectations = ge_ds.get_expectation_suite()\n\n udf = create_validation_udf(\"testUDF\", expectations, feature_table)\n apply_validation(feast_client, feature_table, udf, validation_window_secs=10)\n\n job = start_job(feast_client, feature_table, pytestconfig)\n\n wait_retry_backoff(\n lambda: (None, check_consumer_exist(kafka_broker, topic_name)), 300\n )\n\n test_data = generate_test_data()\n ge_ds = PandasDataset(test_data)\n validation_result = ge_ds.validate(expectations, result_format=\"COMPLETE\")\n unexpected_counts = {\n \"expect_column_values_to_be_between_num_0_100\": validation_result.results[\n 0\n ].result[\"unexpected_count\"],\n \"expect_column_values_to_be_in_set_set\": validation_result.results[1].result[\n \"unexpected_count\"\n ],\n }\n invalid_idx = list(\n {\n idx\n for check in validation_result.results\n for idx in check.result[\"unexpected_index_list\"]\n }\n )\n\n entity_rows = [{\"key\": key} for key in test_data[\"key\"].tolist()]\n\n try:\n ingest_and_retrieve(\n feast_client,\n test_data,\n avro_schema_json=avro_schema(),\n topic_name=topic_name,\n kafka_broker=kafka_broker,\n entity_rows=entity_rows,\n feature_names=[\"validation_ge_metrics:num\", \"validation_ge_metrics:set\"],\n expected_ingested_count=test_data.shape[0] - len(invalid_idx),\n )\n finally:\n stop_job(job, feast_client, feature_table)\n\n expected_metrics = [\n (\n f\"feast_feature_validation_check_failed#check:{check_name},\"\n f\"feature_table:{feature_table.name},project:{feast_client.project}\",\n value,\n )\n for check_name, value in unexpected_counts.items()\n ]\n wait_retry_backoff(\n lambda: (\n None,\n all(statsd_server.metrics.get(m) == v for m, v in expected_metrics),\n ),\n timeout_secs=30,\n timeout_msg=\"Expected metrics were not received: \"\n + str(expected_metrics)\n + \"\\n\"\n \"Actual received metrics\" + str(statsd_server.metrics),\n )\n\n\ndef avro_schema():\n return json.dumps(\n {\n \"type\": \"record\",\n \"name\": \"TestMessage\",\n \"fields\": [\n {\"name\": \"key\", \"type\": \"long\"},\n {\"name\": \"num\", \"type\": \"long\"},\n {\"name\": \"set\", \"type\": \"string\"},\n {\n \"name\": \"event_timestamp\",\n \"type\": {\"type\": \"long\", \"logicalType\": \"timestamp-micros\"},\n },\n ],\n }\n )\n","sub_path":"tests/e2e/test_validation.py","file_name":"test_validation.py","file_ext":"py","file_size_in_byte":8180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"225103124","text":"# Copyright Notice:\n# Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.\n# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/YANG-to-Redfish-Converter/blob/master/LICENSE.md\n\nfrom modgrammar import *\nfrom yang.name import *\nfrom yang.linkage import *\nfrom yang.brace import *\nfrom yang.rpc import *\nfrom yang.leaf import *\nfrom yang.reference import *\nfrom yang.refine import *\nfrom yang.unique import *\nfrom yang.presence import *\nfrom yang.comment import *\nfrom yang.identity import *\nfrom yang.localtypes import *\nfrom yang.typedef import *\nfrom yang.when import *\ngrammar_whitespace_mode = 'optional'\n\n\nclass GroupingKeyword(Grammar):\n grammar = (L('grouping'))\n\n\nclass Grouping(Grammar):\n grammar = (GroupingKeyword, Name, OPENBRACE,\n OPTIONAL(Description),\n REPEAT(REF('ContainerGrammar') | REF(\n 'LeafGrammar') | ReferenceGrammar | REF('ListGrammar'), min=0),\n CLOSEBRACE\n )\n\n\nclass ContainerKeyword(Grammar):\n grammar = (L(\"container\"))\n\n\nclass ContainerGrammar(Grammar):\n grammar = (ContainerKeyword, Name, OPENBRACE,\n REPEAT(Config | ReferenceGrammar | IfFeature | Unmapped | Presence | Description\n | Identity | OrderedBy | REF(\"ContainerGrammar\") | REF(\"ListGrammar\") | LeafGrammar | LeafListGrammar | REF(\"ChoiceGrammar\") | RpcGrammar\n | REF(\"Uses\"), min=0),\n CLOSEBRACE, OPTIONAL(SingleLineComment)\n )\n\n\nclass CaseKeyword(Grammar):\n grammar = (L(\"case\"))\n\n\nclass CaseGrammar(Grammar):\n grammar = (CaseKeyword, Name,\n OPENBRACE,\n OPTIONAL(Description),\n OPTIONAL(IfFeature),\n REPEAT(LeafGrammar, min=0),\n REPEAT(REF(\"ContainerGrammar\"), min=0),\n # REPEAT( ContainerGrammar | LeafGrammar , min=0),\n CLOSEBRACE\n )\n\n\nclass ChoiceKeyword(Grammar):\n grammar = (L(\"choice\"))\n\n\nclass ChoiceGrammar(Grammar):\n grammar = (ChoiceKeyword, Name,\n OPENBRACE,\n REPEAT(Description | CaseGrammar | LeafGrammar | Default | # do we care about default?\n Mandatory | REF('ContainerGrammar'), min=0),\n CLOSEBRACE, OPTIONAL(SingleLineComment)\n )\n\n\nclass InputKeyword(Grammar):\n grammar = (L(\"input\"))\n\n\nclass InputGrammar(Grammar):\n grammar = (InputKeyword, Name, OPENBRACE,\n REPEAT(Key | Description, min= 0),\n REPEAT (LeafGrammar | LeafListGrammar | ChoiceGrammar, min=0),\n CLOSEBRACE\n )\n\n\nclass ListKeyword(Grammar):\n grammar = (L(\"list\"))\n\n\nclass ListGrammar(Grammar):\n grammar = (ListKeyword, Name,\n OPENBRACE,\n REPEAT(Key | Unique | Description | IfFeature | OrderedBy | REF(\"Uses\") | MinElements | MaxElements | ReferenceGrammar | REF(\"ContainerGrammar\") | REF(\"ListGrammar\") | LeafGrammar | LeafListGrammar | ChoiceGrammar | Config, min=0),\n CLOSEBRACE\n )\n\n\nclass Uses(Grammar):\n grammar = (L('uses'), WORD('\"a-zA-Z0-9', restchars='a-zA-Z0-9:\\.\\-\"', fullmatch=True, escapes=True),\n OR(\n (OPENBRACE,\n REPEAT(Description | Refine | IfFeature | Status | ReferenceGrammar, min=0),\n CLOSEBRACE\n ),\n L(';')\n )\n )\n\n\nclass NotificationKeyword(Grammar):\n grammar = (L('notification'))\n\n\nclass Notification(Grammar):\n grammar = (NotificationKeyword, Name,\n OR(L(';'),\n\n (\n OPENBRACE,\n REPEAT(ChoiceGrammar | ContainerGrammar | Description | Grouping | IfFeature | LeafGrammar |\n LeafListGrammar | ListGrammar | ReferenceGrammar | Status | TypedefGrammar | Uses, min=0),\n CLOSEBRACE\n )\n )\n )\n\n\nclass AugmentKeyword(Grammar):\n grammar = (L('augment'))\n\n\nclass AugmentName(Grammar):\n grammar = (WORD('a-zA-Z/\"', restchars='a-zA-Z:/0-9\\\\!=\\'\\s\\t\\-\"',\n fullmatch=True, escapes=True))\n\n\nclass Augment(Grammar):\n grammar = (AugmentKeyword, AugmentName,\n OPENBRACE,\n REPEAT(When | IfFeature | Description | ReferenceGrammar |\n LeafGrammar | ContainerGrammar | CaseGrammar, min=1),\n CLOSEBRACE\n )\n","sub_path":"src/yang/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":4426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"105824554","text":"def coroutine(f):\n def wrap(*args, **kwargs):\n gen = f(*args, **kwargs)\n gen.send(None)\n return gen\n return wrap\n\n\ndef start_dialog(phrase):\n phrase = phrase.strip().lower()\n agreements = [\"yes\", \"of course\", \"yeap\", \"yea\", \"i do\", \"+\", \"true\", \"right\", \"let's go\", \"ok\", \"y\"]\n disagreements = [\"no\", \"never\", \"not\", \"n't\", \"false\", \"-\", \"refuse\", \"nope\"]\n if phrase in agreements:\n return 1\n elif phrase in disagreements:\n return -1\n else:\n num_arg = len(list(filter(lambda phr: phr in phrase, agreements)))\n num_disarg = len(list(filter(lambda phr: phr in phrase, disagreements)))\n if num_disarg != 0:\n if num_disarg % 2: # If odd number of denials - its disagreement\n return -1\n else: # else - agreement\n return 1\n else:\n if num_arg > 0:\n return 1\n return 0\n\n\ndef generate_first_phare(code):\n if code == 1:\n return \"Yoo-hoo! Let's talk :)\"\n if code == -1:\n return \"It's a pity, I feel so lonely in this big digital world, good bye :(\"\n else:\n return \"I don't understand, would you like to talk with me?\"\n\n\ndef get_question(number):\n questions = [\"What is your name?\", \"Where are you from?\", \"Nice. Have you got any hobbies?\"]\n goodbye = \"I was so happy to talk with you \"\n if number < len(questions):\n return questions[number]\n else:\n return goodbye\n","sub_path":"bot/answer_generator.py","file_name":"answer_generator.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"102400","text":"#!/usr/bin/env python3\nimport spotipy\nimport sys\nfrom os import getenv\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\n\nCLIENT_ID = getenv(\"CLIENT_ID\", None)\nCLIENT_SECRET = getenv(\"CLIENT_SECRET\", None)\nif CLIENT_ID is None or CLIENT_SECRET is None:\n print(\"Please set up environment variables 'CLIENT_ID' and 'CLIENT_SECRET\")\n sys.exit(-1)\n\n\ncred_manager = SpotifyClientCredentials(client_id=CLIENT_ID,\n client_secret=CLIENT_SECRET)\n\nsp = spotipy.Spotify(client_credentials_manager=cred_manager)\npaged_albums = sp.new_releases(limit=20, offset=0)['albums']\n\nfor idx, album in enumerate(paged_albums['items'], 1):\n artists_name = ', '.join([artist['name'] for artist in album['artists']])\n print(\"{:2d}: {} - {}\".format(idx, album['name'], artists_name))\n","sub_path":"client_credentials/spotipy_test.py","file_name":"spotipy_test.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"142217378","text":"\"\"\"\nName: Cooper McBurney\nlab8.py\n\n\n\"\"\"\n\ndef number_words():\n walrus_output = open(\"Walrus.txt\", \"w+\")\n content = walrus_output.read()\n list_output = content.split()\n list_output.write(content)\n print(list_output)\n\n\ndef hourly_wages():\n wages_output = open(\"hourly_wages.txt\", \"r\")\n wage_info = wages_output.read()\n names_and_wages = wage_info.split()\n worker1_wage = int(float(names_and_wages[2]))\n worker1_hours = int(float(names_and_wages[3]))\n worker2_wage = int(float(names_and_wages[6]))\n worker2_hours = int(float(names_and_wages[7]))\n updated_wage1 = (worker1_wage + 1.65) * worker1_hours\n updated_wage2 = (worker2_wage + 1.65) * worker2_hours\n print(names_and_wages[0], names_and_wages[1], \":\", updated_wage1)\n print(names_and_wages[4], names_and_wages[5], \":\", updated_wage2)\n\ndef calc_checksum():\n isbn = input(\"Please input a 10 digit ISBN:\")\n digit1 = int(isbn[0]) * 10\n digit2 = int(isbn[1]) * 9\n digit3 = int(isbn[2]) * 8\n digit4 = int(isbn[3]) * 7\n digit5 = int(isbn[4]) * 6\n digit6 = int(isbn[5]) * 5\n digit7 = int(isbn[6]) * 4\n digit8 = int(isbn[7]) * 3\n digit9 = int(isbn[8]) * 2\n digit10 = int(isbn[9]) * 1\n checksum = digit1 + digit2 + digit3 + digit4 +digit5 + digit6 +digit7 + digit8 +digit9 + digit10\n print(checksum)\n\ndef send_message():\n existing_message = open(\"message.txt\", \"w+\")\n new_msg_content = existing_message.write()\n print(new_msg_content)\n\n\nnumber_words()\nhourly_wages()\ncalc_checksum()\nsend_message()\nsend_message()","sub_path":"labs/lab8/lab8.py","file_name":"lab8.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"622029986","text":"from gauss import *\n\ndef least_square(x, y, order, sys_lin_method=gaussian_elimination):\n \"\"\"\n Parameters\n ----------\n x : list of floats\n y : list of floats\n order : int\n \n Returns\n ------- \n list of floats\n coefficients of a polynomial\n \"\"\" \n sx = [sum(x[j]**i for j in range(len(x))) for i in range(order*2+1)]\n sxy = [sum(x[j]**i * y[j] for j in range(len(x))) for i in range(order+1)]\n m = []\n for i in range(order+1):\n a = sx[i:(i+order+1)]\n a.append(sxy[i])\n m.append(a)\n return sys_lin_method(m)\n\nif __name__ == '__main__':\n x = [0, 0.5, 1, 1.5, 2, 2.5]\n y = [0.0674, -0.9156, 1.6253, 3.0377, 3.3535, 7.9409]\n print(least_square(x, y, 2))\n \n #x = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6]\n #y = [2.8, 4.1, 5.2, 5.9, 6.8, 8, 9.3, 10, 10.6, 12, 13.4, 14, 15.5]\n #print(least_square(x, y, 1))\n\n# least square interpolation\n# author : Worasait Suwannik\n# date : Aug 2015\n","sub_path":"least_sq_interpoliation.py","file_name":"least_sq_interpoliation.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"487852609","text":"import base64\nimport uuid\n\nfrom django.utils.crypto import constant_time_compare\n\nfrom db.redis.base import BaseRedisDb\nfrom libs.crypto import get_hmac\nfrom libs.json_utils import dumps, loads\nfrom polyaxon.settings import RedisPools\n\n\nclass RedisEphemeralTokens(BaseRedisDb):\n \"\"\"\n RedisEphemeralTokens provides a db to store ephemeral tokens for users jobs\n that requires in cluster authentication to access scoped resources\n \"\"\"\n KEY_SALT = 'polyaxon.scope.key_salt'\n SEPARATOR = 'XEPH:'\n\n EXPIRATION_TTL = 60 * 60 * 3\n KEY_EPHEMERAL_TOKENS = 'EPHEMERAL_TOKENS:{}'\n\n REDIS_POOL = RedisPools.EPHEMERAL_TOKENS\n\n def __init__(self, key=None):\n self.__dict__['key'] = key or uuid.uuid4().hex\n self.__dict__['_red'] = self._get_redis()\n\n def __getattr__(self, key):\n state = self.get_state()\n\n try:\n return state[key] if state else None\n except KeyError as e:\n raise AttributeError(e)\n\n def __setattr__(self, key, value):\n state = self.get_state()\n\n if state is None:\n return\n\n state[key] = value\n self.set_state(ttl=self.ttl, value=dumps(state))\n\n def get_state(self):\n if not self.redis_key:\n return None\n\n state_json = self._red.get(self.redis_key)\n if not state_json:\n return None\n\n return loads(state_json.decode())\n\n def set_state(self, ttl, value):\n self._red.setex(name=self.redis_key, time=ttl, value=value)\n\n @property\n def redis_key(self):\n return self.KEY_EPHEMERAL_TOKENS.format(self.key)\n\n @classmethod\n def generate(cls, scope, ttl=EXPIRATION_TTL):\n token = RedisEphemeralTokens()\n salt = uuid.uuid4().hex\n value = dumps({\n 'key': token.redis_key,\n 'salt': salt,\n 'scope': scope,\n 'ttl': ttl,\n })\n token.set_state(ttl=ttl, value=value)\n return token\n\n @classmethod\n def make_token(cls, ephemeral_token):\n \"\"\"\n Returns a token to be used x number of times to allow a user account to access\n certain resource.\n \"\"\"\n value = ephemeral_token.key\n if ephemeral_token.scope:\n value += ''.join(ephemeral_token.scope)\n\n return get_hmac(cls.KEY_SALT + ephemeral_token.salt, value)[::2]\n\n def clear(self):\n if not self.redis_key:\n return\n\n self._red.delete(self.redis_key)\n\n def check_token(self, token):\n \"\"\"\n Check that a token is correct for a given scope token.\n \"\"\"\n if self.get_state() is None: # Token expired\n return False\n\n correct_token = self.make_token(self)\n self.clear()\n return constant_time_compare(correct_token, token)\n\n @classmethod\n def create_header_token(cls, ephemeral_token):\n token = cls.make_token(ephemeral_token)\n return base64.b64encode(\n '{}{}{}'.format(token,\n cls.SEPARATOR,\n ephemeral_token.key).encode('utf-8')).decode(\"utf-8\")\n\n @classmethod\n def generate_header_token(cls, scope):\n ephemeral_token = RedisEphemeralTokens.generate(scope=scope)\n return cls.create_header_token(ephemeral_token=ephemeral_token)\n\n @staticmethod\n def get_scope(user, model, object_id):\n return ['user:{}'.format(user), '{}:{}'.format(model, object_id)]\n","sub_path":"polyaxon/db/redis/ephemeral_tokens.py","file_name":"ephemeral_tokens.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"235937136","text":"#! python3\n# -*- coding: utf-8 -*-\n\"\"\"\nGiven a string s consists of upper/lower-case alphabets and empty space characters ' ',\nreturn the length of last word in the string.\n\nIf the last word does not exist, return 0.\n\nNote: A word is defined as a character sequence consists of non-space characters only.\n\nFor example,\nGiven s = \"Hello World\",\nreturn 5.\n\n\"\"\"\nclass Solution(object):\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if len(s) == 0:\n return 0\n else:\n res = 0\n words = s.split(' ')\n for word in words[::-1]:\n if len(word) != 0 and word.isalpha():\n res = len(word)\n break\n return res\n\n\nif __name__ == '__main__':\n solution = Solution()\n res = solution.lengthOfLastWord('Today is a nice day')\n","sub_path":"leetcode/58-Length-of-Last-Word.py","file_name":"58-Length-of-Last-Word.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"377958880","text":"def sqrt(x):\n '''Compute square roots using the method of Heron of Alexandria.\n\n Args:\n x: The number for which the square root is to be computed.\n \n Returns:\n The square root of x\n \n Raises: \n ValueError: en caso que se envie un dato negativo\n '''\n if x <= 0:\n raise ValueError(\" No existe raiz cuadrada de \"\n \"nuemero negativos\")\n guess = x\n i = 0\n while guess * guess != x and i < 20:\n guess = (guess + x / guess) / 2.0\n i += 1\n return guess\n\ndef main():\n try:\n print(sqrt(9))\n print(sqrt(2))\n print(sqrt(-1))\n print(sqrt(0))\n print(sqrt('hola'))\n except ValueError as e:\n print(\"Error en la ejecucion del programa {}\".format(e))\n finally:\n print(\"fin en la ejecucion del programa\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Labs/roots.py","file_name":"roots.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"652003162","text":"import os\nimport random\nimport string\nimport sys\nfrom robot.api.logger import *\nfrom robot.libraries.Screenshot import Screenshot\n\n\ntry:\n while \"paf\\\\\" in os.getcwd():\n os.chdir(\"..\")\n sys.path.append(os.getcwd() + '\\\\libs')\n sys.path.append(os.getcwd() + '\\\\libs\\\\utils')\n sys.path.append(os.getcwd() + '\\\\reports')\n sys.path.append(os.getcwd() + '\\\\setup_infra')\n sys.path.append(os.getcwd() + '\\\\test_runner')\n sys.path.append(os.getcwd() + '\\\\screens')\n sys.path.append(os.getcwd() + '\\\\tests')\n sys.path.append(os.getcwd() + '\\\\test_data')\n sys.path.append(os.getcwd() + '\\\\libs\\\\auto_it_executables')\n info(\"Forming and returning dynamic project path as %s \" %\n sys.path, False, True)\n\nexcept Exception as e1:\n tb1 = sys.exc_info()[2]\n error(\"Exception in CommonUtil. Details are - [%s]::Line Number[%s]\" % (\n e1.with_traceback(tb1), sys.exc_info()[2].tb_lineno), True)\n raise Exception(\"Exception occurred in CommonUtil\")\n\n\ndef set_project_path():\n \"\"\"\n Function Name - set_project_path\n Description - This method sets the project path dynamically.\n Parameters - None\n Return - project path\n Author - Dhananjay Joshi\n Modification date - 17-Apr-2018\n \"\"\"\n try:\n while \"paf\\\\\" in os.getcwd():\n os.chdir(\"..\")\n # path = os.getcwd()\n sys.path.append(os.getcwd() + '\\\\libs')\n sys.path.append(os.getcwd() + '\\\\libs\\\\utils')\n sys.path.append(os.getcwd() + '\\\\reports')\n sys.path.append(os.getcwd() + '\\\\setup_infra')\n sys.path.append(os.getcwd() + '\\\\test_runner')\n sys.path.append(os.getcwd() + '\\\\screens')\n sys.path.append(os.getcwd() + '\\\\tests')\n sys.path.append(os.getcwd() + '\\\\test_data')\n sys.path.append(os.getcwd() + '\\\\libs\\\\auto_it_executables')\n info(\"Forming and returning dynamic project path as %s \" %\n sys.path, False, True)\n if \"AutomationPOC\\\\\" in os.getcwd():\n os.chdir(\"..\")\n path = os.getcwd()\n return path\n except Exception as e:\n tb = sys.exc_info()[2]\n error(\"Exception in set_project_path. Details are - [%s]::\"\n \"Line Number[%s]\" % (e.with_traceback(tb),\n sys.exc_info()[2].tb_lineno), True)\n raise Exception(\"Exception occurred in set_project_path\")\n\n\ndef get_project_path():\n \"\"\"\n Function Name - get_project_path\n Description - This method return project path\n Parameters -\n Return - project path\n Author - Dhananjay Joshi\n Modification date - 17-Apr-2018\n \"\"\"\n try:\n return os.getcwd()\n except Exception as e:\n tb = sys.exc_info()[2]\n error(\"Exception in get_project_path. Details are - [%s]::\"\n \"Line Number[%s]\" % (e.with_traceback(tb),\n sys.exc_info()[2].tb_lineno), True)\n raise Exception(\"Exception occurred in get_project_path\")\n\n\ndef take_desktop_screenshot(file_name):\n \"\"\"\n Function Name - take_desktop_screenshot\n Description - This method takes a snapshot of desktop main window and\n embeds it into report.\n Parameters - image file name\n Return - NA\n Author - Dhananjay Joshi\n Modification date - 17-Apr-2018\n \"\"\"\n try:\n file_name = Screenshot().take_screenshot(file_name)\n info(\"Screenshot taken with screenshot name as [%s]\" % file_name,\n True, True)\n except Exception as e:\n tb = sys.exc_info()[2]\n error(\"Exception in take_desktop_screenshot. Details are - [%s]::\"\n \"Line Number[%s]\" % (e.with_traceback(tb),\n sys.exc_info()[2].tb_lineno), True)\n raise Exception(\"Exception occurred in take_desktop_screenshot\")\n\n\ndef random_string_generator(\n size=2, chars=string.ascii_lowercase + string.digits):\n \"\"\"\n Function Name - take_desktop_screenshot\n Description - This method takes a snapshot of desktop main window and\n embeds it into report.\n Parameters - image file name\n Return - NA\n Author - Dhananjay Joshi\n Modification date - 17-Apr-2018\n \"\"\"\n try:\n return ''.join(random.choice(chars) for _ in range(int(size)))\n except Exception as e:\n tb = sys.exc_info()[2]\n error(\"Exception in random_string_generator. Details are - [%s]::\"\n \"Line Number[%s]\" % (e.with_traceback(tb),\n sys.exc_info()[2].tb_lineno), True)\n raise Exception(\"Exception occurred in random_string_generator\")\n\n\ndef get_print_file_path(file_name):\n \"\"\"\n Function Name - get_print_file_path\n Description - This method gets print file path\n Parameters - file_name\n Return - project path\n Author - Dhananjay Joshi\n Modification date - 17-Apr-2018\n \"\"\"\n try:\n return str(get_project_path()) + file_name\n except Exception as e:\n error(\"Exception thrown in get_print_file_path as [%s]\" % repr(e),\n True)\n\n\ndef compare_dictionaries(dict1, dict2, id1=None):\n \"\"\"\n Function Name - compare_dictionaries\n Description - Compares the dictionaries\n Parameters - dict1, dict2, id1=None\n Return - None\n Author - Dhananjay Joshi\n Modification date - 24-Apr-2018\n \"\"\"\n if dict1 is None and dict2 is None:\n return True, \"Both the dictionaries are None\"\n\n if dict1 is None or dict2 is None:\n return False, \"One of the dictionary contains None\"\n\n if (type(dict1) is not dict) or (type(dict2) is not dict):\n return False, \"One of the dictionary is not a dict type, dict1 %s\" \\\n \" dict2 %s \" % (type(dict1), type(dict2))\n\n shared_keys = set(dict1.keys()) & set(dict2.keys())\n if len(shared_keys) != len(dict1.keys()) or len(shared_keys) != len(\n dict2.keys()):\n return False, \"Dictionary Keys mismatched dict1 %s ,\" \\\n \"dict2 %s , sharedKeys %s \" \\\n % (dict1.keys(), dict2.keys(), shared_keys)\n dicts_are_equal = True\n for key in dict1.keys():\n if type(dict1[key]) is dict:\n result, message = compare_dictionaries(dict1[key], dict2[key])\n if result is False:\n return result, message\n elif type(dict1[key]) is list:\n # If list contains dict\n if id1:\n result2, message2 = compare_list_of_dict(\n dict1[key], dict2[key], id1=id1)\n if result2 is False:\n return result2, message2\n else:\n if dict1[key] != dict2[key]:\n dicts_are_equal = False\n return False, \"Dictionaries value mismatched, dict1 %s:%s,\" \\\n \" dict2 %s:%s\" % (key, dict1[key], key,\n dict2[key])\n return dicts_are_equal, \"Dictionaries are equal\"\n\n\ndef compare_list(act_list, exp_list):\n \"\"\"\n Function Name - compare_list\n Description - Compares the lists\n Parameters - act_list, exp_list\n Return - None\n Author - Dhananjay Joshi\n Modification date - 24-Apr-2018\n \"\"\"\n if sorted(exp_list) == sorted(act_list):\n return\n else:\n msg = 'Following item: {}, is not present in {} list'\n data = [i for i in act_list if i not in exp_list]\n data1 = [i for i in exp_list if i not in act_list]\n if data:\n raise AssertionError(msg.format(data, 'expected'))\n elif data1:\n raise AssertionError(msg.format(data1, 'actual'))\n\n\ndef verify_text(act_str, exp_str):\n \"\"\"\n Function Name - verify_text\n Description - verifies text\n Parameters - act_str, exp_str\n Return - None\n Author - Dhananjay Joshi\n Modification date - 24-Apr-2018\n \"\"\"\n type_msg = 'Can not compare, {0} and {1} are different types'\n msg = \"Failed to verify texts, Actual: {0}, Expected: {1}\"\n assert isinstance(act_str, str) and isinstance(exp_str, str),\\\n type_msg.format(type(act_str), type(exp_str))\n assert act_str.lower() == exp_str.lower(), msg.format(act_str, exp_str)\n\n\ndef verify(expected, actual, message=''):\n \"\"\"\n Function Name - verify\n Description -\n Parameters - expected, actual, message\n Return - None\n Author - Dhananjay Joshi\n Modification date - 24-Apr-2018\n \"\"\"\n check_type = type(expected)\n if type(expected) != type(actual):\n print(\"Type mismatched. Expected type {0} . Actual Type \"\n \"{1}\".format(type(expected), type(actual)))\n return False\n\n elif check_type is not str and check_type is not int and check_type is \\\n not float and check_type is not list and check_type is not dict:\n print('Compares only str, float, int, list of dict type objects')\n return False\n # -------------------------------------------------------------------------\n # Compare dictionaries.\n elif type(expected) is dict:\n input_text_matches, message = compare_dictionaries(expected, actual)\n if input_text_matches is False:\n print(message)\n return False\n else:\n return True\n # -------------------------------------------------------------------------\n # Compare List\n elif type(expected) is list:\n # pdb.set_trace()\n if len(expected) != len(actual):\n print(\n message +\n \" Validation Failed. List Length mismatch. Expected len {0} \"\n \"Actual Len {1}. \".format(len(expected), len(actual)))\n common_item = []\n for item in expected:\n if item in actual:\n common_item.append(item)\n continue\n\n elif check_type is int or check_type is float or check_type is str:\n if expected != actual:\n print(message + \" Validation Failed, Expected Value: {0}, Actual \"\n \"Value: {1} .\".format(expected, actual))\n return False\n else:\n return True\n\n\ndef compare_list_of_dict(act_list, exp_list, id1=None):\n \"\"\"\n Function Name - compare_list_of_dict\n Description -\n Parameters - act_list, exp_list, id1=None\n Return - None\n Author - Dhananjay Joshi\n Modification date - 24-Apr-2018\n \"\"\"\n if len(act_list) != len(exp_list):\n return False, \"list length mismatched\"\n for item in exp_list:\n if isinstance(item, dict):\n for item2 in act_list:\n if item[id1] == item2[id1]:\n result, message = compare_dictionaries(item, item2)\n if result is False:\n return result, message\n else:\n break\n else:\n continue\n else:\n return False, \"Dictionaries value mismatched, dict1: %s and \"\\\n % (item[id1])\n else:\n return False, 'Not a dictionary'\n return True, \"Dictionaries are equal\"","sub_path":"paf/libs/utils/CommonUtil.py","file_name":"CommonUtil.py","file_ext":"py","file_size_in_byte":11145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"101780862","text":"import os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# region input parameters\n# 0: TMZ U87, 1: Pantoprazole U87, 2: Control U 87, 3: Control NG108, 4: Pantoprazole NG108\nconditions_list_i=4\n\nreplicates='biological'\nbox_day=6\n\n# analyze_method='total_normalization'\n# normalization_type='Total_total_normalized_norm_log2'\n\nanalyze_method='fold_change'\nnormalization_type='Total_total_fold_change_norm_log2_Control_DMSO'\n\nplot_context = 'talk'\n# plot_context = 'notebook'\nfont_scale=1.5\nsave_plots=1\n\n\nnorm_colname=normalization_type\ncontrol_condition='Control_DMSO'\nframe='ean'\n\n# endregion\n\n\n# TMX condition list\nconditions_TMZ=['Control_DMSO', 'TMZ_50uM', '1perFBS_cAMP_1mM_Rapamycin_200nM', 'Pantoprazole_100uM_NS1643_50uM',\n 'Pantoprazole_100uM_Retigabine_10uM', 'NS1643_50uM_TMZ_50uM', 'Pantoprazole_100uM_NS1643_20uM',\n 'Pantoprazole_50uM_NS1643_50uM', 'Pantoprazole_100uM_TMZ_50uM' ,'Pantoprazole_100uM_Lamotrigine_100uM',\n 'Pantoprazole_100uM_Rapamycin_150nM' ,'Pantoprazole_100uM_Rapamycin_100nM', 'NS1643_20uM_TMZ_50uM',\n 'Rapamycin_100nM_TMZ_50uM', 'Rapamycin_150nM_TMZ_50uM', 'Pantoprazole_100uM']\n\n# Pantoprazole list\nconditions_Pantaprazole=['Control_DMSO', 'Pantoprazole_100uM' ,'Pantoprazole_100uM_NS1643_50uM' ,'Pantoprazole_100uM_Retigabine_10uM',\n 'Pantoprazole_100uM_NS1643_20uM' ,'Pantoprazole_50uM_NS1643_50uM' ,'Pantoprazole_100uM_TMZ_50uM',\n 'Pantoprazole_100uM_Lamotrigine_100uM' ,'Pantoprazole_100uM_Rapamycin_150nM',\n 'Pantoprazole_100uM_Rapamycin_100nM']\n\n# Control_DMSO condition list\nconditions_Control=['Control_DMSO', 'Pantoprazole_100uM_Retigabine_10uM', '1perFBS_cAMP_1mM_Rapamycin_200nM',\n 'Pantoprazole_100uM_NS1643_50uM', 'Pantoprazole_100uM_NS1643_20uM', 'Pantoprazole_100uM_Rapamycin_150nM',\n 'Pantoprazole_100uM_Rapamycin_100nM', 'Pantoprazole_100uM_Lamotrigine_100uM', 'Pantoprazole_100uM_TMZ_50uM',\n 'NS1643_50uM_TMZ_50uM', 'Rapamycin_100nM_TMZ_50uM', 'Lamotrigine_100uM_TMZ_50uM', 'Rapamycin_150nM_TMZ_50uM',\n 'Pantoprazole_50uM_NS1643_50uM', 'Minoxidil_30uM_TMZ_50uM', 'NS1643_50uM_Rapamycin_100nM', 'NS1643_20uM_TMZ_50uM',\n 'NS1643_50uM_Rapamycin_150nM', 'Pantoprazole_100uM', 'Retigabine_10uM_TMZ_50uM', 'Pantoprazole_50uM_Rapamycin_150nM',\n 'Pantoprazole_50uM_Rapamycin_100nM', 'Pantoprazole_50uM_TMZ_50uM', 'Pantoprazole_50uM_Lamotrigine_100uM',\n 'Pantoprazole_50uM_NS1643_20uM', 'TMZ_50uM', 'Chlorozoxazone_100uM_TMZ_50uM', 'NS1643_50uM',\n 'Pantoprazole_100uM_Chlorozoxazone_100uM', 'NS1643_50uM_Chlorozoxazone_100uM', 'Retigabine_10uM_Rapamycin_100nM',\n 'Retigabine_10uM_Rapamycin_150nM', 'Rapamycin_150nM', 'Rapamycin_100nM']\n\n# Control_DMSO condition list\nconditions_Control_NG108=['Control_DMSO' ,'1perFBS_cAMP_1mM_Rapamycin_200nM' ,'Pantoprazole_100uM_Rapamycin_100nM',\n'Pantoprazole_100uM_NS1643_20uM' ,'Pantoprazole_100uM_Lamotrigine_100uM' ,'Pantoprazole_100uM_Retigabine_10uM',\n'cAMP_1mM_Rapamycin_200nM' ,'Pantoprazole_100uM_TMZ_50uM' ,'Pantoprazole_50uM_Rapamycin_100nM',\n'Pantoprazole_100uM' ,'NS1643_50uM_Rapamycin_100nM' ,'Pantoprazole_50uM_Retigabine_10uM',\n'Pantoprazole_50uM_Lamotrigine_100uM' ,'Pantoprazole_50uM_NS1643_20uM' ,'Rapamycin_100nM_TMZ_50uM',\n'Rapamycin_100nM' ,'NS1643_1uM_Rapamycin_100nM' ,'Rapamycin_150nM' ,'Retigabine_10uM_Rapamycin_100nM',\n'NS1643_1uM_Rapamycin_150nM', 'Pantoprazole_50uM', 'NS1643_50uM', 'Minoxidil_30uM_Rapamycin_100nM',\n'Minoxidil_30uM_Rapamycin_150nM' ,'NS1643_1uM_Retigabine_10uM' ,'Retigabine_10uM' ,'NS1643_20uM']\n\nconditions_Pantaprazole_NG108=['Control_DMSO' ,'Pantoprazole_100uM' ,'Pantoprazole_100uM_Rapamycin_100nM' , 'Pantoprazole_100uM_NS1643_20uM' , 'Pantoprazole_100uM_Lamotrigine_100uM' ]\n\nconditions_list=[conditions_TMZ,conditions_Pantaprazole, conditions_Control,conditions_Control_NG108,conditions_Pantaprazole_NG108]\n\nconditions=conditions_list[conditions_list_i]\n\nconditions_reduced=conditions[1:]\n\nfilepath = filedialog.askopenfilename(\n initialdir=\"/\",\n # initialdir=\"C:\\\\Users\\\\Franz\\\\OneDrive\\\\_PhD\\\\Juanita\\\\Fucci_analysis\\\\NG108_FUCCI_Used\\\\data\\\\\",\n title=\"Select file\",\n filetypes=((\"csv\", \"*.csv\"),)\n)\n\nbase_directory = os.path.dirname(os.path.dirname(filepath))\n\n\nbox_dir = os.path.join(\n base_directory, 'plots', 'boxplots',\n f'{control_condition}_normalized',\n normalization_type, f'm{frame}'\n)\n\n\n\nif not os.path.exists(box_dir):\n os.makedirs(box_dir)\n\n# ax_title_boxplot = f'Day {box_day} Normalized Cell Counts Compared to {control_condition} - frame m{frame}'\n\nGroupt_title = ['TMZ U87 ', 'Pantoprazole U87 ', 'Control U87 ', 'Control NG108 ', 'Pantoprazole NG108 ']\n\nax_title_boxplot = f'Day {box_day}'\nboxplot_fname = os.path.join(box_dir, f'{Groupt_title[conditions_list_i]} {control_condition} normalized {ax_title_boxplot}.png')\n\nprint('Producing Combined Boxplot')\n\nmi_box = pd.read_csv(filepath)\n\n# mi_box = mi_box.loc[mi_box['Condition'].isin(conditions)]\n# sorterIndex = dict(zip(conditions, range(len(conditions))))\n\n\n# mi_box = mi_box.reset_index(drop=True)\n\nif analyze_method == 'fold_change':\n mi_box=mi_box[conditions_reduced]\nelse:\n mi_box=mi_box[conditions]\n\n\n\nswarmplot_size = 10\nswarmplot_offset = 0 # offset to left of boxplot\n\n# ax = sns.swarmplot(x=\"Condition\", y=norm_colname, data=mi_box, hue=\"Date\", size=swarmplot_size,\n# edgecolor=\"white\", linewidth=1, dodge=True)\n# g = mi_box.groupby(by=[\"Condition\"])[norm_colname].median()\nmedians=mi_box.median(axis=0)\n\nmy_order = medians.nlargest(len(medians))\nmy_order = my_order.index.tolist()\n\nsns.set(context=plot_context,font_scale=font_scale,style=\"whitegrid\")\n\n# ax = sns.swarmplot(data=mi_box, size=swarmplot_size, order=my_order,\n# edgecolor=\"black\", linewidth=0.5)\nax = sns.stripplot(data=mi_box, size=swarmplot_size, order=my_order,\n edgecolor=\"black\", linewidth=1)\n\n\npath_collections = [child for child in ax.get_children()\n if isinstance(child, matplotlib.collections.PathCollection)]\n\nfor path_collection in path_collections:\n x, y = np.array(path_collection.get_offsets()).T\n xnew = x + swarmplot_offset\n offsets = list(zip(xnew, y))\n path_collection.set_offsets(offsets)\n\nax = sns.boxplot(data=mi_box, order=my_order, linewidth=2, fliersize=0, showmeans=True,\n meanprops={\"marker\": \"D\",\n \"markeredgecolor\": \"white\",\n \"markerfacecolor\": \"black\",\n \"markersize\": \"14\"})\n\nax.grid(True)\n\nbottom, top = ax.get_ylim()\n\n# if analyze_method == \"fold_change\":\n# ax.set(ylim=(bottom-0.2*np.abs(bottom), 0.1))\n# else:\n# ax.set(ylim=(bottom-0.2*np.abs(bottom), top+0.2*np.abs(top)))\n#\nif analyze_method == \"fold_change\":\n ax.set(ylim=(bottom-0.25, 0.25))\nelse:\n ax.set(ylim=(bottom, top+0.2*np.abs(top)))\n\nfig = plt.gcf()\nfig.set_size_inches(30, 15)\nplt.gcf().subplots_adjust(bottom=0.3)\n\n# ax.set_xticklabels(conditions, rotation=90)\n# ax.set(xticks=ttest_pvalues.columns, rotation=90)\nif analyze_method == \"fold_change\":\n tick_list = np.r_[0:len(conditions_reduced)]\nelse:\n tick_list = np.r_[0:len(conditions)]\nax.set_xticks(tick_list)\n\ncon_list = [item.get_text() for item in ax.get_xticklabels()]\n\nconditions_labels = [w.replace('_', ' ') for w in con_list]\n\nconditions_labels = [w.replace('uM', 'μM\\n') for w in conditions_labels]\n\nconditions_labels = [w.replace('mM', 'mM\\n') for w in conditions_labels]\nconditions_labels = [w.replace('nM', 'nM\\n') for w in conditions_labels]\nconditions_labels = [w.replace('per', '%') for w in conditions_labels]\n\nif len(conditions)<6:\n dx = 0.\n dy = 0.\n rotation=0\n tick_orientation='center'\n\nelif len(conditions)>15:\n rotation=37\n dx = 24 / 72.\n dy = 0.\n conditions_labels = [w.replace('\\n', ' ') for w in conditions_labels]\n # tick_orientation='center'\n tick_orientation='right'\n\nelse:\n rotation=37\n dx = 50 / 72.\n dy = 0.\n # tick_orientation='center'\n tick_orientation='right'\n\n\n\n# Con_list = mi_box['Condition'].to_numpy()\n# con_list = np.unique(Con_list)\n# con_list = con_list.tolist()\n\n\n\n\n# conditions_label_reduced = [w.replace('_', ' \\n ') for w in conditions_reduced]\n# conditions_label_reduced = [w.replace('uM', 'μM') for w in conditions_label_reduced]\n\nax.set_xticklabels(conditions_labels, rotation=rotation,\n ha=tick_orientation) # , rotation_mode=\"anchor\")\nif analyze_method == \"fold_change\":\n # ax.set_xticklabels(conditions_label_reduced, rotation=rotation, ha=tick_orientation) # , rotation_mode=\"anchor\")\n ax.set_ylabel('Log2 (Fold Change to Control)')\n plt.axhline(y=0)\nelse:\n ax.set_xticklabels(conditions_labels, rotation=rotation, ha=tick_orientation) # , rotation_mode=\"anchor\")\n# for tick in ax.xaxis.get_majorticklabels():\n# tick.set_horizontalalignment(\"right\")\n ax.set_ylabel('Log2 (Fold Change to Day 0)')\n\n\noffset = matplotlib.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)\n\n# apply offset transform to all x ticklabels.\nfor label in ax.xaxis.get_majorticklabels():\n label.set_transform(label.get_transform() + offset)\n\n# ax.set_xlabel('Conditions')\nax.set_xlabel('')\n\n# ax.set_title(ax_title_boxplot)\nax.set_title('')\n\n# ax.xaxis.set_ticks_position('none')\n# ax.yaxis.set_ticks_position('none')\n# ax.tick_params(direction='in')\n\n\nif save_plots:\n plt.savefig(boxplot_fname)\n plt.clf()\n plt.close()\nelse:\n plt.show()","sub_path":"Box_plot_from_Prism_data.py","file_name":"Box_plot_from_Prism_data.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"148028838","text":"##########################\r\n# Uber Tanks Project #\r\n# Beta version 0.01 #\r\n# hud.py #\r\n# Created by Donald Bush #\r\n##########################\r\n\r\nimport pygame\r\n\r\nfrom core.menus import gui\r\nimport core.utils.definitions as DEF\r\nimport core.utils.resources as RESRC\r\n\r\nclass Hud:\r\n def __init__(self, parent_game, active_player):\r\n self.active_player = active_player\r\n self.parent_game = parent_game\r\n self.desktop = gui.Desktop()\r\n ## ~Add widgets\r\n lower = pygame.display.get_surface().get_height()\r\n gui.Button((315,lower-45), (200,50), self.desktop,\r\n RESRC.GUISTYLE_MEDBUTTON,\r\n text=\"Quit Game\").onClick = self.kill_game\r\n self.message_panel = gui.ListBox(\r\n position = (10,lower-90),\r\n size = (300, 85),\r\n parent = self.desktop,\r\n items =[\"The Game Begins!\",\"\",\"\",\"\"],\r\n\t style=RESRC.GUISTYLE_LISTBOX)\r\n players = []\r\n self.player_names = {}\r\n scores = []\r\n for i in range(0, len(parent_game.players)):\r\n players.append(parent_game.players[i].name)\r\n self.player_names[parent_game.players[i].name] = i\r\n scores.append(parent_game.players[i].score)\r\n self.score_player_panel = gui.ListBox(\r\n position = (-300,100),\r\n size = (150, 325),\r\n parent = self.desktop,\r\n items = players,\r\n\t style=RESRC.GUISTYLE_LISTBOX)\r\n self.score_number_panel = gui.ListBox(\r\n position = (-150,100),\r\n size = (150, 325),\r\n parent = self.desktop,\r\n items = scores,\r\n\t style=RESRC.GUISTYLE_LISTBOX)\r\n self.score_player_panel.enabled = True\r\n self.score_number_panel.enabled = True\r\n \r\n def kill_game(self, button):\r\n self.parent_game.game_over = True\r\n def update(self, elapsed):\r\n gui.setEvents(pygame.event.get()) #This is needed otherwise the Gui\r\n #Breaks when using Text editing T.T\r\n self.desktop.update()\r\n if pygame.key.get_pressed()[pygame.K_TAB]:\r\n x = min(self.score_player_panel.position[0]+(0.9*elapsed), 10)\r\n else:\r\n x = max(self.score_player_panel.position[0]-(0.9*elapsed), -300)\r\n self.score_player_panel.position = (x, self.score_player_panel.position[1])\r\n self.score_number_panel.position = (x+150, self.score_number_panel.position[1])\r\n \r\n def change_score(self, player):\r\n self.score_number_panel.items[self.player_names[player.name]] = player.score\r\n\r\n not_done = True\r\n while not_done:\r\n if self.player_names[player.name] == 0 or self.score_number_panel.items[self.player_names[player.name]] <= self.score_number_panel.items[self.player_names[player.name]-1]:\r\n not_done = False\r\n else:\r\n index1 = self.player_names[player.name]\r\n index2 = self.player_names[player.name]-1\r\n name1 = player.name\r\n name2 = self.score_player_panel.items[index2]\r\n score1 = self.score_number_panel.items[index1]\r\n score2 = self.score_number_panel.items[index2]\r\n self.player_names[player.name] = index2\r\n self.player_names[name2] = index1\r\n self.score_player_panel.items[index1] = name2\r\n self.score_player_panel.items[index2] = name1\r\n self.score_number_panel.items[index1] = score2\r\n self.score_number_panel.items[index2] = score1\r\n\r\n index = self.player_names[self.parent_game.active_player.name]\r\n\r\n self.score_number_panel.selectedIndex = index\r\n self.score_player_panel.selectedIndex = index\r\n \r\n self.score_number_panel.needs_refresh = True\r\n self.score_number_panel.refresh()\r\n self.score_player_panel.needs_refresh = True\r\n self.score_player_panel.refresh()\r\n\r\n def show_message(self, message):\r\n self.message_panel.items.insert(0, message)\r\n del self.message_panel.items[4]\r\n self.message_panel.refresh()\r\n \r\n def render(self):\r\n self.desktop.draw()\r\n screen = pygame.display.get_surface()\r\n screen_size = screen.get_size()\r\n pygame.draw.rect(screen, (100,100,100),\r\n (screen_size[0]-110, screen_size[1]-110, 100,100))\r\n pygame.draw.rect(screen, (0,0,0),\r\n (screen_size[0]-110, screen_size[1]-110, 100,100), 2)\r\n pos = ((screen_size[0]-60)-(self.active_player.surface.get_width()/2),\r\n (screen_size[1]-60)-(self.active_player.surface.get_height()/2))\r\n screen.blit(self.active_player.surface, pos)\r\n","sub_path":"src/core/game/hud.py","file_name":"hud.py","file_ext":"py","file_size_in_byte":4817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"619525726","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass MyxiaojinFinanceAtsbudgetConsumedamountBatchqueryModel(object):\n\n def __init__(self):\n self._biz_uk_ids = None\n self._ns = None\n\n @property\n def biz_uk_ids(self):\n return self._biz_uk_ids\n\n @biz_uk_ids.setter\n def biz_uk_ids(self, value):\n if isinstance(value, list):\n self._biz_uk_ids = list()\n for i in value:\n self._biz_uk_ids.append(i)\n @property\n def ns(self):\n return self._ns\n\n @ns.setter\n def ns(self, value):\n self._ns = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.biz_uk_ids:\n if isinstance(self.biz_uk_ids, list):\n for i in range(0, len(self.biz_uk_ids)):\n element = self.biz_uk_ids[i]\n if hasattr(element, 'to_alipay_dict'):\n self.biz_uk_ids[i] = element.to_alipay_dict()\n if hasattr(self.biz_uk_ids, 'to_alipay_dict'):\n params['biz_uk_ids'] = self.biz_uk_ids.to_alipay_dict()\n else:\n params['biz_uk_ids'] = self.biz_uk_ids\n if self.ns:\n if hasattr(self.ns, 'to_alipay_dict'):\n params['ns'] = self.ns.to_alipay_dict()\n else:\n params['ns'] = self.ns\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = MyxiaojinFinanceAtsbudgetConsumedamountBatchqueryModel()\n if 'biz_uk_ids' in d:\n o.biz_uk_ids = d['biz_uk_ids']\n if 'ns' in d:\n o.ns = d['ns']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/MyxiaojinFinanceAtsbudgetConsumedamountBatchqueryModel.py","file_name":"MyxiaojinFinanceAtsbudgetConsumedamountBatchqueryModel.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"650899357","text":"\"\"\"\nThis module is used to do the processing for incoming messages related to the security settlement messages (540-543).\n\nHistory\n=======\n2018-05-11 CHG1000406751 Willie vd Bank Initial deployment\n2019-06-20 FAOPS-504\n FAOPS-508 Joash Moodley Added code to handle MT544/5/6/7/8\n2020-07-02 FAOPS-858 Tawanda Mukhalela Refactored code to improve performance\n\"\"\"\n\nimport re\n\nimport acm\nimport at_logging\nimport FSettlementActions\n\nfrom gen_swift_functions import get_text_from_tag, get_trans_ref_from_tag\n\nLOGGER = at_logging.getLogger(__name__)\n\n\ndef get_tag_and_split(field, mtmessage, split_by=None):\n ref = get_text_from_tag(field, mtmessage)\n if ref and split_by and split_by in ref:\n ref = ref.split(split_by)\n return ref[1]\n else:\n return ref\n\n\ndef change_settlement_status(settlement, status):\n \"\"\"\n Update Settlement Status\n \"\"\"\n settlement.Status(status)\n settlement.Commit()\n message = 'Settlement {settlement} status moved to {status}'\n LOGGER.info(message.format(settlement=settlement.Oid(), status=status))\n\n\ndef change_settlement_text(settlement, text_ref):\n \"\"\"\n Update settlement text\n \"\"\"\n settlement.Text(text_ref)\n settlement.Commit()\n LOGGER.info('Settlement {settlement} text updated'.format(settlement=settlement.Oid()))\n\n\ndef find_settlement_top_parent(settlement):\n top_settlement = settlement\n while top_settlement.Parent():\n top_settlement = find_settlement_top_parent(top_settlement.Parent())\n return top_settlement\n\n\ndef update_540s_status_for_NEWCAN(mtmessage, settlement):\n \"\"\"\n Update security settlement status and Text\n \"\"\"\n message_type = get_tag_and_split(':23G:', mtmessage)\n message = '{message_type} received for settlement {oid}.'\n LOGGER.info(message.format(message_type=message_type, oid=str(settlement.Oid())))\n if message_type == 'NEWM':\n status_ref = 'Settled'\n change_settlement_text(settlement, status_ref)\n status = 'Settled'\n change_settlement_status(settlement, status)\n else:\n error_message = 'Error processing security settlement: unknown type {message_type} received.'\n LOGGER.warning(error_message.format(message_type=message_type))\n\n\ndef update_540s_status_for_548(mtmessage, settlement, has_exchange_ref=False):\n \"\"\"\n Update security settlement status and Text\n \"\"\"\n part = get_tag_and_split(':25D::', mtmessage)\n if part:\n if 'CPRC' in part: # Cancellations\n top_parent_settlement = _get_top_parent_for_settlement(settlement)\n if part == 'CPRC//CAND' and not has_exchange_ref:\n change_settlement_text(top_parent_settlement, part) # Has to be done before the Close update otherwise no further updates are possible\n change_settlement_status(top_parent_settlement, 'Pending Closure')\n change_settlement_status(top_parent_settlement, 'Closed')\n return\n\n elif part == 'CPRC//CAND' and has_exchange_ref:\n settlement = cancell_settlement(top_parent_settlement)\n return change_settlement_text(settlement, part)\n\n elif part == 'CPRC//DEND':\n return change_settlement_text(top_parent_settlement, part)\n\n elif part == 'CPRC//REJT':\n return change_settlement_text(top_parent_settlement, part)\n\n elif 'SETT//PENF' in part:\n field_24b = get_tag_and_split(':24B::', mtmessage)\n if field_24b == 'PENF//ADEA':\n settlement = _get_top_parent_for_settlement(settlement)\n return change_settlement_text(settlement, 'SETT//PENF')\n\n else:\n status_ref = get_tag_and_split(':25D::', mtmessage, '//')\n part = get_tag_and_split(':24B::', mtmessage, '//')\n if part:\n status_ref += '//' + part\n if 'NARR' == part:\n part = get_tag_and_split(':70D::', mtmessage, '//')\n if part:\n status_ref += ' ' + part\n\n return change_settlement_text(settlement, status_ref)\n\n\ndef _get_top_parent_for_settlement(settlement):\n \"\"\"\n Gets the top parent settlement for a given settlement hierarchy\n \"\"\"\n if settlement.Trade() and settlement.Trade().Status() == 'Void':\n settlement = find_settlement_top_parent(settlement)\n\n return settlement\n\n\ndef process_incoming(mtmessage, msg_type):\n msg_ref = get_tag_and_split(':20C::RELA', mtmessage, '-')\n exchange_ref = get_trans_ref_from_tag(':20C::RELA//', mtmessage)\n\n if re.search(r\"^[0-9]{10}$\", exchange_ref[0]):\n process_incoming_exchange_ref(mtmessage, msg_type)\n\n elif msg_ref:\n settlement = acm.FSettlement[msg_ref]\n if settlement and '54' in settlement.MTMessages():\n _update_security_settlement(msg_type, mtmessage, settlement)\n else:\n LOGGER.warning('Settlement with reference id {id} not found on Front Arena!'.format(id=msg_ref))\n\n else:\n LOGGER.warning('Matching reference {ref} not found for incoming security message!'.format(ref=msg_ref))\n\n\ndef process_incoming_exchange_ref(mtmessage, msg_type):\n\n related_reference = get_trans_ref_from_tag(':20C::RELA//', mtmessage)\n\n if related_reference:\n related_reference = related_reference[0][1:] + '/NUTRON'\n else:\n LOGGER.warning('Could not find any Related Reference.. skipping processing')\n return\n\n trades = find_all_trades_for_exchange_ref(related_reference)\n for trade in trades:\n for settlement in trade.Settlements().AsArray():\n if settlement.Type() not in (\"Security Nominal\", \"End Security\"):\n continue\n _update_security_settlement(msg_type, mtmessage, settlement, has_exchange_ref=True)\n\n\ndef _update_security_settlement(msg_type, mtmessage, settlement, has_exchange_ref=False):\n \"\"\"\n Updates the settlement\n \"\"\"\n if msg_type in ('544', '545', '546', '547'):\n update_540s_status_for_NEWCAN(mtmessage, settlement)\n elif msg_type == '548':\n update_540s_status_for_548(mtmessage, settlement, has_exchange_ref)\n\n\ndef cancell_settlement(settlement):\n trade_settlements = settlement.Trade().Settlements().AsArray()\n has_cancelled = False\n for trade_settlement in trade_settlements:\n if trade_settlement.Type() == settlement.Type() and trade_settlement.Status() == 'Cancelled':\n has_cancelled = True\n break\n\n if not has_cancelled:\n old_settlement, new_settlement, = FSettlementActions.InstructToCancel(settlement)\n parent = new_settlement[0]\n parent.Status('Cancelled')\n parent.Commit()\n old_settlement[0].Parent(parent)\n old_settlement[0].Commit()\n old_settlement[0].Status('Void')\n old_settlement[0].Commit()\n return parent\n return settlement\n\n\ndef find_trades_by_exchange_ref(exchange_ref):\n \"\"\"\n Finds Trades based on Exchange ref 1 or 2 matching the Related Reference\n \"\"\"\n\n exchange_ref1_spec = retrieve_additional_info_spec_by_name('ExchangeRef1')\n exchange_ref2_spec = retrieve_additional_info_spec_by_name('ExchangeRef2')\n additional_infos_ref1 = find_additional_infos_by_spec_and_field_value(exchange_ref1_spec, exchange_ref)\n additional_infos_ref2 = find_additional_infos_by_spec_and_field_value(exchange_ref2_spec, exchange_ref)\n trades = set()\n trades.update(_get_trades_from_add_info(additional_infos_ref1))\n trades.update(_get_trades_from_add_info(additional_infos_ref2))\n\n return trades\n\n\ndef _get_trades_from_add_info(additional_infos):\n \"\"\"\n Gets all trades related to a particular list of additional infos\n \"\"\"\n trades = [additional_info.Parent() for additional_info in additional_infos]\n return trades\n\n\ndef find_additional_infos_by_spec_and_field_value(additional_info_spec, field_value):\n \"\"\"\n Gets all applicable Additional infos with the Value of the related Reference\n \"\"\"\n return acm.FAdditionalInfo.Select(\"addInf = {additional_info_spec_oid} and fieldValue = '{field_value}'\".format(\n additional_info_spec_oid=additional_info_spec.Oid(),\n field_value=field_value\n )).AsArray()\n\n\ndef retrieve_additional_info_spec_by_name(name):\n \"\"\"\n Gets additional info spec by name\n \"\"\"\n additional_info_spec = acm.FAdditionalInfoSpec[name]\n if additional_info_spec is None:\n raise ValueError(\"An additional info spec with the name '{name}' does not exist.\".format(\n name=name\n ))\n return additional_info_spec\n\n\ndef find_all_trades_for_exchange_ref(exchange_ref):\n \"\"\"\n Finds all trades related to the Exchange Ref\n \"\"\"\n trades = find_trades_by_exchange_ref(exchange_ref)\n number_of_trades = len(trades)\n if number_of_trades > 0:\n trade_numbers = \", \".join([str(trade.Oid()) for trade in trades])\n LOGGER.info(\"Trades {trade_numbers} found for Exchange Ref '{exchange_ref}'\".format(\n trade_numbers=trade_numbers,\n exchange_ref=exchange_ref\n ))\n else:\n LOGGER.info(\"No trades found for Exchange Ref '{exchange_ref}'\".format(\n exchange_ref=exchange_ref\n ))\n\n return trades\n","sub_path":"Python modules/security_settlements.py","file_name":"security_settlements.py","file_ext":"py","file_size_in_byte":9341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"600299968","text":"import os\nimport re\nimport sys\n\ndef check_input(version):\n pat = r'^(\\d+.\\d+.\\d+)((dev|rc)\\d+)?$'\n if not re.match(pat, version):\n print(\"The new version must be in the format X.X.X([dev|rc]X) (ex. '0.12.0')\")\n return False\n return True\n\ndef version_update(version, filename):\n pat = r\"\"\"(release|version)([\\\" ][:=] [\\\"\\'])(\\d+.\\d+.\\d+)((dev|rc)\\d+)?([\\\"\\'])\"\"\"\n\n with open(filename) as f:\n text = f.read()\n match = re.search(pat, text)\n\n if not match:\n print(\"ERROR: Unable to find version string to replace in %s\" % filename)\n sys.exit(1)\n\n old_version = match.group(3)\n if match.group(4) is not None:\n old_version += match.group(4)\n\n text = re.sub(pat, r'\\g<1>\\g<2>%s\\g<6>' % version, text)\n\n with open(filename, 'w') as f:\n f.write(text)\n\n print(\"Edited {filename}: Updated version string '{old_version}' to '{version}'\".format(filename=filename, version=version, old_version=old_version))\n\nif __name__ == '__main__':\n if not len(sys.argv) == 2:\n print(\"Please provide the new version number to update.\")\n sys.exit(1)\n\n version = sys.argv[1]\n\n if not check_input(version):\n sys.exit(1)\n\n os.chdir('../')\n\n filenames = [\n 'bokehjs/src/coffee/version.coffee',\n 'bokehjs/package.json',\n ]\n\n for filename in filenames:\n version_update(version, filename)\n","sub_path":"scripts/update_bokehjs_versions.py","file_name":"update_bokehjs_versions.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"630055057","text":"# base_graphics.py\n# base graphics window; reusable for most graphics applications\n\nimport pygame\nimport time\n\n\n# --------------------------------\n#\n# Reusable graphics window\n#\n# --------------------------------\n\nclass base_graphics:\n\n \"\"\"\n Pygame window class; base graphics window with basic utility methods\n\n Attributes\n ----------\n frame_times : float[]\n log of the past settings.fps_smooth_size frames.\n\n Created by __init__:\n screen : pygame.display\n main pygame display\n clock : pygame.clock\n pygame timing class\n error_handler : error_handler object\n error handler class\n \"\"\"\n\n frame_times = {}\n\n # --------------------------------\n #\n # Initialization\n #\n # --------------------------------\n def __init__(self, settings, error_handler):\n\n \"\"\"\n Create a pygame graphics window.\n\n Parameters\n ----------\n settings: sv_settings object\n object containing settings to be used\n error_handler: error_handler object\n object containing error handling methods\n \"\"\"\n\n self.settings = settings\n\n pygame.init()\n pygame.font.init()\n self.screen = pygame.display.set_mode(\n self.settings[\"main\"].window_size)\n pygame.display.set_caption(self.settings[\"main\"].caption)\n self.clock = pygame.time.Clock()\n\n self.error_handler = error_handler\n\n # --------------------------------\n #\n # Check events; return list of events\n #\n # --------------------------------\n def check_events(self):\n\n \"\"\"\n Returns a list of the names of current events.\n\n Returns\n -------\n array\n List of triggered events as defined by settings.events\n \"\"\"\n\n triggered_events = []\n for current_event in pygame.event.get():\n if(current_event.type == pygame.KEYDOWN and\n current_event.key in self.settings[\"main\"].events):\n triggered_events.append(\n self.settings[\"main\"].events[current_event.key])\n if(current_event.type == pygame.QUIT):\n triggered_events.append(\n self.settings[\"main\"].events[pygame.QUIT])\n\n return(triggered_events)\n\n # --------------------------------\n #\n # Close window\n #\n # --------------------------------\n def close_window(self):\n\n \"\"\"\n Cleanly closes the pygame window.\n \"\"\"\n\n pygame.display.quit()\n pygame.quit()\n\n # --------------------------------\n #\n # Check for update to fps registry\n #\n # --------------------------------\n def update_fps(self, instruction, device_name):\n\n \"\"\"\n Check whether the instruction triggers an fps update.\n\n Parameters\n ----------\n instruction: array following instruction form\n instruction to be checked\n \"\"\"\n\n # initialize frame times for new device\n if device_name not in self.frame_times:\n self.frame_times.update({device_name: []})\n\n # update frame times\n if(instruction[0] == self.settings[device_name].fps_count_keyword):\n self.frame_times[device_name].append(time.time())\n if(len(self.frame_times[device_name]) >\n self.settings[device_name].fps_smooth_size):\n del self.frame_times[device_name][0]\n\n # --------------------------------\n #\n # Compute fps from the registry\n #\n # --------------------------------\n\n def compute_fps(self, device):\n\n \"\"\"\n Returns the current fps.\n\n Returns\n -------\n float\n fps, smoothed over settings.frame_smooth_size frames\n \"\"\"\n\n if(device not in self.frame_times):\n return(0)\n\n elif(len(self.frame_times[device]) < 2):\n return(0)\n\n return(len(self.frame_times[device]) /\n (self.frame_times[device][-1] - self.frame_times[device][0]))\n","sub_path":"serial_vis/graphics_lib/base_graphics.py","file_name":"base_graphics.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"470189105","text":"from CPT import *\nfrom BayesianNetwork import *\nfrom RandomVariable import *\nimport random\nimport copy\nimport math\n\n\n\ndef normalize(Q):\n nf = 0\n for k in Q.keys():\n nf += Q[k]\n\n dis = {}\n try:\n for k in Q.keys():\n dis.update({k: Q[k] / nf})\n except:\n print('Cannot normalize')\n return Q\n return dis\n\n\ndef enumeration_ask(x, e, bn):\n Q = {}\n hidden_variables = [v for v in bn.get_nodes() if (v.ran_var.get_name()) != x.get_name() and v not in e]\n\n for xi in x.get_domain():\n clone_e = [ei for ei in e]\n clone_e.append(x.assign(bn, xi))\n Q[xi] = enumerate_all(bn, bn.get_nodes(), clone_e, hidden_variables)\n\n print(\"\\nExact Sampling:\")\n return normalize(Q)\n\n\ndef enumerate_all(bn, bn_vars, e, hidden_variables):\n if len(bn_vars) == 0:\n return 1\n\n first, rest = bn_vars[0], bn_vars[1:]\n\n if first not in hidden_variables:\n p = first.get_cpt().get_probability(first, first.get_parents())\n r = enumerate_all(bn, rest, e, hidden_variables)\n return p * r\n else:\n value = 0\n # loop over each of variable's possible value for each summation\n for v in hidden_variables:\n if v.ran_var.get_name() is not first.ran_var.get_name():\n for y in first.ran_var.get_domain():\n # print(first.ran_var.get_name(), \"--->\", y)\n p = first.get_cpt().get_probability(first.ran_var.assign(bn, y), first.get_parents())\n e.append(first.ran_var.assign(bn, y))\n r = enumerate_all(bn, rest, e, hidden_variables)\n value += p * r\n return value\n\n\n# ---------------------------------------------------------------------------------------------------\n\n\n# samples from hard to sample distribution given a easy to sample one\n# returns estimated conditional probabiliteis\n# input: node, bayesianNetwork, list of nodes, int\ndef rejection_sampling(query_var, bay_net, evidences, sample_number):\n orig_evi = copy.deepcopy(evidences)\n # counts for ech value of X in x\n counts = {d: 0 for d in query_var.get_domain()}\n reject_c = 0\n for j in range(1, sample_number):\n # prior sample, event with n elements\n ps = prior_sample(bay_net)\n # rejects all the samples that do not match the evidence\n if consistent(ps, orig_evi):\n # the domain value of the query variable in the prior sample\n val_of_query_in_ps = ps.get(query_var.get_name())\n #print(query_var.get_name(), val_of_query_in_ps)\n # tally\n counts[val_of_query_in_ps] += 1\n else:\n reject_c += 1\n # for k, v in counts.items():\n # print(k, v)\n print(\"\\nRejection Sampling: rejected %d samples; Actual counts used: %s\" % (reject_c, str(counts)))\n return normalize(counts)\n\n\n# input: a dictionary with item{node name : [T/F/None]}, a list of nodes\ndef consistent(gen_sample, evidences):\n for evi in evidences:\n evi_rv = evi.ran_var\n if gen_sample.get(evi_rv.get_name()) != evi_rv.get_value():\n #print(evi_rv.get_name(), evi_rv.get_value(), gen_sample.get(evi_rv.get_name()))\n # if one fo the value does not match with the evidence, reject\n return False\n else:\n pass#print(evi_rv.get_name(), evi_rv.get_value(), gen_sample.get(evi_rv.get_name()))\n\n return True\n\n\n# returns an event sampled from the prior specified by bn, with no evidence associated with it\n# example: for [Cloudy, Sprinkler, Rain, WetGrass], returns [true, false, true, true]\n# input: bayesianNetwork\ndef prior_sample(ps_bn):\n sorted_nodes = ps_bn.topsort_nodes()\n\n # a dictionary with item{node name : [T/F/None]}\n event = {ei.ran_var.get_name(): None for ei in sorted_nodes}\n\n # for Xi in X1,...,Xn\n for sn in sorted_nodes:\n sn_rv = sn.ran_var\n ran_sam = random_sample(sn, sn.get_parents())\n # update event with the domain with larger probability value\n\n domain_with_max_pro = None\n max_pro = -math.inf\n for k, v in ran_sam.items():\n if v > max_pro:\n domain_with_max_pro = k\n max_pro = v\n elif v == max_pro:\n domain_with_max_pro = random.choice([k, domain_with_max_pro])\n # choice = random.choice(sn_rv.get_domain())\n event[sn_rv.get_name()] = domain_with_max_pro\n # event[sn_rv.get_name()] = domain_with_max_pro\n\n\n # assign generated value to itself, since parents are assigned before children\n # all parents would have values before children for us to use\n sn_rv.assign(ps_bn, domain_with_max_pro)\n # print(sn_rv.get_name(), domain_with_max_pro)\n\n '''\n print(\"-------\")\n for ri in list(ran_sam.keys()):\n print(ri, ran_sam.get(ri))\n print(domain_with_max_pro)\n print(\"-------\")\n '''\n\n '''\n print(\"-------\")\n for ei in list(event.keys()):\n print(ei, event.get(ei))\n print(\"-------\")\n '''\n return event\n\n\n# example for P(Rain| Cloudy = true) returns <True: 0.9(from cpt), False:0.1(1-0.9)>\n# the larger value would later be assigned\n# input: node, a list of nodes\ndef random_sample(child, parents):\n probabilities = child.get_cpt().get_entries()\n # print(probabilities)\n # format for cpt: {'CTrueSTrue': 0.1, 'CFalseSTrue': 0.5, 'CFalseSFalse': 0.5, 'CTrueSFalse': 0.9}\n # format: (parentNameParentValName)* childNameChildCalue\n c_rv = child.ran_var\n # a dictionary with item{domain name : [T/F/None]}, will be returned\n ran_dis = {d: 0 for d in c_rv.get_domain()}\n\n # for root nodes\n random_domain = random.choice(c_rv.get_domain())\n if len(parents) == 0:\n random_domain_key = c_rv.get_name() + str(random_domain)\n #print(random_domain_key)\n else:\n parents_nameval = ''\n for p in parents:\n p_rv = p.ran_var\n parents_nameval += p_rv.get_name() + str(p_rv.get_value())\n #print (parents_nameval)\n child_nameval = c_rv.get_name() + str(random_domain)\n random_domain_key = parents_nameval + child_nameval\n #print(random_domain_key)\n\n random_domain_value = probabilities.get(random_domain_key)\n # print(random_domain_key, random_domain_value)\n # TODO: what if domain is not t/f? instead of 1-rando value, we do 1-sum of others\n ran_dis[random_domain] = random_domain_value\n for k, v in ran_dis.items():\n # if v is not None:\n if k != random_domain:\n ran_dis[k] = 1 - random_domain_value\n # print(ran_dis[k], random_domain_value)\n\n '''\n print(c_rv.get_name())\n for k, v in ran_dis.items():\n print(k, v)\n '''\n\n return ran_dis\n\n\ndef likelihood_weighting(query_var, bay_net, evidences, sample_size):\n orig_evi = copy.deepcopy(evidences)\n # weighed counts for ech value of X in x\n weighted_counts = {d: 0 for d in query_var.get_domain()}\n\n for j in range(1, sample_size):\n ws_tuple = weighted_sample(bay_net, orig_evi)\n val_of_query_in_ws = ws_tuple[0].get(query_var.get_name())\n #print(query_var.get_name(),val_of_query_in_ws)\n # tally, W[x] <-- w[x] + w\n weighted_counts[val_of_query_in_ws] = weighted_counts[val_of_query_in_ws] + ws_tuple[1]\n #print(val_of_query_in_ws)\n #print(query_var.get_name(), weighted_counts[val_of_query_in_ws])\n print(\"\\nLikelihood Weighting: \")\n return normalize(weighted_counts)\n\n\n# returns an event and a weight\ndef weighted_sample(bay_net, orig_evi):\n sorted_nodes = bay_net.topsort_nodes()\n w = 1\n # a dictionary with item{node name : [T/F/None]}, initialized from e\n event = {ei.ran_var.get_name(): None if ei.ran_var.get_value() is None\n else ei.ran_var.get_value() for ei in sorted_nodes}\n\n for sn in sorted_nodes:\n # if xi is an evidence variable with value xi in e\n s_r = sn.ran_var\n for ori in orig_evi:\n o_r = ori.ran_var\n if s_r.get_name() == o_r.get_name():\n table = sn.get_cpt().get_entries()\n parents = [p for p in sn.get_parents()]\n key = ''\n if len(parents) == 0:\n key += s_r.get_name() + str(s_r.get_value())\n else:\n for p in parents:\n p_r = p.ran_var\n key += p_r.get_name() + str(p_r.get_value())\n key += s_r.get_name() + str(s_r.get_value())\n #print(key, table.get(key), w * table.get(key))\n #then weight the weight times P(xi|parents(xi))\n w = w * table.get(key)\n\n else:\n # x[i] is a random sampe from P(Xi| parents(xi))\n ran_sam = random_sample(sn, sn.get_parents())\n # update event with the domain with larger probability value\n domain_with_max_pro = None\n max_pro = -math.inf\n for k, v in ran_sam.items():\n # print(v, max_pro)\n if v > max_pro:\n domain_with_max_pro = k\n max_pro = v\n elif v == max_pro:\n #print(k, domain_with_max_pro)\n domain_with_max_pro = random.choice([k, domain_with_max_pro])\n\n #domain_with_max_pro = random.choice(list(ran_sam.keys()))\n event[s_r.get_name()] = domain_with_max_pro\n # assign the variable with new value\n s_r.assign(bay_net, domain_with_max_pro)\n #print(s_r.get_name(), domain_with_max_pro)\n\n '''\n for k, v in event.items():\n print(k, v)\n print('---')\n '''\n\n t = (event, w)\n return t\n\n\nif __name__ == '__main__':\n\n '''\n # construction network\n john = RandomVariable(\"J\")\n john.set_domain([True, False])\n mary = RandomVariable(\"M\")\n mary.set_domain([True, False])\n alarm = RandomVariable(\"A\")\n alarm.set_domain([True, False])\n burglary = RandomVariable(\"B\")\n burglary.set_domain([True, False])\n earth = RandomVariable(\"E\")\n earth.set_domain([True, False])\n\n bn = BayesianNetwork()\n bn.add_all([burglary, earth, alarm, john, mary])\n\n cpt_burglary = CPT()\n cpt_burglary.add_entry([burglary],[True], 0.001)\n cpt_burglary.add_entry([burglary], [False], 1 - 0.001)\n bn.get_node_for_variable(burglary).set_cpt(cpt_burglary)\n\n cpt_earth = CPT()\n cpt_earth.add_entry([earth], [True], 0.002)\n cpt_earth.add_entry([earth], [False], 1 - 0.002)\n bn.get_node_for_variable(earth).set_cpt(cpt_earth)\n\n cpt_alarm = CPT()\n cpt_alarm.add_entry([burglary, earth, alarm], [True, True, True], 0.95)\n cpt_alarm.add_entry([burglary, earth, alarm], [True, False, True], 0.94)\n cpt_alarm.add_entry([burglary, earth, alarm], [False, True, True], 0.29)\n cpt_alarm.add_entry([burglary, earth, alarm], [False, False, True], 0.001)\n\n cpt_alarm.add_entry([burglary, earth, alarm], [True, True, False], 1 - 0.95)\n cpt_alarm.add_entry([burglary, earth, alarm], [True, False, False], 1 - 0.94)\n cpt_alarm.add_entry([burglary, earth, alarm], [False, True, False], 1 - 0.29)\n cpt_alarm.add_entry([burglary, earth, alarm], [False, False, False], 1 - 0.001)\n bn.connect(alarm, [burglary, earth], cpt_alarm)\n\n cpt_john = CPT()\n cpt_john.add_entry([alarm, john], [True, True], 0.9)\n cpt_john.add_entry([alarm, john], [False, True], 0.05)\n cpt_john.add_entry([alarm, john], [True, False], 1 - 0.9)\n cpt_john.add_entry([alarm, john], [False, False], 1 - 0.05)\n bn.connect(john, [alarm], cpt_john)\n\n cpt_mary = CPT()\n cpt_mary.add_entry([alarm, mary], [True, True], 0.7)\n cpt_mary.add_entry([alarm, mary], [False, True], 0.01)\n cpt_mary.add_entry([alarm, mary], [True, False], 1 - 0.7)\n cpt_mary.add_entry([alarm, mary], [False, False], 1 - 0.01)\n bn.connect(mary, [alarm], cpt_mary)\n\n # showing network\n # bn.print()\n\n x = burglary\n e = [john.assign(bn, True), mary.assign(bn, True)]\n\n #print(enumeration_ask(x, e, bn))\n #print(rejection_sampling(x, bn, e, 1000))\n #prior_sample(bn)\n #print(likelihood_weighting(x, bn, e, 1000))\n\n '''\n\n # construction network\n cloudy = RandomVariable(\"C\")\n cloudy.set_domain([True, False])\n sprinkler = RandomVariable(\"S\")\n sprinkler.set_domain([True, False])\n rain = RandomVariable(\"R\")\n rain.set_domain([True, False])\n wet = RandomVariable(\"W\")\n wet.set_domain([True, False])\n\n bn = BayesianNetwork()\n bn.add_all([cloudy, sprinkler, rain, wet])\n\n cpt_c = CPT()\n cpt_c.add_entry([cloudy], [True], 0.5)\n cpt_c.add_entry([cloudy], [False], 0.5)\n bn.get_node_for_variable(cloudy).set_cpt(cpt_c)\n\n cpt_s = CPT()\n cpt_s.add_entry([cloudy, sprinkler], [True, True], 0.1)\n cpt_s.add_entry([cloudy, sprinkler], [False, True], 0.5)\n cpt_s.add_entry([cloudy, sprinkler], [True, False], 0.9)\n cpt_s.add_entry([cloudy, sprinkler], [False, False], 0.5)\n bn.connect(sprinkler, [cloudy], cpt_s)\n\n cpt_r = CPT()\n cpt_r.add_entry([cloudy, rain], [True, True], 0.8)\n cpt_r.add_entry([cloudy, rain], [False, True], 0.2)\n cpt_r.add_entry([cloudy, rain], [True, False], 0.2)\n cpt_r.add_entry([cloudy, rain], [False, False], 0.8)\n bn.connect(rain, [cloudy], cpt_r)\n\n cpt_wet = CPT()\n cpt_wet.add_entry([sprinkler, rain, wet], [True, True, True], 0.99)\n cpt_wet.add_entry([sprinkler, rain, wet], [True, False, True], 0.90)\n cpt_wet.add_entry([sprinkler, rain, wet], [False, True, True], 0.90)\n cpt_wet.add_entry([sprinkler, rain, wet], [False, False, True], 0.000)\n\n cpt_wet.add_entry([sprinkler, rain, wet], [True, True, False], 1 - 0.99)\n cpt_wet.add_entry([sprinkler, rain, wet], [True, False, False], 1 - 0.90)\n cpt_wet.add_entry([sprinkler, rain, wet], [False, True, False], 0.10)\n cpt_wet.add_entry([sprinkler, rain, wet], [False, False, False], 1)\n bn.connect(wet, [sprinkler, rain], cpt_wet)\n\n # showing network\n #bn.print()\n\n x = rain\n e = [wet.assign(bn, True)]\n print(enumeration_ask(x, e, bn))\n print(rejection_sampling(x, bn, e, 1000))\n print(likelihood_weighting(x, bn, e, 1000))\n\n\n\n '''\n # construction network\n light = RandomVariable(\"L\")\n light.set_domain([True, False])\n bowel = RandomVariable(\"B\")\n bowel.set_domain([True, False])\n dog = RandomVariable(\"D\")\n dog.set_domain([True, False])\n hear = RandomVariable(\"H\")\n hear.set_domain([True, False])\n family = RandomVariable(\"F\")\n family.set_domain([True, False])\n\n bn = BayesianNetwork()\n bn.add_all([family, bowel, light, dog, hear])\n\n cpt_family = CPT()\n cpt_bowel = CPT()\n cpt_light = CPT()\n cpt_dog = CPT()\n cpt_hear = CPT()\n\n cpt_family.add_entry([family], [True], 0.15)\n cpt_family.add_entry([family], [False], 0.85)\n bn.get_node_for_variable(family).set_cpt(cpt_family)\n\n cpt_bowel.add_entry([bowel], [True], 0.01)\n cpt_bowel.add_entry([bowel], [False], 0.99)\n bn.get_node_for_variable(bowel).set_cpt(cpt_bowel)\n\n cpt_light.add_entry([family, light], [True, True], 0.6)\n cpt_light.add_entry([family, light], [False, True], 0.05)\n cpt_light.add_entry([family, light], [True, False], 0.4)\n cpt_light.add_entry([family, light], [False, False], 0.95)\n bn.get_node_for_variable(light).set_cpt(cpt_light)\n\n cpt_dog.add_entry([family, bowel, dog], [True, True, True], 0.99)\n cpt_dog.add_entry([family, bowel, dog], [True, False, True], 0.90)\n cpt_dog.add_entry([family, bowel, dog], [False, True, True], 0.97)\n cpt_dog.add_entry([family, bowel, dog], [False, False, True], 0.30)\n cpt_dog.add_entry([family, bowel, dog], [True, True, False], 0.01)\n cpt_dog.add_entry([family, bowel, dog], [True, False, False], 0.10)\n cpt_dog.add_entry([family, bowel, dog], [False, True, False], 0.03)\n cpt_dog.add_entry([family, bowel, dog], [False, False, False], 0.70)\n bn.get_node_for_variable(dog).set_cpt(cpt_dog)\n\n cpt_hear.add_entry([dog, hear], [True, True], 0.70)\n cpt_hear.add_entry([dog, hear], [False, True], 0.01)\n cpt_hear.add_entry([dog, hear], [True, False], 0.30)\n cpt_hear.add_entry([dog, hear], [False, False], 0.99)\n bn.get_node_for_variable(hear).set_cpt(cpt_hear)\n\n bn.connect(light, [family], cpt_light)\n bn.connect(dog, [family, bowel], cpt_dog)\n bn.connect(hear, [dog], cpt_hear)\n\n # bn.print()\n\n x = hear\n e = [family.assign(bn, False), dog.assign(bn, True)]\n print(enumeration_ask(x, e, bn))\n print(rejection_sampling(x, bn, e, 1000))\n print(likelihood_weighting(x, bn, e, 1000))\n '''\n\n\n\n\n\n","sub_path":"BayesInference/ProbabilisticAgent.py","file_name":"ProbabilisticAgent.py","file_ext":"py","file_size_in_byte":16780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"522005393","text":"# ----------------------------------------------------------------------------\n# - Open3D: www.open3d.org -\n# ----------------------------------------------------------------------------\n# The MIT License (MIT)\n#\n# Copyright (c) 2020 www.open3d.org\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n# ----------------------------------------------------------------------------\n\nimport open3d as o3d\nimport open3d.core as o3c\nimport numpy as np\nimport pytest\n\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.realpath(__file__)) + \"/..\")\nfrom open3d_test import list_devices\n\n\n@pytest.mark.parametrize(\"device\", list_devices())\ndef test_constructor_and_accessors(device):\n dtype = o3c.Dtype.Float32\n\n # Constructor.\n pcd = o3d.t.geometry.PointCloud(dtype, device)\n assert \"points\" in pcd.point\n assert \"colors\" not in pcd.point\n assert isinstance(pcd.point, o3d.t.geometry.TensorListMap)\n assert isinstance(pcd.point[\"points\"], o3c.TensorList)\n\n # Assignment.\n pcd.point[\"points\"] = o3c.TensorList(o3c.SizeVector([3]), dtype, device)\n pcd.point[\"colors\"] = o3c.TensorList(o3c.SizeVector([3]), dtype, device)\n assert len(pcd.point[\"points\"]) == 0\n assert len(pcd.point[\"colors\"]) == 0\n\n one_point = o3c.Tensor.ones((3,), dtype, device)\n one_color = o3c.Tensor.ones((3,), dtype, device)\n pcd.point[\"points\"].push_back(one_point)\n pcd.point[\"colors\"].push_back(one_color)\n assert len(pcd.point[\"points\"]) == 1\n assert len(pcd.point[\"colors\"]) == 1\n\n # Edit and access values.\n pcd.point[\"points\"][0] = o3c.Tensor([1, 2, 3], dtype, device)\n assert pcd.point[\"points\"][0].allclose(o3c.Tensor([1, 2, 3], dtype, device))\n\n # Pushback.\n pcd.synchronized_push_back({\"points\": one_point, \"colors\": one_color})\n assert len(pcd.point[\"points\"]) == 2\n assert len(pcd.point[\"colors\"]) == 2\n\n\n@pytest.mark.parametrize(\"device\", list_devices())\ndef test_from_legacy_pointcloud(device):\n dtype = o3c.Dtype.Float32\n\n legacy_pcd = o3d.geometry.PointCloud()\n legacy_pcd.points = o3d.utility.Vector3dVector(\n np.array([\n [0, 1, 2],\n [3, 4, 5],\n ]))\n legacy_pcd.colors = o3d.utility.Vector3dVector(\n np.array([\n [6, 7, 8],\n [9, 10, 11],\n ]))\n\n pcd = o3d.t.geometry.PointCloud.from_legacy_pointcloud(\n legacy_pcd, dtype, device)\n assert pcd.point[\"points\"].as_tensor().allclose(\n o3c.Tensor([\n [0, 1, 2],\n [3, 4, 5],\n ], dtype, device))\n assert pcd.point[\"colors\"].as_tensor().allclose(\n o3c.Tensor([\n [6, 7, 8],\n [9, 10, 11],\n ], dtype, device))\n\n\n@pytest.mark.parametrize(\"device\", list_devices())\ndef test_to_legacy_pointcloud(device):\n dtype = o3c.Dtype.Float32\n\n pcd = o3d.t.geometry.PointCloud(dtype, device)\n pcd.point[\"points\"] = o3c.TensorList.from_tensor(\n o3c.Tensor([\n [0, 1, 2],\n [3, 4, 5],\n ], dtype, device))\n pcd.point[\"colors\"] = o3c.TensorList.from_tensor(\n o3c.Tensor([\n [6, 7, 8],\n [9, 10, 11],\n ], dtype, device))\n\n legacy_pcd = pcd.to_legacy_pointcloud()\n np.testing.assert_allclose(np.asarray(legacy_pcd.points),\n np.array([\n [0, 1, 2],\n [3, 4, 5],\n ]))\n np.testing.assert_allclose(np.asarray(legacy_pcd.colors),\n np.array([\n [6, 7, 8],\n [9, 10, 11],\n ]))\n\n\n@pytest.mark.parametrize(\"device\", list_devices())\ndef test_member_functions(device):\n dtype = o3c.Dtype.Float32\n\n # get_min_bound, get_max_bound, get_center.\n pcd = o3d.t.geometry.PointCloud(dtype, device)\n pcd.point[\"points\"] = o3c.TensorList.from_tensor(\n o3c.Tensor([\n [1, 10, 20],\n [30, 2, 40],\n [50, 60, 3],\n ], dtype, device))\n assert pcd.get_min_bound().allclose(o3c.Tensor([1, 2, 3], dtype, device))\n assert pcd.get_max_bound().allclose(o3c.Tensor([50, 60, 40], dtype, device))\n assert pcd.get_center().allclose(o3c.Tensor([27, 24, 21], dtype, device))\n\n # transform.\n with pytest.raises(RuntimeError):\n pcd.transform(o3c.Tensor.eye(4, dtype, device))\n\n # translate.\n pcd = o3d.t.geometry.PointCloud(dtype, device)\n transloation = o3c.Tensor([10, 20, 30], dtype, device)\n\n pcd.point[\"points\"] = o3c.TensorList.from_tensor(\n o3c.Tensor([\n [0, 1, 2],\n [6, 7, 8],\n ], dtype, device))\n pcd.translate(transloation, True)\n assert pcd.point[\"points\"].as_tensor().allclose(\n o3c.Tensor([\n [10, 21, 32],\n [16, 27, 38],\n ], dtype, device))\n\n pcd.point[\"points\"] = o3c.TensorList.from_tensor(\n o3c.Tensor([\n [0, 1, 2],\n [6, 7, 8],\n ], dtype, device))\n pcd.translate(transloation, False)\n assert pcd.point[\"points\"].as_tensor().allclose(\n o3c.Tensor([\n [7, 17, 27],\n [13, 23, 33],\n ], dtype, device))\n\n # scale\n pcd = o3d.t.geometry.PointCloud(dtype, device)\n pcd.point[\"points\"] = o3c.TensorList.from_tensor(\n o3c.Tensor([\n [0, 0, 0],\n [1, 1, 1],\n [2, 2, 2],\n ], dtype, device))\n center = o3c.Tensor([1, 1, 1], dtype, device)\n pcd.scale(4, center)\n assert pcd.point[\"points\"].as_tensor().allclose(\n o3c.Tensor([\n [-3, -3, -3],\n [1, 1, 1],\n [5, 5, 5],\n ], dtype, device))\n\n # rotate.\n with pytest.raises(RuntimeError):\n r = o3c.Tensor.eye(3, dtype, device)\n center = o3c.Tensor.ones((3,), dtype, device)\n pcd.rotate(r, center)\n","sub_path":"python/test/t/geometry/test_pointcloud.py","file_name":"test_pointcloud.py","file_ext":"py","file_size_in_byte":6938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"396403263","text":"import argparse\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\nclass ArgumentParser:\n def __init__(self,):\n pass\n \n def parse_args(self,):\n parser = argparse.ArgumentParser(description='FireClassifier', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n # preprocessing\n parser.add_argument('--multi_scale', dest='multi_scale', default=False, type=str2bool)\n parser.add_argument('--min_image_size', dest='min_image_size', help='min_image_size', default=64, type=int)\n parser.add_argument('--max_image_size', dest='max_image_size', help='max_image_size', default=224, type=int)\n \n parser.add_argument('--num_threads', dest='num_threads', default=6, type=int)\n parser.add_argument('--random_crop', dest='random_crop', help='random_crop', default=True, type=str2bool)\n \n # update !!\n parser.add_argument('--experimenter', dest='experimenter', help='experimenter', default='JSH', type=str)\n \n # for linux\n parser.add_argument('--root_dir', dest='root_dir', help='root_dir', default='../DB/Recon_FireClassifier_DB_20200219/', type=str)\n \n # for windows\n ## NAS\n # parser.add_argument('--root_dir', dest='root_dir', help='root_dir', default='//gynetworks/Data/DATA/Image/Recon_FireClassifier_DB_20200219/', type=str)\n \n ## Local\n # parser.add_argument('--root_dir', dest='root_dir', help='root_dir', default='C:/DB/Recon_FireClassifier_DB_20200219/', type=str)\n \n # gpu option\n parser.add_argument('--use_gpu', dest='use_gpu', help='use gpu', default='0', type=str)\n parser.add_argument('--batch_size_per_gpu', dest='batch_size_per_gpu', default=32, type=int)\n \n # model option\n parser.add_argument('--option', dest='option', default='b0', type=str)\n \n # train technology\n parser.add_argument('--augment', dest='augment', help='None/weakaugment/randaugment', default=None, type=str)\n \n parser.add_argument('--mixup', dest='mixup', help='mixup', default=False, type=str2bool)\n parser.add_argument('--mixup_alpha', dest='mixup_alpha', help='mixup_alpha', default=1.0, type=float)\n\n parser.add_argument('--cutmix', dest='cutmix', help='cutmix', default=False, type=str2bool)\n \n parser.add_argument('--weight_decay', dest='weight_decay', help='weight_decay', default=1e-4, type=float)\n parser.add_argument('--ema_decay', dest='ema_decay', help='ema', default=-1, type=float)\n\n parser.add_argument('--log_iteration', dest='log_iteration', help='log_iteration', default=100, type=int)\n parser.add_argument('--val_iteration', dest='val_iteration', help='val_iteration', default=20000, type=int)\n parser.add_argument('--max_iteration', dest='max_iteration', help='max_iteration', default=200000, type=int)\n \n return vars(parser.parse_args())\n\n \n","sub_path":"utils/ArgumentParser.py","file_name":"ArgumentParser.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"653930156","text":"from decimal import Decimal\nfrom random import randint\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nimport factory\nimport factory.fuzzy\n\nfrom nodeconductor.iaas import models\nfrom nodeconductor.core import models as core_models\nfrom nodeconductor.structure.tests import factories as structure_factories\n\n\nclass CloudFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.Cloud\n\n name = factory.Sequence(lambda n: 'cloud%s' % n)\n customer = factory.SubFactory(structure_factories.CustomerFactory)\n auth_url = 'http://example.com:5000/v2'\n\n @classmethod\n def get_url(self, cloud=None):\n if cloud is None:\n cloud = CloudFactory()\n return 'http://testserver' + reverse('cloud-detail', kwargs={'uuid': cloud.uuid})\n\n @classmethod\n def get_list_url(cls):\n return 'http://testserver' + reverse('cloud-list')\n\n\nclass FlavorFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.Flavor\n\n name = factory.Sequence(lambda n: 'flavor%s' % n)\n cloud = factory.SubFactory(CloudFactory)\n\n cores = 4 * 1024\n ram = 2 * 1024\n disk = 10 * 1024\n\n backend_id = factory.Sequence(lambda n: 'flavor-id%s' % n)\n\n @classmethod\n def get_url(cls, flavor=None):\n if flavor is None:\n flavor = FlavorFactory()\n return 'http://testserver' + reverse('flavor-detail', kwargs={'uuid': flavor.uuid})\n\n @classmethod\n def get_list_url(cls):\n return 'http://testserver' + reverse('flavor-list')\n\n\nclass CloudProjectMembershipFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.CloudProjectMembership\n\n cloud = factory.SubFactory(CloudFactory)\n project = factory.SubFactory(structure_factories.ProjectFactory)\n tenant_id = factory.Sequence(lambda n: 'tenant_id_%s' % n)\n\n @classmethod\n def get_url(cls, membership=None):\n if membership is None:\n membership = CloudProjectMembershipFactory()\n return 'http://testserver' + reverse('cloudproject_membership-detail', kwargs={'pk': membership.pk})\n\n @classmethod\n def get_list_url(cls):\n return 'http://testserver' + reverse('cloudproject_membership-list')\n\n\nclass SecurityGroupFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.SecurityGroup\n\n cloud_project_membership = factory.SubFactory(CloudProjectMembershipFactory)\n name = factory.Sequence(lambda n: 'group%s' % n)\n description = factory.Sequence(lambda n: 'very good group %s' % n)\n\n @classmethod\n def get_url(cls, security_group=None):\n if security_group is None:\n security_group = CloudProjectMembershipFactory()\n return 'http://testserver' + reverse('security_group-detail', kwargs={'uuid': security_group.uuid})\n\n\nclass SecurityGroupRuleFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.SecurityGroupRule\n\n security_group = factory.SubFactory(SecurityGroupFactory)\n protocol = models.SecurityGroupRule.tcp\n from_port = factory.fuzzy.FuzzyInteger(1, 65535)\n to_port = factory.fuzzy.FuzzyInteger(1, 65535)\n cidr = factory.LazyAttribute(lambda o: '.'.join('%s' % randint(1, 255) for i in range(4)) + '/24')\n\n\nclass IpMappingFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.IpMapping\n\n public_ip = factory.LazyAttribute(lambda o: '84.%s' % '.'.join(\n '%s' % randint(0, 255) for _ in range(3)))\n private_ip = factory.LazyAttribute(lambda o: '10.%s' % '.'.join(\n '%s' % randint(0, 255) for _ in range(3)))\n project = factory.SubFactory(structure_factories.ProjectFactory)\n\n @classmethod\n def get_url(cls, ip_mapping=None):\n ip_mapping = ip_mapping or IpMappingFactory()\n\n return 'http://testserver' + reverse('ip_mapping-detail', kwargs={'uuid': ip_mapping.uuid})\n\n @classmethod\n def get_list_url(cls):\n return 'http://testserver' + reverse('ip_mapping-list')\n\n\nclass TemplateFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.Template\n\n name = factory.Sequence(lambda n: 'template%s' % n)\n description = factory.Sequence(lambda n: 'description %d' % n)\n icon_url = factory.Sequence(lambda n: 'http://example.com/%d.png' % n)\n is_active = True\n sla_level = factory.LazyAttribute(lambda o: Decimal('99.9'))\n setup_fee = factory.fuzzy.FuzzyDecimal(10.0, 50.0, 3)\n monthly_fee = factory.fuzzy.FuzzyDecimal(0.5, 20.0, 3)\n\n @classmethod\n def get_url(cls, template=None):\n template = template or TemplateFactory()\n\n return 'http://testserver' + reverse('template-detail', kwargs={'uuid': template.uuid})\n\n @classmethod\n def get_list_url(cls):\n return 'http://testserver' + reverse('template-list')\n\n\nclass TemplateMappingFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.TemplateMapping\n\n template = factory.SubFactory(TemplateFactory)\n backend_image_id = factory.Sequence(lambda n: 'image-id-%s' % n)\n\n\nclass TemplateLicenseFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.TemplateLicense\n\n name = factory.Sequence(lambda n: 'License%s' % n)\n license_type = factory.Sequence(lambda n: 'LicenseType%s' % n)\n service_type = models.TemplateLicense.Services.IAAS\n setup_fee = factory.fuzzy.FuzzyDecimal(10.0, 50.0, 3)\n monthly_fee = factory.fuzzy.FuzzyDecimal(0.5, 20.0, 3)\n\n\nclass ImageFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.Image\n\n cloud = factory.SubFactory(CloudFactory)\n template = factory.SubFactory(TemplateFactory)\n backend_id = factory.Sequence(lambda n: 'id%s' % n)\n\n\nclass SshPublicKeyFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = core_models.SshPublicKey\n\n user = factory.SubFactory(structure_factories.UserFactory)\n name = factory.Sequence(lambda n: 'ssh_public_key%s' % n)\n public_key = (\n \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28\"\n \"TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY\"\n \"dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du\"\n \"D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh\"\n \"vEAFdOJcqjyyH4FOGYa8usP1 test\"\n )\n\n @classmethod\n def get_url(self, key):\n if key is None:\n key = SshPublicKeyFactory()\n return 'http://testserver' + reverse('sshpublickey-detail', kwargs={'uuid': str(key.uuid)})\n\n @classmethod\n def get_list_url(self):\n return 'http://testserver' + reverse('sshpublickey-list')\n\n\nclass InstanceFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.Instance\n\n hostname = factory.Sequence(lambda n: 'host%s' % n)\n template = factory.SubFactory(TemplateFactory)\n\n start_time = factory.LazyAttribute(lambda o: timezone.now())\n external_ips = factory.LazyAttribute(lambda o: '.'.join(\n '%s' % randint(0, 255) for _ in range(4)))\n internal_ips = factory.LazyAttribute(lambda o: '.'.join(\n '%s' % randint(0, 255) for _ in range(4)))\n\n cores = factory.Sequence(lambda n: n)\n ram = factory.Sequence(lambda n: n)\n cloud_project_membership = factory.SubFactory(CloudProjectMembershipFactory)\n\n key_name = factory.Sequence(lambda n: 'instance key%s' % n)\n key_fingerprint = factory.Sequence(lambda n: 'instance key fingerprint%s' % n)\n\n system_volume_id = factory.Sequence(lambda n: 'sys-vol-id-%s' % n)\n system_volume_size = 10 * 1024\n data_volume_id = factory.Sequence(lambda n: 'dat-vol-id-%s' % n)\n data_volume_size = 20 * 1024\n\n backend_id = factory.Sequence(lambda n: 'instance-id%s' % n)\n\n agreed_sla = Decimal('99.9')\n\n @classmethod\n def get_url(self, instance=None, action=None):\n if instance is None:\n instance = InstanceFactory()\n url = 'http://testserver' + reverse('instance-detail', kwargs={'uuid': instance.uuid})\n return url if action is None else url + action + '/'\n\n @classmethod\n def get_list_url(self):\n return 'http://testserver' + reverse('instance-list')\n\n\nclass InstanceSlaHistoryFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.InstanceSlaHistory\n\n period = factory.Sequence(lambda n: '200%s' % n)\n instance = factory.SubFactory(InstanceFactory)\n value = factory.LazyAttribute(lambda o: Decimal('99.9'))\n\n\nclass InstanceLicenseFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.InstanceLicense\n\n instance = factory.SubFactory(InstanceFactory)\n template_license = factory.SubFactory(TemplateLicenseFactory)\n setup_fee = factory.fuzzy.FuzzyDecimal(10.0, 50.0, 3)\n monthly_fee = factory.fuzzy.FuzzyDecimal(0.5, 20.0, 3)\n\n\nclass InstanceSecurityGroupFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.InstanceSecurityGroup\n\n instance = factory.SubFactory(InstanceFactory)\n security_group = factory.SubFactory(SecurityGroupFactory)\n\n\nclass AbstractResourceQuotaFactory(factory.DjangoModelFactory):\n class Meta:\n abstract = True\n\n cloud_project_membership = factory.SubFactory(CloudProjectMembershipFactory)\n vcpu = factory.Iterator([1, 2, 3, 4])\n ram = factory.Iterator([1024, 2048, 4096])\n storage = factory.fuzzy.FuzzyFloat(10240, 51200)\n max_instances = factory.Iterator([1, 2, 3, 4])\n backup_storage = factory.fuzzy.FuzzyFloat(10240, 51200)\n\n\nclass ResourceQuotaFactory(AbstractResourceQuotaFactory):\n class Meta(object):\n model = models.ResourceQuota\n\n\nclass ResourceQuotaUsageFactory(AbstractResourceQuotaFactory):\n class Meta(object):\n model = models.ResourceQuotaUsage\n\n\nclass FloatingIPFactory(factory.DjangoModelFactory):\n class Meta(object):\n model = models.FloatingIP\n\n cloud_project_membership = factory.SubFactory(CloudProjectMembershipFactory)\n status = factory.Iterator(['ACTIVE', 'SHUTOFF', 'DOWN'])\n address = factory.LazyAttribute(lambda o: '.'.join('%s' % randint(0, 255) for _ in range(4)))\n\n @classmethod\n def get_url(self, instance=None):\n if instance is None:\n instance = FloatingIPFactory()\n return 'http://testserver' + reverse('floating_ip-detail', kwargs={'uuid': instance.uuid})\n\n @classmethod\n def get_list_url(self):\n return 'http://testserver' + reverse('floating_ip-list')\n","sub_path":"nodeconductor/iaas/tests/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":10617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"507960956","text":"#https://www.onthemarket.com/for-sale/property/plymouth/\n\nimport requests \nfrom bs4 import BeautifulSoup \nimport pandas \nimport re \nimport numpy as np\nfrom datetime import datetime\n\nimport storage\n\nprint(\"\\nProperty data scraper. UK cities only.\\n\")\nsearch_time = datetime.now().strftime(\"%Y-%m-%d_%H%M\")\n\ncity = input(\"Enter city name: \")\nradius = input(\"Enter geographic search radius (maximum 40): \")\n\naccepted_radii = [1, 3, 5, 10, 15, 20, 30, 40]\n\nif int(radius) not in accepted_radii:\n print(\"Radius must be 40 or less\")\n print(\"Enter one of the following: 1, 3, 5, 10, 15, 20, 30, 40\")\n radius = input(\"Re-enter search radius: \") \n\nheaders = {'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'}\n\nr = requests.get(f\"https://www.onthemarket.com/for-sale/property/{city}/?radius={radius}\", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})\nc = r.content\nsoup = BeautifulSoup(c, \"html.parser\")\nall = soup.find_all(\"li\", {\"class\":\"result property-result panel new first\"})\n\n\nfor page in soup.find_all(\"ul\", {\"class\":\"pagination-tabs\"}):\n for num in soup.find_all(\"li\")[-2]:\n numpages = page.find_all(\"a\",{\"class\":\"\"})[-1].text\n\nprint(str(numpages) + \" pages of results...\\n\")\n\n\nif len(all) < 1:\n print(\"\\nNothing found. Ensure city name entered correctly.\")\n\n#https://www.onthemarket.com/for-sale/property/plymouth/?page=0&radius=5.0\ni = 0\nproplist = []\n#base_url=(f\"https://www.onthemarket.com/for-sale/property/{city}/?page={page}&?radius={radius}\", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})\nchars=\"qwertyuiopasdfghjklzxcvbnm,\"\n\nif int(numpages) > 50:\n cont = input(\"Over 50 pages of results. Are you sure you wish to continue? y/n\\n\")\n if \"y\" in cont:\n pass\n else:\n print(\"Program terminated\")\n exit()\n\nfor page in range(0, int(numpages)+1, 1):\n r = requests.get(f\"https://www.onthemarket.com/for-sale/property/{city}/?page=\" + str(page) + \"&?radius={radius}\", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})\n c = r.content\n soup=BeautifulSoup(c, \"html.parser\")\n all = soup.find_all(\"li\", {\"class\":\"result\"})\n\n for item in all:\n property = {}\n i += 1\n\n try:\n print(str(item.find(\"span\", {\"class\":\"title\"}).text))\n except:\n print(\"Unknown number of bedrooms\")\n\n try:\n property[\"Price\"]=item.find(\"a\", {\"class\":\"price\"}).text\n property[\"Price\"] = ''.join(filter(str.isdigit, property[\"Price\"]))\n if property[\"Price\"] == \"\":\n property[\"Price\"] = \"0\"\n except:\n property[\"Price\"] = \"0\"\n\n property[\"Address\"]=item.find_all(\"span\", {\"class\":\"address\"})[0].text\n try:\n property[\"Beds\"]=item.find(\"span\", {\"class\":\"title\"}).text\n property[\"Beds\"]= ''.join(filter(str.isdigit, property[\"Beds\"]))\n except:\n property[\"Beds\"]=\"0\"\n try:\n property[\"Agent_Name\"]=item.find(\"a\", {\"class\":\"marketed-by-link\"}).text\n except:\n property[\"Agent_Name\"]=\"None\"\n try:\n property[\"Agent_tel\"]=item.find(\"span\", {\"class\":\"call\"}).text #find(\"span\").text\n except:\n property[\"Agent_tel\"]=\"None\"\n property[\"Website\"] = \"OTM\"\n property[\"Acquire_time\"] = str(search_time)\n proplist.append(property)\n\nif len(proplist) > 0:\n print (str(len(proplist)) + \" properties found\")\n print (\"On \" + str(numpages) + \" pages\\n\")\n df = pandas.DataFrame(proplist)\n\n try:\n avprice = np.asarray(df[\"Price\"], dtype=np.int).mean()\n print(\"Average Price: \")\n print(avprice)\n print(\"Properties with price not explicitly specified excluded from average\")\n\n with open(\"average_prices.txt\", 'a') as file:\n file.write(f\"\\n{search_time}_Average Price from OTM for properties within {radius} miles of {city}: \" + \"£\" + str(int(avprice)))\n \n except:\n print(\"Cannot calculate average\")\n\n save_prompt = input(\"\\nSave results as spreadsheet? y/n: \")\n\n if \"y\" in save_prompt:\n filename = f\"{search_time}_{city}\"\n df.to_csv(f\"{filename}.csv\")\n print(f\"Saved data in file: '{filename}.csv'\")\n else:\n print(\"No spreadsheet saved\")\n\n print(f\"Saving {len(proplist)} properties to {city.upper()} database...\")\n storage.connect(city)\n\n properties_saved = 0\n properties_existing = 0\n\n for p in proplist: # consider adding tqdm - and removing print statements in storage\n if storage.insert(city, 'N/A', p['Price'], p['Address'], p['Beds'], 'N/A', 'N/A', p['Agent_Name'], p['Agent_tel'], p['Website'], p['Acquire_time']) == 'new':\n properties_saved += 1\n else:\n properties_existing += 1\n print(f\"Saved {properties_saved} to {city} - {properties_existing} already in database\")\n\n print(\"Saved to DB\")","sub_path":"otm_scraper.py","file_name":"otm_scraper.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"393885902","text":"#All the data you need is two pickle files available here - https://drive.google.com/drive/folders/1lY8Ddz_RNOqRCVmZGC4NDIKzf4KUxFPZ?usp=sharing\n\n# python3 neon.py --batch-size=64 --initial-lr=1e-3 --weight-decay=1e-6 --dropout-i=0.07 --dropout-o=0.10 --dropout-w=0.07 --dense-hidden-units=1024 --spacial-dropout=0.00 --use-roc-star\n\n# python3 neon.py --batch-size=64 --initial-lr=1e-3 --weight-decay=1e-6 --dropout-i=0.07 --dropout-o=0.10 --dropout-w=0.07 --dense-hidden-units=1024 --spacial-dropout=0.00 --use-roc-star\n\nTRUNC = 700000\n#WARNING : TRUNC truncates the dataset for speed of smoke-testing. Set to -1 for full test.\nRELOAD = False\nTRAINS=True\nEPOCHS=30\n\n\n\n\nexplore_dimensions = {\n 'delta':(2.0),\n #'initial_lr' :(1e-3,2e-3,4e-3),\n #'delta': (2.0)\n #'lstm_units' :(50,100),\n #'dense_hidden_units':(64,128)\n}\n\n\n\nimport sys\nraw_stdout = sys.stdout\n\nif TRAINS :\n from trains import Task\n\nfrom pkbar import Kbar as Progbar\nimport traceback\n\n\nimport argparse\n\n###### fix for mean columnwise auc\n\n#https://www.kaggle.com/yekenot/pooled-gru-fasttext\nfrom warnings import simplefilter\nimport time\nimport sys\nfrom copy import copy\n# ignore all future warnings\nsimplefilter(action='ignore', category=FutureWarning)\nsimplefilter(action='ignore', category=UserWarning)\no_explore_dimensions=copy(explore_dimensions)\n\n\nKAGGLE = True\nPROG_AUC_UPDATE = 50\n\n\nmax_features = 200000\nmaxlen = 30\nembed_size = 300\n\n\n\nimport code\nimport torch\nimport pandas as pd\nimport numpy as np\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import PackedSequence\nfrom typing import *\nimport _pickle\nimport gc\n\nfrom keras.preprocessing import text, sequence\nfrom sklearn.metrics import roc_auc_score\nimport torch.nn.functional as F\n\n\nSEED = 43\n\ntorch.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\n\n\n\nx_train_torch,x_valid_torch,y_train_torch,y_valid_torch = None,None,None,None\nembedding_matrix = None\ntask=None\nlogger=None\nEMBEDDING_FILE='/media/chris/Storage/big/glove/glove.6B.300d.txt'\n\ndef init():\n global x_train_torch,x_valid_torch,y_train_torch,y_valid_torch\n global embedding_matrix\n global task,logger\n if RELOAD :\n print(\"Warning - reloading dataset\")\n\n train = pd.read_csv('tweets.csv',engine='python') # from https://www.kaggle.com/kazanova/sentiment140\n train = train.sample(frac=1) ; gc.collect(2)\n\n X_train = preprocess(train[\"text\"])\n #code.interact(local=dict(globals(), **locals()))\n y_train = train[\"sentiment\"]==0\n del train; gc.collect(2)\n print(\"Tokenizing ...\")\n tokenizer = text.Tokenizer(num_words=max_features)\n tokenizer.fit_on_texts(list(X_train))\n x_train = tokenizer.texts_to_sequences(X_train)\n x_train = sequence.pad_sequences(x_train, maxlen=maxlen)\n del X_train; gc.collect(2)\n VALID_SIZE = 50000\n x_valid = x_train[-50000:]\n x_train = x_train[:-50000]\n y_train = np.array(1*y_train)\n y_valid = y_train[-50000:]\n y_train = y_train[:-50000]\n print(\"Dumping tokenized training data to pickle ...\")\n _pickle.dump((x_train,x_valid,y_train,y_valid),open(\"tokenized.pkl\",\"wb\"))\n print('building embedding ...')\n def get_coefs(word, *arr): return word, np.asarray(arr, dtype='float32')\n embeddings_index = dict(get_coefs(*o.rstrip().rsplit(' ')) for o in open(EMBEDDING_FILE))\n\n word_index = tokenizer.word_index\n nb_words = min(max_features, len(word_index))\n embedding_matrix = np.zeros((nb_words, embed_size))\n for word, i in word_index.items():\n if i >= max_features: continue\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None: embedding_matrix[i] = embedding_vector\n print(\"Dumping embedding matrix\")\n _pickle.dump(embedding_matrix,open(\"embedding.pkl\",\"wb\"))\n else:\n print(\"Recovering tokenized text from pickle ...\")\n PICKLE_PATH = \"../input/\" if KAGGLE else \"\"\n x_train,x_valid,y_train,y_valid = _pickle.load(open(PICKLE_PATH+\"tokenized.pkl\",\"rb\"))\n print(\"Reusing pickled embedding ...\")\n embedding_matrix = _pickle.load(open(PICKLE_PATH+\"embedding.pkl\",\"rb\"))\n\n print(\"Moving data to GPU ...\")\n if TRUNC>-1 :\n print(f\"\\r\\r * * WARNING training set truncated to first {TRUNC} items.\\r\\r\")\n\n x_train_torch = torch.tensor(x_train[:TRUNC], dtype=torch.long).cuda()\n x_valid_torch = torch.tensor(x_valid, dtype=torch.long).cuda()\n y_train_torch = torch.tensor(y_train[:TRUNC], dtype=torch.float32).cuda()\n y_valid_torch = torch.tensor(y_valid, dtype=torch.float32).cuda()\n del x_train,y_train,x_valid,y_valid; gc.collect(2)\n if TRAINS :\n if not KAGGLE :\n task = Task.init(project_name='local ROC flyover', task_name='Opener')\n else:\n task = Task.init(project_name='Kaggle ROC flyover', task_name='Opener')\n logger = task.get_logger()\n\ndef preprocess(data):\n '''\n Credit goes to https://www.kaggle.com/gpreda/jigsaw-fast-compact-solution\n '''\n punct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~`\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\n def clean_special_chars(text, punct):\n for p in punct:\n text = text.replace(p, ' ')\n return text\n\n data = data.astype(str).apply(lambda x: clean_special_chars(x, punct))\n return data\n\n\ndef epoch_update_gamma(y_true,y_pred, epoch=-1,delta=2):\n \"\"\"\n Calculate gamma from last epoch's targets and predictions.\n Gamma is updated at the end of each epoch.\n y_true: `Tensor`. Targets (labels). Float either 0.0 or 1.0 .\n y_pred: `Tensor` . Predictions.\n \"\"\"\n DELTA = delta\n SUB_SAMPLE_SIZE = 2000.0\n pos = y_pred[y_true==1]\n neg = y_pred[y_true==0] # yo pytorch, no boolean tensors or operators? Wassap?\n # subsample the training set for performance\n cap_pos = pos.shape[0]\n cap_neg = neg.shape[0]\n pos = pos[torch.rand_like(pos) < SUB_SAMPLE_SIZE/cap_pos]\n neg = neg[torch.rand_like(neg) < SUB_SAMPLE_SIZE/cap_neg]\n ln_pos = pos.shape[0]\n ln_neg = neg.shape[0]\n pos_expand = pos.view(-1,1).expand(-1,ln_neg).reshape(-1)\n neg_expand = neg.repeat(ln_pos)\n diff = neg_expand - pos_expand\n ln_All = diff.shape[0]\n Lp = diff[diff>0] # because we're taking positive diffs, we got pos and neg flipped.\n ln_Lp = Lp.shape[0]-1\n diff_neg = -1.0 * diff[diff<0]\n diff_neg = diff_neg.sort()[0]\n ln_neg = diff_neg.shape[0]-1\n ln_neg = max([ln_neg, 0])\n left_wing = int(ln_Lp*DELTA)\n left_wing = max([0,left_wing])\n left_wing = min([ln_neg,left_wing])\n if diff_neg.shape[0] > 0 :\n gamma = diff_neg[left_wing]\n else:\n gamma = 0.2\n L1 = diff[diff>-1.0*gamma]\n ln_L1 = L1.shape[0]\n if epoch > -1 :\n return gamma\n return 0.10\n\ndef roc_star_loss( _y_true, y_pred, gamma, _epoch_true, epoch_pred):\n \"\"\"\n Nearly direct loss function for AUC.\n See article,\n C. Reiss, \"Roc-star : An objective function for ROC-AUC that actually works.\"\n https://github.com/iridiumblue/articles/blob/master/roc_star.md\n _y_true: `Tensor`. Targets (labels). Float either 0.0 or 1.0 .\n y_pred: `Tensor` . Predictions.\n gamma : `Float` Gamma, as derived from last epoch.\n _epoch_true: `Tensor`. Targets (labels) from last epoch.\n epoch_pred : `Tensor`. Predicions from last epoch.\n \"\"\"\n #convert labels to boolean\n y_true = (_y_true>=0.50)\n epoch_true = (_epoch_true>=0.50)\n\n # if batch is either all true or false return small random stub value.\n if torch.sum(y_true)==0 or torch.sum(y_true) == y_true.shape[0]: return torch.sum(y_pred)*1e-8\n\n pos = y_pred[y_true]\n neg = y_pred[~y_true]\n\n epoch_pos = epoch_pred[epoch_true]\n epoch_neg = epoch_pred[~epoch_true]\n\n # Take random subsamples of the training set, both positive and negative.\n max_pos = 1000 # Max number of positive training samples\n max_neg = 1000 # Max number of positive training samples\n cap_pos = epoch_pos.shape[0]\n cap_neg = epoch_neg.shape[0]\n epoch_pos = epoch_pos[torch.rand_like(epoch_pos) < max_pos/cap_pos]\n epoch_neg = epoch_neg[torch.rand_like(epoch_neg) < max_neg/cap_pos]\n\n ln_pos = pos.shape[0]\n ln_neg = neg.shape[0]\n\n # sum positive batch elements agaionst (subsampled) negative elements\n if ln_pos>0 :\n pos_expand = pos.view(-1,1).expand(-1,epoch_neg.shape[0]).reshape(-1)\n neg_expand = epoch_neg.repeat(ln_pos)\n\n diff2 = neg_expand - pos_expand + gamma\n l2 = diff2[diff2>0]\n m2 = l2 * l2\n len2 = l2.shape[0]\n else:\n m2 = torch.tensor([0], dtype=torch.float).cuda()\n len2 = 0\n\n # Similarly, compare negative batch elements against (subsampled) positive elements\n if ln_neg>0 :\n pos_expand = epoch_pos.view(-1,1).expand(-1, ln_neg).reshape(-1)\n neg_expand = neg.repeat(epoch_pos.shape[0])\n\n diff3 = neg_expand - pos_expand + gamma\n l3 = diff3[diff3>0]\n m3 = l3*l3\n len3 = l3.shape[0]\n else:\n m3 = torch.tensor([0], dtype=torch.float).cuda()\n len3=0\n\n if (torch.sum(m2)+torch.sum(m3))!=0 :\n res2 = (torch.sum(m2)+torch.sum(m3))*(len2+len3)/(len2*len3)\n else:\n res2 = torch.sum(m2)+torch.sum(m3)\n\n res2 = torch.where(torch.isnan(res2), torch.zeros_like(res2), res2)\n\n return res2\n\n#https://github.com/keitakurita/Better_LSTM_PyTorch/blob/master/better_lstm/model.py\nclass VariationalDropout(nn.Module):\n \"\"\"\n Applies the same dropout mask across the temporal dimension\n See https://arxiv.org/abs/1512.05287 for more details.\n Note that this is not applied to the recurrent activations in the LSTM like the above paper.\n Instead, it is applied to the inputs and outputs of the recurrent layer.\n \"\"\"\n def __init__(self, dropout, batch_first=False):\n super().__init__()\n self.dropout = dropout\n self.batch_first = batch_first\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n if not self.training or self.dropout <= 0.:\n return x\n\n is_packed = isinstance(x, PackedSequence)\n if is_packed:\n x, batch_sizes = x\n max_batch_size = int(batch_sizes[0])\n else:\n batch_sizes = None\n max_batch_size = x.size(0)\n\n # Drop same mask across entire sequence\n if self.batch_first:\n m = x.new_empty(max_batch_size, 1, x.size(2), requires_grad=False).bernoulli_(1 - self.dropout)\n else:\n m = x.new_empty(1, max_batch_size, x.size(2), requires_grad=False).bernoulli_(1 - self.dropout)\n x = x.masked_fill(m == 0, 0) / (1 - self.dropout)\n\n if is_packed:\n return PackedSequence(x, batch_sizes)\n else:\n return x\n\n\n#https://github.com/keitakurita/Better_LSTM_PyTorch/blob/master/better_lstm/model.py\nclass LSTM(nn.LSTM):\n def __init__(self, *args, dropouti: float=0.,\n dropoutw: float=0., dropouto: float=0.,\n batch_first=True, unit_forget_bias=True, **kwargs):\n super().__init__(*args, **kwargs, batch_first=batch_first)\n self.unit_forget_bias = unit_forget_bias\n self.dropoutw = dropoutw\n self.input_drop = VariationalDropout(dropouti,\n batch_first=batch_first)\n self.output_drop = VariationalDropout(dropouto,\n batch_first=batch_first)\n self._init_weights()\n\n def _init_weights(self):\n \"\"\"\n Use orthogonal init for recurrent layers, xavier uniform for input layers\n Bias is 0 except for forget gate\n \"\"\"\n for name, param in self.named_parameters():\n if \"weight_hh\" in name:\n nn.init.orthogonal_(param.data)\n elif \"weight_ih\" in name:\n nn.init.xavier_uniform_(param.data)\n elif \"bias\" in name and self.unit_forget_bias:\n nn.init.zeros_(param.data)\n param.data[self.hidden_size:2 * self.hidden_size] = 1\n\n def _drop_weights(self):\n for name, param in self.named_parameters():\n if \"weight_hh\" in name:\n getattr(self, name).data = \\\n torch.nn.functional.dropout(param.data, p=self.dropoutw,\n training=self.training).contiguous()\n\n def forward(self, input, hx=None):\n self._drop_weights()\n input = self.input_drop(input)\n seq, state = super().forward(input, hx=hx)\n return self.output_drop(seq), state\n\nclass SpatialDropout(nn.Dropout2d):\n def forward(self, x):\n x = x.unsqueeze(2) # (N, T, 1, K)\n x = x.permute(0, 3, 2, 1) # (N, K, 1, T)\n x = super(SpatialDropout, self).forward(x) # (N, K, 1, T), some features are masked\n x = x.permute(0, 3, 2, 1) # (N, T, 1, K)\n x = x.squeeze(2) # (N, T, K)\n return x\n\ndef quadratic(tens):\n t2 = torch.exp(tens)*torch.cos(tens)\n tc = torch.cat((tens,t2),1)\n return tc\n\nclass NeuralNet(nn.Module):\n def __init__(self, embedding_matrix,h_params):\n super(NeuralNet, self).__init__()\n embed_size = embedding_matrix.shape[1]\n\n self.embedding = nn.Embedding(max_features, embed_size)\n self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))\n self.embedding.weight.requires_grad = False\n self.embedding_dropout = SpatialDropout(h_params.spacial_dropout)\n self.h_params = copy(h_params)\n\n self.c1 = nn.Conv1d(300,kernel_size=2,out_channels=300,padding=1)\n LSTM_UNITS=h_params.lstm_units\n BIDIR = h_params.bidirectional\n\n LSTM_OUT = 2* LSTM_UNITS if BIDIR else LSTM_UNITS\n\n self.lstm1 = LSTM(embed_size, LSTM_UNITS, dropouti=h_params.dropout_i,dropoutw=h_params.dropout_w, dropouto=h_params.dropout_o,bidirectional=BIDIR, batch_first=True)\n self.lstm2 = LSTM(LSTM_OUT, LSTM_UNITS, dropouti=h_params.dropout_i,dropoutw=h_params.dropout_w, dropouto=h_params.dropout_o,bidirectional=BIDIR, batch_first=True)\n\n\n self.linear1 = nn.Linear(2*LSTM_OUT, 2*LSTM_OUT)\n self.linear2 = nn.Linear(2*LSTM_OUT, 2*LSTM_OUT)\n\n self.hey_norm = nn.LayerNorm(2*LSTM_OUT)\n\n self.linear_out = nn.Linear(2*LSTM_OUT, h_params.dense_hidden_units)\n self.linear_xtra = nn.Linear(h_params.dense_hidden_units,int(h_params.dense_hidden_units/2))\n self.linear_xtra2 = nn.Linear(int(h_params.dense_hidden_units/2),int(h_params.dense_hidden_units/4))\n self.linear_out2= nn.Linear(int(h_params.dense_hidden_units/4), 1)\n\n\n\n def forward(self, x):\n h_embedding = self.embedding(x)\n #h_embedding = self.embedding_dropout(h_embedding)\n h1 = h_embedding.permute(0, 2, 1)\n\n q1 = self.c1(h1)\n f1 = q1.permute(0, 2, 1)\n h_lstm1, _ = self.lstm1(f1)\n h_lstm2, _ = self.lstm2(h_lstm1)\n\n # global average pooling\n avg_pool = torch.mean(h_lstm2, 1)\n # global max pooling\n max_pool, _ = torch.max(h_lstm2, 1)\n\n h_conc = torch.cat((max_pool, avg_pool), 1)\n\n h_conc_linear1 = self.linear1(h_conc)\n h_conc_linear2 = self.linear2(h_conc)\n\n hidden = h_conc + h_conc_linear1 + h_conc_linear2\n #hidden = self.hey_norm(hidden)\n #hidden_sq = quadratic(hidden)\n #hidden_sq = torch.cat((hidden,hidden_sq),1) # quadratic trick\n #hidden = F.selu(hidden)\n hidden = F.selu(self.linear_out(hidden))\n hidden = F.selu(self.linear_xtra(hidden))\n hidden = F.selu(self.linear_xtra2(hidden))\n hidden = F.sigmoid(self.linear_out2(hidden))\n\n result=hidden.flatten()\n #self.lstm1.flatten_parameters()\n #self.lstm2.flatten_parameters()\n #aux_result = self.linear_aux_out(hidden1)\n\n return result\n\ndef train_model(h_params, model, x_train, x_valid, y_train, y_valid, lr,\n BATCH_SIZE=1000, n_epochs=EPOCHS, title='', graph=''):\n param_lrs = [{'params': param, 'lr': lr} for param in model.parameters()]\n\n optimizer = torch.optim.Adam(param_lrs, lr=h_params.initial_lr,\n betas=(0.9, 0.999),\n eps=1e-6,\n #weight_decay=1e-3, # this value suggested by authors of LSTM/Variational dropout,\n # see https://discuss.pytorch.org/t/variational-dropout/23030/9\n\n amsgrad=False\n )\n\n #optimizer = torch.optim.SGD(param_lrs, lr=h_params.initial_lr,\n #betas=(0.9, 0.999),\n #eps=1e-6,\n #weight_decay=1e-3, # this value suggested by authors of LSTM/Variational dropout,\n # see https://discuss.pytorch.org/t/variational-dropout/23030/9\n\n #amsgrad=False\n # )\n #scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=0.6)\n\n train_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(x_train, y_train), batch_size=BATCH_SIZE, shuffle=True)\n valid_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(x_valid, y_valid), batch_size=BATCH_SIZE, shuffle=False)\n\n num_batches = len(x_train)/BATCH_SIZE\n #print_flags(FLAGS)\n results=[]\n\n for epoch in range(n_epochs):\n train_roc_val=-1\n start_time = time.time()\n model.train()\n avg_loss = 0.\n\n\n if not KAGGLE :\n progbar =Progbar(num_batches, stateful_metrics=['train-auc'])\n\n whole_y_pred=np.array([])\n whole_y_t=np.array([])\n\n for i,data in enumerate(train_loader):\n x_batch = data[:-1][0]\n y_batch = data[-1]\n\n y_pred = model(x_batch)\n\n if h_params.use_roc_star and epoch>0 :\n\n\n if i==0 : print('*Using Loss Roc-star')\n loss = roc_star_loss(y_batch,y_pred,epoch_gamma, last_whole_y_t, last_whole_y_pred)\n\n\n else:\n if i==0 : print('*Using Loss BxE')\n loss = F.binary_cross_entropy(y_pred, 1.0*y_batch)\n\n\n optimizer.zero_grad()\n loss.backward()\n # To prevent gradient explosions resulting in NaNs\n # https://discuss.pytorch.org/t/nan-loss-in-rnn-model/655/8\n # https://github.com/pytorch/examples/blob/master/word_language_model/main.py\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n\n optimizer.step()\n\n whole_y_pred = np.append(whole_y_pred, y_pred.clone().detach().cpu().numpy())\n whole_y_t = np.append(whole_y_t, y_batch.clone().detach().cpu().numpy())\n\n if i>0:\n if i%50==1 :\n try:\n train_roc_val = roc_auc_score(whole_y_t>=0.5, whole_y_pred)\n except:\n\n train_roc_val=-1\n\n if not KAGGLE :\n progbar.update(\n i,\n values=[\n (\"loss\", np.mean(loss.detach().cpu().numpy())),\n (\"train-auc\", train_roc_val)\n ]\n )\n\n #scheduler.step()\n model.eval()\n last_whole_y_t = torch.tensor(whole_y_t).cuda()\n last_whole_y_pred = torch.tensor(whole_y_pred).cuda()\n\n all_valid_preds = np.array([])\n all_valid_t = np.array([])\n for i, valid_data in enumerate(valid_loader):\n x_batch = valid_data[:-1]\n y_batch = valid_data[-1]\n\n y_pred = model(*x_batch).detach().cpu().numpy()\n y_t = y_batch.detach().cpu().numpy()\n\n all_valid_preds=np.concatenate([all_valid_preds,y_pred],axis=0)\n all_valid_t = np.concatenate([all_valid_t,y_t],axis=0)\n\n epoch_gamma = epoch_update_gamma(last_whole_y_t, last_whole_y_pred, epoch,h_params.delta)\n\n try:\n valid_auc = roc_auc_score(all_valid_t>=0.5, all_valid_preds)\n except:\n valid_auc=-1\n\n try:\n train_roc_val = roc_auc_score(whole_y_t>=0.5, whole_y_pred)\n except:\n train_roc_val=-1\n\n\n elapsed_time = time.time() - start_time\n print(\"\\n\\nParams :\", title,\" :: \", graph)\n print('\\nEpoch {}/{} \\t loss={:.4f} \\t time={:.2f}s'.format(\n epoch + 1, n_epochs, avg_loss, elapsed_time))\n\n print(\"Gamma = \", epoch_gamma)\n print(\"Validation AUC = \", valid_auc)\n #print(\"Validation MET = \", met)\n print(\"\\r Training AUC = \", train_roc_val)\n if valid_auc>0 and train_roc_val>0 :\n if TRAINS :\n logger.report_scalar(title=title, series=graph,\n value=valid_auc, iteration=epoch)\n logger.report_scalar(title=title, series=graph+\"_train\",\n value=train_roc_val, iteration=epoch)\n \n #logger.report_scalar(title=title, series=graph,\n # value=train_roc_val, iteration=epoch)\n #logger.report_scalar(title=title, series=graph,\n # value=valid_auc, iteration=epoch)\n results.append({\n 'valid_auc': valid_auc,\n 'train_auc': train_roc_val,\n 'gamma': epoch_gamma.item()\n })\n if TRAINS:\n print(f'TRAINS results page: {task._get_app_server()}/projects/{task.project}/experiments/{task.id}/output/log')\n\n print()\n\n\n return results\n\ndef run(h_params,embedding_matrix, title='',graph=''):\n loss_fn=nn.BCEWithLogitsLoss(reduction='mean')\n model = NeuralNet(embedding_matrix,h_params)\n model.cuda()\n\n run_result = train_model(h_params,model, x_train_torch, x_valid_torch, y_train_torch, y_valid_torch, lr=h_params.initial_lr,\n BATCH_SIZE=h_params.batch_size, n_epochs=EPOCHS,title=title,graph=graph)\n return run_result\n\n\n\ndef dflags(FLAGS):\n print('===== PARAMS ==========')\n dv = FLAGS.__dict__\n for k in dv:\n print(f\"{' ** ' if k in explore_dimensions else ''}{k} : {dv[k]}\\r\",flush=True)\n print('===== /PARAMS =========', flush=True)\n\n#def flags_in_flux(explore_dimensions,FLAGS):\n\ndef describe_dims(FLAGS, explore_dimension=o_explore_dimensions):\n return \" | \".join([o + ':' + str(FLAGS.__getattribute__(o)) for o in explore_dimension])\n\nSKIP_BXE=False\ndef descend_dimensions(explore_dimensions,FLAGS,results):\n explore_dimensions = copy(explore_dimensions)\n if len(explore_dimensions)>0 :\n next = explore_dimensions.popitem()\n FLAGS.__setattr__(next[0],next[1])\n ##code.interact(local=dict(globals(), **locals()))\n descend_dimensions(explore_dimensions, FLAGS,results)\n\n else:\n\n #code.interact(local=dict(globals(), **locals()))\n\n title = describe_dims(FLAGS)\n FLAGS.__setattr__('use_roc_star', True)\n\n results_ROC= run(FLAGS, embedding_matrix,title,'ROC_STAR')\n if not SKIP_BXE :\n FLAGS.__setattr__('use_roc_star', False)\n #title = describe_dims(FLAGS)\n results_BXE= run(FLAGS, embedding_matrix, title, 'BxE')\n else:\n results_BXE = ( (0,) * len(results_ROC))\n\ndef automate(FLAGS,embedding_matrix,explore_dimensions):\n explore_dimensions = copy(explore_dimensions)\n #explore_dimensions.pop('use_roc_star')\n FLAGS.__setattr__('use_roc_star', True)\n results_ROC=[]\n descend_dimensions(explore_dimensions, FLAGS,results_ROC)\n FLAGS.__setattr__('use_roc_star', False)\n results_BXE=[]\n descend_dimensions(explore_dimensions, FLAGS,results_BXE)\n\nif True: #__name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--use-roc-star', action='store_true')\n parser.add_argument('--delta', type=float, default=2)\n parser.add_argument('--initial-lr', type=float, default=1e-3)\n parser.add_argument('--dense-hidden-units', type=int, default=1024)\n parser.add_argument('--lstm-units', type=int, default=128)\n parser.add_argument('--batch-size', type=int,default=128)\n parser.add_argument('--bidirectional', action='store_true')\n parser.add_argument('--spacial-dropout', type=float, default=0.00)\n parser.add_argument('--dropout-w', type=float,default=0.20)\n parser.add_argument('--dropout-i', type=float,default=0.20)\n parser.add_argument('--dropout-o', type=float,default=0.20)\n parser.add_argument('--auto', action='store_true')\n #FLAGS, unparsed = parser.parse_known_args()\n #--batch-size=128 --initial-lr=1e-3 --weight-decay=1e-6 --dropout-i=0.07 --dropout-o=0.10 --dropout-w=0.07 --dense-hidden-units=1024 --spacial-dropout=0.00\n hard_opts = [\n '--auto'\n '--batch-size=256',\n '--initial-lr=1e-3',\n '--weight-decay=1e-6',\n '--dropout-i=0.05',\n '--dropout-o=0.05',\n '--dropout-w=0.05',\n '--dense-hidden-units=1024',\n '--spacial-dropout=0.00',\n '--use-roc-star'\n ]\n if not KAGGLE :\n FLAGS, unparsed = parser.parse_known_args()\n else:\n FLAGS, unparsed = parser.parse_known_args(args=hard_opts)\n print(\"KAGGLE opts ...\", FLAGS)\n\n #code.interact(local=dict(globals(), **locals()))\n init()\n print('automatic ...',FLAGS.auto)\n print('kaggle ', KAGGLE)\n\n if False : #WARNING-fix not FLAGS.auto :\n run(FLAGS, embedding_matrix)\n else:\n print('automating ....')\n automate(FLAGS, embedding_matrix,explore_dimensions)\n\nif TRAINS :\n print(f'TRAINS results page: {task._get_app_server()}/projects/{task.project}/experiments/{task.id}/output/log')\n\n\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":26099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"50878484","text":"## Add and Search Word - Data structure design\n\n# Example:\n# Input\n# [\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n# [[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]\n# Output\n# [null,null,null,null,false,true,true,true]\n\n# Explanation\n# WordDictionary wordDictionary = new WordDictionary();\n# wordDictionary.addWord(\"bad\");\n# wordDictionary.addWord(\"dad\");\n# wordDictionary.addWord(\"mad\");\n# wordDictionary.search(\"pad\"); // return False\n# wordDictionary.search(\"bad\"); // return True\n# wordDictionary.search(\".ad\"); // return True\n# wordDictionary.search(\"b..\"); // return True\n\nclass TrieNode:\n def __init__(self):\n self.children = dict()\n self.isWord = False\n\nclass WordDictionary:\n\n def __init__(self):\n self.root = TrieNode()\n # self.counter = 0\n\n def addWord(self, word: str) -> None:\n curr = self.root\n for char in word:\n if char not in curr.children:\n curr.children[char] = TrieNode()\n curr = curr.children[char]\n curr.isWord=True\n\n def search(self, word:str, curr = None, j=0) -> bool:\n \n curr = (curr if curr else self.root)\n for i in range(j,len(word)):\n if word[i]=='.':\n for child in curr.children:\n if self.search(word, curr.children[child],i+1):\n return True\n return False\n else:\n if word[i] not in curr.children:\n return False\n curr = curr.children[word[i]]\n \n return curr.isWord\n \n def search_old(self, word: str) -> bool:\n self.counter+=1\n print(\"SEARCH: \",self.counter)\n curr = self.root\n i=0\n N = len(word)\n \n while i<N:\n char = word[i]\n while char=='.':\n print([child for child in curr.children])\n tempS = [curr.children[child] for child in curr.children]\n print(tempS)\n while tempS:\n curr = tempS.pop()\n j=i+1\n while j<N:\n char2 = word[j]\n print(char2)\n if char2=='.':\n j+=1\n break\n elif char2 not in curr.children and tempS==[]:\n return False\n elif char2 not in curr.children:\n break\n curr = curr.children[char2]\n j+=1\n if curr.isWord:\n return True\n if char not in curr.children:\n return False\n curr = curr.children[char]\n i+=1\n \n# while i<N:\n# char = word[i]\n# print([child for child in curr.children])\n# tempS = [curr.children[child] for child in curr.children]\n# print(tempS)\n# while char=='.' and tempS:\n# curr = tempS.pop()\n# j=i+1\n# while j<N:\n# char2 = word[j]\n# print(char2)\n# if char2 not in curr.children and tempS==[]:\n# return False\n# elif char2 not in curr.children:\n# break\n# curr = curr.children[char2]\n# j+=1\n# if curr.isWord:\n# return True\n# if char not in curr.children:\n# return False\n# curr = curr.children[char]\n# i+=1\n \n# if curr.isWord==True:\n# return True\n# else:\n# return False\n \n \n \n# for char in word:\n# if char in curr.children:\n# curr = curr.children[char]\n# elif char=='.':\n \n# temp = list(curr.children.keys())\n# #print(temp)\n# if temp:\n# curr = curr.children[temp[0]]\n# else:\n# return False\n# else:\n# return False\n# if curr.isWord==True:\n# return True\n# else:\n# return False\n\n\n# Your WordDictionary object will be instantiated and called as such:\n# obj = WordDictionary()\n# obj.addWord(word)\n# param_2 = obj.search(word)","sub_path":"Leetcode/Trie/p1052.py","file_name":"p1052.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"455163416","text":"\"\"\"Trigger implementation for reacting\"\"\"\n\nfrom app import APP_INSTANCE as app\nfrom utils import tts\n\ndef run(execution_context):\n \"\"\"run the action\"\"\"\n event_name = execution_context.event_name\n config_name = 'behavior.react.' + event_name.split('.')[1]\n reacts = app.get_config(config_name)\n tts.say_random(reacts)\n","sub_path":"bot/triggers/misc/react.py","file_name":"react.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"575526359","text":"from xml.etree import ElementTree as ET\nimport unittest\n\ndef clean(s):\n return s.strip()\n\nclass CFentry:\n def __init__(self,elem):\n ''' Take an element tree element from the cf-standard-name table and resolve to a python object '''\n self.name=elem.attrib['id']\n self.units=clean(elem.find('canonical_units').text or '')\n self.description=clean(elem.find('description').text or '')\n \nclass CFtable:\n ''' Provide the cf standard names vocabulary '''\n def __init__(self,path):\n ''' Currently instantiate the vocabulary from a file '''\n et=ET.parse(path)\n root=et.getroot()\n entries=root.findall('entry')\n self.names=[]\n self.version=clean(root.find('version_number').text)\n for entry in entries:\n cfe=CFentry(entry)\n self.names.append(cfe)\n \nclass TestFunctions(unittest.TestCase):\n def testCF(self):\n import os\n d='vocabs'\n p=os.path.join('apps', d,'cf-standard-name-table.xml')\n cf=CFtable(p)\n\n","sub_path":"pimms_apps/qn/vocabs/cf.py","file_name":"cf.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"424699591","text":"# standard imports\nfrom contextlib import contextmanager\n\ntry:\n from urllib2 import urlopen\nexcept ImportError:\n # Python3\n from urllib.request import urlopen\n\ntry:\n import urlparse\nexcept ImportError:\n # Python3\n from urllib.parse import urlparse\n\nimport copy\nimport os\nimport bisect\nfrom fnmatch import fnmatch\nimport shutil\nimport sys\nimport tempfile\nimport time\n# third-party imports\nimport createrepo_c as createrepo\nimport dnf, libdnf, rpm\nimport six\nimport yumsync.util as util\nimport logging\n\nfrom yumsync import progress\n\nfrom threading import Lock\n\nclass MetadataBuildError(Exception):\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n\nclass PackageDownloadError(Exception):\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n\nclass YumRepo(object):\n\n def __init__(self, repoid, base_dir, opts=None):\n # make sure good defaults\n if opts is None:\n opts = {}\n opts = self._set_default_opts(opts)\n self._validate_opts(opts)\n self._validate_type(base_dir, 'base_dir', str)\n\n self.id = repoid\n self.checksum = opts['checksum']\n self.combine = opts['combined_metadata'] if opts['version'] else None\n self.delete = opts['delete']\n self.gpgkey = opts['gpgkey']\n self.link_type = opts['link_type']\n self.local_dir = opts['local_dir']\n self.baseurl = opts['baseurl']\n self.mirrorlist = opts['mirrorlist']\n self.incl_pkgs = opts['includepkgs']\n self.excl_pkgs = opts['excludepkgs']\n self.stable = opts['stable']\n self.version = time.strftime(opts['version']) if opts['version'] else None\n self.srcpkgs = opts['srcpkgs']\n self.newestonly = opts['newestonly']\n self.labels = opts['labels']\n self._dnfcache_file = util.TemporaryDirectory(prefix='yumsync-', suffix='-dnfcache')\n self._dnfcache = self._dnfcache_file.name\n\n # root directory for repo and packages\n self.dir = os.path.join(base_dir, self._friendly(self.id))\n self.package_dir = os.path.join(self.dir, 'packages')\n # version directory for repo and packages\n self.version_dir = os.path.join(self.dir, self.version) if self.version else None\n self.version_package_dir = os.path.join(self.version_dir, 'packages') if self.version_dir else None\n # log directory for repo\n self.log_dir = self.version_dir if self.version_dir else self.dir\n # public directroy for repo\n self.public_dir = os.path.join(base_dir, 'public', self._sanitize(self.id))\n\n # set default callbacks\n self.__repo_callback_obj = None\n self.__yum_callback_obj = None\n\n # set repo placeholders\n self._packages = []\n self._package_headers = {}\n self._comps = None\n self._repomd = None\n\n def setup(self):\n # set actual repo object\n self.__repo_obj = self._get_repo_obj(self.id, self.local_dir, self.baseurl, self.mirrorlist)\n self.__repo_obj.includepkgs = self.incl_pkgs\n self.__repo_obj.excludepkgs = self.excl_pkgs\n\n @staticmethod\n def _validate_type(obj, obj_name, *obj_types):\n valid_types = list(obj_types)\n if obj_name is None:\n obj_name = 'object'\n if len(valid_types) < 1:\n raise ValueError('no valid types were passed in for {}'.format(obj_name))\n if None in obj_types:\n valid_types.remove(None)\n valid_types.append(type(None))\n if not isinstance(obj, tuple(valid_types)):\n valid_str = ', '.join([t.__name__ for t in valid_types])\n raise TypeError('{} is {}; must be {}'.format(obj_name, type(obj).__name__, valid_str))\n\n @staticmethod\n def _validate_url(url):\n if not (url.startswith('http://') or url.startswith('https://') or url.startswith('file://')):\n raise ValueError('Unsupported URL format \"{}\"'.format(url))\n\n @staticmethod\n def _set_default_opts(opts=None):\n if not isinstance(opts, dict):\n opts = {}\n if 'baseurl' not in opts:\n opts['baseurl'] = None\n if 'checksum' not in opts:\n opts['checksum'] = None\n if 'combined_metadata' not in opts:\n opts['combined_metadata'] = None\n if 'delete' not in opts:\n opts['delete'] = None\n if 'excludepkgs' not in opts:\n opts['excludepkgs'] = None\n if 'gpgkey' not in opts:\n opts['gpgkey'] = None\n if 'includepkgs' not in opts:\n opts['includepkgs'] = None\n if 'link_type' in opts and isinstance(opts['link_type'], str):\n opts['link_type'] = opts['link_type'].lower()\n if 'link_type' not in opts or (opts['link_type'] != 'symlink' and opts['link_type'] != 'hardlink' and opts['link_type'] != 'individual_symlink'):\n opts['link_type'] = 'symlink'\n if 'local_dir' not in opts:\n opts['local_dir'] = None\n if 'mirrorlist' not in opts:\n opts['mirrorlist'] = None\n if 'stable' not in opts:\n opts['stable'] = None\n if not isinstance(opts['stable'], str) and opts['stable'] is not None:\n opts['stable'] = str(opts['stable'])\n if 'version' not in opts:\n opts['version'] = '%Y/%m/%d'\n if 'srcpkgs' not in opts:\n opts['srcpkgs'] = None\n if 'newestonly' not in opts:\n opts['newestonly'] = None\n if 'labels' not in opts:\n opts['labels'] = {}\n return opts\n\n @classmethod\n def _validate_opts(cls, opts):\n cls._validate_type(opts['baseurl'], 'baseurl', str, None)\n if isinstance(opts['baseurl'], str):\n cls._validate_url(opts['baseurl'])\n cls._validate_type(opts['checksum'], 'checksum', str, None)\n cls._validate_type(opts['combined_metadata'], 'combined_metadata', bool, None)\n cls._validate_type(opts['delete'], 'delete', bool, None)\n cls._validate_type(opts['excludepkgs'], 'excludepkgs', str, list, None)\n if isinstance(opts['excludepkgs'], list):\n for e in opts['excludepkgs']:\n cls._validate_type(e, 'excludepkgs (in list)', str)\n cls._validate_type(opts['gpgkey'], 'gpgkey', str, list, None)\n if isinstance(opts['gpgkey'], list):\n for g in opts['gpgkey']:\n cls._validate_type(g, 'gpgkey (in list)', str)\n cls._validate_url(g)\n elif opts['gpgkey'] is str:\n cls._validate_url(opts['gpgkey'])\n cls._validate_type(opts['includepkgs'], 'includepkgs', str, list, None)\n if isinstance(opts['includepkgs'], list):\n for i in opts['includepkgs']:\n cls._validate_type(i, 'includepkgs (in list)', str)\n cls._validate_type(opts['link_type'], 'link_type', str)\n cls._validate_type(opts['local_dir'], 'local_dir', str, list, None)\n cls._validate_type(opts['mirrorlist'], 'mirrorlist', str, None)\n if opts['mirrorlist'] is not None:\n cls._validate_url(opts['mirrorlist'])\n cls._validate_type(opts['stable'], 'stable', str, None)\n cls._validate_type(opts['version'], 'version', str, None)\n cls._validate_type(opts['srcpkgs'], 'srcpkgs', bool, None)\n cls._validate_type(opts['newestonly'], 'newestonly', bool, None)\n cls._validate_type(opts['labels'], 'labels', dict)\n for label, value in six.iteritems(opts['labels']):\n cls._validate_type(label, 'label_name_{}'.format(label), str)\n cls._validate_type(value, 'label_value_{}'.format(label), str)\n\n @staticmethod\n def _sanitize(text):\n return text.strip().strip('/')\n\n @classmethod\n def _friendly(cls, text):\n return cls._sanitize(text).replace('/', '_')\n\n def _get_repo_obj(self, repoid, localdir=None, baseurl=None, mirrorlist=None):\n base = dnf.Base()\n base.conf.cachedir = self._dnfcache\n base.conf.debuglevel = 0\n base.conf.errorlevel = 3\n repo = dnf.repo.Repo(repoid.replace('/', '_'), base.conf)\n repo.baseurl = None\n repo.metalink = None\n repo.mirrorlist = None\n repo.module_hotfixes = True\n\n if baseurl is not None:\n repo.baseurl = baseurl\n elif mirrorlist is not None:\n repo.mirrorlist = mirrorlist\n elif (localdir, baseurl, mirrorlist) is (None, None, None):\n raise ValueError('One or more baseurls, mirrorlist or localdir required')\n repo.enable()\n return repo\n\n def set_repo_callback(self, callback):\n self.__repo_callback_obj = callback\n\n def set_yum_callback(self, callback):\n self.__yum_callback_obj = callback\n\n def _set_path(self, path):\n repo = copy.copy(self.__repo_obj)\n try:\n repo.pkgdir = path\n except dnf.RepoError:\n pass\n return repo\n\n def setup_directories(self):\n if self.local_dir and self.link_type == 'symlink':\n if not os.path.islink(self.package_dir) and os.path.isdir(self.package_dir):\n shutil.rmtree(self.package_dir)\n\n assert isinstance(self.local_dir, (list, str))\n if isinstance(self.local_dir, list):\n for idx, local_dir in enumerate(self.local_dir):\n subdir = os.path.join(self.package_dir, \"repo_{}\".format(idx))\n util.symlink(subdir, local_dir)\n elif isinstance(self.local_dir, str):\n util.symlink(self.package_dir, self.local_dir)\n else:\n if os.path.islink(self.package_dir):\n os.unlink(self.package_dir)\n util.make_dir(self.package_dir)\n\n if self.version_dir:\n if os.path.islink(self.version_package_dir) or os.path.isfile(self.version_package_dir):\n os.unlink(self.version_package_dir)\n elif os.path.isdir(self.version_package_dir):\n shutil.rmtree(self.version_package_dir)\n if self.link_type == 'symlink':\n util.symlink(self.version_package_dir, os.path.relpath(self.package_dir, self.version_dir))\n elif self.link_type == 'individual_symlink':\n util.make_dir(self.version_package_dir)\n if isinstance(self.local_dir, list):\n dirs = self.local_dir\n single = False\n elif isinstance(self.local_dir, str):\n dirs = [self.local_dir]\n single = True\n for idx, _dir in enumerate(dirs):\n pkg_dir = self.version_package_dir\n if not single:\n pkg_dir = os.path.join(self.version_package_dir, \"repo_{}\".format(idx))\n util.make_dir(os.path.join(pkg_dir))\n for _file in self._find_rpms(_dir):\n util.symlink(os.path.join(pkg_dir, _file), os.path.join(_dir, _file))\n else: # hardlink\n util.make_dir(self.version_package_dir)\n\n def download_gpgkey(self):\n if self.gpgkey:\n gpgkey_paths = []\n if isinstance(self.gpgkey, list):\n gpgkey_iter = self.gpgkey\n else:\n gpgkey_iter = [self.gpgkey]\n for gpgkey in gpgkey_iter:\n try:\n keyname = os.path.basename(urlparse(gpgkey).path)\n key_path = os.path.join(self.dir, keyname)\n if not os.path.exists(key_path):\n key_data = urlopen(gpgkey)\n with open(key_path, 'w') as f:\n f.write(key_data.read())\n key_data.close()\n self._callback('gpgkey_download', os.path.basename(key_path))\n else:\n self._callback('gpgkey_exists', os.path.basename(key_path))\n gpgkey_paths.append(key_path)\n except Exception as e:\n self._callback('gpgkey_error', str(e))\n return gpgkey_paths\n return None\n\n def prepare_packages(self):\n self.download_packages()\n self.prune_packages()\n self.version_packages()\n\n def download_packages(self):\n if self.local_dir:\n self._download_local_packages()\n else:\n self._download_remote_packages()\n\n def _validate_packages(self, directory, packages):\n if hasattr(rpm, \"RPMVSF_MASK_NOSIGNATURES\"):\n no_signature_check_mask = rpm.RPMVSF_MASK_NOSIGNATURES\n else:\n no_signature_check_mask = rpm.RPMVSF_NODSAHEADER | rpm.RPMVSF_NORSAHEADER | rpm.RPMVSF_NODSA | rpm.RPMVSF_NORSA\n ts = rpm.TransactionSet(\"/\", no_signature_check_mask)\n if isinstance(packages, str):\n self._callback('pkg_exists', packages)\n package, hdr = self._validate_package(ts, directory, packages)\n if hdr:\n return package, hdr\n return package, None\n elif isinstance(packages, list):\n valid = []\n for pkg in packages:\n package, hdr = self._validate_package(ts, directory, pkg)\n if hdr:\n valid.append((package, hdr))\n self._callback('pkg_exists', pkg)\n return valid\n else:\n return None\n\n @staticmethod\n def _validate_package(ts, directory, package):\n try:\n pkg_path = os.path.join(directory, package)\n with open(pkg_path, 'rb') as pkg:\n return package, ts.hdrFromFdno(pkg)\n except:\n return package, None\n\n def _find_rpms(self, local_dir):\n matches = []\n progress_counter = 0\n include_globs = []\n exclude_globs = []\n\n if self.__repo_obj.includepkgs is not None:\n if isinstance(self.__repo_obj.includepkgs, list) or isinstance(self.__repo_obj.includepkgs, libdnf.module.VectorString):\n include_globs = self.__repo_obj.includepkgs\n elif isinstance(self.__repo_obj.includepkgs, str):\n include_globs = [self.__repo_obj.includepkgs]\n if self.__repo_obj.excludepkgs is not None:\n if isinstance(self.__repo_obj.excludepkgs, list) or isinstance(self.__repo_obj.excludepkgs, libdnf.module.VectorString):\n exclude_globs = self.__repo_obj.excludepkgs\n elif isinstance(self.__repo_obj.excludepkgs, str):\n exclude_globs = [self.__repo_obj.excludepkgs]\n\n for root, dirnames, filenames in os.walk(local_dir, topdown=False, followlinks=True):\n for filename in filenames:\n if not filename.endswith('.rpm'):\n continue\n skip = False\n keep = True\n for glob in exclude_globs:\n if fnmatch(filename, glob):\n skip = True\n break\n if skip:\n continue\n for glob in include_globs:\n if fnmatch(filename, glob):\n keep = True\n break\n else:\n keep = False\n if not keep:\n continue\n bisect.insort(matches, os.path.relpath(os.path.join(root, filename), local_dir))\n\n return matches\n\n def _download_local_packages(self):\n try:\n packages = {}\n nb_packages = 0\n self._callback('repo_init', nb_packages, True)\n if isinstance(self.local_dir, str):\n files = self._find_rpms(self.local_dir)\n packages = {(None, self.local_dir): self._validate_packages(self.local_dir, files)}\n nb_packages += len(packages[(None, self.local_dir)])\n elif isinstance(self.local_dir, list):\n packages = {}\n files = {}\n for idx, local_dir in enumerate(self.local_dir):\n files[(idx, local_dir)] = self._find_rpms(local_dir)\n nb_packages += len(files[(idx,local_dir)])\n self._callback('repo_init', nb_packages, True)\n for local_dir_idx, rpm_files in six.iteritems(files):\n packages[local_dir_idx] = self._validate_packages(local_dir_idx[1], rpm_files)\n self._callback('repo_init', nb_packages, True)\n\n for _dir, _files in six.iteritems(packages):\n for _file, _hdr in _files:\n if _dir[0] is not None and isinstance(_dir[0], int):\n package_dir = os.path.join(self.package_dir, \"repo_{}\".format(_dir[0]))\n file_path = os.path.join(\"repo_{}\".format(_dir[0]), _file)\n else:\n package_dir = self.package_dir\n file_path = _file\n self._packages.append(file_path)\n self._package_headers[file_path] = _hdr\n if self.link_type == 'hardlink':\n status = util.hardlink(os.path.join(_dir[1], _file), os.path.join(package_dir, _file))\n if status:\n size = os.path.getsize(os.path.join(_dir[1], _file))\n self._callback('link_local_pkg', _file, size)\n\n self._callback('repo_complete')\n except (KeyboardInterrupt, SystemExit):\n pass\n except Exception as e:\n self._callback('repo_error', str(e))\n raise PackageDownloadError(str(e))\n\n def _download_remote_packages(self):\n self._callback('repo_init', 0, True)\n yb = dnf.Base()\n yb.conf.cachedir = self._dnfcache\n yb.conf.debuglevel = 0\n yb.conf.errorlevel = 3\n repo = self._set_path(self.package_dir)\n yb.repos.add(repo)\n yb.fill_sack()\n p_query = yb.sack.query().available()\n if self.newestonly:\n p_query = p_query.latest()\n packages = list(p_query)\n # Inform about number of packages total in the repo.\n # Check if the packages are already downloaded. This is probably a bit\n # expensive, but the alternative is simply not knowing, which is\n # horrible for progress indication.\n if packages:\n self._callback('repo_init', len(packages), True)\n for po in packages:\n local = po.localPkg()\n self._packages.append(os.path.basename(local))\n if os.path.exists(local):\n self._callback('pkg_exists', os.path.basename(local))\n try:\n yb.download_packages(packages, progress=progress.DownloadProgress(self._callback))\n except (KeyboardInterrupt, SystemExit):\n return\n except dnf.exceptions.DownloadError as e:\n self._callback('repo_error', str(e))\n except Exception as e:\n self._callback('repo_error', str(e))\n raise PackageDownloadError(str(e))\n self._callback('repo_complete')\n\n def deduplicate_rpm(self):\n nevra_index = set()\n print(len(self._packages))\n for pkg_path, pkg_header in six.iteritems(self._package_headers):\n if pkg_header is not None:\n nevra = \"{}-{}-{}-{}.{}\".format(\n pkg_header['name'],\n pkg_header['epoch'],\n pkg_header['version'],\n pkg_header['release'],\n pkg_header['arch'])\n if nevra in nevra_index:\n self._packages.remove(pkg_path)\n else:\n nevra_index.add(nevra)\n\n def prune_packages(self):\n # exit if we don't have packages\n if not self._packages or len(self._packages) == 0:\n return\n packages_filenames = list(map(lambda x: os.path.basename(x), self._packages))\n unique_filenames = set(packages_filenames)\n if len(unique_filenames) != len(packages_filenames):\n # Some RPMs have the same names, prune them\n self.deduplicate_rpm()\n\n if self.delete:\n if not self.version or (self.link_type != 'symlink' and self.link_type != 'individual_symlink'):\n for _file in os.listdir(self.package_dir):\n if _file not in self._packages:\n os.unlink(os.path.join(self.package_dir, _file))\n self._callback('delete_pkg', _file)\n else:\n packages_to_validate = sorted(list(set(os.listdir(self.package_dir)) - set(self._packages)))\n self._packages.extend(self._validate_packages(self.package_dir, packages_to_validate))\n\n def version_packages(self):\n # exit if we don't have packages\n if not self._packages or len(self._packages) == 0:\n return\n if self.version and self.link_type == 'hardlink':\n for pkg in self._packages:\n source_file = os.path.join(self.package_dir, pkg)\n target_file = os.path.join(self.version_package_dir, pkg)\n util.hardlink(source_file, target_file)\n\n def get_md_data(self):\n if self.local_dir:\n # If it's a local_dir, don't bother merging metadata.\n # Only pick the first available metadata (if any)\n self._repomd = {\n (\"modules\", \"modules.yaml\"): \"\",\n (\"group\", \"comps.xml\"): \"\",\n }\n repomds = []\n if isinstance(self.local_dir, str):\n repo_dirs = [ self.local_dir ]\n elif isinstance(self.local_dir, list):\n repo_dirs = [ l for l in self.local_dir ]\n for repo_dir in repo_dirs:\n if not os.path.exists(os.path.join(repo_dir, 'repodata')):\n continue\n yb = dnf.Base()\n yb.conf.cachedir = self._dnfcache\n yb.conf.debuglevel = 0\n yb.conf.errorlevel = 3\n repo = dnf.repo.Repo(\"yumsync_temp_md_repo\", dnf.Base().conf)\n repo.metalink = None\n repo.mirrorlist = None\n repo.baseurl = \"file://{}\".format(repo_dir)\n yb.repos.add(repo)\n yb.fill_sack()\n repomds.append({\n (\"modules\", \"modules.yaml\"): repo.get_metadata_content('modules'),\n (\"group\", \"comps.xml\"): repo.get_metadata_content('group_gz'),\n })\n # Combine modular MD of each repo\n # Only keep the first \"comps\" we find\n for repomd in repomds:\n self._repomd[(\"modules\", \"modules.yaml\")] += repomd.get((\"modules\", \"modules.yaml\"), \"\")\n if self._repomd.get((\"group\", \"comps.xml\"), \"\") == \"\":\n self._repomd[(\"group\", \"comps.xml\")] = repomd.get((\"group\", \"comps.xml\"), \"\")\n else:\n self._repomd = {\n (\"modules\", \"modules.yaml\"): self.__repo_obj.get_metadata_content('modules'),\n (\"group\", \"comps.xml\"): self.__repo_obj.get_metadata_content('group_gz'),\n }\n\n if self._repomd:\n # Filter out empty metadata\n for k, v in six.iteritems(self._repomd.copy()):\n if len(v) != 0:\n continue\n self._repomd.pop(k)\n self._callback('repo_group_data', 'available')\n else:\n self._callback('repo_group_data', 'unavailable')\n\n def build_metadata(self):\n staging = tempfile.mkdtemp(prefix='yumsync-', suffix='-metadata')\n\n if self.checksum == 'sha' or self.checksum == 'sha1':\n sumtype = 'sha'\n else:\n sumtype = 'sha256'\n\n repodata_path = os.path.join(staging, 'repodata')\n os.mkdir(repodata_path)\n\n # Prepare metadata files\n repomd_path = os.path.join(repodata_path, \"repomd.xml\")\n pri_xml_path = os.path.join(repodata_path, \"primary.xml.gz\")\n fil_xml_path = os.path.join(repodata_path, \"filelists.xml.gz\")\n oth_xml_path = os.path.join(repodata_path, \"other.xml.gz\")\n pri_db_path = os.path.join(repodata_path, \"primary.sqlite\")\n fil_db_path = os.path.join(repodata_path, \"filelists.sqlite\")\n oth_db_path = os.path.join(repodata_path, \"other.sqlite\")\n\n # Related python objects\n pri_xml = createrepo.PrimaryXmlFile(pri_xml_path)\n fil_xml = createrepo.FilelistsXmlFile(fil_xml_path)\n oth_xml = createrepo.OtherXmlFile(oth_xml_path)\n pri_db = createrepo.PrimarySqlite(pri_db_path)\n fil_db = createrepo.FilelistsSqlite(fil_db_path)\n oth_db = createrepo.OtherSqlite(oth_db_path)\n\n # Set package list\n if self.local_dir and self.link_type == \"individual_symlink\" and self.version_dir:\n pkg_list = [\n (\n os.path.join(self.version_package_dir,\"{}\".format(pkg)),\n os.path.join(\"packages\",\"{}\".format(pkg))\n ) for pkg in self._packages]\n else:\n pkg_list = [\n (\n os.path.join(self.package_dir,\"{}\".format(pkg)),\n os.path.join(\"packages\",\"{}\".format(pkg))\n )for pkg in self._packages]\n\n pri_xml.set_num_of_pkgs(len(pkg_list))\n fil_xml.set_num_of_pkgs(len(pkg_list))\n oth_xml.set_num_of_pkgs(len(pkg_list))\n\n # Process all packages in // if possible\n self.metadata_progress = 0\n self.total_pkgs = len(pkg_list)\n metadata_mutex = Lock()\n\n def collect_result(future):\n self.metadata_progress += 1\n self._callback('repo_metadata', int((self.metadata_progress+1)*100//self.total_pkgs))\n\n def process_pkg(filename, href):\n pkg = createrepo.package_from_rpm(filename)\n pkg.location_href = href\n return pkg\n\n try:\n from concurrent.futures import ThreadPoolExecutor\n parallelize = True\n except:\n parallelize = False\n\n if parallelize:\n with ThreadPoolExecutor(max_workers=self._workers) as executor:\n futures = []\n for filename in pkg_list:\n future = executor.submit(process_pkg, filename[0], filename[1])\n future.add_done_callback(collect_result)\n futures.append(future)\n for future in futures:\n try:\n pkg = future.result(10)\n except Exception as exc:\n logging.exception(\"Thread generated an exception\")\n else:\n pri_xml.add_pkg(pkg)\n fil_xml.add_pkg(pkg)\n oth_xml.add_pkg(pkg)\n pri_db.add_pkg(pkg)\n fil_db.add_pkg(pkg)\n oth_db.add_pkg(pkg)\n else:\n for idx, filename in enumerate(pkg_list):\n process_pkg(filename[0], filename[1])\n collect_result(None)\n\n pri_xml.close()\n fil_xml.close()\n oth_xml.close()\n\n # Note: DBs are still open! We have to calculate checksums of xml files\n # and insert them to the databases first!\n\n self._callback('repo_metadata', 'building')\n # Prepare repomd.xml\n repomd = createrepo.Repomd()\n\n # Order is important !\n repomdrecords = ((\"primary\", pri_xml_path, pri_db, False),\n (\"filelists\", fil_xml_path, fil_db, False),\n (\"other\", oth_xml_path, oth_db, False),\n (\"primary_db\", pri_db_path, None, True),\n (\"filelists_db\", fil_db_path, None, True),\n (\"other_db\", oth_db_path, None, True))\n\n for name, path, db_to_update, compress in repomdrecords:\n record = createrepo.RepomdRecord(name, path)\n if compress:\n record.compress_and_fill(createrepo.SHA256, createrepo.XZ_COMPRESSION)\n else:\n record.fill(createrepo.SHA256)\n\n if (db_to_update):\n db_to_update.dbinfo_update(record.checksum)\n db_to_update.close()\n\n repomd.set_record(record)\n\n if self._repomd:\n for md_type, md_content in six.iteritems(self._repomd):\n md_file = os.path.join(repodata_path, md_type[1])\n with open(md_file, 'w') as f:\n f.write(md_content)\n record = createrepo.RepomdRecord(md_type[0], md_file)\n record.fill(createrepo.SHA256)\n repomd.set_record(record)\n\n open(repomd_path, \"w\").write(repomd.xml_dump())\n\n return staging\n\n def build_file_list(self):\n if os.path.exists(os.path.join(self.log_dir, 'filelist')):\n os.unlink(os.path.join(self.log_dir, 'filelist'))\n with open(os.path.join(self.log_dir, 'filelist'), 'w') as f:\n for pkg in self._packages:\n f.write('packages/{}\\n'.format(pkg))\n\n\n def prepare_metadata(self):\n self.get_md_data()\n self._callback('repo_metadata', 'building')\n\n try:\n self.build_file_list()\n staging = self.build_metadata()\n except Exception as e:\n self._callback('repo_error', str(e))\n raise MetadataBuildError(str(e))\n\n repodata_dir = os.path.join(self.dir, 'repodata')\n if os.path.exists(repodata_dir):\n shutil.rmtree(repodata_dir)\n if not self.version or self.combine:\n shutil.copytree(os.path.join(staging, 'repodata'), repodata_dir)\n\n if self.version:\n repodata_dir = os.path.join(self.version_dir, 'repodata')\n if os.path.exists(repodata_dir):\n shutil.rmtree(repodata_dir)\n shutil.copytree(os.path.join(staging, 'repodata'), repodata_dir)\n\n # cleanup temporary metadata\n shutil.rmtree(staging)\n\n self._callback('repo_metadata', 'complete')\n\n def create_links(self):\n if self.version:\n util.symlink(os.path.join(self.dir, 'latest'), self.version)\n self._callback('repo_link_set', 'latest', self.version)\n if self.stable:\n util.symlink(os.path.join(self.dir, 'stable'), self.stable)\n self._callback('repo_link_set', 'stable', self.stable)\n elif os.path.lexists(os.path.join(self.dir, 'stable')):\n os.unlink(os.path.join(self.dir, 'stable'))\n for label, version in six.iteritems(self.labels):\n util.symlink(os.path.join(self.dir, label), version)\n self._callback('repo_link_set', label, version)\n\n else:\n if os.path.lexists(os.path.join(self.dir, 'latest')):\n os.unlink(os.path.join(self.dir, 'latest'))\n if os.path.lexists(os.path.join(self.dir, 'stable')):\n os.unlink(os.path.join(self.dir, 'stable'))\n\n def sync(self, workers=1):\n self.setup()\n self._workers = workers\n try:\n self.setup_directories()\n self.download_gpgkey()\n self.prepare_packages()\n self.prepare_metadata()\n self.create_links()\n except MetadataBuildError:\n self._callback('repo_error', 'MetadataBuildError')\n return False\n except PackageDownloadError:\n self._callback('repo_error', 'PackageDownloadError')\n return False\n\n def __str__(self):\n raw_info = {}\n if self.checksum:\n raw_info['checksum'] = self.checksum\n if self.combine is not None:\n raw_info['combine'] = self.combine\n if self.delete is not None:\n raw_info['delete'] = self.delete\n if self.gpgkey:\n raw_info['gpgkey'] = self.gpgkey\n if self.link_type:\n raw_info['link_type'] = self.link_type\n if self.local_dir:\n raw_info['local_dir'] = str(self.local_dir)\n if self.stable:\n raw_info['stable'] = self.stable\n if self.version:\n raw_info['version'] = self.version\n if self.srcpkgs is not None:\n raw_info['srcpkgs'] = self.srcpkgs\n if self.newestonly is not None:\n raw_info['newestonly'] = self.newestonly\n if self.labels is not []:\n raw_info['labels'] = str(self.labels)\n friendly_info = ['{}({})'.format(k, raw_info[k]) for k in sorted(raw_info)]\n return '{}: {}'.format(self.id, ', '.join(friendly_info))\n\n def _callback(self, event, *args):\n logging.debug(\"{}: Send event {} with args {}\".format(type(self), event, args))\n if self.__repo_callback_obj and hasattr(self.__repo_callback_obj, event):\n method = getattr(self.__repo_callback_obj, event)\n method(self.id, *args)\n","sub_path":"yumsync/yumrepo.py","file_name":"yumrepo.py","file_ext":"py","file_size_in_byte":33298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"634191026","text":"from rest_framework import routers\nfrom .api import ProjectViewSet, SprintViewSet, TaskViewSet, \\\n ActiveSprintList, DocumentViewSet, CommentViewSet, DiscussionViewSet, \\\n NoteViewSet, TopDiscussionList, ProblemViewSet, TaskCacheViewSet, UserTaskList\nfrom django.urls import path, include\n\n# https://www.django-rest-framework.org/api-guide/routers/\nrouter = routers.DefaultRouter()\nrouter.register('projects', ProjectViewSet, 'projects')\nrouter.register('sprints', SprintViewSet, 'sprints')\nrouter.register('tasks', TaskViewSet, 'tasks')\n#router.register('documents', DocumentViewSet, 'documents')\nrouter.register('discussions', DiscussionViewSet, 'discussions')\nrouter.register('comments', CommentViewSet, 'comments')\nrouter.register('notes', NoteViewSet, 'notes')\nrouter.register('problems', ProblemViewSet, 'problems')\n\nurlpatterns = [\n path('activeSprints/', ActiveSprintList.as_view()),\n path('topDiscussion/', TopDiscussionList.as_view()),\n path('userTasks/', UserTaskList.as_view()),\n # path('cacheTask/', TaskCacheViewSet.as_view({'get': 'list'})),\n]\n\nurlpatterns += router.urls\n","sub_path":"projectManagement/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"566853945","text":"from botocore import serialize\n\n\n# handles both Hoge.1 / Hoges.member.1 parameter according to locationName\nclass ComputingSerializer(serialize.EC2Serializer):\n\n def serialize_to_request(self, parameters, operation_model):\n serialized = super(ComputingSerializer, self).serialize_to_request(\n parameters, operation_model\n )\n serialized['url_path'] = operation_model.http.get('requestUri', '/')\n # Fix request parameters of DescribeLoadBalancers for NIFCLOUD\n if operation_model.name == 'DescribeLoadBalancers':\n serialized[\"body\"] = self._fix_describe_load_balancers_params(\n parameters, operation_model.metadata['apiVersion']\n )\n return serialized\n\n def _fix_describe_load_balancers_params(self, params, api_version):\n prefix = 'LoadBalancerNames'\n body = {\n \"Action\": \"DescribeLoadBalancers\",\n \"Version\": api_version\n }\n if not params.get(prefix):\n return body\n for i, param in enumerate(params[prefix], 1):\n body['%s.member.%d' % (prefix, i)] = param['LoadBalancerName']\n body['%s.LoadBalancerPort.%d' % (prefix, i)] = param['LoadBalancerPort'] # noqa: E501\n body['%s.InstancePort.%d' % (prefix, i)] = param['InstancePort']\n return body\n\n def _serialize_type_list(self, serialized, value, shape, prefix=''):\n # 'locationName' is renamed to 'name'\n # https://github.com/boto/botocore/blob/cccfdf86bc64877ad41e0af74b752b8a49fc4d33/botocore/model.py#L118\n if shape.member.serialization.get('name'):\n serializer = serialize.QuerySerializer()\n else:\n serializer = super(ComputingSerializer, self)\n serializer._serialize_type_list(serialized, value, shape, prefix)\n\n\nclass ScriptSerializer(serialize.QuerySerializer):\n def serialize_to_request(self, parameters, operation_model):\n serialized = super(ScriptSerializer, self).serialize_to_request(\n parameters, operation_model\n )\n target = '%s.%s' % (operation_model.metadata['targetPrefix'],\n operation_model.name)\n serialized['headers']['X-Amz-Target'] = target\n serialized['url_path'] = operation_model.http.get('requestUri', '/')\n del serialized['body']['Action']\n del serialized['body']['Version']\n return serialized\n\n\nserialize.SERIALIZERS.update({\n 'computing': ComputingSerializer,\n 'script': ScriptSerializer\n})\n","sub_path":"nifcloud/serialize.py","file_name":"serialize.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"519021517","text":"import os, sys\nfrom os.path import isfile, isdir, join\n\nfrom useless.base.util import makepaths\n\nfrom paella.debian.dpkgdeb import DpkgDeb\nfrom paella.profile.base import PaellaConfig\n\ndef unpack_kernel(kernel, target):\n isolinux_dir = join(target, 'isolinux')\n dp = DpkgDeb()\n tmp = join(target, 'tmp')\n if isdir(tmp):\n os.system('rm %s -fr' % tmp)\n makepaths(tmp)\n os.system('dpkg-deb -x %s %s' % (kernel, tmp))\n os.system('cp %s/boot/vmlinuz-* %s/vmlinuz' % (tmp, isolinux_dir))\n os.system('rm %s -fr' % tmp)\n \n \n\ndef setup_directory(target):\n isolinux_dir = join(target, 'isolinux')\n if not isdir(isolinux_dir):\n makepaths(isolinux_dir)\n if not isfile(join(isolinux_dir, 'isolinux.bin')):\n os.system('cp /usr/lib/syslinux/isolinux.bin %s' % isolinux_dir)\n\ndef isolinuxcfg(target):\n isolinux_dir = join(target, 'isolinux')\n lines = ['DEFAULT paella-install',\n 'APPEND ip=dhcp root=/dev/nfs netdev=probe devfs=nomount',\n 'LABEL paella-install',\n 'KERNEL vmlinuz']\n filedata = '\\n'.join(lines) + '\\n'\n cfpath = join(isolinux_dir, 'isolinux.cfg')\n cffile = file(cfpath, 'w')\n cffile.write(filedata)\n cffile.close()\n\n\ndef make_image(target='/tmp/isotarget', kernel='kernel-image-2.6.2installer'):\n cfg = PaellaConfig()\n kpath = '/mirrors/debian/local/questron'\n setup_directory(target)\n isolinuxcfg(target)\n unpack_kernel(kernel, target)\n os.system('mkisofs -V \"paella-nfsboot\" -r -pad -b isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table -o nfsboot.iso %s' % target)\n os.system('rm %s -fr' % target)\n \nif __name__ == '__main__':\n cfg = PaellaConfig()\n kernel = sys.argv[1]\n make_image(kernel=kernel)\n","sub_path":"branches/stable/src/paella/installer/nfsbootcd.py","file_name":"nfsbootcd.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"603710015","text":"# 큐\n# https://www.acmicpc.net/problem/10845\n\nimport queue\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n\nclass MyQueue:\n def __init__(self):\n self.head = Node(None)\n self.tail = Node(None)\n self.head.next = self.tail\n self.tail.prev = self.head\n self.size = 0\n\n def isEmpty(self):\n if self.size == 0:\n return True\n return False\n\n def push(self, data):\n newNode = Node(data)\n self.tail.prev.next = newNode\n newNode.prev = self.tail.prev\n newNode.next = self.tail\n self.tail.prev = newNode\n self.size += 1\n\n def pop(self):\n if self.isEmpty():\n return -1\n retData = self.head.next\n self.head.next.next.prev = self.head\n self.head.next = self.head.next.next\n self.size -= 1\n return retData.data\n\n def getSize(self):\n return self.size\n\n def getFront(self):\n if self.isEmpty():\n return -1\n return self.head.next.data\n\n def getBack(self):\n if self.isEmpty():\n return -1\n return self.tail.prev.data\n\ndef solution(orders):\n q = MyQueue()\n\n for ord in orders:\n if len(ord)==2:\n q.push(ord[1])\n elif ord[0] == 'pop':\n print(q.pop())\n elif ord[0] == 'size':\n print(q.getSize())\n elif ord[0] == 'empty':\n if q.isEmpty():\n print(1)\n else:\n print(0)\n elif ord[0] == 'front':\n print(q.getFront())\n elif ord[0] == 'back':\n print(q.getBack())\n\nn = int(input())\norders = []\nfor xxx in range(n):\n orders.append(input().split(' '))\nsolution(orders)\n\n","sub_path":"baekjun/exercise/2020Jan/10845.py","file_name":"10845.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"328140303","text":"'''\ntrain:\npython test_hmm_beam.py wiki.best.model 6 <../../data/wiki-en-test.norm >ans.pos\n../../script/gradepos.pl ../../data/wiki-en-test.pos ans.pos\n'''\n\nfrom collections import defaultdict\nfrom itertools import chain\nfrom sklearn.externals import joblib\nimport sys, os\n\nEPOCH = 20\n\ndef main():\n model_path = sys.argv[1]\n beam = int(sys.argv[2])\n\n w, transition, tags = joblib.load(model_path)\n\n for X in load_test_data(sys.stdin):\n Y = hmm_viterbi(w, X, transition, tags, beam)\n print(*Y)\n\ndef load_test_data(doc):\n for line in doc:\n yield line.strip().split()\n\ndef create_emit(tag, word):\n yield (f'E|{tag}|{word}', 1)\n\ndef create_trans(first_tag, next_tag):\n yield (f'T|{first_tag}|{next_tag}', 1)\n\ndef hmm_viterbi(w, X, transition, possible_tags, beam=2):\n best_score, best_edge = {}, {}\n best_score['0 <s>'] = 0\n best_edge['0 <s>'] = None\n active_tags = [[\"<s>\"]]\n\n for i, x in enumerate(chain(X, ['</s>'])):\n my_best = dict()\n for prev_tag in active_tags[-1]:\n for next_tag in (possible_tags if x != '</s>' else [x]):\n prev_node = f'{i} {prev_tag}'\n next_node = f'{i+1} {next_tag}'\n tag_trans = f'{prev_tag} {next_tag}'\n if prev_node in best_score and tag_trans in transition:\n score = best_score[prev_node]\n for k, v in create_trans(prev_tag, next_tag):\n score += w[k] * v\n for k, v in create_emit(next_tag, x):\n score += w[k] * v\n if next_node not in best_score or best_score[next_node] < score:\n best_score[next_node] = score\n best_edge[next_node] = prev_node\n my_best[next_tag] = score\n *next_active_tags, = map(lambda a:a[0], sorted(my_best.items(), key=lambda a: a[1], reverse=True))\n next_beam = min(len(my_best), beam)\n active_tags.append(next_active_tags[:next_beam])\n \n next_edge = f'{len(X)+1} </s>'\n tags = []\n while next_edge != None:\n idx, tag = next_edge.split(' ')\n tags.append(tag)\n next_edge = best_edge[next_edge]\n \n tags.reverse()\n \n return tags[1:-1] \n\nif __name__ == '__main__':\n main()\n # import cProfile\n # cProfile.run('main()')","sub_path":"tosho/tutorial13/test_hmm_beam.py","file_name":"test_hmm_beam.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"440034211","text":"import os\nimport uuid\nimport json\nimport numpy as np\nfrom django.shortcuts import render\nfrom api.forms import UserForm,UserProfileInfoForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom api.models import Member,Food_Category,Member_Fridge,Recipe\nfrom django.http import JsonResponse\nfrom core.image import (convert_and_save, create_dir_folder, getBase64Str,\n is_base64_image)\n\nfrom yolo.predict import _main_\nfrom django.views.decorators.csrf import csrf_exempt\nimport numpy as np\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.conf import settings\nfrom .face_encoding import detect_faces_in_image\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n####set up parameter####\nmedia_root=settings.MEDIA_ROOT\nconfig_path=settings.BASE_DIR+'/config.json'\nori_dirname=media_root+'/base64/'\nyolo_output_path=media_root+'/yolo/'\n########################\n\n\n\ndef index(request):\n return render(request,'api/index.html')\n@login_required\ndef special(request):\n return HttpResponse(\"You are logged in !\")\n@login_required\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('index'))\n\ndef register(request):\n registered = False\n if request.method == 'POST':\n user_form = UserForm(data=request.POST)\n profile_form = UserProfileInfoForm(data=request.POST)\n if user_form.is_valid() and profile_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n profile = profile_form.save(commit=False)\n profile.user = user\n # if 'image_url' in request.FILES:\n # print('found it')\n profile.image_url = request.FILES.get('image_url')\n profile.save()\n registered = True\n else:\n print(user_form.errors,profile_form.errors)\n else:\n user_form = UserForm()\n profile_form = UserProfileInfoForm()\n return render(request,'api/registration.html',\n {'user_form':user_form,\n 'profile_form':profile_form,\n 'registered':registered})\ndef user_login(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user:\n if user.is_active:\n login(request,user)\n return HttpResponseRedirect(reverse('index'))\n else:\n return HttpResponse(\"Your account was inactive.\")\n else:\n print(\"Someone tried to login and failed.\")\n print(\"They used username: {} and password: {}\".format(username,password))\n return HttpResponse(\"Invalid login details given\")\n else:\n return render(request, 'api/login.html', {})\n@login_required()\ndef detail(request):\n list_detail = Member.objects.filter(user=request.user) # 把資料庫中對應user的資料全部撈出來\n context ={\"list_detail\":list_detail}\n return render(request, 'upload_profile/detail.html', context)\n\n@login_required()\ndef my_account(request):\n account = Member.objects.filter(user_id=request.user.id).first()\n context = {\"account\": account}\n return render(request, 'my_account.html', context)\n\n@login_required()\ndef My_Fridge(request):\n data = Member_Fridge.objects.filter(user=request.user.id)#.values('food_qty')\n jsondata ={}\n food_list = []\n\n for item in data:\n food_list.append({\"id\":item.food_category.id,\"food_name\":item.food_category.food_name,\n \"fridge_predict_img_url\": item.fridge_predict_img_url,\n \"food_qty\":item.food_qty,\"created_at\":item.created_at,\"updated_at\":item.updated_at})\n jsondata['foods']=food_list\n return render(request, 'fridge.html', jsondata)\n\n@login_required()\ndef Recommandation(request):\n data = Member_Fridge.objects.filter(user=request.user.id) # .values('food_qty')\n food_list = []\n mapping={\"milk\":\"牛奶\",\"guava\":\"芭樂\",\"cabbage\":\"高麗菜\"}\n for item in data:\n food_list.append(mapping[item.food_category.food_name])\n data_r = Recipe.objects.all()\n recipe_dict={}\n for item in data_r:\n ingred = item.ingredient_table\n recipe_dict[item.id]=''.join(ingred)\n\n recommand_id = []\n for food in food_list:\n for k,v in recipe_dict.items():\n if food in v:\n recommand_id.append(k)\n recommand_id=list(set(recommand_id))\n recommand=[]\n\n for rid in recommand_id:\n a=Recipe.objects.filter(pk=rid)\n for i in a:\n recommand.append({\"id\":i.id,\"name\":json.loads(json.dumps(i.name)),\"description\":json.loads(json.dumps(i.description))})\n jsondata={}\n jsondata['recommand']=recommand\n return render(request, 'recommand.html', jsondata)\n # return HttpResponse('shit')\ndef Recipe_detail(request,pk):\n data =Recipe.objects.filter(pk=pk)\n jsondata = {}\n recipe_detail = []\n for item in data:\n recipe_detail.append({\"id\":item.id,\"name\":item.name,\n \"description\": item.description,\n \"img_url\":item.img_url,\"cooking_time\":item.cooking_time,\n \"ingredient_table\":json.loads(json.dumps(item.ingredient_table)),\n \"cooking_steps\": json.loads(json.dumps(item.cooking_steps))})\n jsondata['recipe_detail'] = recipe_detail\n return render(request,'recipe_detail.html',jsondata)\n\n\n@api_view(['POST'])\ndef verify_face_recognition(request):\n if request.method == 'POST':\n data = request.data\n\n if is_base64_image(data['file']):\n b64_string = getBase64Str(data['file'])\n else:\n return Response({\"error\": \"base64 image format is not correct\"}, status=status.HTTP_400_BAD_REQUEST)\n\n dirname = 'media/face_recognition/'\n filename = str(uuid.uuid1())\n\n if not os.path.exists(dirname):\n create_dir_folder(dirname)\n\n try:\n members = Member.objects.values(\"slug\", \"user_id\", \"avatar_encoding\")\n except Member.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n # Get face encodings for any faces in the uploaded image\n unknown_face_img = convert_and_save(b64_string, dirname, filename)\n\n known_face_encoding = []\n known_faces = []\n known_face_names = []\n user_ids = []\n\n for member in members:\n known_face_encoding.append(np.array(json.loads(member['avatar_encoding'])))\n known_face_names.append(member['slug'])\n user_ids.append(member['user_id'])\n\n result = detect_faces_in_image(unknown_face_img, known_face_encoding, known_face_names, user_ids)\n\n return Response(result)\n\n\n@api_view(['POST'])\ndef Object_Detection(request):\n if request.method == \"POST\":\n data = request.data\n\n id = int(data['user_id'])\n #save origin base64 and predicted image\n file = data['file']\n if is_base64_image(file):\n b64_string = getBase64Str(file)\n else:\n return JsonResponse({\"error\": \"base64 image format is not correct\"})\n\n if not os.path.exists(ori_dirname):\n create_dir_folder(ori_dirname)\n username = User.objects.get(id=id).username\n img_ori = convert_and_save(b64_string,ori_dirname, username)\n\n label_result, fridge_predict_img_url= _main_(config_path=config_path,input_path=img_ori,output_path=yolo_output_path)\n\n # calculate total inventory of in DB\n inventory = Member_Fridge.objects.all()\n inventories = {}\n for invent in inventory:\n # print(invent.food_category,type(invent.food_category),invent.food_category.id,type(invent.food_category.id))\n food_name = str(invent.food_category)\n if food_name not in inventories.keys():\n inventories[food_name] = int(invent.food_qty)\n else:\n inventories[food_name] += int(invent.food_qty)\n\n # calculate difference between inventories and label_result\n # part1: calculate food \"vanished\"\n diff={}\n for k in inventories.keys():\n if k not in label_result.keys():\n diff[k]=-1*int(inventories[k])\n # food_category = Food_Category.objects.get(food_name=k)\n # Member_Fridge.objects.filter(food_category=food_category,user=id).delete()\n #\n # part2: calculate diff of food still \"existed\"\n for k in label_result.keys():\n if k in inventories.keys():\n diff[k]=label_result[k]-inventories[k]\n else:\n diff[k]=label_result[k]\n # calculate updated inventory of in DB under corresponding \"id\"\n p_inventory = Member_Fridge.objects.filter(user=id)\n p_inventories = {}\n for invent in p_inventory:\n food_name = str(invent.food_category)\n if food_name not in p_inventories.keys():\n p_inventories[food_name] = int(invent.food_qty)\n else:\n p_inventories[food_name] += int(invent.food_qty)\n\n p_updates={}\n for k in diff.keys():\n if k in p_inventories.keys():\n p_updates[k]=diff[k]+p_inventories[k]\n else:\n p_updates[k]=diff[k]\n\n # update new inventory into db_Member_Fridge of under corresponding \"id\"\n for k in p_updates.keys():\n if k in p_inventories.keys():\n food_qty = int(p_updates[k])\n food_category = Food_Category.objects.get(food_name=k)\n user_id = User.objects.get(id=id)\n Member_Fridge_instance = Member_Fridge.objects.get(user=user_id, food_category=food_category)\n Member_Fridge_instance.food_qty = food_qty\n Member_Fridge_instance.save()\n else:\n food_qty = int(p_updates[k])\n food_category = Food_Category.objects.get(food_name=k)\n user_id = User.objects.get(id=id)\n mf = Member_Fridge(user=user_id, food_category=food_category, food_qty=food_qty, fridge_img_url=img_ori,\n fridge_predict_img_url=fridge_predict_img_url, created_at=timezone.now())\n mf.save()\n #response to IOT\n data = Member_Fridge.objects.filter(user=id) # .values('food_qty')\n jsondata = {}\n # user info\n\n jsondata['user'] = {\"id\": id, \"name\":username}\n # food info\n food_list = []\n for item in data:\n food_list.append({\"id\": item.food_category.id, \"food_name\": item.food_category.food_name,\n \"food_qty\": item.food_qty, \"created_at\": item.created_at, \"updated_at\": item.updated_at})\n jsondata['foods'] = food_list\n return JsonResponse(jsondata)\n return HttpResponse(\"It's not POST!!\")","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"284851524","text":"# -*- coding: utf-8 -*-\nimport sys,os\nimport jieba\nimport matplotlib.pyplot as plt\n\n## 打开语气词 词表,保存在yuqi_list里\nf_yuqi = open('biyuci.txt','r')\nyuqi_list = []\n\nfor line in f_yuqi:\n\ta,*_ = line.split('、')\n\tyuqi_list.append(a)\n\n#print(yuqi_list)\n\n## 打开两篇小说,并对特殊词进行清理处理\nraw_content1 = open('yukongchuan.txt',\"r\",encoding=\"utf-8\").read() #打开并读取文件,返回字符串\npunc1 = list(\"。,!”“:‘’……?《》——?\") #建立包含中文符号的列表\nraw_content2 = open('xiyouji.txt',\"r\",encoding=\"utf-8\").read() #打开并读取文件,返回字符串\nj = 0\n\n## 语气词\n\n\nfor i in punc1:#去除字符串中的符号和换行符\n\t#print(i)\n\tif j == 0 :\n\t\tcontent1 = raw_content1.replace(i,'')\n\t\tcontent2 = raw_content2.replace(i,'')\n\t\tcontent1 = content1.strip()\n\t\tcontent2 = content2.strip()\n\telse:\n\t\tcontent1 = content1.replace(i,'')\n\t\tcontent2 = content2.replace(i, '')\n\t\tcontent1 = content1.strip()\n\t\tcontent2 = content2.strip()\n\tj += 1\n\nlens1 = len(content1) # 求小说长度\nlens2 = len(content2)\nprint('《悟空传》有',lens1,'个汉字')\nprint('《西游记》有',lens2,'个汉字')\n\nfor i in yuqi_list:\n\tjieba.add_word(i)\ncontent1_words = list(jieba.cut(content1))#jieba分词\ncontent2_words = list(jieba.cut(content2))\n#print(content1_words)\n\ndic1 = {}\ndic2 = {}\nfor i in yuqi_list:\n\tdic1[i] = dic1.get(i, 0)\n\tdic2[i] = dic2.get(i, 0)\n\nfor i in content1_words:\n\tfor j in yuqi_list:\n\t\tif i.encode('utf-8') == j.encode('utf-8'):\n\t\t\t#print(\"!!!\")\n\t\t\tdic1[i] = dic1.get(i, 0) + 1\n\t\t\tbreak\nfor i in content2_words:\n\tfor j in yuqi_list:\n\t\tif i.encode('utf-8') == j.encode('utf-8'):\n\t\t\t#print(\"!!!\")\n\t\t\tdic2[i] = dic2.get(i, 0) + 1\n\t\t\tbreak\n\nwc1 = list(dic1.items())\nwc1.sort(key=lambda x: x[1], reverse=True)#以出现次数为标准排列,从大到小排序\nwc2 = list(dic2.items())\nwc2.sort(key=lambda x: x[1], reverse=True)#以出现次数为标准排列,从大到小排序\nx1 = []\ny1 = []\nfor i in wc1:\n\tx1.append(i[0])\n\ty1.append(i[1])\n\nprint(x1)\nplt.plot(x1,y1,'r',label = 'biyuci')\nplt.title(\"biyuci frequancy of yukongchuan\")\nplt.xlabel('biyucis')\nplt.ylabel('frequancy')\nplt.savefig(\"biyuci frequancy of yukongchuan.png\")\nplt.close()\n\nx2 = []\ny2 = []\nfor i in wc2:\n\tx2.append(i[0])\n\ty2.append(i[1])\n\nprint(x2)\nplt.plot(x2,y2,'r',label = 'biyuci')\nplt.title(\"biyuci frequancy of xiyouji\")\nplt.xlabel('biyucis')\nplt.ylabel('frequancy')\nplt.savefig(\"biyuci frequancy of xiyouji.png\")\nplt.close()\n","sub_path":"text_analy/text_biyu.py","file_name":"text_biyu.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"453761285","text":"\n\n#\n# Copyright 2019 Xilinx Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport pickle\nimport six\n\nfrom nndct_shared.base.key_names import NNDCT_OP\nfrom nndct_shared.pruning import node_group as node_group_lib\nfrom nndct_shared.pruning import logging\nfrom nndct_shared.utils import registry\n\n_op_modifier = registry.Registry(\"Pruning Modifier Functions\")\n\nclass RegisterOpModifier(object):\n \"\"\"A decorator for registering the modification function for an op.\n This decorator can be defined for an op type so that it can infer the op's\n NodePruningResult and modify its attribute by existing pruning result.\n\n If a modifier for an op is registered multiple times, a KeyError will be\n raised.\n For example, you can define a new modifier for a Conv2D operation\n by placing this in your code:\n ```python\n @pruning.RegisterOpModifier(\"Conv2D\")\n def _modify_conv2d(graph, node, pruning_res):\n ...\n ```\n Then in client code you can retrieve the value by making this call:\n ```python\n pruning_lib.modify_node_by_pruning(graph, node, pruning_res)\n ```\n \"\"\"\n\n def __init__(self, op_type):\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string.\")\n if \",\" in op_type:\n raise TypeError(\"op_type must not contain a comma.\")\n self._op_type = op_type\n\n def __call__(self, f):\n \"\"\"Registers \"f\" as the statistics function for \"op_type\".\"\"\"\n # TODO(yuwang): Validate function signature before it is registered.\n _op_modifier.register(f, self._op_type)\n return f\n\ndef _update_pruning_by_upstream(node, pruning_res):\n node_pruning = pruning_res[node.name]\n input_pruning = pruning_res[node.in_nodes[0]]\n node_pruning.removed_inputs = input_pruning.removed_outputs\n node_pruning.in_dim = input_pruning.out_dim\n return node_pruning\n\ndef _copy_pruning_from_input(node, pruning_res):\n node_pruning = pruning_res[node.name]\n node_pruning.removed_outputs = node_pruning.removed_inputs\n node_pruning.out_dim = node_pruning.in_dim\n return node_pruning\n\ndef propagate_node_pruning(node, pruning_res):\n _update_pruning_by_upstream(node, pruning_res)\n _copy_pruning_from_input(node, pruning_res)\n\ndef is_depthwise(op):\n if op.type == NNDCT_OP.DEPTHWISE_CONV2D:\n return True\n\n if op.type != NNDCT_OP.CONV2D:\n return False\n\n out_channels = op.attr['out_dim']\n in_channels = op.attr['in_dim']\n group = op.attr['group']\n return group == in_channels and out_channels % in_channels == 0\n\ndef _modify_depthwise_conv2d(graph, node, pruning_res):\n node_pruning = _update_pruning_by_upstream(node, pruning_res)\n if not node_pruning.in_dim:\n return\n\n dw_multiplier = node.op.attr['out_dim'] // node.op.attr['in_dim']\n removed_outputs = []\n for c in node_pruning.removed_inputs:\n for k in range(dw_multiplier):\n removed_outputs.append(c * dw_multiplier + k)\n\n node_pruning.removed_inputs = []\n node_pruning.removed_outputs = removed_outputs\n node_pruning.out_dim = node_pruning.in_dim * dw_multiplier\n\n node.op.attr['group'] = node_pruning.in_dim\n node.op.attr['in_dim'] = node_pruning.in_dim\n node.op.attr['out_dim'] = node_pruning.out_dim\n\n@RegisterOpModifier(NNDCT_OP.DEPTHWISE_CONV2D)\ndef modify_depthwise_conv2d(graph, node, pruning_res):\n _modify_depthwise_conv2d(graph, node, pruning_res)\n\n@RegisterOpModifier(NNDCT_OP.CONV2D)\ndef modify_conv2d(graph, node, pruning_res):\n # In pytorch, dw conv is repesented by conv2d with groups == in_channels and\n # out_channels == K * in_channels, where K is a positive integer.\n if is_depthwise(node.op):\n _modify_depthwise_conv2d(graph, node, pruning_res)\n return\n\n node_pruning = _update_pruning_by_upstream(node, pruning_res)\n if node_pruning.in_dim:\n node.op.attr['in_dim'] = node_pruning.in_dim\n\n if node_pruning.out_dim:\n node.op.attr['out_dim'] = node_pruning.out_dim\n\n#@RegisterOpModifier(NNDCT_OP.ADAPTIVEAVGPOOL2D)\n#def modify_adaptive_avg_pool2d(graph, node, pruning_res):\n# is_global_avg_pool = node.op.attr['global']\n# if is_global_avg_pool:\n# propagate_node_pruning(node, pruning_res)\n# else:\n# raise NotImplementedError(\"Non-global avg pool not supported yet.\")\n\n@RegisterOpModifier(NNDCT_OP.FLATTEN)\ndef modify_flatten(graph, node, pruning_res):\n downstream_nodes = []\n\n queue = [node.name]\n while len(queue):\n cur_node = graph.node(queue.pop())\n downstream_nodes.append(cur_node)\n queue.extend(cur_node.out_nodes)\n\n for downstream_node in downstream_nodes:\n if downstream_node.op.type == NNDCT_OP.CONV2D:\n raise NotImplementedError(\n \"The downstream nodes of flatten can not contain a Conv2D\")\n\n propagate_node_pruning(node, pruning_res)\n\n@RegisterOpModifier(NNDCT_OP.DENSE)\ndef modify_dense(graph, node, pruning_res):\n input_pruning = pruning_res[node.in_nodes[0]]\n\n orig_out_depth = len(input_pruning.removed_outputs) + input_pruning.out_dim\n spatial_size = node.op.attr['in_dim'] // orig_out_depth\n\n # Two data formats:\n # [-1, 7, 7, 64(32)] => [-1, 3136(1518)]\n # [-1, 32(16), 5, 5] => [-1, 800(400)]\n removed_inputs = []\n #layout = graph.layout\n layout = 'NCHW'\n #layout = 'NHWC'\n # TODO(yuwang): Encapsulate below code to a function avoid repeatness.\n if layout == 'NHWC':\n for s in range(spatial_size):\n for c in input_pruning.removed_outputs:\n removed_inputs.append(s * spatial_size + c)\n else:\n for c in input_pruning.removed_outputs:\n for s in range(spatial_size):\n removed_inputs.append(c * spatial_size + s)\n\n in_features = spatial_size * input_pruning.out_dim\n node.op.attr['in_dim'] = in_features\n\n node_pruning = pruning_res[node.name]\n node_pruning.removed_inputs = removed_inputs\n node_pruning.in_dim = in_features\n node_pruning.out_dim = node.op.attr['out_dim']\n\n@RegisterOpModifier(NNDCT_OP.RESHAPE)\ndef modify_reshape(graph, node, pruning_res):\n node_pruning = pruning_res[node.name]\n input_pruning = pruning_res[node.in_nodes[0]]\n assert input_pruning.out_dim, \"Unknown out_dim of reshape\\'s input node\"\n\n shape = node.node_attr('shape')\n assert len(shape) == 2, \"Node {} has an unexpected shape {}\".format(\n node.name, shape)\n orig_out_depth = len(input_pruning.removed_outputs) + input_pruning.out_dim\n spatial_size = shape[-1] // orig_out_depth\n\n # Two data formats:\n # [-1, 7, 7, 64(32)] => [-1, 3136(1518)]\n # [-1, 32(16), 5, 5] => [-1, 800(400)]\n removed_outputs = []\n input_node = graph.node(node.in_nodes[0])\n layout = input_node.node_attr('layout')\n if layout == 'NHWC':\n for s in range(spatial_size):\n for c in input_pruning.removed_outputs:\n removed_outputs.append(s * spatial_size + c)\n else:\n for c in input_pruning.removed_outputs:\n for s in range(spatial_size):\n removed_outputs.append(c * spatial_size + s)\n\n node_pruning.removed_outputs = removed_outputs\n node_pruning.out_dim = spatial_size * input_pruning.out_dim\n\n pruned_shape = list(shape)\n pruned_shape[-1] = node_pruning.out_dim\n node.op.attr['shape'] = pruned_shape\n\n@RegisterOpModifier(NNDCT_OP.CONCAT)\ndef modify_concat(graph, node, pruning_res):\n node_pruning = pruning_res[node.name]\n cur_offset = 0\n out_dim = 0\n removed_outputs = []\n for tensor in node.in_tensors:\n input_node = tensor.node\n input_pruning = pruning_res[input_node.name]\n for ro in input_pruning.removed_outputs:\n removed_outputs.append(ro + cur_offset)\n out_dim += input_pruning.out_dim\n cur_offset += len(input_pruning.removed_outputs) + input_pruning.out_dim\n node_pruning.removed_outputs = removed_outputs\n node_pruning.out_dim = out_dim\n\n@RegisterOpModifier(NNDCT_OP.BATCH_NORM)\ndef modify_batchnorm(graph, node, pruning_res):\n node_pruning = pruning_res[node.name]\n input_pruning = pruning_res[node.in_nodes[0]]\n\n node_pruning.removed_inputs = input_pruning.removed_outputs\n node_pruning.in_dim = input_pruning.out_dim\n\n node_pruning.removed_outputs = input_pruning.removed_outputs\n node_pruning.out_dim = input_pruning.out_dim\n\n if node_pruning.out_dim:\n node.op.attr['out_dim'] = node_pruning.out_dim\n\ndef update_node_by_pruning(graph, node, pruning_res):\n \"\"\"Looks up the node's modification function in the registry and calls it.\n This function takes a NndctGraph object, a NndctNode from it, and the\n dictionary of PruningInfo and if there's an associated modification method,\n calls it. If no function has been registered for the particular op type,\n a general fucntion will be called which simply set current node's pruning info\n and do not update the node's attribute.\n statistics object\n Args:\n graph: A NndctGraph that the pruning is performed on.\n node: A NndctNode describing the operator.\n pruning_res: A dictionary of `NodePruningResult`.\n \"\"\"\n op_type = node.op.type\n if op_type in _op_modifier.list():\n mod_func = _op_modifier.lookup(op_type)\n mod_func(graph, node, pruning_res)\n else:\n propagate_node_pruning(node, pruning_res)\n\n node_pruning = pruning_res[node.name]\n if not node_pruning.out_dim:\n raise ValueError(\n \"Invalid NodePruningResult: out_dim not set, please check your modification function for %s \"\n % op_type)\n\nclass PrunableGroup(\n collections.namedtuple('PrunableGroup', ['nodes', 'sparsity'])):\n \"\"\"A group of nodes to be pruned by given sparsity.\"\"\"\n\n def __eq__(self, other):\n if len(self.nodes) != len(other.nodes):\n return False\n\n for index in range(len(self.nodes)):\n if self.nodes[index] != other.nodes[index]:\n return False\n\n return self.sparsity == other.sparsity\n\nclass PruningSpec(object):\n \"\"\"Specification indicates how to prune the network.\"\"\"\n\n def __init__(self, channel_batch=2, groups=None):\n self._channel_batch = 2\n self._groups = groups if groups else []\n self._node_to_group = {}\n\n def __str__(self):\n return \"PruningSpec(groups=[%s], channel_batch=%d)\" % (\", \".join(\n [str(group) for group in self._groups]), self._channel_batch)\n\n def __eq__(self, other):\n if len(self.groups) != len(other.groups):\n return False\n\n for index in range(len(self.groups)):\n if self.groups[index] != other.groups[index]:\n return False\n return True\n\n @property\n def channel_batch(self):\n return self._channel_batch\n\n @channel_batch.setter\n def channel_batch(self, channel_batch):\n if channel_batch <= 0:\n raise ValueError(\"'channel_batch' must be positive.\")\n self._channel_batch = channel_batch\n\n @property\n def groups(self):\n return self._groups\n\n def add_group(self, group):\n if not isinstance(group, PrunableGroup):\n raise ValueError(\"'group' must be a dictionary.\")\n\n self._groups.append(group)\n for node_name in group.nodes:\n self._node_to_group[node_name] = group\n\n def group(self, node_name):\n return self._node_to_group.get(node_name, None)\n\nclass GroupSens(object):\n\n def __init__(self, nodes, metrics):\n self.nodes = nodes\n self.metrics = metrics\n\n def __repr__(self):\n nodes = '\\n'.join([' ' + node for node in self.nodes])\n metrics = '\\n'.join(\n [' ({}, {})'.format(m.sparsity, m.value) for m in self.metrics])\n return ('GroupSens {\\n'\n ' nodes {\\n%s\\n }\\n'\n ' metrics {\\n%s\\n }\\n'\n '}') % (nodes, metrics)\n\nclass NetSens(object):\n \"\"\"The sensitivity results of the network generated by model analysis.\"\"\"\n\n def __init__(self):\n self.groups = []\n\n def load(self, fp):\n self.groups = pickle.load(fp)\n\n def dump(self, fp):\n pickle.dump(self.groups, fp)\n\n def __repr__(self):\n strs = []\n for group in self.groups:\n strs.append(repr(group))\n return \"\\n\".join(strs)\n\ndef read_sens(filename):\n net_sens = NetSens()\n with open(filename, 'rb') as f:\n net_sens.load(f)\n return net_sens\n\ndef write_sens(net_sens, filename):\n with open(filename, 'wb') as f:\n net_sens.dump(f)\n\ndef sens_path(model):\n # md5 = hashlib.md5()\n # md5.update()\n # md5.hexdigest()\n return '.ana'\n\nclass NodePruningResult:\n \"\"\"A data class that saves the pruning info of the `Node` object.\"\"\"\n\n def __init__(self,\n node_name,\n sparsity=None,\n removed_outputs=None,\n out_dim=None,\n removed_inputs=None,\n in_dim=None,\n master=False):\n self.node_name = node_name\n self.sparsity = sparsity\n self.removed_outputs = removed_outputs if removed_outputs else []\n self.out_dim = out_dim\n self.removed_inputs = removed_inputs if removed_inputs else []\n self.in_dim = in_dim\n self.master = master\n\n def __str__(self):\n return \"NodePruningResult({}, sparsity={}, in_dim={}, out_dim={})\".format(\n self.node_name, self.sparsity, self.in_dim, self.out_dim)\n\n def __repr__(self):\n return (\"NodePruningResult<name={}, sparsity={}, removed_inputs={}, \"\n \"in_dim={}, removed_outputs={}, out_dim={}>\").format(\n self.node_name, self.removed_inputs, self.in_dim,\n self.removed_outputs, self.out_dim)\n\ndef group_nodes(graph, nodes_to_exclude=[]):\n \"\"\"Divide conv2d nodes into different groups.\n The nodes that connected with each other by elementwise operation\n will be divided into one group.\n \"\"\"\n node_group = node_group_lib.NodeGroup()\n for node in graph.nodes:\n if node.op.type == NNDCT_OP.CONV2D:\n node_group.add_node(node.name)\n\n for node in graph.nodes:\n if node.op.type != NNDCT_OP.ADD:\n continue\n eltwise_inputs = []\n for name in node.in_nodes:\n input_node = graph.node(name)\n # Depthwise conv must be treated as a slave node.\n if input_node.op.type == NNDCT_OP.CONV2D and not is_depthwise(\n input_node.op):\n eltwise_inputs.append(name)\n else:\n ancestor = find_node_ancestor(graph, input_node, [NNDCT_OP.CONV2D],\n [NNDCT_OP.CONCAT])\n if ancestor and not is_depthwise(input_node.op):\n eltwise_inputs.append(ancestor.name)\n if len(eltwise_inputs) < 2:\n continue\n logging.vlog(2, \"Union ({}, {})\".format(eltwise_inputs[0],\n eltwise_inputs[1]))\n node_group.union(eltwise_inputs[0], eltwise_inputs[1])\n\n # TODO(yuwang): Exclude group convolution nodes.\n # i.e. groups > 1 and groups != in_channels.\n all_groups = node_group.groups()\n groups = []\n for group in all_groups:\n skip = False\n for node in nodes_to_exclude:\n if node in group:\n skip = True\n break\n if not skip:\n groups.append(group)\n return groups\n\ndef find_node_ancestor(graph, node, target_ops, barrier_ops=[]):\n visited = set()\n queue = []\n\n # start from input nodes\n for input_name in node.in_nodes:\n queue.append(input_name)\n\n ancestor = None\n while len(queue) != 0:\n node_name = queue.pop(0)\n node = graph.node(node_name)\n if node.op.type in target_ops:\n ancestor = node\n break\n elif node.op.type in barrier_ops:\n continue\n else:\n for input_name in node.in_nodes:\n if input_name not in visited:\n queue.append(input_name)\n visited.add(input_name)\n return ancestor\n\ndef prunable_groups_by_threshold(net_sens, threshold, excludes=[]):\n prunable_groups = []\n for group in net_sens.groups:\n skip = False\n for node in group.nodes:\n for exclude in excludes:\n if node == exclude:\n skip = True\n break\n\n if skip:\n continue\n\n baseline_metric = group.metrics[0]\n for sparsity, value in reversed(group.metrics):\n bias = value - baseline_metric.value\n if abs(bias / baseline_metric.value) <= threshold:\n break\n\n if sparsity is not None:\n prunable_groups.append(PrunableGroup(group.nodes, sparsity))\n\n return prunable_groups\n","sub_path":"tools/RNN/rnn_quantizer/nndct_shared/pruning/pruning_lib.py","file_name":"pruning_lib.py","file_ext":"py","file_size_in_byte":16366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"636166560","text":"#!/usr/bin/python\n\nfrom joblib import Parallel, delayed\nimport multiprocessing\nimport subprocess\nimport os\n\ndef run_shell_command(script_to_run):\n try:\n os.system(script_to_run)\n except KeyboardInterrupt:\n raise\n except:\n return \"FAILURE\"\n return \"DONE\"\n\ndef run_shell_command_timeout(parameter_dict):\n p = None\n try:\n print(parameter_dict[\"command\"])\n p = subprocess.Popen(parameter_dict[\"command\"])\n p.wait(parameter_dict[\"timeout\"])\n except subprocess.TimeoutExpired:\n p.kill()\n return \"FAILURE\"\n except KeyboardInterrupt:\n raise\n except:\n return \"FAILURE\"\n return \"DONE\"\n\n#Wraps running in parallel a set of shell scripts\ndef run_parallel_shellcommands(input_shell_commands, parallelism_level, timeout=None):\n if timeout != None:\n parameters_list = []\n for command in input_shell_commands:\n parameter_object = {}\n parameter_object[\"command\"] = command\n parameter_object[\"timeout\"] = timeout\n parameters_list.append(parameter_object)\n return run_parallel_job(run_shell_command_timeout, parameters_list, parallelism_level)\n else:\n return run_parallel_job(run_shell_command, input_shell_commands, parallelism_level)\n\n#Wraps the parallel job running, simplifying code\ndef run_parallel_job(input_function, input_parameters_list, parallelism_level):\n if parallelism_level == 1:\n output_results_list = []\n for input_param in input_parameters_list:\n result_object = input_function(input_param)\n output_results_list.append(result_object)\n return output_results_list\n else:\n results = Parallel(n_jobs = parallelism_level)(delayed(input_function)(input_object) for input_object in input_parameters_list)\n return results\n\n#Wraps calling a parallel map and a subsequent reduce function\ndef map_reduce_parallel_job(map_function, reduce_function, input_parameters_list, parallelism_level):\n map_results = run_parallel_job(map_function, input_parameters_list, parallelism_level)\n reduce_results = reduce_function(map_results)\n return reduce_results\n","sub_path":"ccmsproteosafepythonapi/parallel_library.py","file_name":"parallel_library.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"368639688","text":"import numpy as np\nimport pandas as pd\nimport math\nfrom datetime import datetime\nfrom binance.client import Client\n\nclient = Client()\n\ndef fetch4Hour(symbol, days):\n # https://python-binance.readthedocs.io/en/latest/binance.html#binance.client.Client.get_klines\n\n candleList = []\n #symbol = 'BATUSDT'\n hrs = 4\n\n # Time Now\n end = client.get_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_4HOUR)[-1][0]\n\n # Time is in ms\n diff = hrs * 3600000 \n \n # Specify how long the loop should last\n maxDays = days\n # Round up\n daysPerLoop = math.ceil(maxDays / (hrs * 500 / 24))\n #print(daysPerLoop)\n\n # Get as much data as possible\n for x in range(daysPerLoop):\n # Make the list from oldest to newest\n candleList = client.get_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_4HOUR, endTime = end) + candleList\n end = end - diff * 500\n\n #print(candleList)\n #print(\"Done\")\n df = pd.DataFrame(candleList)\n\n # Keep OHLCV data\n df.drop(columns = [6,7,8,9,10,11],axis=1,inplace=True)\n df.columns = [\"date\", \"open\", \"high\", \"low\", \"close\", \"volume\"]\n\n \n\n # Conver time in ms to datetime\n df['date'] = pd.to_datetime(df['date'], unit='ms')\n\n df['open'] = pd.to_numeric(df['open'])\n df['high'] = pd.to_numeric(df['high'])\n df['low'] = pd.to_numeric(df['low'])\n df['close'] = pd.to_numeric(df['close'])\n df['volume'] = pd.to_numeric(df['volume'])\n\n # Volume in USDT\n df['volume'] = df.volume * df.close\n\n return df\n\n #Convert to csv file\n #df.to_csv(r'C:\\Users\\Stephan\\OneDrive\\KI 3 Blok 3\\Scriptie\\TensorTrade\\Data\\data.csv',index=False)\n\n#if __name__ == '__main__':\n\n #data = fetch4Hour(symbol=\"BTCUSDT\", days=365)\n \n # tensorboard --logdir=C:\\Users\\Stephan\\ray_results\\IMPALA","sub_path":"Old Versions/TT_v2 (Impala)/BinanceData.py","file_name":"BinanceData.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"501151681","text":"# -*- coding: utf-8 -*-\n\"\"\"Base classes for the actual pipeline steps\"\"\"\n\nfrom collections import OrderedDict\nfrom collections.abc import MutableMapping\nfrom fnmatch import fnmatch\nfrom functools import lru_cache\nfrom io import StringIO\nimport itertools\nimport os\nimport os.path\nimport sys\n\nfrom biomedsheets import io_tsv\nfrom biomedsheets.io import SheetBuilder, json_loads_ordered\nfrom biomedsheets.models import SecondaryIDNotFoundException\nfrom biomedsheets.naming import NAMING_SCHEMES, NAMING_SECONDARY_ID_PK, name_generator_for_scheme\nfrom biomedsheets.ref_resolver import RefResolver\nfrom biomedsheets.shortcuts import (\n donor_has_dna_ngs_library,\n write_pedigree_to_ped,\n write_pedigrees_to_ped,\n)\nimport ruamel.yaml as yaml\nfrom snakemake.io import touch\n\nfrom snappy_pipeline.base import (\n MissingConfiguration,\n merge_dicts,\n merge_kwargs,\n print_config,\n print_sample_sheets,\n snakefile_path,\n)\nfrom snappy_pipeline.find_file import FileSystemCrawler, PatternSet\nfrom snappy_pipeline.utils import dictify, listify\n\n#: String constant with bash command for redirecting stderr to ``{log}`` file\nSTDERR_TO_LOG_FILE = r\"\"\"\n# -----------------------------------------------------------------------------\n# Redirect stderr to log file and enable printing executed commands\nexec 2> >(tee -a \"{log}\")\nset -x\n# -----------------------------------------------------------------------------\n\n\"\"\".lstrip()\n\n\nclass ImplementationUnavailableError(NotImplementedError):\n \"\"\"Raised when a function that is to be overridden optionally is called\n\n This is provided as an alternative to ``NotImplementedError`` as the Python linters warn if\n a class does not override functions throwing ``NotImplementedError``.\n \"\"\"\n\n\nclass BaseStepPart:\n \"\"\"Base class for a part of a pipeline step\"\"\"\n\n name = \"<base step>\"\n\n def __init__(self, parent):\n self.name = self.__class__.name\n self.parent = parent\n self.config = parent.config\n self.w_config = parent.w_config\n\n def update_cluster_config(self, cluster_config):\n \"\"\"Override and configure the cluster resource requirements for all rules that this\n pipeline step part uses\n \"\"\"\n\n def get_args(self, action):\n \"\"\"Return args for the given action of the sub step\"\"\"\n raise NotImplementedError(\"Called abstract method. Override me!\") # pragma: no cover\n\n def get_input_files(self, action):\n \"\"\"Return input files for the given action of the sub step\"\"\"\n raise NotImplementedError(\"Called abstract method. Override me!\") # pragma: no cover\n\n def get_output_files(self, action):\n \"\"\"Return output files for the given action of the sub step and\"\"\"\n raise NotImplementedError(\"Called abstract method. Override me!\") # pragma: no cover\n\n def get_log_file(self, action):\n \"\"\"Return path to log file\n\n The default implementation tries to call ``self._get_log_files()`` and in the case of\n this function returning a ``dict``, augments it with paths to MD5 files.\n \"\"\"\n if hasattr(self, \"_get_log_file\"):\n inner = self._get_log_file(action)\n if not isinstance(inner, dict):\n return inner\n else:\n result = {}\n for k, v in inner.items():\n result[k] = v\n if not k.endswith(\"_md5\") and (k + \"_md5\") not in inner:\n result[k + \"_md5\"] = v + \".md5\"\n return result\n else:\n raise NotImplementedError(\n \"Log file name generation not implemented!\"\n ) # pragma: no cover\n\n def get_shell_cmd(self, action, wildcards): # NOSONAR\n \"\"\"Return shell command for the given action of the sub step and the given wildcards\"\"\"\n raise ImplementationUnavailableError(\n \"Override this method before calling it!\"\n ) # pragma: no cover\n\n def run(self, action, wildcards): # NOSONAR\n \"\"\"Run the sub steps action action's code with the given wildcards\"\"\"\n raise ImplementationUnavailableError(\n \"Override this method before calling it!\"\n ) # pragma: no cover\n\n def check_config(self):\n \"\"\"Check configuration, raise ``ConfigurationMissing`` on problems\n\n Override in sub classes.\n\n :raises:MissingConfiguration: on missing configuration\n \"\"\"\n\n\nclass WritePedigreeStepPart(BaseStepPart):\n \"\"\"Write out pedigree file for primary DNA sample given the index NGS library name\"\"\"\n\n name = \"write_pedigree\"\n\n def __init__(self, parent, require_dna_ngs_library=False, only_trios=False):\n super().__init__(parent)\n #: Whether or not to prevent writing out of samples with out NGS library.\n self.require_dna_ngs_library = require_dna_ngs_library\n # Build shortcut from index library name to pedigree\n self.index_ngs_library_to_pedigree = OrderedDict()\n for sheet in self.parent.shortcut_sheets:\n if require_dna_ngs_library:\n for name, pedigree in sheet.index_ngs_library_to_pedigree.items():\n pedigree = pedigree.with_filtered_donors(donor_has_dna_ngs_library)\n if only_trios:\n in_trio = set()\n for donor in pedigree.donors:\n if donor.father and donor.mother:\n in_trio |= {donor.name, donor.father.name, donor.mother.name}\n if not any((donor.name in in_trio for donor in pedigree.donors)):\n continue # ignore empty pedigree post filtration\n pedigree = pedigree.with_filtered_donors(\n lambda donor: donor.name in in_trio\n )\n self.index_ngs_library_to_pedigree[name] = pedigree\n else:\n self.index_ngs_library_to_pedigree.update(sheet.index_ngs_library_to_pedigree)\n\n def get_input_files(self, action):\n \"\"\"Returns function returning input files.\n\n Returns a dict with entry ``\"bam\"`` mapping to list of input BAM files. This list will\n be empty if the parent step does not define an ``\"ngs_mapping\"`` workflow.\n \"\"\"\n\n @listify\n def get_input_files(wildcards):\n if \"ngs_mapping\" not in self.parent.sub_workflows:\n return # early exit\n # Get shorcut to NGS mapping sub workflow\n ngs_mapping = self.parent.sub_workflows[\"ngs_mapping\"]\n # Get names of primary libraries of the selected pedigree. The pedigree is selected\n # by the primary DNA NGS library of the index.\n pedigree = self.index_ngs_library_to_pedigree[wildcards.index_ngs_library]\n if not pedigree.index or not pedigree.index.dna_ngs_library:\n msg = \"INFO: pedigree without index (names: {})\" # pragma: no cover\n donor_names = list(sorted(d.name for d in pedigree.donors))\n print(msg.format(donor_names), file=sys.stderr) # pragma: no cover\n return\n mappers = self.w_config[\"step_config\"][\"ngs_mapping\"][\"tools\"][\"dna\"]\n tpl = \"output/{mapper}.{library_name}/out/{mapper}.{library_name}{ext}\"\n for donor in filter(lambda d: d.dna_ngs_library, pedigree.donors):\n library_name = donor.dna_ngs_library.name\n for mapper in mappers:\n path = tpl.format(\n library_name=library_name, mapper=mapper, ext=\".bam\", **wildcards\n )\n yield ngs_mapping(path)\n\n assert action == \"run\", \"Unsupported actions\"\n return get_input_files\n\n def get_output_files(self, action):\n assert action == \"run\"\n return \"work/write_pedigree.{index_ngs_library}/out/{index_ngs_library}.ped\"\n # return os.path.realpath(\n # \"work/write_pedigree.{index_ngs_library}/out/{index_ngs_library}.ped\"\n # )\n\n def run(self, wildcards, output):\n \"\"\"Write out the pedigree information\"\"\"\n if wildcards.index_ngs_library == \"whole_cohort\":\n write_pedigrees_to_ped(self.index_ngs_library_to_pedigree.values(), str(output))\n else:\n write_pedigree_to_ped(\n self.index_ngs_library_to_pedigree[wildcards.index_ngs_library], str(output)\n )\n\n\nclass LinkOutStepPart(BaseStepPart):\n \"\"\"Generically link out\n\n This is for output files that are created unconditionally, i.e., for output files where the\n output name is the same as for the work file.\n \"\"\"\n\n name = \"link_out\"\n\n def __init__(self, parent, disable_patterns=None):\n super().__init__(parent)\n self.base_pattern_out = \"output/{path}/{file}.{ext}\"\n self.base_path_out = self.base_pattern_out.replace(\",[^/]\", \"\")\n self.base_path_in = \"work/{path}/{file}.{ext}\"\n #: Patterns for disabling linking out to. This is useful/required when there is a\n #: specialized link out step part, e.g., for the case of alignment where realignment is\n #: performed or not, depending on the configuration.\n self.disable_patterns = list(disable_patterns or [])\n\n def get_input_files(self, action):\n \"\"\"Return input file pattern\"\"\"\n\n def input_function(wildcards):\n \"\"\"Helper wrapper function\"\"\"\n result = self.base_path_in.format(**wildcards)\n for pattern in self.disable_patterns:\n if fnmatch(result, pattern):\n raise ValueError(\"Blocking match...\")\n return result\n\n assert action == \"run\", \"Unsupported action\"\n return input_function\n\n def get_output_files(self, action):\n \"\"\"Return output file pattern\"\"\"\n assert action == \"run\", \"Unsupported action\"\n return self.base_pattern_out\n\n def get_shell_cmd(self, action, wildcards):\n \"\"\"Return call for linking out\"\"\"\n assert action == \"run\", \"Unsupported action\"\n tpl = \"test -h {out} || ln -sr {in_} {out}\"\n in_ = self.base_path_in.replace(\"{\", \"{wildcards.\")\n out = self.base_path_out.replace(\"{\", \"{wildcards.\")\n return tpl.format(in_=in_, out=out)\n\n\n@lru_cache()\ndef _cached_read_cancer_tsv_sheet(path_abs, path_rel, naming_scheme):\n \"\"\"Cached reading of cancer TSV sheets.\"\"\"\n with open(path_abs, \"rt\") as f:\n return io_tsv.read_cancer_tsv_sheet(f, path_rel, naming_scheme)\n\n\n@lru_cache()\ndef _cached_read_germline_tsv_sheet(path_abs, path_rel, naming_scheme):\n \"\"\"Cached reading of germline TSV sheets.\"\"\"\n with open(path_abs, \"rt\") as f:\n return io_tsv.read_germline_tsv_sheet(f, path_rel, naming_scheme)\n\n\n@lru_cache()\ndef _cached_read_generic_tsv_sheet(path_abs, path_rel, naming_scheme):\n \"\"\"Cached reading of generic TSV sheets.\"\"\"\n with open(path_abs, \"rt\") as f:\n return io_tsv.read_generic_tsv_sheet(f, path_rel, naming_scheme)\n\n\n@lru_cache()\ndef _cached_yaml_round_trip_load_str(str_value):\n \"\"\"Cached reading of YAML ``str`` objects.\"\"\"\n return yaml.round_trip_load(StringIO(str_value))\n\n\nclass DataSetInfo:\n \"\"\"Information on a DataSet\"\"\"\n\n def __init__(\n self,\n name,\n sheet_path,\n base_paths,\n search_paths,\n search_patterns,\n sheet_type,\n is_background,\n naming_scheme,\n mixed_se_pe,\n sodar_uuid,\n sodar_title,\n pedigree_field=None,\n ):\n \"\"\"Constructor.\n\n :param name: Name of the data set.\n :type name: str\n\n :param sheet_path: Path to sheet file that should be loaded.\n :type sheet_path: str\n\n :param base_paths: All base paths of all configuration, too look for ``sheet_path``.\n :type base_paths: list\n\n :param search_paths: Search paths for the files in the sample sheet.\n\n :param search_patterns: Search patterns. Example: \"{left: '**/*_R1_*.fastq.gz',\n right: '**/*_R2_*.fastq.gz'}\".\n :type search_patterns: dict\n\n :param sheet_type: Explicite sheet type (e.g. \"matched_cancer\"), if any. Otherwise, will\n attempt to load from sheet.\n :type sheet_type: str\n\n :param is_background: Whether or not the data set info is to be used only for background.\n :type is_background: bool\n\n :param naming_scheme: Selected naming schema: either 'secondary_id_pk' or\n 'only_secondary_id'.\n :type naming_scheme: str\n\n :param mixed_se_pe: Whether or not mixing SE and PE data sets is allowed.\n\n :param sodar_uuid: The UUID of the corresponding SODAR project.\n :type sodar_uuid: str\n\n :param sodar_title: The title of the project in SODAR [optional].\n :type sodar_title: str\n\n :param pedigree_field: Custom field from sample sheet used to define pedigree, e.g.,\n 'familyId'. If none defined, it will set pedigree based on sample sheet 'row'.\n Default: None.\n :type pedigree_field: str\n \"\"\"\n #: Name of the data set\n self.name = name\n #: Path to the sheet file, for loading\n self.sheet_path = sheet_path\n #: All base paths of all configuration, too look for ``sheet_path``\n self.base_paths = base_paths\n #: Search paths for the files in the sample sheet\n self.search_paths = list(search_paths)\n #: Search patterns\n self.search_patterns = search_patterns\n #: Explicite sheet type (e.g. \"matched_cancer\"), if any. Otherwise, will attempt to load\n # from sheet.\n self.sheet_type = sheet_type\n #: Whether or not the data set info is to be used only for background\n self.is_background = is_background\n #: Selected naming schema\n if naming_scheme not in NAMING_SCHEMES:\n raise ValueError(\"Invalid naming scheme: {}\".format(naming_scheme)) # pragma: no cover\n self.naming_scheme = naming_scheme\n #: Whether or not mixing SE and PE data sets is allowed.\n self.mixed_se_pe = mixed_se_pe\n #: The BioMed SampleSheet\n self.sheet = self._load_sheet()\n #: The UUID of the corresponding SODAR project.\n self.sodar_uuid = sodar_uuid\n #: The (optional) title of the project in SODAR.\n self.sodar_title = sodar_title\n #: The (optional) custom field used to define pedigree\n self.pedigree_field_kwargs = None\n if pedigree_field:\n self.pedigree_field_kwargs = {\"join_by_field\": pedigree_field}\n\n def _load_sheet(self):\n for base in self.base_paths:\n fname = os.path.join(base, self.sheet_path)\n if not os.path.exists(fname):\n continue\n if self.sheet_path.endswith(\".tsv\"):\n if self.sheet_type == \"matched_cancer\":\n return self._set_is_background(\n _cached_read_cancer_tsv_sheet(fname, self.sheet_path, self.naming_scheme),\n self.is_background,\n )\n elif self.sheet_type == \"germline_variants\":\n return self._set_is_background(\n _cached_read_germline_tsv_sheet(fname, self.sheet_path, self.naming_scheme),\n self.is_background,\n )\n elif self.sheet_type == \"generic\":\n return self._set_is_background(\n _cached_read_generic_tsv_sheet(fname, self.sheet_path, self.naming_scheme),\n self.is_background,\n )\n else:\n raise ValueError(\"Invalid sheet type {}\".format(self.sheet_type))\n elif self.sheet_path.endswith(\".json\"):\n with open(fname, \"rt\") as f:\n sheet_json = json_loads_ordered(f.read())\n resolver = RefResolver(\n lookup_paths=os.path.dirname(os.path.abspath(self.sheet_path)),\n dict_class=OrderedDict,\n )\n resolved_json = resolver.resolve(\"file://\" + self.sheet_path, sheet_json)\n return self._set_is_background(\n SheetBuilder(resolved_json).run(\n name_generator=name_generator_for_scheme(self.naming_scheme)\n ),\n self.is_background,\n )\n else:\n raise ValueError( # pragma: no cover\n \"Invalid sheet file type of {}\".format(self.sheet_path)\n )\n # Raise problem if we could not find the sample sheet\n raise ValueError( # pragma: no cover\n \"Could not find sample sheet file {} in the lookup paths {}\".format(\n self.sheet_path, self.base_paths\n )\n )\n\n @classmethod\n def _set_is_background(cls, sheet, flag):\n \"\"\"Override \"is_background\" flag\"\"\"\n # TODO: check whether is already there and fail if not compatible\n sheet.json_data[\"extraInfoDefs\"][\"is_background\"] = {\"type\": \"boolean\", \"default\": False}\n sheet.extra_infos[\"is_background\"] = flag\n return sheet\n\n\nclass BaseStep:\n \"\"\"Base class for the pipeline steps\n\n Each pipeline step is a Snakemake workflow\n \"\"\"\n\n #: Override with step name\n name = None\n\n #: Override with the sheet shortcut class to use\n sheet_shortcut_class = None\n\n #: Override with arguments to pass into sheet shortcut class constructor\n sheet_shortcut_args = None\n\n #: Override with keyword arguments to pass into sheet shortcut class\n #: constructor\n sheet_shortcut_kwargs = None\n\n @classmethod\n def default_config_yaml(cls):\n \"\"\"Override this function for providing default configuration\n\n The configuration should be a YAML fragment. Your configuration should define a top-level\n key starting with '_' and then consist of the name of the schema, e.g.,\n '_ngs_mapping_schema'. Your default configuration is then merged into the main\n configuration where the main configuration takes precedence.\n\n Example: ::\n\n def default_config_yaml(self):\n return textwrap.dedent(\"\"\\\"\n schema_config:\n ngs_mapping:\n max_threads: 16\n \"\"\\\").lstrip()))\n\n Return ``None`` for no default configuration.\n\n You can also return an iterable of configurations, these will be merged in the order given\n (earlier ones will be overwritten by later ones). This is useful if your schema needs\n configuration for a later one.\n \"\"\"\n return \"\" # pragma: no cover\n\n def __init__(\n self,\n workflow,\n config,\n cluster_config,\n config_lookup_paths,\n config_paths,\n work_dir,\n previous_steps=None,\n ):\n self.name = self.__class__.name\n #: Tuple with absolute paths to configuration files read\n self.config_paths = config_paths\n #: Absolute path to directory of where to perform work\n self.work_dir = work_dir\n #: Classes of previously executed steps, used for merging their default configuration as\n #: well.\n self.previous_steps = tuple(previous_steps or [])\n #: Snakefile \"workflow\" object\n self.workflow = workflow\n #: Merge default configuration with true configuration\n self.w_config = config\n self.w_config.update(self._update_config(config))\n self.config = self.w_config[\"step_config\"].get(self.name, OrderedDict())\n #: Cluster configuration dict\n self.cluster_config = cluster_config\n #: Paths with configuration paths, important for later retrieving sample sheet files\n self.config_lookup_paths = config_lookup_paths\n self.sub_steps = {}\n self.data_set_infos = list(self._load_data_set_infos())\n # Check configuration\n self._check_config()\n #: Shortcut to the BioMed SampleSheet objects\n self.sheets = [info.sheet for info in self.data_set_infos]\n #: Shortcut BioMed SampleSheet keyword arguments\n sheet_kwargs_list = [\n merge_kwargs(\n first_kwargs=self.sheet_shortcut_kwargs, second_kwargs=info.pedigree_field_kwargs\n )\n for info in self.data_set_infos\n ]\n #: Shortcut sheets\n self.shortcut_sheets = []\n klass = self.__class__.sheet_shortcut_class\n for sheet, kwargs in zip(self.sheets, sheet_kwargs_list):\n kwargs = kwargs or {}\n kwargs = {k: v for k, v in kwargs.items() if k in klass.supported_kwargs}\n self.shortcut_sheets.append(\n klass(sheet, *(self.__class__.sheet_shortcut_args or []), **kwargs)\n )\n # Setup onstart/onerror/onsuccess hooks\n self._setup_hooks()\n #: Functions from sub workflows, can be used to generate output paths into these workflows\n self.sub_workflows = {}\n\n def _setup_hooks(self):\n \"\"\"Setup Snakemake workflow hooks for start/end/error\"\"\"\n # In the following, the \"log\" parameter to the handler functions is set to \"_\" as we\n # don't use them\n def on_start(_):\n \"\"\"Print configuration and sample sheets on start\"\"\"\n verbose = False\n if verbose:\n # Print configuration back to the user after merging workflow step-specific\n # configuration\n print_config(self.config, file=sys.stderr)\n # Print sample sheets to the user\n print_sample_sheets(self, file=sys.stderr)\n\n def on_error(_):\n \"\"\"Error handler, print message\"\"\"\n msg = \"Oh no! Something went wrong.\"\n print(\"\\n\" + \"*\" * len(msg), file=sys.stderr)\n print(msg, file=sys.stderr)\n print(\"*\" * len(msg) + \"\\n\", file=sys.stderr)\n\n def on_success(_):\n \"\"\"Success handler, print message\"\"\"\n msg = \"All done; have a nice day!\"\n print(\"\\n\" + \"*\" * len(msg), file=sys.stderr)\n print(msg, file=sys.stderr)\n print(\"*\" * len(msg) + \"\\n\", file=sys.stderr)\n\n self.workflow.onstart(on_start)\n self.workflow.onerror(on_error)\n self.workflow.onsuccess(on_success)\n\n def _update_config(self, config):\n \"\"\"Update configuration config with the configuration returned by subclass'\n ``default_config_yaml()`` and return\n \"\"\"\n result = OrderedDict()\n for cls in itertools.chain([self.__class__], self.previous_steps):\n result = merge_dicts(\n result, _cached_yaml_round_trip_load_str(cls.default_config_yaml())\n )\n return merge_dicts(result, config)\n\n def _check_config(self):\n \"\"\"Internal method, checks step and sub step configurations\"\"\"\n self.check_config()\n for step in self.sub_steps.values():\n step.check_config()\n\n def check_config(self):\n \"\"\"Check ``self.w_config``, raise ``ConfigurationMissing`` on problems\n\n Override in sub classes.\n\n :raises:MissingConfiguration: on missing configuration\n \"\"\"\n\n def ensure_w_config(self, config_keys, msg, e_class=MissingConfiguration):\n \"\"\"Check parameters in configuration.\n\n Method ensures required configuration setting are present in the provided configuration;\n if not, it raises exception.\n\n :param config_keys: List of strings with all keys that must be present in the configuration\n for a given step of the analysis to be performed.\n :type config_keys: list\n\n :param msg: Message to be used in case of exception.\n :type msg: str\n\n :param e_class: Preferred exception class to be raised in case of error.\n Default: MissingConfiguration.\n :type e_class: class\n \"\"\"\n # Initialise variables\n so_far = []\n handle = self.w_config\n\n # Check if configuration is empty\n if not handle:\n tpl = 'Empty configuration (\"{full_path}\"): {msg}'.format(\n full_path=\"/\".join(config_keys), msg=msg\n )\n raise e_class(tpl)\n\n # Iterate over required configuration keys\n for entry in config_keys:\n # Check if keys are present in config dictionary\n if entry in handle:\n handle = handle[entry]\n so_far.append(entry)\n else:\n tpl = 'Missing configuration (\"{full_path}\", got up to \"{so_far}\"): {msg}'.format(\n full_path=\"/\".join(config_keys), so_far=\"/\".join(so_far), msg=msg\n )\n raise e_class(tpl)\n\n def update_cluster_config(self):\n \"\"\"Update cluster configuration for rule \"__default__\"\n\n The sub parts' ``update_cluster_config()`` routines are called on creation in\n ``register_sub_step_classes()``.\n \"\"\"\n self.cluster_config[\"__default__\"] = {\"mem\": 4 * 1024, \"time\": \"12:00\", \"ntasks\": 1}\n\n def register_sub_step_classes(self, classes):\n \"\"\"Register an iterable of sub step classes\n\n Initializes objects in ``self.sub_steps`` dict\n \"\"\"\n self.update_cluster_config()\n for pair_or_class in classes:\n try:\n klass, args = pair_or_class\n except TypeError:\n klass = pair_or_class\n args = ()\n obj = klass(self, *args)\n obj.update_cluster_config(self.cluster_config)\n obj.check_config()\n self.sub_steps[klass.name] = obj\n\n def register_sub_workflow(self, step_name, workdir, sub_workflow_name=None):\n \"\"\"Register workflow with given pipeline ``step_name`` and in the given ``workdir``.\n\n Optionally, the sub workflow name can be given separate from ``step_name`` (the default)\n value for it.\n \"\"\"\n sub_workflow_name = sub_workflow_name or step_name\n if sub_workflow_name in self.sub_workflows:\n raise ValueError(\"Sub workflow {} already registered!\".format(sub_workflow_name))\n if os.path.isabs(workdir):\n abs_workdir = workdir\n else:\n abs_workdir = os.path.realpath(os.path.join(os.getcwd(), workdir))\n self.workflow.subworkflow(\n sub_workflow_name,\n workdir=abs_workdir,\n snakefile=snakefile_path(step_name),\n configfile=abs_workdir + \"/\" + \"config.yaml\",\n )\n self.sub_workflows[sub_workflow_name] = self.workflow.globals[sub_workflow_name]\n\n def get_args(self, sub_step, action):\n \"\"\"Return arguments for action of substep with given wildcards\n\n Delegates to the sub step object's get_input_files function\n \"\"\"\n return self._get_sub_step(sub_step).get_args(action)\n\n def get_input_files(self, sub_step, action):\n \"\"\"Return input files for action of substep with given wildcards\n\n Delegates to the sub step object's get_input_files function\n \"\"\"\n return self._get_sub_step(sub_step).get_input_files(action)\n\n def get_output_files(self, sub_step, action):\n \"\"\"Return list of strings with output files/patterns\n\n Delegates to the sub step object's get_output_files function\n \"\"\"\n return self._get_sub_step(sub_step).get_output_files(action)\n\n def get_params(self, sub_step, action):\n \"\"\"Return parameters\n\n Delegates to the sub step object's get_params function\n \"\"\"\n return self.substep_dispatch(sub_step, \"get_params\", action)\n\n def get_log_file(self, sub_step, action):\n \"\"\"Return path to the log file\n\n Delegates to the sub step object's get_log_file function\n \"\"\"\n return self.substep_dispatch(sub_step, \"get_log_file\", action)\n\n def get_shell_cmd(self, sub_step, action, wildcards):\n \"\"\"Return shell command for the pipeline sub step\n\n Delegates to the sub step object's get_shell_cmd function\n \"\"\"\n return self.substep_dispatch(sub_step, \"get_shell_cmd\", action, wildcards)\n\n def run(self, sub_step, action, wildcards):\n \"\"\"Run command for the given action of the given sub step with the given wildcards\n\n Delegates to the sub step object's run function\n \"\"\"\n return self._get_sub_step(sub_step).get_shell_cmd(action, wildcards)\n\n def get_result_files(self):\n \"\"\"Return actual list of file names to build\"\"\"\n raise NotImplementedError(\"Implement me!\") # pragma: no cover\n\n def substep_getattr(self, step, name):\n \"\"\"Return attribute from substep\"\"\"\n return getattr(self._get_sub_step(step), name)\n\n def substep_dispatch(self, step, function, *args, **kwargs):\n \"\"\"Dispatch call to function of sub step implementation\"\"\"\n return self.substep_getattr(step, function)(*args, **kwargs)\n\n def _get_sub_step(self, sub_step):\n if sub_step in self.sub_steps:\n return self.sub_steps[sub_step]\n else:\n raise ValueError(\n 'Could not find sub step \"{}\" in workflow step \"{}\"'.format(sub_step, self.name)\n ) # pragma: no cover\n\n def _load_data_set_infos(self):\n \"\"\"Load BioMed Sample Sheets as given by configuration and yield them\"\"\"\n for name, data_set in self.w_config[\"data_sets\"].items():\n yield DataSetInfo(\n name,\n data_set[\"file\"],\n self.config_lookup_paths,\n data_set[\"search_paths\"],\n data_set[\"search_patterns\"],\n data_set[\"type\"],\n data_set.get(\"is_background\", False),\n data_set.get(\"naming_scheme\", NAMING_SECONDARY_ID_PK),\n data_set.get(\"mixed_se_pe\", False),\n data_set.get(\"sodar_uuid\", None),\n data_set.get(\"sodar_title\", None),\n data_set.get(\"pedigree_field\", None),\n )\n\n @classmethod\n def wrapper_path(cls, path):\n \"\"\"Generate path to wrapper\"\"\"\n return \"file://\" + os.path.abspath(\n os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"..\", \"snappy_wrappers\", \"wrappers\", path\n )\n )\n\n\nclass LinkInPathGenerator:\n \"\"\"Helper class for generating paths to link in\"\"\"\n\n def __init__(\n self, work_dir, data_set_infos, config_paths, cache_file_name=\".snappy_path_cache\"\n ):\n #: Working directory\n self.work_dir = work_dir\n #: Data set info list from configuration\n self.data_set_infos = data_set_infos\n #: Path to configuration files, used for invalidating cache\n self.config_paths = config_paths\n #: Name of cache file to create\n self.cache_file_name = cache_file_name\n #: File system crawler to use\n invalidate_paths_list = self._merge_cache_invalidate_paths(data_set_infos)\n invalidate_paths_list += config_paths\n self.crawler = FileSystemCrawler(\n os.path.join(self.work_dir, self.cache_file_name), invalidate_paths_list\n )\n\n def run(self, folder_name, pattern_set_keys=(\"left\", \"right\", \"bam\")):\n \"\"\"Yield (src_path, path_infix, filename) one-by-one\n\n Cache is saved after the last iteration\n \"\"\"\n # Iterate over data set infos and crawl file system\n filenames = set([])\n # TODO: crawling the actual data sheet of the current data set is enough!\n seen_root_paths = set()\n for info in self.data_set_infos:\n patterns = []\n # Build PatternSet objects, based on types in configuration\n for pat in info.search_patterns:\n if not isinstance(pat, (dict, MutableMapping)):\n raise ValueError(\"search_patterns must be a dict!\") # pragma: no cover\n patterns.append(PatternSet(pat.values(), names=pat.keys()))\n # Crawl all root paths, link in the resulting files\n for root_path in self._get_shell_cmd_root_paths(info):\n if root_path in seen_root_paths:\n continue # skip this root path\n seen_root_paths.add(root_path)\n for result in self.crawler.run(root_path, folder_name, patterns, info.mixed_se_pe):\n res_dict = result.to_dict()\n for key in pattern_set_keys:\n if key not in res_dict:\n continue # skip if not found\n path_infix = os.path.relpath(\n os.path.dirname(res_dict[key]), result.base_folder\n )\n filename = os.path.basename(res_dict[key])\n if res_dict[key] in filenames:\n raise ValueError(\"Detected double link-in {}\".format(filename))\n filenames.add(filename)\n src_dir = os.path.dirname(res_dict[key])\n yield src_dir, path_infix, filename\n # Finally, save the cache\n self.crawler.save_cache()\n\n @classmethod\n def _get_shell_cmd_root_paths(cls, info):\n for base_path in info.base_paths:\n if not os.path.exists(os.path.join(base_path, info.sheet_path)):\n continue # skip this one\n for search_path in info.search_paths:\n yield os.path.abspath(\n os.path.join(\n os.path.dirname(os.path.join(base_path, info.sheet_path)), search_path\n )\n )\n\n @classmethod\n def _merge_cache_invalidate_paths(cls, data_set_infos):\n \"\"\"\n :param data_set_infos: List of DataSetInfo objects.\n :type data_set_infos: list\n\n :return: Returns list with paths that should be used to potentially\n invalidate a cache file based on the DataSetInfo. Method merges paths\n to a project tsv file as well as the search paths into a single list of strings.\n \"\"\"\n # Initialise variable\n out_list = []\n # Iterate over DataSetInfo objects\n for info in data_set_infos:\n\n # Search paths - expects a list already\n out_list.extend(getattr(info, \"search_paths\"))\n\n # Sheet path\n # Only name of file is stored in config file (relative path used),\n # hence we need to find it in the base paths\n sheet_file_name = getattr(info, \"sheet_path\") # expects a string\n base_paths = getattr(info, \"base_paths\") # expects a list\n sheet_path = cls._find_sheet_file(sheet_file_name, base_paths)\n # Append if not None\n if sheet_path:\n out_list.append(sheet_path)\n\n # Return\n return out_list\n\n @classmethod\n def _find_sheet_file(cls, sheet_file_name, base_paths):\n \"\"\"Method searches for sheet file in base paths.\n\n :param sheet_file_name: Sheet file name.\n :type sheet_file_name: str\n\n :param base_paths: List of strings with base paths.\n :type base_paths: list\n\n :return: Returns path to sheet file.\n \"\"\"\n # Check if full path already\n if os.path.exists(sheet_file_name):\n return sheet_file_name\n # Iterate over base paths\n # Assumption: sheet file stored in the same level as config file,\n # i.e., one of the base paths.\n for base_p in base_paths:\n dir_path = os.path.realpath(base_p)\n # Find all files\n for item in os.listdir(dir_path):\n if sheet_file_name == item:\n return os.path.join(dir_path, sheet_file_name)\n # If not found: None\n return None\n\n\ndef get_ngs_library_folder_name(sheets, library_name):\n \"\"\"Return library's folder name\n\n The library is searched for based on the ``library_name``. In the case of\n multiple NGS library matches, the first one is returned.\n \"\"\"\n for sheet in sheets:\n try:\n ngs_library = sheet.crawl(sheet.name_generator.inverse(library_name))\n except SecondaryIDNotFoundException:\n continue # skip, not in this sheet\n if ngs_library:\n try:\n return ngs_library.extra_infos[\"folderName\"]\n except AttributeError:\n raise ValueError(\"No folderName extraInfos entry for {}\".format(ngs_library.name))\n raise ValueError(\"Found no folders for NGS library of name {}\".format(library_name))\n\n\n# TODO: Rename to LinkInStepPart\nclass LinkInStep(BaseStepPart):\n \"\"\"Link in the raw files, e.g. FASTQ files\n\n Depending on the configuration, the files are linked out after postprocessing\n \"\"\"\n\n name = \"link_in\"\n\n def __init__(self, parent):\n super().__init__(parent)\n self.base_pattern_out = \"work/input_links/{library_name}/.done\"\n # Path generator.\n self.path_gen = LinkInPathGenerator(\n self.parent.work_dir, self.parent.data_set_infos, self.parent.config_lookup_paths\n )\n\n def get_input_files(self, action):\n \"\"\"Return required input files\"\"\"\n return [] # no input\n\n def get_output_files(self, action):\n \"\"\"Return output files that are generated by snappy-gatk_post_bam\"\"\"\n assert action == \"run\", \"Unsupported action\"\n return touch(self.base_pattern_out)\n\n def get_shell_cmd(self, action, wildcards):\n \"\"\"Return call for linking in the files\n\n The files are linked, keeping their relative paths to the item matching the \"folderName\"\n intact.\n \"\"\"\n assert action == \"run\", \"Unsupported action\"\n # Get base out path\n out_path = os.path.dirname(self.base_pattern_out.format(**wildcards))\n # Get folder name of first library candidate\n folder_name = get_ngs_library_folder_name(self.parent.sheets, wildcards.library_name)\n # Perform the command generation\n lines = []\n tpl = (\n \"mkdir -p {out_path}/{path_infix} && \"\n \"{{{{ test -h {out_path}/{path_infix}/{filename} || \"\n \"ln -sr {src_path}/{filename} {out_path}/{path_infix}; }}}}\"\n )\n filenames = {} # generated so far\n for src_path, path_infix, filename in self.path_gen.run(folder_name):\n new_path = os.path.join(out_path, path_infix, filename)\n if new_path in filenames:\n if filenames[new_path] == src_path:\n continue # ignore TODO: better correct this\n msg = \"WARNING: Detected double output path {}\"\n print(msg.format(filename), file=sys.stderr)\n filenames[new_path] = src_path\n lines.append(\n tpl.format(\n src_path=src_path, out_path=out_path, path_infix=path_infix, filename=filename\n )\n )\n if not lines:\n msg = \"Found no files to link in for {}\".format(dict(**wildcards))\n print(msg, file=sys.stderr)\n raise Exception(msg)\n return \"\\n\".join(lines)\n\n def run(self, action, wildcards):\n raise ImplementationUnavailableError(\n \"run() not implemented for linking in reads\"\n ) # pragma: no cover\n\n\nclass InputFilesStepPartMixin:\n \"\"\"Mixin with predefined \"get_input_files\" function.\"\"\"\n\n #: Whether to include path to PED file or not\n include_ped_file = None\n\n #: Class with input VCF file name\n prev_class = None\n\n #: Extensions of files to create as main payload\n ext_values = None\n\n #: Names of the files to create for the extension\n ext_names = None\n\n def get_input_files(self, action):\n @dictify\n def input_function(wildcards):\n if self.include_ped_file:\n yield \"ped\", os.path.realpath(\n \"work/write_pedigree.{index_library}/out/{index_library}.ped\"\n ).format(**wildcards)\n name_pattern = self.prev_class.name_pattern.replace(r\",[^\\.]+\", \"\")\n tpl_path_out = os.path.join(\"work\", name_pattern, \"out\", name_pattern)\n for key, ext in zip(self.ext_names, self.ext_values):\n yield key, tpl_path_out.format(ext=ext, **wildcards) + ext\n\n assert action == \"run\"\n return input_function\n","sub_path":"snappy_pipeline/workflows/abstract/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":40565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"125042231","text":"class TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\nclass Solution:\n def isValidBST(self, root):\n self.lastVal = None\n self.isBST = True\n self.validate(root)\n return self.isBST\n def validate(self, root):\n if root is None:\n return\n self.validate(root.left)\n if self.lastVal is not None and self.lastVal >= root.val:\n self.isBST = False\n return\n self.lastVal = root.val\n self.validate(root.right)\n# 主函数\nif __name__ == '__main__':\n root = TreeNode(2)\n root.left = TreeNode(1)\n root.right = TreeNode(4)\n root.right.left = TreeNode(3)\n root.right.right = TreeNode(5)\n solution = Solution()\nprint(\"是否是BST:\", solution.isValidBST(root))","sub_path":"数据结构练习/Python算法指南数据结构/158_验证二叉查找树.py","file_name":"158_验证二叉查找树.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"552229836","text":"from mpi4py import MPI\nimport os\nfrom core import errMod\nimport numpy as np\n\nclass MpiConfig:\n \"\"\"\n Abstract class for defining the MPI parameters,\n along with initialization of the MPI communication\n handle from mpi4py.\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialize the MPI abstract class that will contain basic\n information and communication handles.\n \"\"\"\n self.comm = None\n self.rank = None\n self.size = None\n\n def initialize_comm(self,ConfigOptions):\n \"\"\"\n Initial function to initialize MPI.\n :return:\n \"\"\"\n try:\n self.comm = MPI.COMM_WORLD\n except:\n ConfigOptions.errMsg = \"Unable to initialize the MPI Communicator object\"\n raise Exception()\n\n try:\n self.size = self.comm.Get_size()\n except:\n ConfigOptions.errMsg = \"Unable to retrieve the MPI size.\"\n raise Exception()\n\n try:\n self.rank = self.comm.Get_rank()\n except:\n ConfigOptions.errMsg = \"Unable to retrieve the MPI processor rank.\"\n raise Exception()\n\n def broadcast_parameter(self,value_broadcast,ConfigOptions):\n \"\"\"\n Generic function for sending a parameter value out to the processors.\n :param ConfigOptions:\n :return:\n \"\"\"\n # Create dictionary to hold value.\n if self.rank == 0:\n tmpDict = {'varTmp':value_broadcast}\n else:\n tmpDict = None\n try:\n tmpDict = self.comm.bcast(tmpDict,root=0)\n except:\n ConfigOptions.errMsg = \"Unable to broadcast single value from rank 0.\"\n errMod.log_critical(ConfigOptions,MpiConfig)\n return None\n return tmpDict['varTmp']\n\n def scatter_array(self,geoMeta,array_broadcast,ConfigOptions):\n \"\"\"\n Generic function for calling scatter functons based on\n the input dataset type.\n :param geoMeta:\n :param array_broadcast:\n :param ConfigOptions:\n :return:\n \"\"\"\n # Determine which type of input array we have based on the\n # type of numpy array.\n data_type_flag = -1\n if self.rank == 0:\n if array_broadcast.dtype == np.float32:\n data_type_flag = 1\n if array_broadcast.dtype == np.float64:\n data_type_flag = 2\n\n # Broadcast the numpy datatype to the other processors.\n if self.rank == 0:\n tmpDict = {'varTmp':data_type_flag}\n else:\n tmpDict = None\n try:\n tmpDict = self.comm.bcast(tmpDict,root=0)\n except:\n ConfigOptions.errMsg = \"Unable to broadcast numpy datatype value from rank 0\"\n errMod.log_critical(ConfigOptions,MpiConfig)\n return None\n data_type_flag = tmpDict['varTmp']\n\n # Broadcast the global array to the child processors, then\n if self.rank == 0:\n arrayGlobalTmp = array_broadcast\n else:\n if data_type_flag == 1:\n arrayGlobalTmp = np.empty([geoMeta.ny_global,\n geoMeta.nx_global],\n np.float32)\n if data_type_flag == 2:\n arrayGlobalTmp = np.empty([geoMeta.ny_global,\n geoMeta.nx_global],\n np.float64)\n try:\n self.comm.Bcast(arrayGlobalTmp, root=0)\n except:\n ConfigOptions.errMsg = \"Unable to broadcast a global numpy array from rank 0\"\n errMod.log_critical(ConfigOptions,MpiConfig)\n return None\n arraySub = arrayGlobalTmp[geoMeta.y_lower_bound:geoMeta.y_upper_bound,\n geoMeta.x_lower_bound:geoMeta.x_upper_bound]\n return arraySub\n\n #def gather_array(self,array_gather,ConfigOptions):\n # \"\"\"\n # Generic function for gathering local arrays from each processor\n # to a global array on processor 0.\n # :param array_gather:\n # :param ConfigOptions:\n # :return:\n # \"\"\"\n # final = MpiConfig.comm.gather(array_gather[:, :], root=0)\n\n # MpiConfig.comm.barrier()\n\n\n # if self.rank == 0:\n # arrayGlobal = np.concatenate([final[i] for i in range(MpiConfig.size)].axis=0)\n # else:\n # arrayGlobal = None\n\n # return arrayGlobal\n","sub_path":"core/parallelMod.py","file_name":"parallelMod.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"605395830","text":"\"\"\"\nLa idea es simple: con una imagen donde el espacio se encuentre vacio se compara con otra imagenes y dependiendo las diferencias\nse concluye si está ocupado o vacio\nLas pruebas van a tomar la primer imagen de un espacio vacio que exista dentro de todas las imagenes pertenecientes a un espacio\nen concreto en un estacionamiento en concreto, esta imagen va a ser comparada usa dos metodos ssim y nrmse pero se puede hacer uso de cualquier otro\n\"\"\"\n\nimport cv2\nimport os\nfrom skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_nrmse as nrmse\nimport pickle\nimport argparse\nfrom operator import itemgetter\nfrom itertools import groupby\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm\nimport ntpath\nimport json\n\npath_pklot = 'C:\\\\Eduardo\\\\ProyectoFinal\\\\Datasets\\\\PKLot'\n\ndef getGrayscaleImage(filepath):\n\t\t\"\"\"\n\t\tRead the image files and converts it to gray scale\n\t\t:param filepath: the path to the image\n\t\t:return: the image in grayscale\n\t\t\"\"\"\n\t\timage = cv2.imread(filepath)\n\t\treturn cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n\n\n\ndef extractUniqueItemsByKey(list, key):\n\t\t\"\"\"\n\t\tThis will take a list and sorted by the key and\n\t\tthen it will return the list with just the elements from that\n\t\tkey without duplicates\n\t\t:param list:\n\t\t:param key:\n\t\t:return:\n\t\t\"\"\"\n\t\tlist.sort(key=lambda x: x[key])\n\t\treturn [k for k, v in groupby(list, key=lambda x: x[key])]\n\ndef getNewImageInfo(image_info):\n\t\timage_info['filepath'] = os.path.join(path_pklot, image_info['filepath'], image_info['filename'])\n\t\treturn image_info\n\n\ndef mse(imageA, imageB):\n\t\t# the 'Mean Squared Error' between the two images is the\n\t\t# sum of the squared difference between the two images;\n\t\t# NOTE: the two images must have the same dimension\n\t\terr = np.sum((imageA.astype(\"float\") - imageB.astype(\"float\")) ** 2)\n\t\terr /= float(imageA.shape[0] * imageA.shape[1])\n\n\t\t# return the MSE, the lower the error, the more \"similar\"\n\t\t# the two images are\n\t\treturn err\n\ndef main():\n\t\tparser = argparse.ArgumentParser(description='Select the type of reduced.')\n\t\tparser.add_argument(\"-f\", \"--filename\", type=str, required=True,\n\t\t\t\t\t\t\t\t\t\thelp='Path to the file the contains the dictionary with the info of the dataset reduced.')\n\n\t\targs = vars(parser.parse_args())\n\n\t\tinfo_filename = args[\"filename\"]\n\n\t\t# test set\n\t\twith open(info_filename, \"rb\") as fp: # Unpickling\n\t\t\timages_info = pickle.load(fp)\n\n\t\tgrouper = itemgetter('parkinglot', 'space')\n\t\timages_info = sorted(images_info, key=grouper)\n\n\t\tparkinglots = extractUniqueItemsByKey(images_info, 'parkinglot')\n\n\t\timages_info_by_patkinglot = {}\n\n\t\tfor parkinglot in parkinglots:\n\t\t\t\timage_info_parkinglot = [i for i in images_info if i['parkinglot'] == parkinglot]\n\t\t\t\tspaces_parkinglot = extractUniqueItemsByKey(image_info_parkinglot, 'space')\n\t\t\t\timages_info_by_spaces = {}\n\t\t\t\tfor space in spaces_parkinglot:\n\t\t\t\t\t\timages_info_by_spaces[space] = [getNewImageInfo(i) for i in image_info_parkinglot if i['space'] == space]\n\t\t\t\timages_info_by_patkinglot[parkinglot] = images_info_by_spaces\n\n\t\t# Hasta este punto ya tengo un dictionario dividido por estacionamiento que a su vez se divide por espacios\n\n\t\t# Voy a obtener la lista de un espacio en particular de un estacionamiento, voy a obtener el primer espacio vacio que\n\t\t# encuentre y despues voy a compararlo con los demas\n\t\t# Mostrar en una ventana el espacio vacio y en la otra la comparacion y el resultado\n\n\n\t\tempty_space_filepath = ''\n\n\t\terrors = []\n\t\tnrmse_errors = []\n\t\tfor parkinglot, images_info_by_spaces in images_info_by_patkinglot.items():\n\t\t\t\tfor space, images_info_of_space in images_info_by_spaces.items():\n\t\t\t\t\t\terror_count_empty = 0\n\t\t\t\t\t\terror_count_occupied = 0\n\t\t\t\t\t\terror_empty = 0\n\t\t\t\t\t\terror_occupied = 0\n\t\t\t\t\t\tnrmse_error_count_empty = 0\n\t\t\t\t\t\tnrmse_error_count_occupied = 0\n\t\t\t\t\t\tnrmse_error_empty = 0\n\t\t\t\t\t\tnrmse_error_occupied = 0\n\t\t\t\t\t\tempty_space_filepath = ''\n\t\t\t\t\t\texample_list = images_info_of_space\n\t\t\t\t\t\tfor example in tqdm(example_list):\n\t\t\t\t\t\t\t\tif example['state'] == '0' and len(empty_space_filepath) == 0:\n\t\t\t\t\t\t\t\t\t\tempty_space_filepath = example['filepath']\n\t\t\t\t\t\t\t\t\t\timg_empty_space = getGrayscaleImage(empty_space_filepath)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tfor example in tqdm(example_list):\n\t\t\t\t\t\t\t\tcomparision_space_filepath = example['filepath']\n\t\t\t\t\t\t\t\timg_comparision_space = getGrayscaleImage(comparision_space_filepath)\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tsim = ssim(img_empty_space, img_comparision_space)\n\t\t\t\t\t\t\t\t\tnm = nrmse(img_empty_space, img_comparision_space)\n\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\theight1, width1 = img_empty_space.shape\n\t\t\t\t\t\t\t\t\timg_comparision_space = cv2.resize(img_comparision_space, (width1, height1))\n\t\t\t\t\t\t\t\t\tsim = ssim(img_empty_space, img_comparision_space)\n\n\n\t\t\t\t\t\t\t\t#m = mse(img_empty_space, img_comparision_space)\n\t\t\t\t\t\t\t\t#space_comparing_name = 'state: {} sim: {} mse: {}'.format(example['state'], sim, m)\n\n\t\t\t\t\t\t\t\tif sim < 0.4 and example['state'] == '0':\n\t\t\t\t\t\t\t\t\terror_count_empty += 1\n\t\t\t\t\t\t\t\t\terror_empty += abs(0.4 - sim)\n\t\t\t\t\t\t\t\tif sim >= 0.4 and example['state'] == '1':\n\t\t\t\t\t\t\t\t\terror_count_occupied += 1\n\t\t\t\t\t\t\t\t\terror_occupied += abs(sim - 0.4)\n\n\t\t\t\t\t\t\t\tif nm < 0.4 and example['state'] == '1':\n\t\t\t\t\t\t\t\t\tnrmse_error_count_empty += 1\n\t\t\t\t\t\t\t\t\tnrmse_error_empty += abs(0.4 - sim)\n\t\t\t\t\t\t\t\tif nm >= 0.4 and example['state'] == '0':\n\t\t\t\t\t\t\t\t\tnrmse_error_count_occupied += 1\n\t\t\t\t\t\t\t\t\tnrmse_error_occupied += abs(sim - 0.4)\n\n\t\t\t\t\t\t\t\t\"\"\"\n\t\t\t\t\t\t\t\tfig = plt.figure('title')\n\t\t\t\t\t\t\t\tplt.suptitle(space_comparing_name)\n\t\t\n\t\t\t\t\t\t\t\t# show first image\n\t\t\t\t\t\t\t\tax = fig.add_subplot(1, 2, 1)\n\t\t\t\t\t\t\t\tplt.imshow(img_empty_space, cmap=plt.cm.gray)\n\t\t\t\t\t\t\t\tplt.axis(\"off\")\n\t\t\n\t\t\t\t\t\t\t\t# show the second image\n\t\t\t\t\t\t\t\tax = fig.add_subplot(1, 2, 2)\n\t\t\t\t\t\t\t\tplt.imshow(img_comparision_space, cmap=plt.cm.gray)\n\t\t\t\t\t\t\t\tplt.axis(\"off\")\n\t\t\n\t\t\t\t\t\t\t\t# show the images\n\t\t\t\t\t\t\t\tplt.show()\n\t\t\t\t\t\t\t\t\"\"\"\n\t\t\t\t\t\terror_occupied = 0 if error_count_occupied == 0 else (error_occupied / error_count_occupied)\n\t\t\t\t\t\terror_empty = 0 if error_count_empty == 0 else (error_empty / error_count_empty)\n\t\t\t\t\t\tnrmse_error_occupied = 0 if nrmse_error_count_occupied == 0 else (nrmse_error_occupied / nrmse_error_count_occupied)\n\t\t\t\t\t\tnrmse_error_empty = 0 if nrmse_error_count_empty == 0 else (nrmse_error_empty / nrmse_error_count_empty)\n\t\t\t\t\t\tprint('In the space {} in a total of {} there was an ssim error of occupied {} {} empty {} {} nrmse error of occupied {} {} empty {} {}'.format(space, len(\n\t\t\t\t\t\t\t\texample_list), error_count_occupied, error_occupied, error_count_empty, error_empty,\n\t\t\t\t\t\t\t\tnrmse_error_count_occupied, nrmse_error_occupied, nrmse_error_count_empty, nrmse_error_empty))\n\t\t\t\t\t\terrors.append({'parkinglot': parkinglot, 'space': space, 'total': len(example_list),\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'error_count_occupied': error_count_occupied,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'error_occupied': error_occupied,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'error_count_empty': error_count_empty, 'error_empty': error_empty})\n\t\t\t\t\t\terrors.append({'parkinglot': parkinglot, 'space': space, 'total': len(example_list),\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'error_count_occupied': nrmse_error_count_occupied,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'error_occupied': nrmse_error_occupied,\n\t\t\t\t\t\t\t\t\t\t\t\t\t 'error_count_empty': nrmse_error_count_empty, 'error_empty': nrmse_error_empty})\n\n\t\tinfo = {'dataset': info_filename, 'threshold': 0.4, 'comparision_methods': {'sim': errors, 'nrmse': nrmse_errors}}\n\t\tdataset_name = ntpath.basename(info_filename).split('.')[0]\n\t\tfeedback_filename = '{}_{}_{}.json'.format(dataset_name, 0.4, 'sim')\n\t\twith open(feedback_filename, 'w') as outfile:\n\t\t\t\tjson.dump(info, outfile)\n\t\t#s = ssim(grayscale_selected_image, grayscale_current_image)\n\nif __name__ == \"__main__\":\n\t\tmain()","sub_path":"MyOwnSolution/compare_images.py","file_name":"compare_images.py","file_ext":"py","file_size_in_byte":7640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"523383592","text":"\"\"\"https://www.acmicpc.net/problem/11725\"\"\"\n\n\n\n\"\"\"트리의 부모 찾기\"\"\"\n\n\n# git add week_05/Re_boj_S2_11725_Heegun.py\n# git commit -m \"[김희건] boj 트리의 부모 찾기\"\n\n\n\nfrom collections import defaultdict\nimport sys\n\nsys.setrecursionlimit(1000000)\n\nN = int(input())\ngraph = defaultdict(list)\n\nfor _ in range(N-1):\n s,e = map(int,input().split())\n\n graph[s].append(e)\n graph[e].append(s)\n\n#print(graph)\n\n\nparents = [0 for _ in range(N+1)]\n\ndef dfs(s):\n for i in graph[s]:\n if parents[i] == 0:\n parents[i] = s\n dfs(i)\n\n \n\ndfs(1)\n\n\nfor i in parents[2:]:\n print(i)\n\n\n\n\n\n\n\n\n\n","sub_path":"week_05/Re_boj_S2_11725_Heegun.py","file_name":"Re_boj_S2_11725_Heegun.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"631471020","text":"from files import MediaFile\nimport os\nimport uuid\nimport re\n\nclass Image(MediaFile):\n\n CURRENT_FILEPATH = 'current'\n UUID_REGEX = \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"\n UUID_LEN = 36\n\n def __init__(self, filePath, logger, tagSource, fileManager):\n self.filePath = filePath\n self.logger = logger\n self.fileId = None\n self.tags = {}\n self.labelTags = []\n self.tagSource = tagSource\n self.fileManager = fileManager\n self._load(filePath)\n\n def _getuuid(self, string):\n \"\"\" trys to extract a uuid from a string. returns first result. generates a new one if none found \"\"\"\n if len(string) < self.UUID_LEN:\n return str(uuid.uuid4())\n\n match = re.search(self.UUID_REGEX, string)\n if match:\n return match.group(0)\n\n return str(uuid.uuid4())\n\n def _getUpdatedPath(self):\n \"\"\" updates the current path \"\"\"\n diskName = os.path.split(self.filePath)[-1]\n updatedName = self._getUpdatedName(diskName)\n path = list(os.path.split(self.filePath))\n path[-1] = updatedName\n return '/'.join(path)\n\n def _getUpdatedName(self, currentName):\n \"\"\" create a unique and descriptive name based on tags \"\"\"\n fileName = self.fileId\n\n # Add Tags\n for labelTag in self.labelTags:\n fileName.append(\"_\" + labelTag)\n\n # Add Extension\n fileName += '.' + currentName.split('.')[-1]\n\n return fileName\n\n def getHtml(self):\n \"\"\" get the html needed to display the image \"\"\"\n return \"Not Implemented\"\n\n def addTags(self, newTags):\n \"\"\" adds tags {'subclass' : ['tag1', 'tag2']}\"\"\"\n for tagClassKey in newTags:\n classTags = newTags.get(tagClassKey)\n if not self.tags.get(tagClassKey):\n self.tags[tagClassKey] = []\n\n for newTag in classTags:\n if not newTag in self.tags[tagClassKey]:\n self.tags[tagClassKey].append(newTag)\n\n self._save(self.filePath)\n\n def removeTags(self, toRemove):\n \"\"\" remove tags {'subclass' : ['tag1', 'tag2']}\"\"\"\n for tagClassKey in toRemove:\n tagsToRemove = toRemove[tagClassKey]\n tagClass = self.tags.get(tagClassKey)\n if tagClass:\n for tagToRemove in tagsToRemove:\n tagClass.remove(tagToRemove)\n\n self._save(self.filePath)\n\n def _save(self, source):\n \"\"\" save the image with the current filename, deleting old if the name changed \"\"\"\n if not self.fileManager.fileExists(self.filePath):\n raise IOError\n\n newPath = self._getUpdatedPath()\n if newPath != self.filePath:\n self.fileManager.move(source, newPath)\n self.filePath = newPath\n\n self.tagSource.update(self.fileId, self.tags)\n\n def _load(self, filePath):\n \"\"\" load the image with the current filename, deleting old if the name changed \"\"\"\n if not self.fileManager.fileExists(filePath):\n self.logger.logError(\"File Not Found: {}\".format(filePath))\n raise IOError\n\n self.filePath = filePath\n self.fileId = self._getuuid(filePath)\n self.tags = self._getTags()\n\n def _getTags(self):\n \"\"\" Extracts tags for this file ID \"\"\"\n tags = self.tagSource.lookup(self.fileId)\n if not tags:\n return self.tagSource.create(self.fileId)\n\n return tags","sub_path":"images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"390331305","text":"from django.db import models\nfrom datetime import date\nimport requests\n\n#seta a data inicial das cotações\nhoje = date.today()\ndia1 = date.fromordinal(hoje.toordinal() - 6)\ndias = []\n\n#chave para requisição do currencylayer\nkey = 'a0b70a88d40ae4f5226e23d401b4ab94'\n\n\nbrl_cotacoes = []\nars_cotacoes = []\neur_cotacoes = []\n\n#itera as listas com os dados retornados da api\nfor i in range(0, 7):\n #requisição a api do currencylayer\n parametros = {'access_key': key, 'date': dia1, 'source': 'USD', 'currencies': 'BRL,ARS,EUR'}\n requisicao = requests.get('http://apilayer.net/api/historical', params=parametros)\n json_data = requisicao.json()\n brl_cotacoes.append(json_data['quotes']['USDBRL'])\n ars_cotacoes.append(json_data['quotes']['USDARS'])\n eur_cotacoes.append(json_data['quotes']['USDEUR'])\n dias.append(str(dia1))\n dia1 = date.fromordinal(dia1.toordinal() + 1)\n\n\nBRL = {'nome': 'Real(BRL)', 'dado': brl_cotacoes}\nARS = {'nome': 'Peso Argentino(ARS)', 'dado': ars_cotacoes}\nEUR = {'nome': 'Euro(EUR)', 'dado': eur_cotacoes}\n\n#dicionário passado como dados json pela view get_dados\ncotacoes = {'BRL': BRL, 'ARS': ARS, 'EUR': EUR, 'DIAS': dias}\n","sub_path":"cotacao/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"457914015","text":"\n# To support both python 2 and python 3\nfrom __future__ import division, print_function, unicode_literals\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport timeit\nnp.random.seed(2)\n\n# ------------- Preparing data\nX = np.random.rand(10000, 1)\ny = 4 + 3 * X + .2*np.random.randn(10000, 1) # noise added\n\n\ndef grad(X, y, w):\n N = X.shape[0]\n return 1/N * X.T.dot(X.dot(w) - y)\n\n\ndef cost(X, y, w):\n N = X.shape[0]\n return .5/N*np.linalg.norm(y - X.dot(w), 2)**2\n\n\ndef myGD2(x, y, eta, w0):\n w = [w0]\n for it in range(10000):\n w_new = w[-1] - eta*grad(x, y, w[-1])\n if np.linalg.norm(grad(x, y, w_new))/len(w_new) < 1e-3:\n break\n w.append(w_new)\n return (w, it)\n\n\ndef GDwithBatch(X, Y, batchsize, eta, w0):\n w = [w0]\n X_size = X.shape[0]\n for it in range(1000):\n index = 0\n while index < X_size:\n index_to = index+batchsize\n x = X[index: index_to, :]\n y = Y[index:index_to, :]\n w_new = w[-1] - eta*grad(x, y, w[-1])\n #if np.linalg.norm(grad(x, y, w_new))/len(w_new) < 1e-3:\n if np.linalg.norm(w_new - w[-1])/len(w_new) < 1e-3: \n return (w, it)\n w.append(w_new)\n index = index_to+1\n X_temp = np.append(X,Y,axis=1)\n np.random.shuffle(X_temp)\n X = X_temp[:,:X_temp.shape[1]-1]\n Y = X_temp[:,X_temp.shape[1]-1:X_temp.shape[1]]\n return (w, it)\n\n# single point gradient\ndef sgrad(w, i, rd_id):\n true_i = rd_id[i]\n xi = Xbar[true_i, :]\n yi = y[true_i]\n a = np.dot(xi, w) - yi\n return (xi*a).reshape(2, 1)\n\ndef SGD(X,y, eta,w_init):\n w = [w_init]\n w_last_check = w_init\n iter_check_w = 10\n N = X.shape[0]\n count = 0\n for it in range(10):\n # shuffle data \n rd_id = np.random.permutation(N)\n for i in range(N):\n count += 1 \n g = sgrad(w[-1], i, rd_id)\n w_new = w[-1] - eta*g\n w.append(w_new)\n if count%iter_check_w == 0:\n w_this_check = w_new \n if np.linalg.norm(w_this_check - w_last_check)/len(w_init) < 1e-3: \n return w\n w_last_check = w_this_check\n return w,it\n\n# Building Xbar\none = np.ones((X.shape[0], 1))\nXbar = np.concatenate((one, X), axis=1)\n\n# init weight\nw = np.array([[2], [3]])\n\n# ------------- Learning GD and print result\nstart = timeit.default_timer()\n#(w_new, it1) = myGD2(Xbar, y, 1, w)\n(w_new, it1) = GDwithBatch(Xbar, y,50, 1, w)\n#(w_new, it1) = SGD(Xbar, y, 1, w)\nend = timeit.default_timer()\nprint('Time: ',end-start)\n\nprint('GD: weight= ', w_new[-1])\nprint('GD: cost = %f, obtained after %d iterations' %\n (cost(Xbar, y, w_new[-1]), it1))\n\n# ------------- Learning LinerRegression and print result\n# A = np.dot(Xbar.T, Xbar)\n# b = np.dot(Xbar.T, y)\n# w_lr = np.dot(np.linalg.pinv(A), b)\n# print('LR: weight = ', w_lr.T)\n# print('LR: cost = %f' % (cost(Xbar, y, w_lr)))\n\n# # ------------- Display result\n# w = w_new[-1]\n# w_0 = w[0][0]\n# w_1 = w[1][0]\n# x0 = np.linspace(0, 1, 2, endpoint=True)\n# y0 = w_0 + w_1*x0\n\n# Draw the fitting line\n# plt.plot(X.T, y.T, 'b.') # data\n# plt.plot(x0, y0, 'y', linewidth=2) # the fitting line\n# plt.axis([0, 1, 0, 10])\n# plt.show()\n\n","sub_path":"GD/MLCB_GD2.py","file_name":"MLCB_GD2.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"122600281","text":"import os\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset\nimport numpy as np\n\n# from .spermFeatureDataLoaderNormalized_unsqueezed import SpermFeatureDatasetNormalizedUnsqueezed\n\n\n\n\ndata_csv_file = \"/home/vajira/DL/Medicotask_2019/csv_files/semen_analysis_data.csv\"\nid_csv_file = \"/home/vajira/DL/Medicotask_2019/csv_files/videos_id.csv\"\n\ndata_root = \"/work/vajira/data/stacked_original_frames_9x256x256/fold_1\"\ncolumns_to_return = [\"Head defects (%)\",\"Non progressive sperm motility (%)\", \"Immotile sperm (%)\"]\n\n\ndef get_dataframe_of_subdirectorylist(root_dir):\n d = {'video_directory_name': [], 'file_name': []}\n df = pd.DataFrame(data=d)\n\n for d in os.listdir(root_dir):\n full_d = os.path.join(root_dir, d)\n\n for f in os.listdir(full_d):\n df2 = pd.DataFrame({'video_directory_name': [d], 'file_name': [f]})\n df = df.append(df2, ignore_index=True)\n\n return df\n\n\nclass SpermFeatureDatasetNormalizedUnsqueezed(Dataset):\n\n def __init__(self, csv_file_data, csv_file_id, root_dir, selected_dataColums):\n self.sperm_original_data = pd.read_csv(csv_file_data, sep=\";\", decimal=\",\")\n\n self.normalized_data = self.sperm_original_data.iloc[:, 1:]\n\n self.mean = self.normalized_data.mean()\n self.std = self.normalized_data.std()\n\n #print(self.std)\n #print(self.mean)\n\n self.normalized_data = (self.normalized_data - self.mean) / self.std\n # self.normalized_data = (self.normalized_data - self.normalized_data.min())/\n # (self.normalized_data.max() - self.normalized_data.min())\n # self.normalized_data = (self.normalized_data)# / 100\n\n self.non_nomalized_data = self.normalized_data * self.std + self.mean # * 100 # to check the accuracy of recovering data\n # print(self.non_nomalized_data)\n\n self.normalized_data[\"ID\"] = self.sperm_original_data[\"ID\"]\n self.non_nomalized_data[\"ID\"] = self.sperm_original_data[\"ID\"]\n\n self.sperm_analysed_data = self.normalized_data # pd.read_csv(csv_file_data, sep=\";\", decimal=\",\")\n self.sperm_video_ids = pd.read_csv(csv_file_id, sep=\";\")\n self.root_dir = root_dir\n\n self.data_df = get_dataframe_of_subdirectorylist(root_dir)\n self.data_columns = selected_dataColums\n\n def __len__(self):\n return len(self.data_df)\n\n def __getitem__(self, idx):\n # img_tuple = self.image_data[idx] # read image data\n data_row = self.data_df.iloc[idx]\n\n\n video_name = data_row[\"video_directory_name\"]\n file_name = data_row[\"file_name\"]\n\n data_recod_id = self.sperm_video_ids.loc[\n self.sperm_video_ids[\"video\"] == video_name][\"ID\"].item()\n\n df_record = self.sperm_analysed_data.loc[self.sperm_analysed_data[\"ID\"] == data_recod_id]\n df_record_non_normalized = self.non_nomalized_data.loc[self.sperm_analysed_data[\"ID\"] == data_recod_id]\n\n # df_record_normalized = (df_record.iloc[:,1:] - df_record.iloc[:, 1:].mean())/df_record.iloc[:, 1:].std()\n # df_record_normalized[\"ID\"] = df_record[\"ID\"]\n data_values = df_record[self.data_columns].values\n data_values = np.squeeze(data_values)\n # data_values = data_values.astype('double') # .reshape(-1, 1)\n\n # get non-normalized data\n data_values_non_normalized = df_record_non_normalized[self.data_columns].values\n data_values_non_normalized = np.squeeze(data_values_non_normalized)\n\n\n # load pt files to return\n features_dir = os.path.join(self.root_dir, video_name)\n pt_file = os.path.join(features_dir, file_name)\n\n feature_tensor = torch.load(pt_file, map_location=torch.device('cpu')) # map_location=torch.device('cpu')\n # feature_tensor = feature_tensor.unsqueeze(0) # to add a channel dimension\n feature_tensor = feature_tensor.detach() # requires_grad(False)\n feature_tensor = feature_tensor.numpy()\n \n #print(feature_tensor.shape)\n sample = {\"features\": feature_tensor,\n 'data_normalized': data_values,\n 'data_non_normalized': data_values_non_normalized}\n\n return sample\n\nif __name__==\"__main__\":\n data = SpermFeatureDatasetNormalizedUnsqueezed(data_csv_file,id_csv_file, data_root, columns_to_return)\n m = data.mean[columns_to_return].values\n s = data.std[columns_to_return].values\n print(m)\n print(s)\n print(len(data))\n # print()\n print(data[600]['features'].shape)\n print(data[600]['data_normalized'] * s + m)\n print(data[600]['data_non_normalized'])\n","sub_path":"Dataloaders/spermFeatureDataLoaderNormalized_unsqueezed_stackedFrames.py","file_name":"spermFeatureDataLoaderNormalized_unsqueezed_stackedFrames.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"16726043","text":"from itertools import combinations\n\n# goal is to print every combination from 1 to n\n# inputs a word and a number seperated with space\nword = input().split()\n\n# range is from 1 to the n\nfor x in range(1,int(word[1])+1):\n myList = sorted((combinations(sorted(word[0]),x)))\n print(myList)\n for y in myList:\n print(\"\".join(y))\n\n\n","sub_path":"Python/Hackerrank/Built-in Functions/Combinations.py","file_name":"Combinations.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"235706958","text":"from bottle import Bottle, run, route, get, post, request, static_file\nfrom bottle import TEMPLATE_PATH, jinja2_template as template\nimport sqlite3\nimport datetime\nfrom const import DB_NAME\nimport markdown\nimport os\n\napp = Bottle()\nmarkdown = markdown.Markdown()\n\n# CSSとか\n@app.get(\"/static/<filename:path>\")\ndef css(filename):\n return static_file(filename, root=\"./static/\")\n\n# 画像\n@app.get('/static/img/<filename:path>')\ndef img(filename):\n return static_file(filename, root=\"./static/img/\")\n\n# トップページ\n@app.get('/')\ndef top():\n return template('views/top.html')\n\n# 記事一覧の閲覧\n@app.get('/showlist')\ndef show_list():\n blogs = ExecuteGetContents(\\\n 'SELECT * FROM blogs INNER JOIN categories ON blogs.category_id = categories.category_id')\n if not blogs:\n return '記事はまだありません。'\n else:\n return template('views/showlist.html', blogs = blogs)\n\n# 指定された記事の閲覧\n@app.get('/showblog<id:re:[0-9]+>')\ndef show(id):\n blog = ExecuteGetContent('SELECT * FROM blogs WHERE id = %s' % id)\n if not blog:\n return 'このアイテムはみつかりませんでした。'\n else:\n content = markdown.convert(blog[2])\n return template('views/show.html', blog = blog, content = content)\n\n#カテゴリ一覧\n@app.get('/show_categorylist')\ndef show_categorylist():\n categories = ExecuteGetContents(\"SELECT * FROM categories\")\n return template('show_categorylist', categories=categories)\n\n# 指定されたカテゴリの記事一覧\n@app.get('/show_category<id:re:[0-9]+>')\ndef show_category(id):\n blogs = ExecuteGetContents('SELECT * FROM blogs WHERE category_id = %s' % id)\n category = ExecuteGetContents('SELECT * FROM categories WHERE category_id = %s' % id)\n print(blogs)\n if not blogs:\n return 'このアイテムはみつかりませんでした。'\n else:\n return template('views/show_category.html', blogs = blogs, category = category)\n\n# 記事一覧ページ\n@app.get('/admin/showlist')\ndef show_list():\n blogs = ExecuteGetContents(\\\n 'SELECT * FROM blogs INNER JOIN categories ON blogs.category_id = categories.category_id')\n if not blogs:\n return '記事はまだありません。'\n else:\n return template('admin/showlist.html', blogs = blogs)\n\n# 指定された記事の閲覧\n@app.get('/admin/showblog<id:re:[0-9]+>')\ndef show(id):\n blog = ExecuteGetContent('SELECT * FROM blogs WHERE id = %s' % id)\n if not blog:\n return 'このアイテムはみつかりませんでした。'\n else:\n content = markdown.convert(blog[2])\n return template('admin/show.html', blog = blog, content = content)\n\n\n# SQLクエリを実行する\ndef ExecuteQuery(query):\n conn = sqlite3.connect(DB_NAME)\n cursor = conn.cursor()\n cursor.execute(query)\n conn.commit()\n cursor.close()\n\n# SELECT文を実行して、その内容を得る\ndef ExecuteGetContents(get_contents_query):\n conn = sqlite3.connect(DB_NAME)\n cursor = conn.cursor()\n cursor.execute(get_contents_query)\n result = cursor.fetchall()\n return result\n\n#SELECT文を実行して、その最初の内容を得る\ndef ExecuteGetContent(get_content_query):\n conn = sqlite3.connect(DB_NAME)\n cursor = conn.cursor()\n cursor.execute(get_content_query)\n result = cursor.fetchone()\n return result\n\n\n####admin#####\n@app.get('/admin')\ndef admin():\n return template('admin/top.html')\n\n# 記事作成ページ\n@app.get('/admin/create')\ndef create():\n categories = ExecuteGetContents('SELECT * FROM categories')\n return template('admin/create.html', categories=categories)\n# 記事を作成\n@app.post('/admin/create')\ndef do_create():\n title = request.POST.getunicode('title')\n content = request.POST.getunicode('content')\n category_id = request.POST.getunicode('category')\n\n conn = sqlite3.connect(DB_NAME)\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO blogs (title, content, created_at, category_id) VALUES(?, ?, ?, ?)\", (title, content, str(datetime.datetime.now()), category_id))\n conn.commit()\n cursor.close()\n\n return template('admin/top.html')\n\n# カテゴリ作成ページ\n@app.get('/admin/create_category')\ndef create_category():\n return template('admin/create_category.html')\n# カテゴリを作成\n@app.post('/admin/create_category')\ndef create_category():\n category_name = request.POST.getunicode('category')\n ExecuteQuery('INSERT INTO categories (category_name) values (\"%s\")' % category_name)\n return template('admin/top.html')\n\n#カテゴリ一覧\n@app.get('/admin/show_categorylist')\ndef show_categorylist():\n categories = ExecuteGetContents(\"SELECT * FROM categories\")\n return template('admin/show_categorylist', categories=categories)\n# 指定されたカテゴリの記事一覧\n@app.get('/admin/show_category<id:re:[0-9]+>')\ndef show_category(id):\n blogs = ExecuteGetContents('SELECT * FROM blogs WHERE category_id = %s' % id)\n print(blogs)\n if not blogs:\n return 'このアイテムはみつかりませんでした。'\n else:\n return template('admin/show_category.html', blogs = blogs)\n\n\n# 編集ページ\n@app.get('/admin/updateblog<id:re:[0-9]+>')\ndef update(id):\n blog = ExecuteGetContent('SELECT * FROM blogs WHERE id = %s' % id)\n return template('admin/update.html', blog = blog)\n# 編集を実行\n@app.post('/admin/updateblog<id:re:[0-9]+>')\ndef do_update(id):\n title = request.POST.getunicode('title')\n content = request.POST.getunicode('content')\n conn = sqlite3.connect(DB_NAME)\n cursor = conn.cursor()\n cursor.execute('UPDATE blogs SET title = ?, content = ? where id = ?', (title, content, id))\n conn.commit()\n cursor.close()\n blog = ExecuteGetContent('SELECT * FROM blogs WHERE id = %s' % id)\n return template('admin/show.html', blog = blog, content=content)\n\n# 記事作成\n@app.post('/admin/deleteblog<id:re:[0-9]+>')\ndef delete(id):\n ExecuteQuery('DELETE FROM blogs where id = %s' % id)\n blogs = ExecuteGetContents('SELECT * FROM blogs')\n return template('admin/showlist.html', blogs = blogs)\n\n# 画像のアップロード画面を表示\n@app.get('/admin/upload_img')\ndef update_img():\n return template('admin/upload_img.html')\n# 画像をアップロード\n@app.post('/admin/upload_img')\ndef do_update_img():\n upload = request.files.get('upload_img', '')\n if not upload.filename.lower().endswith(('.png', '.jpg', '.jpeg')):\n return 'File extension not allowed!'\n save_path = get_save_path()\n upload.save(save_path)\n return 'Upload OK. FilePath: %s%s' % (save_path, upload.filename)\ndef get_save_path():\n dt_now = datetime.datetime.now()\n path_dir = \"./static/img/\" + str(dt_now.year) + \"/\" + str(dt_now.month) + \"/\" + str(dt_now.day)\n os.makedirs(path_dir, exist_ok=True)\n return path_dir\n\nrun(app=app, host='localhost', port=8080, reloader=True, debug=True)\n\n# 参考サイト\n# http://note.kurodigi.com/python-bottle-01/\n# https://www.takasay.com/entry/2015/07/04/010000\n# https://qiita.com/Gen6/items/f1636be0fe479f42b3ee\n# https://qiita.com/masakuni-ito/items/593b9d753c44da61937b\n\n# todo\n# ・削除あとの全記事閲覧ページでのカテゴリ表示がされてない\n# ・カテゴリ一覧\n# ・カテゴリ別一覧","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"257673933","text":"import csv\nimport os\n\nfrom django.shortcuts import render\nfrom django.views.generic import TemplateView, ListView\nfrom django.http import HttpResponse, request\nfrom .models import CourseContent, Prof, Spec\n\n\n# Create your views here.\n# def HomePage(request):\n# return HttpResponse(\"Hey Mara\")\n\nclass HomePage(ListView):\n model = CourseContent\n template_name = 'home.html'\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.import_csvs()\n\n def import_csvs(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n specs = []\n lecturers = []\n\n with open(dir_path + '/professors_tab.tsv', encoding='utf-8') as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n # Professor,Description,Specialization\n # Professor\tDescription\tSpecializations\tFOMO\n\n for i, row in enumerate(reader):\n\n if i == 0:\n continue\n\n spec = Spec()\n spec.special=row[2]\n spec.FOMO=row[3]\n spec.save()\n specs.append(spec)\n\n with open(dir_path + '/professors_tab.tsv', encoding='utf-8') as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n # Professor,Description,Specialization\n # Professor\tDescription\tSpecializations\tFOMO\n\n for i, row in enumerate(reader):\n\n if i == 0:\n continue\n\n x = Prof()\n x.prof = row[0]\n x.description = row[1]\n for item in specs:\n if row[2] == item.special:\n x.specialisation = item\n break\n\n x.save()\n lecturers.append(x)\n\n with open(dir_path + '/course_list_tab.tsv', encoding='utf-8') as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n # Number,Title,Faculty,Semester,Section,Credits,Modality**\n\n for i, row in enumerate(reader):\n\n if i == 0:\n continue\n\n faculty = \"\"\n if \";\" in row[2]:\n x = row[2].split(\";\")\n for item in x:\n faculty += item\n else:\n faculty = row[2]\n\n found = False\n for item in lecturers:\n if faculty in item.prof or item.prof in faculty:\n faculty = item\n found = True\n break\n if not found:\n faculty = None\n\n x = CourseContent()\n\n x.ID = row[0]\n x.title = row[1]\n x.faculty = faculty\n x.semester = row[3]\n x.section = row[4]\n x.course_credits = row[5]\n x.modality = row[6]\n x.save()\n\n\n","sub_path":"course_picker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"451377927","text":"\"\"\"Practice with dictionaries.\"\"\"\n\n__author__ = \"730391424\"\n\n# Define your functions below\n\n\ndef main() -> None:\n \"\"\"Main.\"\"\"\n original_dict: dict[str, str]\n original_dict = {\"a\": \"b\", \"c\": \"d\"}\n print(invert(original_dict))\n colors: dict[str, str]\n colors = {\"Nupur\": \"blue\", \"Lydia\": \"orange\", \"Ellie\": \"blue\", \"Saurya\": \"blue\", \"Meredith\": \"green\"}\n print(favorite_color(colors))\n list0: list[str] = [\"a\", \"b\", \"c\", \"c\", \"d\"]\n print(count(list0))\n\n\ndef invert(original_dict: dict[str, str]) -> dict[str, str]:\n \"\"\"A function that inverts a dictionary.\"\"\"\n inverted_dict: dict[str, str] = {}\n for key in original_dict:\n if original_dict[key] in inverted_dict:\n raise KeyError(\"You can't have duplicate keys!\")\n else:\n inverted_dict[original_dict[key]] = key\n return inverted_dict\n\n\ndef favorite_color(colors: dict[str, str]) -> str:\n \"\"\"A function that returns the most popular favorite color.\"\"\"\n favorite_color: str = \"\"\n colors_dict: dict[str, int] = {}\n for key in colors:\n colors_dict[colors[key]] = 1\n for key in colors: \n if colors[key] in colors_dict:\n colors_dict[colors[key]] += 1\n max: int = 1 \n for key in colors_dict:\n if colors_dict[key] > max:\n max = colors_dict[key]\n favorite_color = key\n return favorite_color\n\n\ndef count(list0: list[str]) -> dict[str, int]:\n \"\"\"A function that keeps score.\"\"\"\n count_dict: dict[str, int] = {}\n for item in list0:\n count_dict[item] = 0\n for item in list0:\n if item in count_dict: \n count_dict[item] = count_dict[item] + 1\n return count_dict\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"exercises/ex06/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"397439597","text":"class Book:\n def __init__(self, name, author, price) -> None:\n self.name = name\n self.author = author\n self.price = price\n \n def __str__(self) -> str:\n return f'{self.name} by {self.author}'\n \n def __repr__(self) -> str:\n return f'{self.name} by {self.author}'\n\n\nif __name__ == '__main__':\n books_raw = [\n {'name': 'Book1', 'author': 'Tareq', 'price': 100},\n {'name': 'Book2', 'author': 'John', 'price': 200},\n {'name': 'Book3', 'author': 'Alif', 'price': 150},\n ]\n\n books_obj = []\n\n for book in books_raw:\n books_obj.append(\n Book(**book)\n )\n\n\n for book_obj in books_obj:\n print(\n book_obj.name,\n book_obj.author,\n book_obj.price\n )\n\n\n","sub_path":"classes_without_main.py","file_name":"classes_without_main.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"137482221","text":"import bs4, requests\r\nfrom bs4 import BeautifulSoup\r\nimport lxml\r\n\r\n#pos1 = 'QB'\r\n#yr = '2012'\r\n#wk = '1'\r\n#i = 0\r\n#filename = \"testfile.csv\"\r\n\r\n\r\n\r\ndef scrape(yr, wk, filename):\r\n url = 'https://www.fantasypros.com/nfl/reports/leaders/dst.php?year=' + yr + '&start=1&end='+wk\r\n headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}\r\n r = requests.get(url, headers=headers)\r\n data = r.text\r\n soup = BeautifulSoup(data, 'lxml')\r\n\r\n list = []\r\n\r\n table = soup.find_all('table')\r\n\r\n for row in table:\r\n col = row.find_all('td')\r\n col = [ele.text.strip() for ele in col]\r\n list.append([ele for ele in col if ele])\r\n x = 0\r\n j = 0\r\n #print(list[0][1])\r\n name = \"\"\r\n pos = 0\r\n size = len(list[0])\r\n #j=filename\r\n file = open(filename, \"a\")\r\n file.write(yr + ', ' + wk + ', ')\r\n for i in range(size):\r\n line = list[0][i] + ', '\r\n file.write(line)\r\n x += 1\r\n j += 1\r\n if x == 5:\r\n x = 0\r\n file.write('\\n')\r\n if j != 160:\r\n file.write(yr + ', ' + wk + ', ')\r\ndef main():\r\n #arrays from which to loop\r\n filename = 'dscraperesults.csv'\r\n years = ['2012', '2013', '2014', '2015', '2016', '2017']\r\n for x in range(0, 6):\r\n print('Year: ' + str(x))\r\n for i in range(1, 18):\r\n print('Week: ' + str(i))\r\n scrape(years[x], str(i), filename)\r\n\r\n\r\n#if __name__ == \"__main__\":\r\n# main()\r\n\r\n\r\n\r\nmain()","sub_path":"BackEnd/defense scraper.py","file_name":"defense scraper.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"25671365","text":"from icarus.query.query_classes import SearchQuery\nfrom icarus.query.query_model import FacetRange\nfrom icarus.test.integration.abstract_test_classes import IcarusIntegrationTestCase\nfrom icarus.test.integration.dummy_doc_util import insert_dummy_doc\nfrom icarus.test.integration.solr_util import get_test_interface\n\n__author__ = 'shillaker'\n\n\nclass FacetingIntegrationTest(IcarusIntegrationTestCase):\n def setUp(self):\n super(FacetingIntegrationTest, self).setUp()\n\n self.ii = get_test_interface()\n\n # Insert dummy docs\n self.doc_a = insert_dummy_doc(price=15.00)\n self.doc_b = insert_dummy_doc(price=25.00)\n self.doc_c = insert_dummy_doc(price=35.00)\n self.doc_d = insert_dummy_doc(price=45.00)\n\n # Tests basic faceting on field\n def test_basic_facet_field(self):\n # Simple query\n q = SearchQuery(self.ii)\n q.add_facet_field('brand')\n actual = q.execute(0, 1)\n actual_facet_fields = actual.facet_counts['facet_fields']\n\n # Check we get four results\n self.assertEqual(actual.n_total, 4)\n\n # Expected facet count result\n expected_facet_fields = {\n 'brand': [\n (self.doc_a['brand'], 1),\n (self.doc_b['brand'], 1),\n (self.doc_c['brand'], 1),\n (self.doc_d['brand'], 1)\n ]\n }\n\n # Check the result is as expected\n self.assertDictEqual(expected_facet_fields, actual_facet_fields)\n\n # Tests range faceting\n def test_range_facet(self):\n # Simple query\n q = SearchQuery(self.ii)\n fr = FacetRange('price', 10, 50, 10)\n q.add_facet_range(fr)\n actual = q.execute(0, 1)\n\n # Check we get four results\n self.assertEqual(actual.n_total, 4)\n\n # Expected facet count result\n expected_facet_counts = {\n 'facet_fields': {},\n 'facet_ranges': {\n 'price': {\n 'counts': [\n (\"10.0\", 1),\n (\"20.0\", 1),\n (\"30.0\", 1),\n (\"40.0\", 1)\n ],\n 'gap': 10.0,\n 'start': 10.0,\n 'end': 50.0\n }\n }\n }\n\n # Check the result is as expected\n self.assertDictEqual(actual.facet_counts, expected_facet_counts)\n","sub_path":"icarus/test/integration/int_test_faceting.py","file_name":"int_test_faceting.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"74302379","text":"import pyblish.api\n\n\nclass AnimationFPSValidator(pyblish.api.InstancePlugin):\n\n order = pyblish.api.ValidatorOrder - 0.29\n label = 'Validate Animation FPS'\n families = ['lyt', 'anm']\n\n def process(self, instance):\n from maya import cmds\n\n assert cmds.currentUnit(q=True, time=True) == 'pal', \\\n 'Current FPS is NOT 25.'\n\n @staticmethod\n def fix(objects):\n from maya import cmds\n\n cmds.currentUnit(time='pal', updateAnimation=False)\n return True\n\n\nclass AnimationCameraValidator(pyblish.api.InstancePlugin):\n\n order = pyblish.api.ValidatorOrder - 0.28\n label = 'Validate Animation Camera'\n families = ['lyt', 'anm']\n\n def process(self, instance):\n from maya import cmds\n\n for shape in cmds.ls(type='camera'):\n cam = cmds.listRelatives(shape, allParents=True)[0]\n if cam == 'MainCam':\n break\n else:\n assert False, 'MainCam NOT found.'\n\n\nclass AnimationExtractor(pyblish.api.InstancePlugin):\n\n order = pyblish.api.ExtractorOrder\n label = 'Export FBX Data'\n families = ['lyt', 'anm']\n\n def process(self, instance):\n import os\n from maya import cmds, mel\n import samkit\n\n task = instance.data['task']\n samkit.open_file(task)\n\n name = instance.data['name']\n path = instance.data['pathDat'].replace('\\\\', '/')\n project = task['project']\n tag = task['tag']\n\n mint = int(cmds.playbackOptions(q=1, min=1))\n maxt = int(cmds.playbackOptions(q=1, max=1))\n mins = '%04d' % mint\n maxs = '%04d' % maxt\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n for ref in cmds.ls(type='reference'):\n if ref != 'sharedReferenceNode':\n cmds.file(importReference=True, referenceNode=ref)\n\n mel.eval('FBXExportAnimationOnly -v false;')\n mel.eval('FBXExportApplyConstantKeyReducer -v false;')\n mel.eval('FBXExportBakeComplexStart -v %s;' % mint)\n mel.eval('FBXExportBakeComplexEnd -v %s;' % maxt)\n mel.eval('FBXExportBakeComplexStep -v 1;')\n mel.eval('FBXExportBakeResampleAnimation -v true;')\n mel.eval('FBXExportAxisConversionMethod convertAnimation;')\n mel.eval('FBXExportBakeComplexAnimation -v true;')\n mel.eval('FBXExportCameras -v false;')\n mel.eval('FBXExportConstraints -v false;')\n mel.eval('FBXExportEmbeddedTextures -v false;')\n mel.eval('FBXExportFileVersion -v FBX201400;')\n mel.eval('FBXExportGenerateLog -v false;')\n mel.eval('FBXExportLights -v false;')\n mel.eval('FBXExportQuaternion -v quaternion;')\n mel.eval('FBXExportReferencedAssetsContent -v false;')\n mel.eval('FBXExportScaleFactor 1.0;')\n mel.eval('FBXExportShapes -v false;')\n mel.eval('FBXExportSkeletonDefinitions -v false;')\n mel.eval('FBXExportSkins -v false;')\n mel.eval('FBXExportSmoothingGroups -v false;')\n mel.eval('FBXExportSmoothMesh -v false;')\n mel.eval('FBXExportTangents -v true;')\n mel.eval('FBXExportUpAxis z;')\n mel.eval('FBXExportUseSceneName -v true;')\n\n chars = []\n anims = []\n family = instance.data['family']\n for joint in cmds.ls(type='joint'):\n try:\n char = joint.split(':')[0]\n skel = cmds.getAttr('%s.UE_Skeleton' % joint)\n anim = '{project}_{tag}_{name}_{family}_{char}'.format(**locals())\n chars.append(skel)\n anims.append(anim)\n print('joint ------------ ' + joint)\n print('skel ------------ ' + skel)\n instance.data['message'] = {\n 'stage': task['stage'],\n 'source': '%s/%s.fbx' % (path, anim),\n 'target': '/Game/%s' % task['path'].split(';')[1],\n 'skeleton': skel,\n 'shot': {\n 'fps': 25.0,\n 'start': float(mint),\n 'end': float(maxt),\n }\n }\n\n except ValueError:\n continue\n\n namespace = ':'+':'.join(joint.split(':')[:-1])\n\n cmds.select(joint, r=True)\n try:\n cmds.parent(joint, world=True)\n except: pass\n\n if namespace != ':':\n cmds.namespace(removeNamespace=namespace, mergeNamespaceWithRoot=True)\n\n mel.eval('FBXExport -f \"%s\" -s' % instance.data['message']['source'])\n\n samkit.ue_command(instance.data['message'])\n cmds.delete()\n\n try:\n instance.data['message'] = {\n 'stage': 'cam',\n 'source': '{path}/{project}_{tag}_{name}_{family}_MainCam_S{mins}_E{maxs}.fbx'.format(**locals()),\n 'target': '/Game/%s' % task['path'].split(';')[1],\n 'shot': {\n 'fps': 25.0,\n 'start': float(mint),\n 'end': float(maxt),\n 'chars': chars,\n 'anims': anims,\n }\n }\n\n cmds.duplicate('MainCam', name='OutputCam')\n try: cmds.parent('OutputCam', world=True)\n except: pass\n cmds.xform('OutputCam', ra=[0.0, -90.0, 0.0], roo='xzy', p=True)\n cmds.parentConstraint('MainCam', 'OutputCam', mo=True)\n cmds.connectAttr('MainCamShape.focalLength', 'OutputCamShape.focalLength', f=True)\n\n cmds.select('OutputCam', r=True)\n cmds.setKeyframe('OutputCamShape.fl', t=['0sec'])\n mel.eval('FBXExportCameras -v true;')\n mel.eval('FBXExportApplyConstantKeyReducer -v false;')\n mel.eval('FBXExport -f \"%s\" -s' % instance.data['message']['source'])\n\n samkit.ue_command(instance.data['message'])\n\n except ValueError:\n pass\n\n samkit.open_file(task, True)\n","sub_path":"maya/scripts/samkit/plugins/anm.py","file_name":"anm.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"507674210","text":"import datetime\nfrom nose.tools import eq_, raises\nfrom textwrap import dedent\n\nfrom pyecharts_javascripthon.api import TRANSLATOR\n\n\ndef test_basic_usage():\n\n def my_fmt(x):\n return x + 5\n\n def my_fmt2(x, z, y):\n return '{x},{y},{z}'.format(x=x, y=y, z=z)\n\n source = {'a': '23', 'b': my_fmt, 'c': my_fmt2, 'd': '-=>test<=-'}\n snippet = TRANSLATOR.translate(source)\n assert 'function my_fmt' in snippet.function_snippet\n assert 'function my_fmt2' in snippet.function_snippet\n assert 'function test' not in snippet.function_snippet\n assert '\"my_fmt\"' not in snippet.option_snippet\n assert '\"my_fmt2\"' not in snippet.option_snippet\n assert '\"-=>test<=-\"' in snippet.option_snippet\n\n source2 = {'e': my_fmt}\n snippet = TRANSLATOR.translate(source2)\n assert 'function my_fmt' in snippet.function_snippet\n assert '\"my_fmt\"' not in snippet.option_snippet\n\n\ndef test_datetime():\n a_date_time = datetime.datetime(2018, 4, 20, 19, 2, 30)\n option = {'datetime': a_date_time}\n expected = \"\"\"\n {\n \"datetime\": \"2018-04-20T19:02:30\"\n }\n \"\"\"\n\n actual = TRANSLATOR.translate(option)\n eq_(actual.option_snippet, dedent(expected).strip())\n\n\ndef test_date():\n a_date = datetime.date(2018, 4, 20)\n option = {'date': a_date}\n expected = \"\"\"\n {\n \"date\": \"2018-04-20\"\n }\n \"\"\"\n\n actual = TRANSLATOR.translate(option)\n eq_(actual.option_snippet, dedent(expected).strip())\n\n\n@raises(Exception)\ndef test_time():\n a_time = datetime.time(19, 2, 30)\n option = {'time': a_time}\n TRANSLATOR.translate(option)\n","sub_path":"tests/test_translator.py","file_name":"test_translator.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"2013636","text":"# Main program starts here\ndef make_sublist(a_list):\n new_list = []\n for x in range(len(a_list)+1):\n item_x = a_list[0:x]\n if item_x not in new_list:\n new_list.append(item_x)\n for y in range(len(a_list)+1):\n item_xy = a_list[y:x]\n if item_xy not in new_list:\n new_list.append(item_xy)\n return new_list\n \n \n\n\nuser_input = input(\"Enter a list separated with commas: \")\na_list = user_input.split(\",\") \nsub_lists = make_sublist(a_list)\n\n# This should be the last statement in your main program/function \nprint(sorted(sub_lists))\n","sub_path":"Assignments/MidTerm2_3.py","file_name":"MidTerm2_3.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"530503282","text":"# The entertainment_center.py file is used to create the movie list and \n# and open the webpage with said list as an argument.\n# In order to do so, it imports two additional python files:\n# media.py that contains the class definition of the movies and \n# fresh_tomatoes.py which provides the html \"scaffolding\" of the webpage.\n\nimport media\nimport fresh_tomatoes\n\n\nlawrence_of_arabia = media.Movie(\"Lawrence Of Arabia\", \"How a man's determina\"\n \"tion changed the face of History\",\n \"http://www.filmaps.com/nposters/n-419923664\"\n \"-300412011951.jpg\",\n \"https://www.youtube.com/watch?v=XgmdcZEz_\"\n \"b0\", \"1962\")\n\navatar = media.Movie(\"Avatar\", \"A marine on an alien planet\",\n \"http://cdn.traileraddict.com/content/20th-century-fox/\"\n \"avatar-6.jpg\",\n \"https://www.youtube.com/watch?v=5PSNL1qE6VY\", \"2009\")\n\na_beautiful_mind = media.Movie(\"A Beautiful Mind\", \"A story love and science\"\n \" overcoming madness\",\n \"https://upload.wikimedia.org/wikipedia/en/b/\"\n \"b8/A_Beautiful_Mind_Poster.jpg\",\n \"https://www.youtube.com/watch?v=aS_d0Ayjw4o\",\n \"2001\")\n\nthe_matrix = media.Movie(\"The Matrix\", \"The Matrix has us\",\n \"http://www.cyber-cinema.com/gallery/MatrixC.jpg\",\n \"https://www.youtube.com/watch?v=m8e-FF8MsqU\",\n \"1999\")\n\nthe_ice_age = media.Movie(\"The Ice Age\", \"Three animals return a baby human\"\n \"to its family\", \"http://vignette4.wikia.nocookie.\"\n \"net/iceage/images/9/94/Ice_Age_Original_Poster.\"\n \"jpg/revision/latest?cb=20100512224000\",\n \"https://www.youtube.com/watch?v=cMfeWyVBidk\",\n \"2002\")\n\nequilibrium = media.Movie(\"Equilibrium\", \"A man takes on the system that \"\n \"created him\", \"http://cafegeek.org/ax/pics/images\"\n \"/urlgeg.jpg\", \"https://www.youtube.com/watch?v=\"\n \"raleKODYeg0\", \"2002\")\n\nmovies = [lawrence_of_arabia, avatar, a_beautiful_mind, the_matrix,\n the_ice_age, equilibrium]\n\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"443377504","text":"'''\r\nCreated on Jun 9, 2014\r\n\r\nPart of the codes are from git-cc (https://github.com/landys/git-cc).\r\n@author: Wang Jinde\r\n'''\r\n\r\nfrom os.path import join, isdir\r\nimport os, stat\r\nimport common\r\nfrom fnmatch import fnmatch\r\nfrom re import search\r\nfrom mstr.exception import AppError\r\nfrom cleartool import LongLshFmt, ShortLshFmt\r\nimport logging\r\n\r\n\"\"\"\r\nThings remaining:\r\n1. Renames with no content change. Tricky.\r\n\"\"\"\r\n\r\nDELIM = '|'\r\n\r\nclass CC2Git(object):\r\n def __init__(self, repo, ct, sync_config, core_config):\r\n self.repo = repo\r\n self.ct = ct\r\n self.sync_config = sync_config\r\n self.core_config = core_config\r\n \r\n def sync_cc_to_git(self):\r\n self.since = self.get_since()\r\n self.new_since = common.get_since_utc_time(self.core_config.get_since_delta());\r\n \r\n start_history = self.get_start_history(self.since)\r\n \r\n logger = logging.getLogger(__name__)\r\n logger_level = logger.getEffectiveLevel()\r\n if logger_level <= logging.DEBUG:\r\n common.write(join(self.ct.cc_dir, '.git', 'lsh_short.log'), start_history.encode(common.ENCODING))\r\n \r\n view_info = self.parse_start_history(start_history)\r\n \r\n # update cc view\r\n self.ct.update(True, join(self.ct.cc_dir, '.git', 'cc.updt'))\r\n if not self.repo.is_dirty():\r\n return False\r\n \r\n # clean the files in cc view/gcc to the status that not updated\r\n self.repo.git.checkout('.')\r\n self.repo.git.clean('-f', '-d', '-q')\r\n \r\n # start to get the history to do real synchronization from cc view to git repo.\r\n history = self.get_updated_history(self.since)\r\n if logger_level <= logging.DEBUG:\r\n common.write(join(self.ct.cc_dir, '.git', 'lsh_long.log'), history.encode(common.ENCODING))\r\n \r\n cs = self.parse_updated_history(history, view_info)\r\n cs = reversed(cs)\r\n cs = self.merge_history(cs)\r\n\r\n if not len(cs):\r\n return False\r\n \r\n self.log_groups(cs, logger)\r\n \r\n self.commit(cs)\r\n \r\n # update the sync.config file.\r\n self.update_since()\r\n \r\n return True\r\n \r\n def get_since(self):\r\n return self.sync_config.get_since()\r\n \r\n def update_since(self):\r\n self.sync_config.set_last_since(self.since)\r\n self.sync_config.set_since(self.new_since)\r\n self.sync_config.save()\r\n \r\n def filter_branches(self, version):\r\n '''Args:\r\n version: i.e. '\\main\\ONETIER_HTML5-9.4.0000.0102-BRANCH\\Visualization_Engine-9.4.0802.0007-BRANCH\\0'.'''\r\n version_parts = version.split(common.FS)\r\n version_branch = version_parts[-2]\r\n branches = self.core_config.get_braches().split('|');\r\n\r\n for branch in branches:\r\n if fnmatch(version_branch, branch):\r\n return True\r\n return False\r\n \r\n def get_start_history(self, since):\r\n return self.get_history(ShortLshFmt, since)\r\n \r\n def get_updated_history(self, since):\r\n return self.get_history(LongLshFmt, since)\r\n \r\n def get_history(self, fmt, since):\r\n return self.ct.lsh(fmt, since)\r\n\r\n def _get_file_version(self, file_path):\r\n try:\r\n file_version = self.ct.cc_exec(['ls', '-d', '-s', file_path])\r\n except:\r\n file_version = file_path\r\n \r\n return file_version\r\n \r\n def parse_start_history(self, lines):\r\n '''It's only used to get the time for the version of the elements going to be updated in current local view.\r\n For cleartool lsh subcommand, it will only list the history for the elements already loaded in the local view.\r\n We run it before updating the view, for after updating, the loaded version will be replaced with the updated one.'''\r\n view_info = {}\r\n for line in lines.splitlines():\r\n split = line.split(DELIM)\r\n cstype = split[0]\r\n if cstype in TYPES:\r\n version = split[2]\r\n try:\r\n if self.filter_branches(version):\r\n file_path = split[1]\r\n file_version = self._get_file_version(file_path).strip()\r\n # check if the date of the check-in is later than the local one.\r\n # we need to use the file with version info to execute \"describe\", \r\n # for for the hijacked files, it will treat it as a view-private object without version selector.\r\n view_version_date = self.ct.cc_exec(['describe', '-fmt', '%Nd', file_version])\r\n view_info[file_path] = view_version_date\r\n except:\r\n logger = logging.getLogger(__name__)\r\n msg = ('Bad line in cc history: %s; %s' % (line, str(split)))\r\n logger.exception(msg)\r\n raise AppError(msg)\r\n \r\n return view_info\r\n \r\n def parse_updated_history(self, lines, view_info):\r\n '''Args:\r\n lines: Each line is like:\r\n 'checkinversion|20140608.025721|jindwang|new_c\\c1.txt|\\main\\ONETIER_HTML5-9.4.0000.0102-BRANCH\\Visualization_Engine-9.4.0802.0007-BRANCH\\1|{#ke;jindwang;test;add for test#}',\r\n or\r\n 'checkindirectory version|20140614.103449|jindwang|a|\\main\\ONETIER_HTML5-9.4.0000.0102-BRANCH\\Visualization_Engine-9.4.0802.0007-BRANCH\\4|{#ke;jindwang;test;add for test#}',\r\n or etc.\r\n But we only deal with the history type 'checkinversion' and 'checkindirectory version'.\r\n '''''\r\n changesets = []\r\n def add(split, comment):\r\n if not split:\r\n return\r\n cstype = split[0]\r\n if cstype in TYPES:\r\n cs = TYPES[cstype](split, comment, self)\r\n try:\r\n if self.filter_branches(cs.version):\r\n # check if the date of the check-in is later than the local one.\r\n # cs.file not in view_info means it's a new added elements.\r\n if (not cs.file in view_info) or cs.date > view_info[cs.file]:\r\n changesets.append(cs)\r\n except Exception:\r\n logger = logging.getLogger(__name__)\r\n msg = ('Bad line in cc history: %s; %s; %s' % (line, str(split), comment))\r\n logger.exception(msg)\r\n raise AppError(msg)\r\n last = None\r\n comment = None\r\n for line in lines.splitlines():\r\n split = line.split(DELIM)\r\n if len(split) < 6 and last:\r\n # Cope with comments with '|' character in them\r\n comment += \"\\n\" + DELIM.join(split)\r\n else:\r\n add(last, comment)\r\n comment = DELIM.join(split[5:])\r\n last = split\r\n add(last, comment)\r\n return changesets\r\n \r\n def merge_history(self, changesets):\r\n last = None\r\n groups = []\r\n def same(a, b):\r\n return a.subject == b.subject and a.user == b.user\r\n for cs in changesets:\r\n if last and same(last, cs):\r\n last.append(cs)\r\n else:\r\n last = Group(cs)\r\n groups.append(last)\r\n for group in groups:\r\n group.fix_comment()\r\n return groups\r\n \r\n def commit(self, co_list):\r\n for cs in co_list:\r\n cs.commit()\r\n \r\n def log_groups(self, groups, logger):\r\n for cs in groups:\r\n logger.debug('%s \"%s\"' % (cs.user, cs.subject))\r\n for cs_file in cs.files:\r\n logger.debug(\" %s\" % cs_file.file)\r\n\r\nclass Group:\r\n def __init__(self, cs):\r\n self.user = cs.user\r\n self.comment = cs.comment\r\n self.subject = cs.subject\r\n self.cc2git = cs.cc2git\r\n self.ct = self.cc2git.ct\r\n self.repo = self.cc2git.repo\r\n self.files = []\r\n self.append(cs)\r\n def append(self, cs):\r\n self.date = cs.date\r\n self.files.append(cs)\r\n def fix_comment(self):\r\n #self.comment = cc.getRealComment(self.comment)\r\n self.subject = self.comment.split('\\n')[0]\r\n # change format to git comment.\r\n git_comment_split = common.cc_comment_2_git(self.subject)\r\n self.git_comment = git_comment_split[-1]\r\n def commit(self):\r\n def get_commit_date(date):\r\n return date[:4] + '-' + date[4:6] + '-' + date[6:8] + ' ' + \\\r\n date[9:11] + ':' + date[11:13] + ':' + date[13:15]\r\n def get_user_email(user):\r\n return '<%s@%s>' % (user, common.MAIL_SUFFIX)\r\n files = []\r\n for cur_file in self.files:\r\n files.append(cur_file.file)\r\n for cur_file in self.files:\r\n cur_file.add(files)\r\n #cache.write()\r\n env = os.environ\r\n env['GIT_AUTHOR_DATE'] = env['GIT_COMMITTER_DATE'] = str(get_commit_date(self.date))\r\n env['GIT_AUTHOR_NAME'] = env['GIT_COMMITTER_NAME'] = str(self.user)\r\n env['GIT_AUTHOR_EMAIL'] = env['GIT_COMMITTER_EMAIL'] = str(get_user_email(self.user))\r\n comment = self.git_comment if self.git_comment.strip() != \"\" else \"cc;no comment\"\r\n try:\r\n common.git_exec(self.ct.cc_dir, ['commit', '-m', comment.encode(common.ENCODING)], env=env)\r\n except Exception as e:\r\n if search('nothing( added)? to commit', e.args[0]) == None:\r\n raise\r\n\r\ndef cc_file(file_path, version):\r\n return '%s@@%s' % (file_path, version)\r\n\r\nclass Changeset(object):\r\n def __init__(self, split, comment, cc2git):\r\n self.date = split[1]\r\n self.user = split[2]\r\n self.file = split[3]\r\n self.version = split[4]\r\n self.comment = comment\r\n self.subject = comment.split('\\n')[0]\r\n self.cc2git = cc2git\r\n self.ct = cc2git.ct\r\n self.repo = cc2git.repo\r\n def add(self, files):\r\n self._add(self.file, self.version)\r\n def _add(self, file_path, version):\r\n #if not cache.update(CCFile(file_path, version)):\r\n # return\r\n #if [e for e in cfg.getExclude() if fnmatch(file_path, e)]:\r\n # return\r\n toFile = join(self.ct.cc_dir, file_path)\r\n common.mkdirs(toFile)\r\n common.removeFile(toFile)\r\n try:\r\n self.ct.cc_exec(['get','-to', toFile, cc_file(file_path, version)])\r\n except Exception as e:\r\n # we already set core.longpaths as true to support long path in git.\r\n # So if exceptions raised, we just need to raise it.\r\n raise AppError(e.message)\r\n #if len(file_path) < 200:\r\n # raise\r\n #print(\"Ignoring %s as it may be related to https://github.com/charleso/git-cc/issues/9\" % file_path)\r\n os.chmod(toFile, os.stat(toFile).st_mode | stat.S_IWRITE)\r\n self.repo.git.add('-f', file_path)\r\n #common.git_exec(self.ct.cc_dir, ['add', '-f', file_path], errors=False)\r\n\r\nclass Uncataloged(Changeset):\r\n def add(self, files):\r\n cur_dir = cc_file(self.file, self.version)\r\n dir_date = None\r\n diff = self.ct.cc_exec(['diff', '-diff_format', '-pred', cur_dir], errors=False)\r\n def get_file(line):\r\n return join(self.file, line[2:max(line.find(' '), line.find(common.FS + ' '))])\r\n \r\n logger = logging.getLogger(__name__)\r\n for line in diff.split('\\n'):\r\n sym = line.find(' -> ')\r\n if sym >= 0:\r\n continue\r\n if line.startswith('<'):\r\n #common.removeFile(join(self.ct.cc_dir, get_file(line)))\r\n self.repo.git.rm('-r', get_file(line))\r\n #common.git_exec([self.ct.cc_dir, 'rm', '-r', get_file(line)], errors=False)\r\n #cache.remove(get_file(line))\r\n elif line.startswith('>'):\r\n added = get_file(line)\r\n cc_added = join(self.ct.cc_dir, added)\r\n # we use the same location as cc view and git repo, so we cannot check exists(cc_added) here.\r\n #if not exists(cc_added) or isdir(cc_added) or added in files:\r\n if isdir(cc_added) or added in files:\r\n continue\r\n history = self.ct.cc_exec(['lshistory', '-fmt', '%o%m|%Nd|%Vn\\\\n', added], errors=False)\r\n if not history:\r\n continue\r\n # we only need to execute cleartool describe once to get the dir_date.\r\n if not dir_date:\r\n dir_date = self.ct.cc_exec(['describe', '-fmt', '%Nd', cur_dir])\r\n def f(s):\r\n return s[0] == 'checkinversion' and s[1] < dir_date and self.cc2git.filter_branches(s[2])\r\n versions = list(filter(f, list(map(lambda x: x.split('|'), history.split('\\n')))))\r\n if not versions:\r\n logger.error(\"It appears that you may be missing a branch for the file: '%s'.\" % added) \r\n continue\r\n self._add(added, versions[0][2].strip())\r\n\r\nTYPES = {\\\r\n 'checkinversion': Changeset,\\\r\n 'checkindirectory version': Uncataloged,\\\r\n}","sub_path":"src/mstr/cc2git.py","file_name":"cc2git.py","file_ext":"py","file_size_in_byte":13420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"300601997","text":"# MEDIA\nimport pygame\nimport os\nimport glob\n\npygame.init()\npygame.mixer.init()\n\n# Setting Up Items\nSCREEN = pygame.display.set_mode((500, 600))\nMEDIA = {}\nFILES = glob.glob(os.path.join(os.path.dirname(__file__), 'MEDIA_DATA', 'IMAGE', '*.png'))\nFILES2 = glob.glob(os.path.join(os.path.dirname(__file__), 'MEDIA_DATA', 'AUDIO', '*.wav'))\n\n# Loading images to use\nfor FILE_NAME in FILES:\n OBJ = pygame.image.load(FILE_NAME).convert_alpha()\n MEDIA[os.path.split(FILE_NAME)[-1][:-4]] = OBJ\n\n# Loading audio to use\nfor FILE_NAME in FILES2:\n OBJ = pygame.mixer.Sound(FILE_NAME)\n MEDIA[os.path.split(FILE_NAME)[-1][:-4]] = OBJ\n","sub_path":"Rects Fight Archive/Rects-Fight-master/Rects-Fight-Abilities-Build/GAME_DATA/MEDIA.py","file_name":"MEDIA.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"557367439","text":"# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Tests the metrics system.\"\"\"\n\nimport os\nimport host_tools.logging as log_tools\n\n\ndef test_flush_metrics(test_microvm_with_api):\n \"\"\"Check the `FlushMetrics` vmm action.\"\"\"\n microvm = test_microvm_with_api\n microvm.spawn()\n microvm.basic_config()\n\n # Configure metrics system.\n metrics_fifo_path = os.path.join(microvm.path, 'metrics_fifo')\n metrics_fifo = log_tools.Fifo(metrics_fifo_path)\n\n response = microvm.metrics.put(\n metrics_path=microvm.create_jailed_resource(metrics_fifo.path)\n )\n assert microvm.api_session.is_status_no_content(response.status_code)\n\n microvm.start()\n\n microvm.flush_metrics(metrics_fifo)\n","sub_path":"tests/integration_tests/functional/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"326212216","text":"import os\nimport sys\nimport SCons.Script\n\nenv = SCons.Environment.Environment(MSVC_VERSION='14.1', TARGET_ARCH='x86')\n\n\nqt_root = 'C:/svn/3rdParty/3rdPartyPackages/Qt-5.12.1_vs2017/5.12.1/msvc2017'\nenv['QTDIR'] = qt_root\nenv.Tool('qt')\nprint('originial QT_UICCOM:')\nprint(env['QT_UICCOM'])\n\nenv['ENV']['PKG_CONFIG_PATH'] = os.path.join(qt_root, 'lib', 'pkgconfig')\n\n\nqt_inc_dir = [os.path.join(qt_root, 'include'),\n os.path.join(qt_root, 'include', 'QtCore'),\n os.path.join(qt_root, 'include', 'QtWidgets'),\n os.path.join(qt_root, 'include', 'QtGui')]\n\n\n\n\nenv.Append(CPPFLAGS=['-Od', '-D_DEBUG', '-RTC1', '-MDd'])\nenv.Append(LINKFLAGS=['/INCREMENTAL', '/DEBUG', '/NOLOGO'])\n \n\n\nenv.Append(CPPPATH=qt_inc_dir)\n \n# Default scons implementation fo the Uic tool chain does that :\n# [['$QT_UIC', '$QT_UICDECLFLAGS', '-o', '${TARGETS[0]}', '$SOURCE'], ['$QT_UIC', '$QT_UICIMPLFLAGS', '\n# TARGETS[1]}', '$SOURCE'], ['$QT_MOC', '$QT_MOCFROMHFLAGS', '-o', '${TARGETS[2]}', '${TARGETS[0]}']]\n# We only need the first action in this list of 3 actions. So we override QT_UICCOM\nenv['QT_UICCOM'] = [['$QT_UIC', '$QT_UICDECLFLAGS', '-o', '${TARGETS[0]}', '$SOURCE']]\nenv['QT_UICDECLPREFIX'] = 'ui_'\nprint('QT_UICCOM I need:')\nprint(env['QT_UICCOM'])\n\nSCons.Script.SConscript('#ASREngineSpawner/ASREngineSpawner.sc',\n exports='env',\n variant_dir='build/ASREngineSpawner',\n duplicate=0)","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"614247723","text":"from PyQt5.QtWidgets import QTableWidgetItem, QWidget\n\nfrom Ui_TablePreviewWidget import Ui_TablePreviewWidget\n\n\nclass TablePreviewWidget(QWidget):\n\n table = property()\n\n @table.setter\n def table(self, cols):\n self.ui.tableWidget.setColumnCount(6)\n self.ui.tableWidget.setRowCount(len(cols))\n self.ui.tableWidget.setHorizontalHeaderLabels(\n ['Field', 'Type', 'Null', 'Key', 'Default', 'Extra'])\n for indx, col in enumerate(cols.values()):\n self.ui.tableWidget.setItem(indx, 0, QTableWidgetItem(col.name))\n self.ui.tableWidget.setItem(indx, 1, QTableWidgetItem(col.type))\n self.ui.tableWidget.setItem(\n indx, 2, QTableWidgetItem(col.nullable))\n self.ui.tableWidget.setItem(indx, 3, QTableWidgetItem(col.keytype))\n self.ui.tableWidget.setItem(indx, 4, QTableWidgetItem(col.default))\n self.ui.tableWidget.setItem(indx, 5, QTableWidgetItem(col.extra))\n\n def __init__(self, model, controller):\n super().__init__()\n self.model = model\n self.controller = controller\n\n self.build_ui()\n\n self.upd_ui_from_model()\n\n def build_ui(self):\n self.ui = Ui_TablePreviewWidget()\n self.ui.setupUi(self)\n\n # connections\n self.ui.rowNumSpin.valueChanged.connect(self.on_value_changed)\n\n def upd_ui_from_model(self):\n self.table = self.model.columns\n self.ui.rowNumSpin.setValue(self.model.generate_size)\n\n def on_value_changed(self, value):\n self.controller.change_value(value)\n","sub_path":"TablePreviewWidget.py","file_name":"TablePreviewWidget.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"250060217","text":"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nimport math\nimport numpy as np\n\n\nclass ScaledDotProductAttention(nn.Module):\n def __init__(self, d_k, dropout=0.1):\n super(ScaledDotProductAttention, self).__init__()\n\n self.temper = math.pow(d_k, 0.5)\n self.attn_dropout = nn.Dropout(dropout)\n\n def forward(self, q, k, v, attn_mask=None):\n \"\"\"\n Args:\n q: A long Tensor of shape [num_head x batch, n, d_k]\n k: A long Tensor of shape [num_head x batch, m, d_k]\n v: A long Tensor of shape [num_head x batch, m, d_v]\n attn_mask: A ByteTensor Tensor of shape [num_head x batch, n, m]\n returns:\n output: A float Tensor of shape [num_head x batch, n, d_v]\n attn: A float Tensor of shape [num_head x batch, n, m]\n \"\"\"\n # Tensor with shape [batch, n, m]\n attn = torch.bmm(q, k.transpose(1, 2))/self.temper\n\n # make the attention weights of padding position 0\n if attn_mask is not None:\n assert attn.size() == attn_mask.size()\n attn = attn.masked_fill(attn_mask, -float('inf'))\n\n # Tensor with shape [batch, n, m]\n attn = F.softmax(attn, dim=2)\n\n # attn dropout\n attn = self.attn_dropout(attn)\n\n output = torch.bmm(attn, v)\n return output, attn\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, d_model=512, num_head=8, dropout=0.1):\n \"\"\"\n Args:\n d_model: dimension of outputs\n num_head: number of parallel scaled dot-product attention block\n dropout:\n\n \"\"\"\n super(MultiHeadAttention, self).__init__()\n\n assert d_model % num_head == 0\n self.d_model = d_model\n self.num_head = num_head\n self.d_k = int(d_model/num_head)\n self.d_v = int(d_model/num_head)\n\n self.attention = ScaledDotProductAttention(self.d_k)\n self.layer_norm = nn.LayerNorm(d_model)\n self.linear_out = nn.Linear(int(num_head * self.d_v), d_model, bias=False)\n self.dropout = nn.Dropout(dropout)\n\n self.w_q = nn.Parameter(torch.empty((num_head, d_model, self.d_k), dtype=torch.float))\n self.w_k = nn.Parameter(torch.empty((num_head, d_model, self.d_k), dtype=torch.float))\n self.w_v = nn.Parameter(torch.empty((num_head, d_model, self.d_v), dtype=torch.float))\n\n init.xavier_normal_(self.w_q)\n init.xavier_normal_(self.w_k)\n init.xavier_normal_(self.w_v)\n init.xavier_normal_(self.linear_out.weight)\n\n def forward(self, q, k, v, attn_mask=None):\n \"\"\"\n Args:\n q: A long Tensor of shape [batch, n, d_model]\n k: A long Tensor of shape [batch, m, d_model]\n v: A long Tensor of shape [batch, m, d_model]\n attn_mask: A ByteTensor Tensor of shape [batch, n, m]\n\n returns:\n outputs: A float Tensor of shape [batch, n, d_model]\n attn: A ByteTensor Tensor of shape [num_head x batch, n, m]\n \"\"\"\n batch_size, len_q, d_model = q.size()\n _, len_k, _ = k.size()\n _, len_v, _ = v.size()\n assert d_model == self.d_model\n assert len_k == len_v\n\n num_head = self.num_head\n d_k = self.d_k\n d_v = self.d_v\n residual = q\n\n # projections before scaled dot production attention\n # num_head x (batch_size x len_q) x d_model\n q_s = q.repeat(num_head, 1, 1).view(num_head, -1, d_model)\n\n # num_head x (batch_size x len_k) x d_model\n k_s = k.repeat(num_head, 1, 1).view(num_head, -1, d_model)\n\n # num_head x (batch_size x len_v) x d_model\n v_s = v.repeat(num_head, 1, 1).view(num_head, -1, d_model)\n\n q_s = torch.bmm(q_s, self.w_q).view(-1, len_q, d_k)\n k_s = torch.bmm(k_s, self.w_k).view(-1, len_k, d_k)\n v_s = torch.bmm(v_s, self.w_v).view(-1, len_v, d_v)\n\n # scaled dot production attention\n if attn_mask is not None:\n attn_mask = attn_mask.repeat(num_head, 1, 1)\n outputs, attn = self.attention(q_s, k_s, v_s, attn_mask=attn_mask)\n\n # Concat multihead attention, outputs size = batch_size * len_q * (h * d_v)\n outputs = torch.cat(torch.split(outputs, batch_size, dim=0), dim=-1)\n\n # final linear\n outputs = self.linear_out(outputs)\n\n #dropout\n outputs = self.dropout(outputs)\n\n # layer normalization\n outputs = self.layer_norm(outputs + residual)\n\n return outputs, attn\n\n\nclass PositionWiseFeedForward(nn.Module):\n\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionWiseFeedForward, self).__init__()\n\n self.d_model = d_model\n self.d_ff = d_ff\n self.dropout = nn.Dropout(dropout)\n\n self.feed_1 = nn.Conv1d(d_model, d_ff, 1)\n self.feed_2 = nn.Conv1d(d_ff, d_model, 1)\n self.layer_norm = nn.LayerNorm(d_model)\n\n # init weights\n # init.kaiming_normal_(self.feed_1.weight, mode='fan_in', nonlinearity='relu')\n init.xavier_normal_(self.feed_1.weight)\n init.xavier_normal_(self.feed_2.weight)\n init.constant_(self.feed_1.bias, 0)\n init.constant_(self.feed_2.bias, 0)\n\n def forward(self, x):\n\n residual = x\n\n outputs = self.feed_1(x.transpose(1, 2))\n outputs = F.relu(outputs, inplace=True)\n outputs = self.feed_2(outputs).transpose(1, 2)\n outputs = self.dropout(outputs)\n\n outputs = self.layer_norm(outputs + residual)\n\n return outputs\n\n\nclass DecoderLayer(nn.Module):\n def __init__(self, d_model, num_head, d_ff, dropout=0.1):\n super(DecoderLayer, self).__init__()\n\n self.self_attn = MultiHeadAttention(d_model, num_head, dropout)\n self.bt_attn = MultiHeadAttention(d_model, num_head, dropout)\n self.feed_forward = PositionWiseFeedForward(d_model, d_ff, dropout)\n\n def forward(self, dec_input, bt_feats, self_attn_mask=None):\n outputs, dec_self_attn = self.self_attn(dec_input, dec_input, dec_input, self_attn_mask)\n outputs, cross_attn_bt = self.bt_attn(outputs, bt_feats, bt_feats, None)\n outputs = self.feed_forward(outputs)\n return outputs, dec_self_attn, cross_attn_bt\n\n\nclass CNNEncoderLayer(nn.Module):\n def __init__(self, d_model, num_head, d_ff, dropout=0.1):\n super(CNNEncoderLayer, self).__init__()\n self.self_attn = MultiHeadAttention(d_model, num_head, dropout)\n self.feed_forward = PositionWiseFeedForward(d_model, d_ff, dropout)\n\n def forward(self, att_feats):\n outputs, cnn_self_attn = self.self_attn(att_feats, att_feats, att_feats, None)\n outputs = self.feed_forward(outputs)\n return outputs, cnn_self_attn\n\n\nclass CNNEncoder(nn.Module):\n def __init__(self, d_model, num_head, d_ff, num_layer, dropout=0.1):\n super(CNNEncoder, self).__init__()\n\n self.proj_spa = nn.Linear(2048, d_model)\n self.dropout = nn.Dropout(dropout)\n\n self.cnn_stack = nn.ModuleList([CNNEncoderLayer(d_model, num_head, d_ff, dropout)\n for _ in range(num_layer)])\n\n # init weight\n # init.kaiming_normal_(self.proj_1.weight, mode='fan_in', nonlinearity='relu')\n\n # init.kaiming_normal_(self.proj_2.weight, mode='fan_in', nonlinearity='relu')\n init.xavier_normal_(self.proj_spa.weight)\n init.constant_(self.proj_spa.bias, 0)\n\n def forward(self, att_feats, return_attn=False):\n\n x = self.proj_spa(att_feats) # B x 49 x 512\n x = F.relu(x, inplace=True)\n x = self.dropout(x)\n\n if return_attn:\n att_self_attn = []\n for cnn_layer in self.cnn_stack:\n x, attn = cnn_layer(x)\n if return_attn:\n att_self_attn += [attn]\n\n if return_attn:\n return x, att_self_attn\n else:\n return x\n\n\ndef padding_attn_mask(seq_q, seq_k):\n\n assert seq_q.dim() == seq_k.dim()\n assert seq_q.dim() == 2 and seq_k.dim() == 2\n batch_size, len_q = seq_q.size()\n batch_size, len_k = seq_k.size()\n # b x 1 x len(seq_k)\n pad_attn_mask = seq_k.eq(0).unsqueeze(1)\n pad_attn_mask = pad_attn_mask.expand(batch_size, len_q, len_k)\n if seq_q.is_cuda:\n return pad_attn_mask.cuda()\n return pad_attn_mask\n\n\ndef sequence_attn_mask(seq_q):\n\n assert seq_q.dim() == 2\n shape = (seq_q.size(0), seq_q.size(1), seq_q.size(1))\n\n # torch.triu can not deal with batch input\n seq_attn_mask = np.triu(np.ones(shape), k=1).astype('uint8')\n seq_attn_mask = torch.from_numpy(seq_attn_mask)\n\n if seq_q.is_cuda:\n return seq_attn_mask.cuda()\n return seq_attn_mask\n\n\n","sub_path":"model/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":8742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"328520293","text":"from core.helpers import all\nfrom core.logger import Logger\nfrom core.plugin import PLUGIN_IDENTIFIER\nfrom plex.plex_base import PlexBase\nimport os\n\nlog = Logger('plex.plex_media_server')\n\n\nclass PlexMediaServer(PlexBase):\n #\n # Server\n #\n\n @classmethod\n def get_info(cls, quiet=False):\n return cls.request(quiet=quiet)\n\n @classmethod\n def get_version(cls, default=None, quiet=False):\n server_info = cls.get_info(quiet)\n if server_info is None:\n return default\n\n return server_info.attrib.get('version') or default\n\n @classmethod\n def get_client(cls, client_id):\n if not client_id:\n log.warn('Invalid client_id provided')\n return None\n\n result = cls.request('clients')\n if not result:\n return None\n\n found_clients = []\n\n for section in result.xpath('//Server'):\n found_clients.append(section.get('machineIdentifier'))\n\n if section.get('machineIdentifier') == client_id:\n return section\n\n log.info(\"Unable to find client '%s', available clients: %s\" % (client_id, found_clients))\n return None\n\n @classmethod\n def get_sessions(cls):\n return cls.request('status/sessions')\n\n @classmethod\n def get_session(cls, session_key):\n sessions = cls.get_sessions()\n if sessions is None:\n log.warn('Sessions request failed')\n return None\n\n for section in sessions:\n if section.get('sessionKey') == session_key and '/library/metadata' in section.get('key'):\n return section\n\n log.warn('Session \"%s\" not found', session_key)\n return None\n\n #\n # Collection\n #\n\n @classmethod\n def get_sections(cls, types=None, keys=None, titles=None, cache_id=None):\n \"\"\"Get the current sections available on the server, optionally filtering by type and/or key\n\n :param types: Section type filter\n :type types: str or list of str\n\n :param keys: Section key filter\n :type keys: str or list of str\n\n :return: List of sections found\n :rtype: (type, key, title)\n \"\"\"\n\n if types and isinstance(types, basestring):\n types = [types]\n\n if keys and isinstance(keys, basestring):\n keys = [keys]\n\n if titles:\n if isinstance(titles, basestring):\n titles = [titles]\n\n titles = [x.lower() for x in titles]\n\n container = cls.request('library/sections', cache_id=cache_id)\n\n sections = []\n for section in container:\n # Try retrieve section details - (type, key, title)\n section = (\n section.get('type', None),\n section.get('key', None),\n section.get('title', None)\n )\n\n # Validate section, skip over bad sections\n if not all(x for x in section):\n continue\n\n # Apply type filter\n if types is not None and section[0] not in types:\n continue\n\n # Apply key filter\n if keys is not None and section[1] not in keys:\n continue\n\n # Apply title filter\n if titles is not None and section[2].lower() not in titles:\n continue\n\n sections.append(section)\n\n return sections\n\n @classmethod\n def get_section(cls, key, cache_id=None):\n return cls.request('library/sections/%s/all' % key, timeout=10, cache_id=cache_id)\n\n @classmethod\n def scrobble(cls, key):\n result = cls.request(\n ':/scrobble?identifier=com.plexapp.plugins.library&key=%s' % key,\n response_type='text'\n )\n\n return result is not None\n\n @classmethod\n def rate(cls, key, value):\n value = int(round(value, 0))\n\n result = cls.request(\n ':/rate?key=%s&identifier=com.plexapp.plugins.library&rating=%s' % (key, value),\n response_type='text'\n )\n\n return result is not None\n\n @classmethod\n def restart_plugin(cls, identifier=None):\n if identifier is None:\n identifier = PLUGIN_IDENTIFIER\n\n # Touch plugin directory to update modified time\n os.utime(os.path.join(Core.code_path), None)\n\n cls.request(':/plugins/%s/reloadServices' % identifier)\n","sub_path":"Trakttv.bundle/Contents/Code/plex/plex_media_server.py","file_name":"plex_media_server.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"634687489","text":"import requests\nimport json\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport csv\nimport pandas as pd\n\n# Q1\npost_url = 'https://www.dell.com/community/Laptops/ct-p/Laptops'\npost_page = urlopen(post_url)\nsoup = BeautifulSoup(post_page, 'html.parser')\n\nmodel_post = {}\nlaptops = soup.find_all('div', attrs={'class':'cat-card'})\nfor i in range(len(laptops)):\n laptop = laptops[i] \n name = laptop.get_text().split('\\n')[1]\n posts = laptop.get_text().split('\\n')[4].strip()\n if name in ['Inspiron', 'XPS', 'Latitude']:\n model_post[name] = posts\n \nprint (model_post)\n\n\n# Q2\nbase_url = 'https://www.dell.com/community/Inspiron/bd-p/Inspiron/page/'\nls = []\n\n\nfor page in range(1,6):\n # connecting to target webpage\n target_url = base_url + str(page)\n disc_page = urlopen(target_url)\n soup = BeautifulSoup(disc_page, 'html.parser')\n\n titles = soup.find_all('div', attrs={'class':'MessageSubjectCell'})\n for i in range(len(titles)):\n \n # init a row to write\n row = []\n \n # 1. discussion title\n title_mess = soup.find_all('a', attrs={'class':'page-link lia-link-navigation lia-custom-event'})[i]\n title = title_mess.get_text().split('\\n')[1].strip()\n row.append(title)\n\n #2. author, time\n info = soup.find_all('div', attrs={'class':'lia-info-area'})[i] \n author = info.get_text().split('\\n')[3]\n # In pinned posts the location is differnet from normal posts\n if author == '':\n author = info.get_text().split('\\n')[4]\n row.append(author)\n \n time = info.get_text().split('\\n')[6] \n if ':' not in time:\n time = info.get_text().split('\\n')[7] \n row.append(time)\n\n #3. author, time of the latest post, if any\n if 'Latest' in info.get_text().split() and 'post' in info.get_text().split():\n latest_post = info.get_text().split()\n\n latest_post_name = info.get_text().split()[len(latest_post)-1]\n # name not specified\n if latest_post_name == 'by':\n latest_post_name = None\n \n time = info.get_text().split()[10:12]\n latest_post_time = ''\n for x in time:\n latest_post_time += x + ' '\n \n else:\n latest_post_name = None\n \n latest_post_time = None\n \n row.append(latest_post_name)\n row.append(latest_post_time)\n \n #4. kudos, replies, views\n kudos = soup.find_all('div', attrs={'class':'lia-component-messages-column-message-kudos-count'})[i]\n kudo = kudos.get_text().split()[0]\n row.append(kudo)\n \n stats = soup.find_all('div', attrs={'class':'lia-stats-area'})[i]\n replies = stats.get_text().split()[0]\n row.append(replies)\n views = stats.get_text().split()[2]\n row.append(views)\n \n #5. solved or not \n parts = soup.find_all('td',attrs={'class':'triangletop lia-data-cell-secondary lia-data-cell-icon'})\n if 'td aria-label=\"This thread is solved' in str(parts[i]):\n row.append('Yes')\n else:\n row.append('No')\n \n # Finally, append the rows to one huge list\n ls.append(row)\n\n\nwith open('data.csv','w+') as f:\n writer = csv.writer(f)\n writer.writerow(['title','author','time','latest_author','latest_time','kudos','replies','views','solved'])\n for row in ls:\n writer.writerow(row)\nf.close()\n\nprint('Job done, please find the data.csv file in the same folder for the results.')","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"256846401","text":"\nfrom tkinter import *\nimport tkinter.ttk as ttk\nimport RPi.GPIO as GPIO\nimport time\n\nr1 = 31\nr2 = 33\nr3 = 35\nr4 = 37\nrel1_s=0\nrel2_s=0\nrel3_s=0\nrel4_s=0\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(r1,GPIO.OUT)\nGPIO.setup(r2,GPIO.OUT)\nGPIO.setup(r3,GPIO.OUT)\nGPIO.setup(r4,GPIO.OUT)\n\ndef tab_new():\n print (\"New\")\ndef tab_open():\n print (\"Open\")\ndef tab_help():\n print (\"‫Help\")\ndef stopProg():\n root.destroy()\ndef transfertext():\n global label1\n label1.config(text = \"sina\")\n\ndef rel1():\n global rel1_s\n if rel1_s == 1:\n GPIO.output(r1,0)\n rel1_s=0\n else:\n GPIO.output(r1,1)\n rel1_s=1\ndef rel2():\n global rel2_s\n if rel2_s == 1:\n GPIO.output(r2,0)\n rel2_s=0\n else:\n GPIO.output(r2,1)\n rel2_s=1\ndef rel3():\n global rel3_s\n if rel3_s == 1:\n GPIO.output(r3,0)\n rel3_s=0\n else:\n GPIO.output(r3,1)\n rel3_s=1\ndef rel4():\n global rel4_s\n if rel4_s == 1:\n GPIO.output(r4,0)\n rel4_s=0\n else:\n GPIO.output(r4,1)\n rel4_s=1\n\n\ncolor = '#111131'\n\nroot=Tk()\nroot.geometry(\"%dx%d+%d+%d\"%(800,600,100,50)) #x,y,horizental,vertical\nroot.title('SAJAB')\nroot.configure(background='lightblue')\n\nnb = ttk.Notebook(root)\nnb.pack(fill='both',expand='yes')\n\nmain = Frame(bg=color)\nmonitoring = Frame(bg=color)\ncontrol = Frame(bg=color)\n\nnb.add(main,text='Main')\nnb.add(monitoring,text='Monitoring')\nnb.add(control,text='Control')\n\n#____ Main Tab __________\nLabel(main,text='SAJAB Management System',fg='#8888f1',bg=color,font=\"tahoma 24 bold\",pady=10).pack()\n#btn1f1 = Button(f1,text='btn1')\n#btn1f1.pack(side='left',anchor='nw',padx=50,pady=50)\n#_______End\n\n#____ Monitoring Tab\nsensors = ['Sensor 1','Sensor 2','Sensor 3','Sensor 4']\nrelays = ['Relay 1','Relay 2','Relay 3','Relay 4']\nr=0\nfor c in sensors:\n Label(monitoring,text=c,fg='white',bg=color,relief=RIDGE,width=15).place(x=20,y=100+r*40)\n r=r+1\nr=0\nfor c in relays:\n Label(monitoring,text=c,fg='white',bg=color,relief=RIDGE,width=15).place(x=300,y=100+r*40)\n r=r+1\nglobal rel1_s\nglobal rel2_s\nglobal rel3_s\nglobal rel4_s\nButton(monitoring,text='Toggle',command=rel1).place(x=450,y=100)\nButton(monitoring,text='Toggle',command=rel2).place(x=450,y=140)\nButton(monitoring,text='Toggle',command=rel3).place(x=450,y=180)\nButton(monitoring,text='Toggle',command=rel4).place(x=450,y=220)\n\nbtn_refresh = Button(monitoring,text='Refresh')\nbtn_refresh.place(x=20,y=400)\n#btn_refresh.pack(side='left',anchor='nw',padx=50,pady=50)\n#_______End\n\n#____ Control Tab\n\n#btn1f1 = Button(f1,text='btn1')\n#btn1f1.pack(side='left',anchor='nw',padx=50,pady=50)\n#_______End\nmenu = Menu(root)\nroot.config(menu=menu)\nfilemenu = Menu(menu)\nmenu.add_cascade(label=\"File\", menu=filemenu)\nfilemenu.add_command(label=\"New\", command=tab_new)\nfilemenu.add_command(label=\"Open...\", command=tab_open)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Exit\", command=root.destroy)\nhelpmenu = Menu(menu)\nmenu.add_cascade(label=\"Help\", menu=helpmenu)\nhelpmenu.add_command(label=\"About...\", command=tab_help)\n\nbtn1 = Button(root,text=\"Exit\",command = stopProg).pack()\nbtn1 = Button(root,text=\"Click Here!\",command = transfertext).pack()\nlabel1=Label(root,text=\"Orginal Text\",fg=\"green\")\nlabel1.pack()\n\n#top=Toplevel()\n#top.mainloop()\n\nroot.mainloop()\n\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"72578734","text":"import torch\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\ntorch.manual_seed(2) # torch.manual_seed(1)的时候拟合线是一条直线,改成2才能出来最后的效果\n# manual_seed 给PyTorch里的随机数生成器指定一个随机种子,可以保证每次生成的随机数是从随机种子开始取值的\n# 就是说每次调用 torch.rand() 的结果都是可以复现的\n# 我觉得这是个坑。用同样的种子来运行CPU的程序应该可以重复过去的实验\n# 然而,如果用了GPU,某些运算操作(如卷积)是有随机因素的\n# 原因超出我的知识范畴,貌似是为了运算优化,只保证结果小数点后N位小数是准确的。如此以来就产生了蝴蝶效应\n# 即使用了同样的种子初始化,训练出来的模型也是不同的\n\n# fake data\nx = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # shape=(100, 1)\ny = x.pow(2) + 0.2*torch.rand(x.size()) # y=x^2+雜訊,x.size()=(100, 1)\nx, y = Variable(x, requires_grad=False), Variable(y, requires_grad=False) # 把x、y設定為變量\n\n# 在训练时如果想要固定网络的底层,那么可以令这部分网络对应子图的参数requires_grad为False。\n# 这样,在反向过程中就不会计算这些参数对应的梯度\n# Variable的参数volatile=True和requires_grad=False的功能差不多\n\n# torch.rand(2, 3)\n# 0.0836 0.6151 0.6958\n# 0.6998 0.2560 0.0139\n# unsqueeze()在dim维插入一个维度为1的维,例如原来x是n×m维的,torch.unqueeze(x,0)这返回1×n×m的tensor\n# queeze() 函数功能:去除size为1的维度,包括行和列。当维度大于等于2时,squeeze()无作用。\n# 其中squeeze(0)代表若第一维度值为1则去除第一维度,squeeze(1)代表若第二维度值为1则去除第二维度。\n\n# x = torch.zeros(4,3,2)\n# tensor([[[0., 0.], # 最小的括號裡面有2個元素\n# [0., 0.],\n# [0., 0.]], # 次小的括號有3組最小括號\n# [[0., 0.],\n# [0., 0.],\n# [0., 0.]],\n# [[0., 0.],\n# [0., 0.],\n# [0., 0.]],\n# [[0., 0.],\n# [0., 0.],\n# [0., 0.]]]) # 再次小的括號有4組次小括號\n\ndef save():\n # save net\n # 之後要用net2、net3來提取出來\n net1 = torch.nn.Sequential( # 利用Sequantial來建立一系列流程\n torch.nn.Linear(1, 10),\n torch.nn.ReLU(),\n torch.nn.Linear(10, 1)\n )\n optimizer = torch.optim.SGD(net1.parameters(), lr=0.5)\n loss_func = torch.nn.MSELoss()\n # 都要先定義網路、優化器、損失函數\n\n for t in range(100): # 迭代100次\n # 一樣要先定義網路、優化器、損失\n prediction = net1(x) # 在最開始定義了輸入數據x,也在上面定義了net1的網路架構,所以運算之後就是輸出prediction\n loss = loss_func(prediction, y) # 後面放ground truth\n optimizer.zero_grad()\n # Before the backward pass, use the optimizer object to zero all of the gradients for the variables it will update\n loss.backward() # 將損失函數向後傳遞\n optimizer.step() # 只有用了optimizer.step(),模型才会更新\n\n torch.save(net1, 'net.pkl') # entire\n # 要傳進去的參數,要保存的名字\n torch.save(net1.state_dict(), 'net_params.pkl') # 只保存网络中的参数 (速度快, 占内存少)\n\n plt.figure(1, figsize=(10, 3)) # 這個figure的代稱為1\n plt.subplot(131) # 1列3行的子圖®,其中的第1個\n plt.title('Net1')\n plt.scatter(x.data.numpy(), y.data.numpy())\n plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5) # 先顏色,再線條的款式(虛線)\n\n\ndef restore_net():\n net2 = torch.load('net.pkl')\n prediction = net2(x)\n\n plt.figure(1, figsize=(10, 3)) # 這個figure的代稱為1\n plt.subplot(132)\n plt.title('Net2')\n plt.scatter(x.data.numpy(), y.data.numpy())\n plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)\n\n\ndef restore_params(): #因為要截取net1的參數過來,所以要建立一樣的網路\n net3 = torch.nn.Sequential(\n torch.nn.Linear(1, 10),\n torch.nn.ReLU(),\n torch.nn.Linear(10, 1)\n )\n\n net3.load_state_dict(torch.load('net_params.pkl'))\n # 如果上面那行結尾少了),下面這行就會出錯,然後就算把下面這行#掉,下下行還是會出錯\n\n prediction = net3(x)\n\n plt.figure(1, figsize=(10, 3)) # 這個figure的代稱為1\n plt.subplot(133)\n plt.title('Net3')\n plt.scatter(x.data.numpy(), y.data.numpy())\n plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)\n\n\n\nsave() # 保存 net1 (1. 整个网络, 2. 只有参数)\nrestore_net() # 提取整个网络\nrestore_params() # 提取网络参数, 复制到新网络\n\nplt.show() # 如果在三個def各自plt.show(),那就會分成3張圖\n# 如果plt.figure(1, figsize=(10, 3))沒有在每個def裡面都寫,比如只寫在第3個呼叫的地方\n# 那變成呼叫第一個的時候沒有這樣的figsize定義,就會變成3個def的畫布大小不同,造成無法按照想要的畫布大小呈現\n# 如果不要在每個def裡面都寫,也可以直接另外寫一個def來定義畫布,不然也可以像plt.show()一樣,寫在主文(save())的前、後。","sub_path":"test9-Restore.py","file_name":"test9-Restore.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"271491607","text":"#-*- coding:utf-8 _*- \n\"\"\" \n@author:bluesli \n@file: data_utils.py \n@time: 2018/10/27 \n\"\"\"\nimport random\nimport numpy as np\nfrom tensorflow.python.client import device_lib\nfrom word_sequence import WordSequence\n\n# 设置一个全局的数据量阈值:\nVOCAB_SIZE_THRESHOLD_CPU = 50000\n\ndef _get_available_gpus():\n # 获取数据的信息;\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type =='GPU']\n\n\n#对于输入的数据是需要占据内存的,如果全部使用gpu处理会占用过多的显存,可能现存吃不下;\n#所以需要对数据设置一个阈值,如果大于某一个阈值就使用CPU;\n# 跟训练时的情况相反;\ndef _get_embed_device(vocab_size):\n gpus = _get_available_gpus()\n if not gpus and vocab_size> VOCAB_SIZE_THRESHOLD_CPU:\n return \"/cpu:0\"\n return \"/gup:0\"\n\n\n# 转换一下句子\n# 一个句子经过ws转换,转化成数组;\ndef transform_sentence(sentence,ws,max_len=None,add_end=False):\n encoded = ws.transform(\n sentence,\n max_len=max_len if max_len is not None else len(sentence))\n encoded_len = len(sentence) +(1 if add_ else 0)\n\nif __name__ == '__main__':\n print(_get_available_gpus())\n size =30000\n print(_get_embed_device(size))\n","sub_path":"chatbot_programset/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"429577589","text":"import random\nimport os, sys\nimport string\nimport subprocess\nimport time\n\nsize_word = 2\n\ndef make_pattern(size_pattern, file1, arg1, file2, arg2):\n pattern = []\n max_size_pattern = size_word\n\n file_1 = open(file1, arg1)\n file_2 = open(file2, arg2)\n\n file_1.write(str(size_pattern) + \"\\n\")\n\n for iter in range(size_pattern):\n letters = string.ascii_lowercase\n a = random.random()\n if a > 0.3:\n # make letter\n size_current = random.randrange(1, max_size_pattern, 1)\n letter = \"\".join(random.choice(letters) for _ in range(size_current))\n pattern.append(letter)\n\n file_1.write(letter + '\\n')\n file_2.write(letter + ' ')\n else:\n # make joker\n file_1.write('?' + '\\n')\n file_2.write('?' + ' ')\n\n file_2.write('\\n')\n file_1.close()\n file_2.close()\n\ndef make_text(size_text, file1, arg1, file2, arg2):\n text = []\n max_size_pattern = size_word\n\n line = 1\n column = 1\n\n file_1 = open(file1, arg1)\n file_2 = open(file2, arg2)\n\n file_1.write(str(size_text) + \"\\n\")\n\n for iter in range(size_text):\n letters = string.ascii_lowercase\n a = random.random()\n if a > 0.3:\n # same line\n pass\n else:\n # new line\n line = line + 1\n column = 1\n file_2.write('\\n')\n\n size_current = random.randrange(1, max_size_pattern, 1)\n letter = \"\".join(random.choice(letters) for _ in range(size_current))\n\n file_1.write(letter + '\\n' + str(line) + '\\n' + str(column) + '\\n')\n file_2.write(letter + ' ')\n column = column + 1\n\n file_1.close()\n file_2.close()\n\n\n# main\nos.system(\"rm pattern.txt text.txt test.txt\")\n\npatt = input(\"how many pattern? \")\ntext = input(\"how many text? \")\n\nmake_pattern(patt, 'pattern.txt', 'w', 'test.txt', 'a')\nmake_text(text, 'text.txt', 'w', 'test.txt', 'a')\n","sub_path":"Da/4lab/src/Tester.py","file_name":"Tester.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"295376894","text":"# coding: utf-8\n\nimport pika\nimport sys\nimport random\n\nclass Rabbitmq(object):\n\t\"\"\"define a Rabbitmq\"\"\"\n\n\tdef __init__(self):\n\t\n\t\tself.connection=None\n\t\tself.channel=None\n\t\t\n\n\tdef creat_channel(self, IP, exchange):\n\t\tself.connection = pika.BlockingConnection(pika.ConnectionParameters(IP))\n\t\tself.channel = self.connection.channel()\n\t\tself.channel.exchange_declare(exchange=exchange, exchange_type=\"fanout\")\n\t\n\n\tdef creat_queue(self, IP, Name, exchange):\n\t\tself.creat_channel(IP, exchange)\n\t\tif Name:\n\t\t\tqueue = self.channel.queue_declare(queue=Name, durable=True)\n\t\t\treturn queue\n\t\telse:\n\t\t\treturn False\n\t\t\n\n\tdef send_message(self, message, Name, exchange):\n\t\tif Name:\n\t\t\tself.channel.basic_publish(exchange=\"\", routing_key=Name, body=message,\n\t\t\t\tproperties=pika.BasicProperties(delivery_mode=2))# make message persistent\n\t\telse:\n\t\t\tself.channel.basic_publish(exchange=exchange, routing_key='', body=message,\n\t\t\t\tproperties=pika.BasicProperties(delivery_mode=2))# make message persistent\n\t\tprint(\" [x] Sent %r\" % message)\n\t\tself.connection.close()\n\n\nif __name__ == '__main__':\n\trabbitmq = Rabbitmq()\n\tqueue = rabbitmq.creat_queue(\"localhost\", \"\", \"logs\")\n\tmessage = random.randint(1,10)\n\tprint(message)\n\trabbitmq.send_message(str(message), \"\", \"logs\")\n\n\t\t\n\t\t","sub_path":"pro-nameko-rabbit/rabbitmq-queue-define/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"500016859","text":"\"\"\"\nPerforms training, validation, testing for nvs_model.py with a GAN and calculates loss and saves it to tensorboard.\n\nAuthor: Lukas Hoellein\n\"\"\"\n\nimport numpy as np\n\nfrom util.nvs_solver import NVS_Solver\nfrom models.gan.gan_loss import DiscriminatorLoss\n\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom time import time\nfrom tqdm.auto import tqdm\n\nclass GAN_Wrapper_Solver(object):\n default_adam_args = {\"lr\": 1e-4,\n \"betas\": (0.9, 0.999),\n \"eps\": 1e-8,\n \"weight_decay\": 0.0}\n\n def __init__(self,\n optim_d=torch.optim.Adam,\n optim_d_args={},\n optim_g=torch.optim.Adam,\n optim_g_args={},\n g_loss_func=None, # if left None, the NVS_Solver will instantiate a standard SynthesisLoss class\n extra_args={},\n log_dir=None,\n num_D=3,\n size_D=64,\n loss_D='ls',\n no_gan_feature_loss=False,\n lr_step=10,\n lr_gamma=0.1,\n log_depth=False,\n init_discriminator_weights=True):\n \"\"\"\n\n Parameters\n ----------\n optim_d: which optimizer to use for discriminator, e.g. Adam\n optim_d_args: see also default_adam_args: specify here valid dictionary of arguments for chosen optimizer\n optim_g: which optimizer to use for generator, e.g. Adam\n optim_g_args: see also default_adam_args: specify here valid dictionary of arguments for chosen optimizer\n extra_args: extra_args that should be used when logging to tensorboard (e.g. model hyperparameters)\n log_dir: where to log to tensorboard\n num_D: number of discriminators to use, every discriminator will work with lower resolution.\n e.g. One discriminator at full resolution and one with input downsampled to half the resolution\n size_D: number of channels/filters in each Conv2d in discriminator\n loss_D: the loss that the discriminator uses, options are ls (MSE-Loss), hinge, wgan (Wasserstein-GAN)\n or original (Cross-Entropy)\n init_discriminator_weights: if weights of the discriminator should be initialized\n \"\"\"\n optim_d_args_merged = self.default_adam_args.copy()\n optim_d_args_merged.update(optim_d_args)\n self.optim_d_args = optim_d_args_merged\n self.optim_d = optim_d\n self.lr_step = lr_step\n self.lr_gamma = lr_gamma\n self.log_depth = log_depth\n\n\n self.writer = SummaryWriter(log_dir)\n\n self.netD = DiscriminatorLoss(optim_d_args['lr'],\n gan_mode=loss_D,\n no_ganFeat_loss=no_gan_feature_loss,\n num_D=num_D,\n ndf=size_D,\n init=init_discriminator_weights)\n\n self.optimizer_D = self.optim_d(\n filter(lambda p: p.requires_grad, self.netD.parameters()),\n **self.optim_d_args\n )\n\n self.scheduler_D = torch.optim.lr_scheduler.StepLR(self.optimizer_D,\n step_size=self.lr_step,\n gamma=self.lr_gamma)\n\n self.nvs_solver = NVS_Solver(optim=optim_g,\n optim_args=optim_g_args,\n loss_func=g_loss_func,\n extra_args={},\n tensorboard_writer=self.writer)\n\n nvs_solver_args = {'generator_'+k: str(v) for k, v in self.nvs_solver.hparam_dict.items()}\n for key in extra_args.keys():\n extra_args[key] = str(extra_args[key])\n self.hparam_dict = {'discriminator': type(self.netD).__name__,\n 'discriminator_optim': self.optim_d.__name__,\n 'discriminator_learning_rate': self.optim_d_args['lr'],\n **nvs_solver_args,\n **extra_args}\n\n print(\"Hyperparameters of this solver: {}\".format(self.hparam_dict))\n\n self._reset_histories()\n\n def _reset_histories(self):\n \"\"\"\n Resets train and val histories for the accuracy and the loss.\n \"\"\"\n self.train_loss_history = []\n self.train_acc_history = []\n self.val_acc_history = []\n self.val_loss_history = []\n\n\n def log_iteration_loss_and_acc(self, loss_dir, acc_dir, prefix, idx): # acc_dir argument needed\n # WRITE LOSSES\n for loss in loss_dir.keys():\n self.writer.add_scalar(prefix + 'Batch/Loss/' + loss,\n loss_dir[loss].detach().cpu().numpy(),\n idx)\n if 'D_Fake' and 'GAN' in loss_dir.keys():\n self.writer.add_scalars(prefix + 'Batch/CombinedLoss/',\n {'GAN': loss_dir['GAN'].detach().cpu().numpy(),\n 'D_Fake': loss_dir['D_Fake'].detach().cpu().numpy()},\n idx)\n self.writer.flush()\n\n # WRITE ACCS\n for acc in acc_dir.keys():\n self.writer.add_scalar(prefix + 'Batch/Accuracy/' + acc,\n acc_dir[acc].detach().data.cpu().numpy(),\n idx)\n return loss_dir['Total Loss'].detach().cpu().numpy(), acc_dir[\"rgb_ssim\"].detach().cpu().numpy() # could also use acc_dir[\"rgb_psnr\"]\n\n\n def log_epoch_loss_and_acc(self, train_loss, val_loss, train_acc, val_acc, idx):\n self.train_loss_history.append(train_loss)\n self.train_acc_history.append(train_acc)\n self.writer.add_scalar('Epoch/Loss/Train', train_loss, idx)\n self.writer.add_scalar('Epoch/Accuracy/Train', train_acc, idx)\n\n if val_loss is not None:\n self.val_loss_history.append(val_loss)\n self.writer.add_scalar('Epoch/Loss/Val', val_loss, idx)\n self.writer.add_scalars('Epoch/Loss',\n {'train': train_loss,\n 'val': val_loss},\n idx)\n\n if val_acc is not None:\n self.val_acc_history.append(val_acc)\n self.writer.add_scalar('Epoch/Accuracy/Val', val_acc, idx)\n self.writer.add_scalars('Epoch/Accuracy',\n {'train': train_acc,\n 'val': val_acc},\n idx)\n\n self.writer.flush()\n\n\n def train(self,\n model,\n train_loader,\n val_loader,\n num_epochs=10,\n log_nth_iter=1,\n log_nth_epoch=1,\n tqdm_mode='total',\n steps=1):\n \"\"\"\n Train a given nvs_model with the provided data.\n\n Inputs:\n :param model: nvs_model object initialized from nvs_model.py\n :param train_loader: train data in torch.utils.data.DataLoader\n :param val_loader: val data in torch.utils.data.DataLoader\n :param num_epochs: total number of training epochs\n :param log_nth_iter: log training accuracy and loss every nth iteration. Default 1: meaning \"Log everytime\", 0 means \"never log\"\n :param log_nth_epoch: log training accuracy and loss every nth epoch. Default 1: meaning \"Log everytime\", 0 means \"never log\"\n :param tqdm_mode:\n 'total': tqdm log how long all epochs will take,\n 'epoch': tqdm for each epoch how long it will take,\n anything else, e.g. None: do not use tqdm\n :param steps: how many generator/discriminator steps to take before changing to discriminator/generator\n \"\"\"\n\n optimizer_G = self.nvs_solver.optim(\n filter(lambda p: p.requires_grad, model.parameters()),\n **self.nvs_solver.optim_args\n )\n\n scheduler_G = torch.optim.lr_scheduler.StepLR(optimizer_G,\n step_size=self.lr_step,\n gamma=self.lr_gamma)\n\n self._reset_histories()\n iter_per_epoch = len(train_loader)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n model.to(device)\n self.netD.to(device)\n weight = 1.0 / float(steps)\n\n print('START TRAIN on device: {}'.format(device))\n\n #start = time()\n epochs = range(num_epochs)\n if tqdm_mode == 'total':\n epochs = tqdm(range(num_epochs))\n\n for epoch in epochs: # for every epoch...\n model.train() # TRAINING mode (for dropout, batchnorm, etc.)\n train_losses = []\n train_accs = []\n\n train_minibatches = train_loader\n if tqdm_mode == 'epoch':\n train_minibatches = tqdm(train_minibatches)\n for i, sample in enumerate(train_minibatches): # for every minibatch in training set\n # RUN GENERATOR steps times\n all_output_images = []\n for j in range(0, steps):\n nvs_losses, output, nvs_accs = self.nvs_solver.forward_pass(model, sample)\n g_losses = self.netD.run_generator_one_step(output[\"PredImg\"], output[\"OutputImg\"])\n (\n g_losses[\"Total Loss\"] / weight\n + nvs_losses[\"Total Loss\"] / weight\n ).mean().backward()\n all_output_images += [output]\n optimizer_G.step() # TODO: Why step after loop and not during every loop run?\n optimizer_G.zero_grad()\n\n # RUN DISCRIMINATOR steps times\n for step in range(0, steps):\n d_losses = self.netD.run_discriminator_one_step(\n all_output_images[step][\"PredImg\"],\n all_output_images[step][\"OutputImg\"],\n )\n (d_losses[\"Total Loss\"] / weight).mean().backward()\n self.optimizer_D.step()\n self.optimizer_D.zero_grad()\n\n # UPDATE LOSS: nvs_losses contains G_LOSS and D_LOSS\n # TODO why not combine Total Loss to have nvs_loss + g_loss for logging (gets done for backward pass anyways?\n g_losses.pop(\"Total Loss\")\n d_losses.pop(\"Total Loss\")\n nvs_losses.update(g_losses)\n nvs_losses.update(d_losses)\n\n # LOGGING of loss\n train_loss, train_acc = self.log_iteration_loss_and_acc(nvs_losses, nvs_accs, 'Train/', epoch * iter_per_epoch + i)\n train_losses.append(train_loss) # TODO is this correct? see above: why not combine everything into Total Loss?\n train_accs.append(train_acc)\n\n # Print loss every log_nth iteration\n if log_nth_iter != 0 and (i+1) % log_nth_iter == 0:\n print(\"[Iteration {cur}/{max}] TRAIN loss: {loss}\".format(cur=i + 1,\n max=iter_per_epoch,\n loss=train_loss))\n self.nvs_solver.visualize_output(all_output_images[-1], tag=\"train\", step=epoch*iter_per_epoch + i, depth=self.log_depth)\n\n self.scheduler_D.step()\n scheduler_G.step()\n\n # ONE EPOCH PASSED --> calculate + log mean train accuracy/loss for this epoch\n mean_train_loss = np.mean(train_losses)\n mean_train_acc = np.mean(train_accs)\n\n if log_nth_epoch != 0 and (epoch+1) % log_nth_epoch == 0:\n print(\"[EPOCH {cur}/{max}] TRAIN mean acc/loss: {acc}/{loss}\".format(cur=epoch + 1,\n max=num_epochs,\n acc=mean_train_acc,\n loss=mean_train_loss))\n self.nvs_solver.visualize_output(all_output_images[-1], tag=\"train\", step=epoch*iter_per_epoch + i, depth=self.log_depth)\n\n # ONE EPOCH PASSED --> calculate + log validation accuracy/loss for this epoch\n mean_val_loss = None\n mean_val_acc = None\n if len(val_loader) > 0:\n model.eval() # EVAL mode (for dropout, batchnorm, etc.)\n with torch.no_grad():\n val_losses = []\n val_accs = []\n val_minibatches = val_loader\n if tqdm_mode == 'epoch':\n val_minibatches = tqdm(val_minibatches)\n for i, sample in enumerate(val_minibatches):\n\n nvs_losses, output, nvs_accs = self.nvs_solver.forward_pass(model, sample)\n val_loss, val_acc = self.log_iteration_loss_and_acc(nvs_losses, nvs_accs, 'Val/', epoch * len(val_minibatches) + i)\n val_losses.append(val_loss)\n val_accs.append(val_acc)\n\n # Print loss every log_nth iteration\n if log_nth_iter != 0 and (i+1) % log_nth_iter == 0:\n print(\"[Iteration {cur}/{max}] Val loss: {loss}\".format(cur=i + 1,\n max=len(val_loader),\n loss=val_loss))\n self.nvs_solver.visualize_output(output, tag=\"val\", step=epoch*len(val_minibatches) + i, depth=self.log_depth)\n\n mean_val_loss = np.mean(val_losses)\n mean_val_acc = np.mean(val_accs)\n\n if log_nth_epoch != 0 and (epoch+1) % log_nth_epoch == 0:\n print(\"[EPOCH {cur}/{max}] VAL mean acc/loss: {acc}/{loss}\".format(cur=epoch + 1,\n max=num_epochs,\n acc=mean_val_acc,\n loss=mean_val_loss))\n self.nvs_solver.visualize_output(output, tag=\"val\", step=epoch*len(val_minibatches) + i, depth=self.log_depth)\n\n # LOG EPOCH LOSS / ACC FOR TRAIN AND VAL IN TENSORBOARD\n self.log_epoch_loss_and_acc(mean_train_loss, mean_val_loss, mean_train_acc, mean_val_acc, epoch)\n\n self.writer.add_hparams(self.hparam_dict, {\n 'HParam/Accuracy/Val': self.val_acc_history[-1] if len(val_loader) > 0 else 0,\n 'HParam/Accuracy/Train': self.train_acc_history[-1],\n 'HParam/Loss/Val': self.val_loss_history[-1] if len(val_loader) > 0 else 0,\n 'HParam/Loss/Train': self.train_loss_history[-1]\n })\n self.writer.flush()\n print('FINISH.')\n","sub_path":"util/gan_wrapper_solver.py","file_name":"gan_wrapper_solver.py","file_ext":"py","file_size_in_byte":15364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"278281051","text":"from .rman_translator import RmanTranslator\nfrom ..rman_sg_nodes.rman_sg_mesh import RmanSgMesh\nfrom ..rman_utils import object_utils\nfrom ..rman_utils import string_utils\nfrom ..rman_utils import property_utils\n\nimport bpy\nimport math\n\ndef _get_mats_faces_(nverts, material_ids):\n\n mats = {}\n for face_id, num_verts in enumerate(nverts):\n mat_id = material_ids[face_id]\n if mat_id not in mats:\n mats[mat_id] = []\n mats[mat_id].append(face_id)\n return mats\n\ndef _is_multi_material_(ob, mesh):\n if type(mesh) != bpy.types.Mesh or len(ob.data.materials) < 2 \\\n or len(mesh.polygons) == 0:\n return False\n first_mat = mesh.polygons[0].material_index\n for p in mesh.polygons:\n if p.material_index != first_mat:\n return True\n return False\n\n# requires facevertex interpolation\ndef _get_mesh_uv_(mesh, name=\"\", flipvmode='NONE'):\n uvs = []\n if not name:\n uv_loop_layer = mesh.uv_layers.active\n else:\n # assuming uv loop layers and uv textures share identical indices\n idx = mesh.uv_textures.keys().index(name)\n uv_loop_layer = mesh.uv_layers[idx]\n\n if uv_loop_layer is None:\n return None\n\n for uvloop in uv_loop_layer.data:\n uvs.append(uvloop.uv.x)\n # renderman expects UVs flipped vertically from blender\n # best to do this in pattern, provided here as additional option\n if flipvmode == 'UV':\n uvs.append(1.0-uvloop.uv.y)\n elif flipvmode == 'TILE':\n uvs.append(math.ceil(uvloop.uv.y) - uvloop.uv.y + math.floor(uvloop.uv.y))\n elif flipvmode == 'NONE':\n uvs.append(uvloop.uv.y)\n\n return uvs\n\ndef _get_mesh_vcol_(mesh, name=\"\"):\n vcol_layer = mesh.vertex_colors[name] if name != \"\" \\\n else mesh.vertex_colors.active\n cols = []\n\n if vcol_layer is None:\n return None\n\n for vcloop in vcol_layer.data:\n cols.extend(vcloop.color)\n\n return cols \n\ndef _get_mesh_vgroup_(ob, mesh, name=\"\"):\n vgroup = ob.vertex_groups[name] if name != \"\" else ob.vertex_groups.active\n weights = []\n\n if vgroup is None:\n return None\n\n for v in mesh.vertices:\n if len(v.groups) == 0:\n weights.append(0.0)\n else:\n weights.extend([g.weight for g in v.groups\n if g.group == vgroup.index])\n\n return weights\n\ndef _get_material_ids(ob, geo):\n \n material_ids = string_utils.convert_val([p.material_index for p in geo.polygons])\n return material_ids\n\ndef _get_primvars_(ob, geo, rixparams, interpolation=\"\"):\n\n rm = ob.data.renderman\n\n interpolation = 'facevarying' if not interpolation else interpolation\n\n if rm.export_default_uv:\n flipvmode = 'NONE'\n if hasattr(rm, 'export_flipv'):\n flipvmode = rm.export_flipv\n uvs = _get_mesh_uv_(geo, flipvmode=flipvmode)\n if uvs and len(uvs) > 0:\n rixparams.SetFloatArrayDetail(\"st\", uvs, 2, interpolation)\n\n \n # FIXME: SetColorDetail seems to be failing. Might be a bug in RtParamList.\n if rm.export_default_vcol:\n vcols = _get_mesh_vcol_(geo)\n if vcols and len(vcols) > 0:\n rixparams.SetColorDetail(\"Cs\", string_utils.convert_val(vcols, type_hint=\"color\"), interpolation)\n \n # custom prim vars\n\n for p in rm.prim_vars:\n if p.data_source == 'VERTEX_COLOR':\n vcols = _get_mesh_vcol_(geo, p.data_name)\n \n # FIXME: SetColorDetail seems to be failing. Might be a bug in RtParamList.\n if vcols and len(vcols) > 0:\n rixparams.SetColorDetail(p.name, string_utils.convert_val(vcols, type_hint=\"color\"), interpolation)\n \n elif p.data_source == 'UV_TEXTURE':\n flipvmode = 'NONE'\n if hasattr(rm, 'export_flipv'):\n flipvmode = rm.export_flipv\n uvs = _get_mesh_uv_(geo, p.data_name, flipvmode=flipvmode)\n if uvs and len(uvs) > 0:\n rixparams.SetFloatArrayDetail(p.name, uvs, 2, interpolation)\n\n elif p.data_source == 'VERTEX_GROUP':\n weights = _get_mesh_vgroup_(ob, geo, p.data_name)\n if weights and len(weights) > 0:\n rixparams.SetFloatDetail(p.name, weights, \"vertex\")\n\n for prop_name, meta in rm.prop_meta.items():\n if 'primvar' not in meta:\n continue\n\n val = getattr(rm, prop_name)\n if not val:\n continue\n\n if 'inheritable' in meta:\n if float(val) == meta['inherit_true_value']:\n if hasattr(rm_scene, prop_name):\n val = getattr(rm_scene, prop_name)\n\n ri_name = meta['primvar']\n is_array = False\n array_len = -1\n if 'arraySize' in meta:\n is_array = True\n array_len = meta['arraySize']\n param_type = meta['renderman_type']\n property_utils.set_rix_param(rixparams, param_type, ri_name, val, is_reference=False, is_array=is_array, array_len=array_len) \n\nclass RmanMeshTranslator(RmanTranslator):\n\n def __init__(self, rman_scene):\n super().__init__(rman_scene)\n self.bl_type = 'MESH' \n\n def _get_subd_tags_(self, ob, mesh, primvar):\n creases = []\n\n # only do creases 1 edge at a time for now,\n # detecting chains might be tricky..\n for e in mesh.edges:\n if e.crease > 0.0:\n creases.append((e.vertices[0], e.vertices[1],\n e.crease * e.crease * 10))\n # squared, to match blender appareance better\n #: range 0 - 10 (infinitely sharp)\n\n tags = ['interpolateboundary', 'facevaryinginterpolateboundary']\n nargs = [1, 0, 0, 1, 0, 0]\n intargs = [ int(ob.data.renderman.rman_subdivInterp),\n int(ob.data.renderman.rman_subdivFacevaryingInterp)]\n floatargs = []\n stringargs = [] \n\n if len(creases) > 0:\n for c in creases:\n tags.append('crease')\n nargs.extend([2, 1, 0])\n intargs.extend([c[0], c[1]])\n floatargs.append(c[2]) \n\n primvar.SetStringArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtags, tags, len(tags))\n primvar.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagnargs, nargs, len(nargs))\n primvar.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagintargs, intargs, len(intargs))\n primvar.SetFloatArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagfloatargs, floatargs, len(floatargs))\n primvar.SetStringArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagstringtags, stringargs, len(stringargs)) \n\n def export(self, ob, db_name):\n \n sg_node = self.rman_scene.sg_scene.CreateMesh(db_name)\n rman_sg_mesh = RmanSgMesh(self.rman_scene, sg_node, db_name)\n\n if self.rman_scene.do_motion_blur:\n rman_sg_mesh.is_transforming = object_utils.is_transforming(ob)\n rman_sg_mesh.is_deforming = object_utils._is_deforming_(ob)\n\n return rman_sg_mesh\n\n def export_deform_sample(self, rman_sg_mesh, ob, time_sample):\n\n mesh = None\n mesh = ob.to_mesh()\n primvar = rman_sg_mesh.sg_node.GetPrimVars()\n P = object_utils._get_mesh_points_(mesh)\n npoints = len(P)\n\n if rman_sg_mesh.npoints != npoints:\n primvar.SetTimeSamples([])\n rman_sg_mesh.sg_node.SetPrimVars(primvar)\n rman_sg_mesh.is_transforming = False\n rman_sg_mesh.is_deforming = False\n if rman_sg_mesh.is_multi_material:\n for c in rman_sg_mesh.multi_material_children:\n pvar = c.GetPrimVars()\n pvar.SetTimeSamples( [] ) \n c.SetPrimVars(pvar) \n return \n\n primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, \"vertex\", time_sample) \n\n rman_sg_mesh.sg_node.SetPrimVars(primvar)\n\n if rman_sg_mesh.is_multi_material:\n for c in rman_sg_mesh.multi_material_children:\n pvar = c.GetPrimVars()\n pvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, \"vertex\", time_sample) \n c.SetPrimVars(pvar)\n\n ob.to_mesh_clear() \n\n def export_mesh_primvars(self, ob, primvar, mesh):\n rm = ob.data.renderman \n\n def update(self, ob, rman_sg_mesh, input_mesh=None):\n\n rm = ob.renderman\n mesh = input_mesh\n if not mesh:\n mesh = ob.to_mesh()\n\n rman_sg_mesh.is_subdiv = object_utils.is_subdmesh(ob)\n get_normals = (rman_sg_mesh.is_subdiv == 0)\n (nverts, verts, P, N) = object_utils._get_mesh_(mesh, get_normals=get_normals)\n \n # if this is empty continue:\n if nverts == []:\n if not input_mesh:\n ob.to_mesh_clear()\n rman_sg_mesh.sg_node = None\n rman_sg_mesh.is_transforming = False\n rman_sg_mesh.is_deforming = False\n return None\n\n npolys = len(nverts) \n npoints = len(P)\n numnverts = len(verts)\n\n rman_sg_mesh.npoints = npoints\n rman_sg_mesh.npolys = npolys\n rman_sg_mesh.nverts = numnverts\n\n rman_sg_mesh.sg_node.Define( npolys, npoints, numnverts )\n rman_sg_mesh.is_multi_material = _is_multi_material_(ob, mesh)\n \n primvar = rman_sg_mesh.sg_node.GetPrimVars()\n primvar.Clear()\n\n if rman_sg_mesh.is_deforming:\n primvar.SetTimeSamples(rman_sg_mesh.motion_steps)\n \n primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, \"vertex\")\n _get_primvars_(ob, mesh, primvar, \"facevarying\") \n\n primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_nvertices, nverts, \"uniform\")\n primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_vertices, verts, \"facevarying\") \n\n if rman_sg_mesh.is_subdiv:\n creases = self._get_subd_tags_(ob, mesh, primvar)\n if ob.data.renderman.rman_subdiv_scheme == 'none':\n # we were tagged as a subdiv by a modifier\n rman_sg_mesh.sg_node.SetScheme(self.rman_scene.rman.Tokens.Rix.k_catmullclark) \n else:\n rman_sg_mesh.sg_node.SetScheme(ob.data.renderman.rman_subdiv_scheme) \n\n else:\n rman_sg_mesh.sg_node.SetScheme(None)\n primvar.SetNormalDetail(self.rman_scene.rman.Tokens.Rix.k_N, N, \"facevarying\") \n rman_sg_mesh.subdiv_scheme = ob.data.renderman.rman_subdiv_scheme\n\n if rman_sg_mesh.is_multi_material:\n material_ids = _get_material_ids(ob, mesh)\n for mat_id, faces in \\\n _get_mats_faces_(nverts, material_ids).items():\n\n mat = ob.data.materials[mat_id]\n mat_handle = object_utils.get_db_name(mat) \n sg_material = None\n if mat_handle in self.rman_scene.rman_materials:\n sg_material = self.rman_scene.rman_materials[mat_handle]\n\n if mat_id == 0:\n primvar.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_shade_faceset, faces, len(faces))\n rman_sg_mesh.sg_node.SetMaterial(sg_material.sg_node)\n else: \n sg_sub_mesh = self.rman_scene.sg_scene.CreateMesh(\"\")\n sg_sub_mesh.Define( npolys, npoints, numnverts ) \n if rman_sg_mesh.is_subdiv:\n sg_sub_mesh.SetScheme(self.rman_scene.rman.Tokens.Rix.k_catmullclark)\n pvars = sg_sub_mesh.GetPrimVars() \n if rman_sg_mesh.is_deforming:\n pvars.SetTimeSamples(rman_sg_mesh.motion_steps) \n pvars.Inherit(primvar)\n pvars.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_shade_faceset, faces, len(faces))\n sg_sub_mesh.SetPrimVars(pvars)\n sg_sub_mesh.SetMaterial(sg_material.sg_node)\n rman_sg_mesh.sg_node.AddChild(sg_sub_mesh)\n rman_sg_mesh.multi_material_children.append(sg_sub_mesh)\n else:\n rman_sg_mesh.multi_material_children = []\n\n rman_sg_mesh.sg_node.SetPrimVars(primvar)\n\n if not input_mesh:\n ob.to_mesh_clear() \n\n return True ","sub_path":"translators/rman_mesh_translator.py","file_name":"rman_mesh_translator.py","file_ext":"py","file_size_in_byte":12629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"308212636","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Tests ensuring codebase style compliance for Rust.\"\"\"\n\nfrom framework import utils\n\n\ndef test_rust_style():\n \"\"\"\n Test that rust code passes style checks.\n\n @type: style\n \"\"\"\n\n # ../src/io_uring/src/bindings.rs\n config = open(\"fmt.toml\", encoding=\"utf-8\").read().replace(\"\\n\", \",\")\n # Check that the output is empty.\n _, stdout, _ = utils.run_cmd(f\"cargo fmt --all -- --check --config {config}\")\n\n # rustfmt prepends `\"Diff in\"` to the reported output.\n assert \"Diff in\" not in stdout\n\n\ndef test_ensure_mod_tests():\n \"\"\"\n Check that files containing unit tests have a 'tests' module defined.\n\n @type: style\n \"\"\"\n # List all source files containing rust #[test] attribute,\n # (excluding generated files and integration test directories).\n # Take the list and check each file contains 'mod tests {', output file\n # name if it doesn't.\n cmd = (\n \"/bin/bash \"\n \"-c \"\n '\"grep '\n \"--files-without-match \"\n \"'mod tests {' \"\n \"\\\\$(grep \"\n \"--files-with-matches \"\n \"--recursive \"\n \"--exclude-dir=src/*_gen/* \"\n \"'\\\\#\\\\[test\\\\]' ../src/*/src)\\\" \"\n '| grep -v \"../src/io_uring/src/bindings.rs\"'\n )\n\n # The outer grep returns 0 even if it finds files without the match, so we\n # ignore the return code.\n result = utils.run_cmd(cmd, no_shell=False, ignore_return_code=True)\n\n stdout = result.stdout.strip()\n\n error_msg = (\n f'Tests found in files without a \"tests\" module:\\n {stdout} '\n \"To ensure code coverage is reported correctly, please check that \"\n 'your tests are in a module named \"tests\".'\n )\n\n assert not stdout, error_msg\n","sub_path":"tests/integration_tests/style/test_rust.py","file_name":"test_rust.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"159580274","text":"from django.http.response import HttpResponse\nimport requests \nimport json\n\n\ndef index(request):\n def query(url):\n # url = \"http://pokeapi.co/api/v2/pokemon/\"\n response = requests.get(url)\n if response.status_code == 200:\n data = json.loads(response.text)\n a=data['results']\n l=len(a)\n lst=[]\n \n for i in range(l):\n lst.append(a[i][\"name\"])\n return [lst]\n\n\n else:\n return (\"An error occurred querying the API\")\n\n return HttpResponse(query(\"http://pokeapi.co/api/v2/pokemon/\"))\n","sub_path":"pokemon/pokemon/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"422274797","text":"def has_seven(k):\n \"\"\"Has a has_seven\n >>> has_seven(3)\n False\n >>> has_seven(7)\n True\n >>> has_seven(2734)\n True\n >>> has_seven(2634)\n False\n >>> has_seven(734)\n True\n >>> has_seven(7777)\n True\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n if k % 10 == 7:\n return True\n if ((k//10)==0) and (k != 7):\n return False\n return has_seven(k//10)\n\n# Q3.\n\n\ndef pingpong(n):\n \"\"\"Return the nth element of the ping-pong sequence.\n\n >>> pingpong(7)\n 7\n >>> pingpong(8)\n 6\n >>> pingpong(15)\n 1\n >>> pingpong(21)\n -1\n >>> pingpong(22)\n 0\n >>> pingpong(30)\n 6\n >>> pingpong(100)\n 2\n \"\"\"\n def is_seven(n):\n if n % 7 == 0 or has_seven(n):\n return True\n return False\n def isUp(a):\n if a <= 7:\n return True\n if is_seven(a-1):\n return (not isUp(a-1))\n else:\n return isUp(a-1)\n if n <=7:\n return n\n if isUp(n):\n return pingpong(n-1) + 1\n return pingpong(n-1) - 1","sub_path":"hw/hw3/pingpong.py","file_name":"pingpong.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"113007733","text":"import os\n\n\nfirstTower = []\nsecondTower = []\nthirdTower = [8, 7, 6, 5, 4, 3, 2, 1]\n\ncommandsList = ['exit', 'e', 'move', 'm', 'help', 'h']\ncurrent_error = 'none'\n\n\ndef check_values(fr, to):\n if fr == 1:\n if to == 2:\n if not secondTower:\n return True\n else:\n if secondTower[len(secondTower) - 1] < firstTower[len(firstTower) - 1]:\n return False\n else:\n return True\n elif to == 3:\n if not thirdTower:\n return True\n else:\n if thirdTower[len(thirdTower) - 1] < firstTower[len(firstTower) - 1]:\n return False\n else:\n return True\n elif fr == 2:\n if to == 1:\n if not firstTower:\n return True\n else:\n if firstTower[len(firstTower) - 1] < secondTower[len(secondTower) - 1]:\n return False\n else:\n return True\n elif to == 3:\n if not thirdTower:\n return True\n else:\n if thirdTower[len(thirdTower) - 1] < secondTower[len(secondTower) - 1]:\n return False\n else:\n return True\n elif fr == 3:\n if to == 1:\n if not firstTower:\n return True\n else:\n if firstTower[len(firstTower) - 1] < thirdTower[len(thirdTower) - 1]:\n return False\n else:\n return True\n elif to == 2:\n if not secondTower:\n return True\n else:\n if secondTower[len(secondTower) - 1] < thirdTower[len(thirdTower) - 1]:\n return False\n else:\n return True\n\n\ndef is_tower_empty(tow):\n if tow == 1:\n if firstTower:\n return False\n else:\n return True\n elif tow == 2:\n if secondTower:\n return False\n else:\n return True\n elif tow == 3:\n if thirdTower:\n return False\n else:\n return True\n\n\ndef check_num(num, tow):\n if num == 1:\n if tow == 1:\n if 1 in firstTower:\n return 1\n elif tow == 2:\n if 1 in secondTower:\n return 1\n elif tow == 3:\n if 1 in thirdTower:\n return 1\n elif num == 2:\n if tow == 1:\n if 2 in firstTower:\n return 1\n elif tow == 2:\n if 2 in secondTower:\n return 1\n elif tow == 3:\n if 2 in thirdTower:\n return 1\n elif num == 3:\n if tow == 1:\n if 3 in firstTower:\n return 1\n elif tow == 2:\n if 3 in secondTower:\n return 1\n elif tow == 3:\n if 3 in thirdTower:\n return 1\n elif num == 4:\n if tow == 1:\n if 4 in firstTower:\n return 1\n elif tow == 2:\n if 4 in secondTower:\n return 1\n elif tow == 3:\n if 4 in thirdTower:\n return 1\n elif num == 5:\n if tow == 1:\n if 5 in firstTower:\n return 1\n elif tow == 2:\n if 5 in secondTower:\n return 1\n elif tow == 3:\n if 5 in thirdTower:\n return 1\n elif num == 6:\n if tow == 1:\n if 6 in firstTower:\n return 1\n elif tow == 2:\n if 6 in secondTower:\n return 1\n elif tow == 3:\n if 6 in thirdTower:\n return 1\n elif num == 7:\n if tow == 1:\n if 7 in firstTower:\n return 1\n elif tow == 2:\n if 7 in secondTower:\n return 1\n elif tow == 3:\n if 7 in thirdTower:\n return 1\n elif num == 8:\n if tow == 1:\n if 8 in firstTower:\n return 1\n elif tow == 2:\n if 8 in secondTower:\n return 1\n elif tow == 3:\n if 8 in thirdTower:\n return 1\n return 0\n\n\ndef move(fr, to):\n if fr == 1:\n if to == 2:\n secondTower.append(firstTower.pop())\n elif to == 3:\n thirdTower.append(firstTower.pop())\n elif fr == 2:\n if to == 1:\n firstTower.append(secondTower.pop())\n elif to == 3:\n thirdTower.append(secondTower.pop())\n elif fr == 3:\n if to == 1:\n firstTower.append(thirdTower.pop())\n elif to == 2:\n secondTower.append(thirdTower.pop())\n\n\ndef current_situation():\n os.system('clear')\n print('Current situation:\\t', 'Error: ', current_error, sep='', end='\\n\\n')\n print('Tower #1: ', '8' * check_num(8, 1), '7' * check_num(7, 1), '6' * check_num(6, 1), '5' * check_num(5, 1),\n '4' * check_num(4, 1), '3' * check_num(3, 1), '2' * check_num(2, 1), '1' * check_num(1, 1), sep='',\n end='\\n\\n')\n print('Tower #2: ', '8' * check_num(8, 2), '7' * check_num(7, 2), '6' * check_num(6, 2), '5' * check_num(5, 2),\n '4' * check_num(4, 2), '3' * check_num(3, 2), '2' * check_num(2, 2), '1' * check_num(1, 2), sep='',\n end='\\n\\n')\n print('Tower #3: ', '8' * check_num(8, 3), '7' * check_num(7, 3), '6' * check_num(6, 3), '5' * check_num(5, 3),\n '4' * check_num(4, 3), '3' * check_num(3, 3), '2' * check_num(2, 3), '1' * check_num(1, 3), sep='',\n end='\\n\\n')\n\n\ndef game_cycle():\n while secondTower != [8, 7, 6, 5, 4, 3, 2, 1]:\n global current_error\n next_turn = input('\\nEnter the next command: ')\n if next_turn not in commandsList:\n current_error = 'Command does not exist'\n continue\n else:\n current_error = 'none'\n if next_turn == 'exit' or next_turn == 'e':\n exit()\n elif next_turn == 'move' or next_turn == 'm':\n try:\n f = int(input('\\nFrom which tower you want to move disc? '))\n except ValueError:\n current_error = 'Value Error'\n current_situation()\n continue\n if is_tower_empty(f):\n current_error = 'Chosen tower is empty'\n current_situation()\n continue\n try:\n t = int(input('\\nTo which tower you want to move disc? '))\n except ValueError:\n current_error = 'Value Error'\n current_situation()\n continue\n if t == f:\n current_error = 'You can\\'t move to this tower'\n current_situation()\n continue\n if check_values(f, t):\n move(f, t)\n else:\n current_error = 'You can\\'t do this'\n current_situation()\n continue\n elif next_turn == 'help' or next_turn == 'h':\n print('\\n', 'move(m) - move disc from one tower to another', 'exit(e) - exit from program',\n 'help(h) - prints help', sep='\\n', end='\\n\\n')\n wait = input()\n del wait\n current_situation()\n\ncurrent_situation()\ngame_cycle()\n","sub_path":"towers-of-hanoi.py","file_name":"towers-of-hanoi.py","file_ext":"py","file_size_in_byte":7422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"643232047","text":"import heapq\n\n\nclass Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n \"\"\"\n Time complexity:\n The time complexity of this algorithm is (N*logK) as we iterating\n all points and pushing them into the heap.\n\n Space complexity:\n The space complexity will be O(K) because we need to store ‘K’\n point in the heap.\n \"\"\"\n\n max_heap = []\n results = []\n\n for point in points:\n dist = point[0]**2+point[1]**2\n if len(max_heap) < K:\n heapq.heappush(max_heap, (-dist, point))\n else:\n if max_heap[0][0] < -dist:\n heapq.heapreplace(max_heap, (-dist, point))\n\n for i in range(K):\n results.append(heapq.heappop(max_heap)[1])\n\n return results\n","sub_path":"Problems/Leetcode/973_KClosestPointsToOrigin.py","file_name":"973_KClosestPointsToOrigin.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"182593813","text":"#!/usr/bin/env python3\n# -*- encoding:utf-8 -*-\n\nimport os\nimport gzip\n\n_cur_dir_path = os.path.split(os.path.realpath(__file__))[0]\n_data_dir = os.path.join(_cur_dir_path, \"../data_from_3rdparty/scir_training_day/3-nlp-practice\")\n\n_train_data_path = os.path.join(_data_dir, \"penn.train.pos.gz\")\n_devel_data_path = os.path.join(_data_dir, \"penn.devel.pos.gz\")\n_test_data_path = os.path.join(_data_dir, \"penn.test.pos.blind.gz\")\n\ndef _read_annotated_data(fpath):\n '''read annotated data. (from format 'word/tag ...)' => ( word_list, tag_list )'''\n with gzip.open(fpath, 'rt', encoding=\"utf-8\") as f:\n annotated_dataset = []\n for line in f:\n line = line.strip()\n word_tag_pair_list = line.split()\n instance = ([], [])\n for word_tag_pair in word_tag_pair_list:\n (word, tag) = word_tag_pair.rsplit('/', 1) # may have multiple '/'\n instance[0].append(word)\n instance[1].append(tag)\n annotated_dataset.append(instance)\n return annotated_dataset\n\ndef _read_unannotated_data(fpath):\n '''read unannotated data. (from format 'word/_ ...') => word_list '''\n with gzip.open(fpath, 'rt', encoding=\"utf-8\") as f:\n unannotated_dataset = []\n for line in f:\n line = line.strip()\n word_tag_pair_list = line.split()\n instance = [ pair.rsplit('/', 1)[0] for pair in word_tag_pair_list ]\n unannotated_dataset.append(instance)\n return unannotated_dataset\n\n\ndef read_training_data():\n return _read_annotated_data(_train_data_path)\n\ndef read_devel_data():\n return _read_annotated_data(_devel_data_path)\n\ndef read_test_data():\n return _read_unannotated_data(_test_data_path)\n","sub_path":"dataset_handler/reader_py3.py","file_name":"reader_py3.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"258439945","text":"import geojson\nimport json\nimport numpy as np\nimport os\nimport pyproj\nimport rasterio\nimport shapely\nimport shapely.wkt\nimport subprocess\n\nfrom osgeo import gdal\nfrom rasterio.features import sieve, shapes\nfrom scipy.ndimage import gaussian_filter\nfrom shapely.ops import transform\nfrom shapely.geometry import shape\nfrom statsmodels.distributions.empirical_distribution import ECDF\n \ndef get_utm_zone(latitude, longitude):\n \"\"\"\n compute utm zone and weather it is in North or South given by a lat/lon coordinate\n\n Arguments\n longitude : float\n latitude : float\n\n Returns\n utm_zone, is_north : list (or list like)\n utm zone number and N or S string\n\n \"\"\"\n\n utm_zone = int(1 + (longitude + 180.0) / 6.0)\n\n is_north = 0\n if (latitude < 0.0):\n is_north = \"S\";\n else:\n is_north = \"N\";\n\n return utm_zone, is_north\n\ndef convert_wkt_to_geometry(geometry_wkt):\n \"\"\" \n Convert wkt string to a shapely.geometry.polygon.Polygon object\n \n Arguments\n geometry_wkt : wkt string\n\n Returns\n geom: shapely geometry object\n\n \"\"\"\n \n geom = shapely.wkt.loads(geometry_wkt)\n\n return geom\n\n\ndef compute_centroid_from_geometry(geometry_wkt):\n \"\"\"\n compute centroid of a geometry; can be polygon, point\n\n Arguments\n geometry : str\n geojson geometry string\n\n Returns\n y, x: latitude and longitude of centroid\n\n \"\"\"\n\n geometry = shapely.wkt.loads(geometry_wkt)\n x = geometry.centroid.x\n y = geometry.centroid.y\n\n return y, x\n\ndef convert_geojson_to_wkt(boundary):\n \"\"\"\n Returns wkt geometry from geojson \n\n Arguments:\n ----------\n geojson : json\n geojson \n\n Returns:\n -------\n geometry wkt : wkt \n \"\"\" \n \n s = json.dumps(boundary)\n # convert to geojson.geometry.Polygon\n geo = geojson.loads(s)\n # Feed to shape() to convert to shapely.geometry.polygon.Polygon\n geom = shape(geo)\n # get a WKTrepresentation\n return geom.wkt\n \ndef convert_geom_latlon_to_utm_na(geometry, utmzone):\n \"\"\"\n reproject geometry in wgs84 lat/lon to utm projection for nothern hemisphere\n \n Arguments\n geometry: wkt string\n wkt format geometry string\n utmzone: string or int\n 2 digit utmzone\n \n Return: None \n \"\"\"\n source_crs = 'epsg:4326'\n target_crs = 'epsg:326{}'.format(utmzone)\n\n project = partial(\n pyproj.transform,\n pyproj.Proj(init = source_crs), # source coordinate system\n pyproj.Proj(init = target_crs)) # destination coordinate system\n\n utm_geom = transform(project, geometry) # apply projection\n return utm_geom\n\ndef convert_geom_latlon_to_utm_sa(geometry, utmzone):\n \"\"\"\n reproject geometry in wgs84 lat/lon to utm projection for southern hemisphere\n \n Arguments\n geometry: wkt string\n wkt format geometry string\n utmzone: string or int\n 2 digit utmzone\n \n Return: None \n \"\"\"\n\n source_crs = 'epsg:4326'\n target_crs = 'epsg:327{}'.format(utmzone)\n\n project = partial(\n pyproj.transform,\n pyproj.Proj(init = source_crs), # source coordinate system\n pyproj.Proj(init = target_crs)) # destination coordinate system\n\n utm_geom = transform(project, geometry) # apply projection\n return utm_geom\n\n\ndef gdal_convert_raster_to_shp(input_raster, output_shp):\n \"\"\"\n convert raster file to ESRI shapefile\n \n Arguments\n input_raster: string\n path to a input raster file\n \n Return: None \n \"\"\"\n cmd = \"gdal_polygonize.py \" + \\\n input_raster + \" \" + \\\n output_shp\n subprocess.check_call(cmd, shell=True)\n \ndef read_mask_image(raster_path, mask_feature):\n \"\"\"\n clipping (masking) raster data to polygon geometry \n \n \n Arguments\n raster_path: string\n path to the raster file\n \n mask_feature: shapely geometry object\n * be sure to be in list format\n\n Returns\n arr_ma: nd array\n clipped nd array\n arr_ma_tranform: rasterio geotransform object\n \n \"\"\"\n \n with rasterio.Env():\n with rasterio.open(raster_path) as src:\n arr = src.read(masked=True)\n arr_ma, arr_ma_transform = mask(src, mask_feature, nodata=np.nan, crop=True,\n all_touched=False, invert=False)\n return arr_ma, arr_ma_transform\n\ndef ecef_normalizer(arr):\n \"\"\"\n apply ecef normalization to 2d nd array\n \n For details can be found \n https://www.statsmodels.org/stable/generated/statsmodels.distributions.empirical_distribution.ECDF.html\n \n ** need to import the model from statsmodel package\n from statsmodels.distributions.empirical_distribution import ECDF\n \n ** input to ECDF must be 1-dimensional\n \n Arguments\n arr: numpy nd array\n 2-d nd array\n\n Returns\n arr_norm: normalized 2d nd array\n \n \"\"\"\n \n # reshape to 1d\n arr_new = np.reshape(arr, -1)\n \n ecdf = ECDF(arr_new)\n arr_norm = ecdf(arr_new)\n \n # convert back to 2d nd array\n arr_norm = arr_norm.reshape(arr.shape[0], arr.shape[1])\n \n return arr_norm\n\ndef gaussian_filter_kernel5(arr):\n \"\"\"\n apply gaussian filter to 2d nd array with a kernel size of 5x5\n \n **Need to import \"gaussian_filter\" module from scipy ndimage\n from scipy.ndimage import gaussian_filter\n \n For details can be found \n https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.gaussian_filter.html\n \n Parameters\n arr: numpy nd array\n 2-d nd array\n\n Returns\n g_filtered: gaussian filtered (smoothed) 2d nd array\n \n \"\"\"\n \n s = 4 # sigma (default=4)\n w = 5 # kernel size\n t = (((w - 1)/2)-0.5)/s # truncate\n\n g_filterd = gaussian_filter(arr, sigma=s, truncate=t)\n \n return g_filterd\n\ndef sieve_small_cluster(raster_path, out_path):\n\n \"\"\"\n remove (sieve) small clusters using raterio (GDAL) sieve function\n\n ** threshold size for removing small area for production system is 8.573278464267728E-8 sqaure degrees\n that corresponds to 1072 square meters (~ 11 pixels at 10 m)\n but can be user defined with a value of number of pixels\n Argument\n raster_path: string\n raster file path\n\n Returns\n None\n\n \"\"\"\n\n # Register GDAL and OGR drivers.\n with rasterio.Env():\n\n # Read a raster to be sieved.\n with rasterio.open(raster_path) as src:\n shade = src.read(1)\n mask = shade != np.nan\n \n # Sieve out features with 11 pixels or smaller.\n sieved = sieve(shade, 11, out=np.zeros(src.shape, src.dtypes[0]))\n\n # Print the number of shapes in the sieved raster.\n print(\"Sieved (11) shapes: %d\" % len(list(shapes(sieved))))\n\n # Write out the sieved raster.\n kwargs = src.meta\n kwargs['transform'] = rasterio.transform.guard_transform(kwargs['transform'])\n\n with rasterio.open(out_path, 'w', **kwargs) as dst:\n dst.write(sieved, indexes=1)\n\ndef reproject_raster_latlon_to_utm_gdalwarp(infile_path, outfile_path, t_epsg, resolution):\n \"\"\"\n reproject raster from lat/lon to UTM with a designated spatial resolution\n \n Arguments\n \n infile_path: string\n path to a input raster file\n outfile_path: string\n path to a input raster file\n t_epsg: string\n EPSG code in string format, for example epsg 32615 is UTM projection zone 15 in Norther Hemisphere\n resolution: string\n output resolution in meter\n \n \"\"\"\n cmd = \"gdalwarp \" + \\\n \"-of GTiff \" + \\\n \"-tr \" + resolution + ' ' + resolution + ' ' + \\\n \"-s_srs EPSG:4326 \" + \\\n \"-t_srs EPSG:\" + t_epsg + ' ' + \\\n infile_path + ' ' + \\\n outfile_path\n subprocess.check_call(cmd, shell=True)\n \ndef resample_raster_gdalwarp(infile_path, outfile_path, resolution):\n \"\"\"\n Resample raster file. this is based on UTM projection which is the meter unit.\n The resolution must be the same unit to input raster. \n \n Arguments\n \n infile_path: string\n path to input raster\n \n outfile_path: string\n path to output file\n \n resolution: string\n \n \"\"\"\n cmd = \"gdalwarp \" + \\\n \"-of GTiff \" + \\\n \"-tr \" + resolution + ' ' + resolution + ' ' + \\\n \"-r bilinear \" + \\\n infile_path + ' ' + \\\n outfile_path\n subprocess.check_call(cmd, shell=True)","sub_path":"notebooks/.ipynb_checkpoints/custom_geospatial_utils-checkpoint.py","file_name":"custom_geospatial_utils-checkpoint.py","file_ext":"py","file_size_in_byte":8511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"455670690","text":"import numpy as np\n\n\ndef getHist(img):\n row, col = img.shape\n y = np.zeros(256)\n for i in range(0,row):\n for j in range(0,col):\n y[img[i,j]] += 1\n return y\n\ndef uncompressed(img,file):\n row,col=img.shape\n f = open(file+\".unc\",\"w\")\n for i in range(0,row):\n f.write(str(img[i][0]))\n for j in range(1,col):\n f.write('\\t')\n f.write(hex(img[i][j]).lstrip(\"0x\").zfill(2))\n f.close()\n\n\n\ndef getProbabilities(histogram,pixels):\n for i in range (0,histogram.shape[0]):\n if (histogram[i] != 0):\n histogram[i] = histogram[i]/pixels\n else:\n histogram[i] = 0\n return histogram\n\ndef getOrder(probabilites):\n probabilitiesOrder=[]\n max=1;\n while max != 0:\n maxArray=np.where(probabilites == np.amax(probabilites))[0]\n # print(maxArray)\n for i in maxArray:\n # print(probabilites[i])\n probabilites[i]=0\n probabilitiesOrder.append(i)\n max=np.amax(probabilites)\n return probabilitiesOrder\n\ndef setTree(probabilitiesOrder,file):\n treeStructure = [0]*len(probabilitiesOrder)\n maxPosition = len(probabilitiesOrder)-1\n while(maxPosition!=0):\n for i in range (0,maxPosition):\n treeStructure[i]+=1\n # print(hex(treeStructure[i]).lstrip(\"0x\"))\n maxPosition-=1\n # print(order)\n f = open(file+\".huf\", \"w\")\n f.write(hex(probabilitiesOrder[0]).lstrip(\"0x\"))\n for i in range(1,len(probabilitiesOrder)):\n f.write('\\t')\n f.write(hex(probabilitiesOrder[i]).lstrip(\"0x\"))\n f.write('\\n')\n f.close()\n\ndef compressionMethod(probabilitiesOrder,img,file):\n row, col = img.shape\n f = open(file+\".huf\", \"a\")\n for i in range (0,row-1):\n f.write(hex(probabilitiesOrder.index(img[i][0])).lstrip(\"0x\"))\n # print(hex(probabilitiesOrder.index(img[i][0])).lstrip(\"0x\"),end='\\t')\n for j in range (1,col):\n f.write('\\t')\n aux = hex(probabilitiesOrder.index(img[i][j])).lstrip(\"0x\")\n # print(aux,end='\\t')\n f.write(aux)\n f.write('\\n')\n # print('\\n')\n f.write(hex(probabilitiesOrder.index(img[row-1][0])).lstrip(\"0x\"))\n for j in range (1,col):\n f.write('\\t')\n aux = hex(probabilitiesOrder.index(img[row-1][j])).lstrip(\"0x\")\n # print(aux,end='\\t')\n f.write(aux)\n f.close()\n\ndef compress(img,file):\n row, col = img.shape\n pixels= row*col\n histogram = getHist(img)\n probabilites = getProbabilities(histogram,pixels)\n order= getOrder(probabilites)\n setTree(order,file)\n compressionMethod(order,img,file)\n","sub_path":"Huffman1canal/Compress.py","file_name":"Compress.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"240437981","text":"import random\nimport time\nimport winsound\nfrom colorama import Fore, Style\nfrom text_formatting import Bold_text\n\n\n# logic to build Simon's pattern each round\ndef pattern_builder(colors, simon_pattern):\n # https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list\n simon_pattern.append(random.choice(colors))\n for color in simon_pattern:\n if color == 'R':\n time.sleep(.8) # delay before displaying next color\n winsound.PlaySound('audio\\\\red_sound.wav', winsound.SND_ASYNC) # plays called audio file\n print(f'{Fore.RED}{Bold_text.BOLD}{color}{Style.BRIGHT}', end=' ')\n elif color == 'G':\n time.sleep(.8)\n winsound.PlaySound('audio\\\\green_sound.wav', winsound.SND_ASYNC)\n print(f'{Fore.GREEN}{Bold_text.BOLD}{color}{Style.BRIGHT}', end=' ')\n elif color == 'B':\n time.sleep(.8)\n winsound.PlaySound('audio\\\\blue_sound.wav', winsound.SND_ASYNC)\n print(f'{Fore.BLUE}{Bold_text.BOLD}{color}{Style.BRIGHT}', end=' ')\n else:\n time.sleep(.8)\n winsound.PlaySound('audio\\\\yellow_sound.wav', winsound.SND_ASYNC)\n print(f'{Fore.YELLOW}{Bold_text.BOLD}{color}{Style.BRIGHT}', end=' ')\n return simon_pattern\n","sub_path":"pattern_builder.py","file_name":"pattern_builder.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"369587689","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef to_float_list(data_line):\n return [float(el) for el in data_line.replace('\\n', '').split(' ')]\n\n\ndef main():\n with open('../lsd.dat') as f:\n lines = f.readlines()\n points = [to_float_list(line) for line in lines]\n\n x, y = zip(*points)\n x = np.array(x)\n y = np.array(y)\n\n # http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html\n # Least squares polynomial fit. \n # Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). \n # Returns a vector of coefficients p that minimises the squared error:\n # (a, b) for y = a * x + b\n fit = np.polyfit(x, y, 1)\n\n # fit_fn is now a function which takes in x and returns an estimate for y\n fit_fn = np.poly1d(fit) \n\n plt.plot(x, y, 'x', x, fit_fn(x))\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"linear-regression/linear-regression-1-var/python/visualize_regression.py","file_name":"visualize_regression.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"575491697","text":"# -*- coding: utf-8 -*-\n\"\"\"\n__magicMethods__ COMPARATORS OVERLOADING:\n__lt__ for <\n__le__ for <=\n__eq__ for ==\n__ne__ for !=\n__gt__ for >\n__ge__ for >=\n\"\"\"\n\nclass Vector2D:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __lt__(self, other):\n if (self.x < other.x) & (self.y < other.y):\n return True\n else:\n return False\n \nv_5_7 = Vector2D(5, 7); v_3_9 = Vector2D(3, 9); print(v_5_7 < v_3_9)\nv_3_5 = Vector2D(3, 5); v_4_6 = Vector2D(4, 6); print(v_3_5 < v_4_6)\n\n\n","sub_path":"xSoloLearn_basics/OOP/oop_03_magicMethods_03_comparisons.py","file_name":"oop_03_magicMethods_03_comparisons.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"438473861","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n# -----------------------------------------------------------------------------\n#\n# P A G E B O T E X A M P L E S\n#\n# Copyright (c) 2017 Thom Janssen <https://github.com/thomgb>\n# www.pagebot.io\n# Licensed under MIT conditions\n#\n# Supporting DrawBot, www.drawbot.com\n# Supporting Flat, xxyxyz.org/flat\n# -----------------------------------------------------------------------------\n#\n# ElementPaddingMargin.py\n#\n# Show element padding and margin\n#\nfrom pagebot.document import Document\nfrom pagebot.elements import newRect\nfrom pagebot.toolbox.units import p, pt\nfrom pagebot.toolbox.color import color\nfrom pagebot.conditions import *\n\nW = H = 500\nPADDING = p(2)\nMARGIN = p(1)\n\ndoc = Document(w=W, h=H)\nview = doc.view\nview.padding = p(4)\nview.showCropMarks = True\nview.showFrame = True\nview.showPadding = True # Show padding and margin on page\nview.showMargin = True\n\npage = doc[1] # Get the single page from te document.\npage.margin = page.bleed = MARGIN\npage.padding = PADDING\n\n# Add element without conditions. Hard positioning from bottom-left\nnewRect(parent=page, x=60, y=60, fill=color(0.7, 0.7, 0.7, 0.3), \n w=150, h=200, showMargin=True, showPadding=True, \n margin=MARGIN, padding=PADDING)\n\n# Condition alignment takes the element margin into account.\nnewRect(parent=page, fill=color(0.7, 0.7, 0.7, 0.3), \n w=150, h=200, showMargin=True, showPadding=True, \n margin=MARGIN, padding=PADDING,\n conditions=[Right2Right(), Top2Top()])\n\npage.solve()\n\n# Export in _export folder that does not commit in Git. \n# Force to export PDF.\nEXPORT_PATH = '_export/ElementPaddingMargin.pdf'\ndoc.export(EXPORT_PATH)\n\n\n","sub_path":"Basics/E04_Elements/ElementPaddingMargin.py","file_name":"ElementPaddingMargin.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"398927303","text":"'''\r\n재관이의 옷 매장에서 대량 세일을 하고자 한다.\r\n\r\n세일에는 조건이 한가지 있는데, 세 벌의 옷을 사면 그 중 가장 저렴한 한 벌에 해당하는 값은 내지 않아도 된다는 조건이다.\r\n\r\n그리고 세 벌보다 많은 옷을 구매하는 경우에도 옷을 세 벌씩 나눠서 계산하면 같은 방식의 할인을 받을 수 있다.\r\n\r\n예를 들면 10, 3, 2, 4, 6, 4, 9원짜리 옷을 사고자 할 때 (3, 2, 4), (10, 4, 9), (6)원짜리로 묶어서 계산을 하게 된다면,\r\n\r\n첫 묶음에서 2원, 두 번째 묶음에서 4원 총 6원의 할인을 받게 되는 것이다.\r\n\r\n다만 세 번째 묶음은 한 벌만 구매하므로 할인이 적용되지 않는다.\r\n\r\n재관이네 매장에서 사고자 하는 옷이 있을 때 어떻게 묶어서 결제를 하면 가장 할인을 많이 받아서 구매를 할 수 있는지 계산하여라.\r\n\r\n\r\n\r\n두 번째 테스트케이스를 예로 보면, {6,4,5,5,5,5}의 옷들이 있을 때 (6,4,5), (5,5,5)로 묶으면 가장 저렴한 조합이 된다.\r\n\r\n[입력]\r\n\r\n맨 위 줄에 테스트케이스의 개수가 주어진다.\r\n\r\n각 테스트케이스 별로 순서대로 첫째 줄에 사고자 하는 옷의 벌 수 N (1 ≤ N ≤ 100,000)이 주어진다.\r\n\r\n다음 줄에는 N개의 옷의 가격 Ci (1 ≤ Ci ≤ 100,000)가 띄어쓰기로 구분되어 주어진다.\r\n\r\n[출력]\r\n\r\n각 테스트케이스 별로 순서대로 한 줄씩 답을 출력하는데, 지불해야 할 최소의 금액을 출력한다.\r\n'''\r\nimport sys\r\nsys.stdin = open('4050.txt')\r\nT = int(input())\r\nfor case in range(1, T+1):\r\n N = int(input())\r\n values = list(map(int, input().split()))\r\n\r\n # 가격 정렬 역순\r\n values.sort(reverse=True)\r\n\r\n # index를 위해 0번 항목 추가\r\n values = [0] + values\r\n\r\n # 3의 배수 index의 가격 = 0\r\n for n in range(N+1):\r\n if n % 3 == 0:\r\n values[n] = 0\r\n\r\n # 총 가격 합계\r\n result = sum(values)\r\n print('#{} {}'.format(case, result))\r\n","sub_path":"before2021/python/190824/2_D4_4050_재관이의대량할인.py","file_name":"2_D4_4050_재관이의대량할인.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"360741614","text":"from typing import List, Optional\n\nimport boto3\nimport click\nfrom google.cloud import storage # type: ignore\nfrom google.cloud.exceptions import NotFound\n\nfrom opta.amplitude import amplitude_client\nfrom opta.core.gcp import GCP\nfrom opta.core.generator import gen_all\nfrom opta.core.terraform import Terraform\nfrom opta.layer import Layer\nfrom opta.utils import fmt_msg, logger, yaml\n\n\n@click.command(hidden=True)\n@click.option(\"-c\", \"--config\", default=\"opta.yml\", help=\"Opta config file.\")\n@click.option(\n \"-e\", \"--env\", default=None, help=\"The env to use when loading the config file.\"\n)\n@click.option(\n \"--auto-approve\",\n is_flag=True,\n default=False,\n help=\"Automatically approve terraform plan.\",\n)\ndef destroy(config: str, env: Optional[str], auto_approve: bool) -> None:\n \"\"\"Destroy all opta resources from the current config\"\"\"\n amplitude_client.send_event(amplitude_client.DESTROY_EVENT)\n layer = Layer.load_from_yaml(config, env)\n if not Terraform.download_state(layer):\n logger.info(\n \"The opta state could not be found. This may happen if destroy ran successfully before.\"\n )\n return\n\n # Any child layers should be destroyed first before the current layer.\n children_layers = _fetch_children_layers(layer)\n if children_layers:\n logger.info(\n f\"Got the following children layers which we are going to destroy first: \"\n f\"{[x.name for x in children_layers]}\"\n )\n destroy_order = [*children_layers, layer]\n\n tf_flags: List[str] = []\n if auto_approve:\n # Note that for ci, you can just do \"yes | opta destroy --auto-approve\"\n click.confirm(\n fmt_msg(\n f\"\"\"\n Are you REALLY sure you want to run destroy with auto-approve?\n ~Please make sure *{layer.name}* is the correct opta config.\n \"\"\"\n ),\n abort=True,\n )\n tf_flags.append(\"-auto-approve\")\n\n for layer in destroy_order:\n gen_all(layer)\n Terraform.init(\"-reconfigure\")\n logger.info(f\"Destroying layer {layer.name}\")\n Terraform.destroy_all(layer, *tf_flags)\n\n\n# Fetch all the children layers of the current layer.\ndef _fetch_children_layers(layer: \"Layer\") -> List[\"Layer\"]:\n # Only environment layers have children (service) layers.\n # If the current layer has a parent, it is *not* an environment layer.\n if layer.parent is not None:\n return []\n\n # Download all the opta config files in the bucket\n bucket_name = layer.state_storage()\n if layer.cloud == \"aws\":\n opta_configs = _aws_download_all_opta_configs(bucket_name)\n elif layer.cloud == \"google\":\n opta_configs = _gcp_download_all_opta_configs(bucket_name)\n else:\n raise Exception(f\"Not handling deletion for cloud {layer.cloud}\")\n # Keep track of children layers as we find them.\n children_layers = []\n for config_path in opta_configs:\n config_data = yaml.load(open(config_path))\n\n # If the config has no 'environments' field, then it cannot be\n # a child/service layer.\n if \"environments\" not in config_data:\n continue\n\n # Try all the possible environments for this config\n envs = [env[\"name\"] for env in config_data[\"environments\"]]\n for env in envs:\n # Load the child layer, and check if its parent is the current layer.\n child_layer = Layer.load_from_yaml(config_path, env)\n if child_layer.parent and child_layer.parent.name == layer.name:\n children_layers.append(child_layer)\n\n return children_layers\n\n\n# Download all the opta config files from the specified bucket and return\n# a list of temporary file paths to access them.\ndef _aws_download_all_opta_configs(bucket_name: str) -> List[str]:\n # Opta configs for every layer are saved in the opta_config/ directory\n # in the state bucket.\n s3_config_dir = \"opta_config/\"\n s3_client = boto3.client(\"s3\")\n\n resp = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=s3_config_dir)\n s3_config_paths = [obj[\"Key\"] for obj in resp.get(\"Contents\", [])]\n\n configs = []\n # Download every opta config file and write each to a temp file.\n for config_path in s3_config_paths:\n config_name = config_path[len(s3_config_dir) :]\n local_config_path = f\"tmp.opta.{config_name}\"\n with open(local_config_path, \"wb\") as f:\n s3_client.download_fileobj(bucket_name, config_path, f)\n\n configs.append(local_config_path)\n\n return configs\n\n\ndef _gcp_download_all_opta_configs(bucket_name: str) -> List[str]:\n gcs_config_dir = \"opta_config/\"\n credentials, project_id = GCP.get_credentials()\n gcs_client = storage.Client(project=project_id, credentials=credentials)\n try:\n bucket_object = gcs_client.get_bucket(bucket_name)\n except NotFound:\n logger.warn(\n \"Couldn't find the state bucket, must have already been destroyed in a previous destroy run\"\n )\n return []\n blobs: List[storage.Blob] = list(\n gcs_client.list_blobs(bucket_object, prefix=gcs_config_dir)\n )\n configs: List[str] = []\n for blob in blobs:\n configs.append(blob.download_as_bytes().decode(\"utf-8\"))\n return configs\n","sub_path":"opta/commands/destroy.py","file_name":"destroy.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"151018503","text":"import unittest\nfrom solution import cat\nfrom subprocess import call\n\nclass CatTest(unittest.TestCase):\n def setUp(self):\n self.name=\"test_cat_command\"\n self.file=open(self.name,\"w\")\n \n def test_cat_command(self):\n self.file.write(\"Test some text\")\n self.file.close()\n self.assertEqual(\"Test some text\",cat(self.name))\n\n def tearDown(self):\n call(\"rm \" + self.name,shell=True)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"hack0/cat/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"283466280","text":"import os, glob\n\n# Gather up all the files we need.\n\nfiles = glob.glob(\"*.c\")\nfiles += glob.glob(\"*.i\") \n\n## Distutils Script\n#\nfrom distutils.core import setup, Extension\n\n# Some useful directories. \nfrom distutils.sysconfig import get_python_inc, get_python_lib\n\npython_incdir = os.path.join( get_python_inc(plat_specific=1) )\npython_libdir = os.path.join( get_python_lib(plat_specific=1) )\n\nsetup(name=\"NumPtr\",\n version=\"1.0a\",\n description=\"CliMT - CSC Climate Modeling Toolkit\",\n author=\"Rodrigo Caballero\",\n author_email=\"rca@geosci.uchicago.edu\",\n url=\"http://geosci.uchicago.edu/~rca/climt.tar\",\n ext_modules = [Extension('_NumPtr',\n files,\n include_dirs=[python_incdir],\n library_dirs=[python_libdir],\n ),\n ],\n # Install these to their own directory\n # *I want to be able to remove them if I screw up this script\n # *\"Sandboxing\", if you will\n extra_path = 'NumPtr',\n py_modules=[\"NumPtr\",\"test\"],\n )\n","sub_path":"tutorials/python/distutils/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"261016986","text":"import sqlite3\nimport json \n\n#db related work\nclass DBWorker:\n def __init__(self):\n try:\n self.createDB()\n self.createTable()\n except:\n #we will throw the result later on \n pass\n \n def dto(self,code,payload):\n data = {\n 'code' : 0,\n 'payload' : []\n }\n data['code'] = code\n data['payload'] = payload\n return data\n \n def createDB(self):\n self.conn = sqlite3.connect('test5.db')\n \n def createTable(self):\n self.conn.execute('''CREATE TABLE ASSETS (NAME TEXT NOT NULL)''');\n self.conn.commit() \n \n def addAsset(self,asset):\n try:\n #self.check_db_init_or_throw()\n cursor = self.conn.execute(\"SELECT * FROM ASSETS WHERE NAME = ?\", (asset,))\n data = cursor.fetchall()\n if data != [] : \n return self.dto(409,'Value exisits')\n self.conn.execute(\"INSERT INTO ASSETS (NAME) VALUES('\"+asset+\"')\")\n self.conn.commit() \n return self.dto(201,'Ok')\n except: \n return self.dto(400,'Exception')\n\n def getAssets(self):\n try:\n #self.check_db_init_or_throw()\n cursor = self.conn.execute(\"SELECT * FROM ASSETS\")\n rows = cursor.fetchall()\n dt = []\n for row in rows:\n dt.append(row[0])\n return self.dto(200,dt)\n except:\n return self.dto(400,'Exception')\n\n","sub_path":"ta_assignment/api/dbworker.py","file_name":"dbworker.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"514511230","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport dropbox\nimport os\nfrom os.path import expanduser\n\ndef diff_files(local_files, remote_files):\n \"\"\"Check for which files to add and which ones to delete\n \"\"\"\n files_to_be_added = []\n files_to_be_deleted = []\n for file in local_files:\n if file not in remote_files:\n files_to_be_added.append(file)\n\n for file in remote_files:\n if file not in local_files:\n files_to_be_deleted.append(file)\n\n return files_to_be_added, files_to_be_deleted\n\nclass LocalFileSystem:\n def __init__(self, local_path):\n self.folder_path = local_path\n \n def get_files_list(self):\n return os.listdir(self.folder_path)\n\nclass TransferData:\n def __init__(self, access_token, folder_from, folder_to):\n self.dbx = dropbox.Dropbox(access_token)\n self.folder_from = folder_from\n self.folder_to = folder_to\n\n def upload_file(self, file):\n \"\"\"upload a file to Dropbox using API v2\n \"\"\"\n with open(os.path.join(self.folder_from, file), 'rb') as f:\n self.dbx.files_upload(f.read(), self.folder_to + '/' + file)\n\n def remove_file(self, file):\n \"\"\"remove a file from Dropbox using API v2\n \"\"\"\n self.dbx.files_delete(self.folder_to + '/' + file)\n \n\n def get_files_list(self):\n \"\"\"check the contents of a folder in Dropbox\n \"\"\"\n files = []\n file_list = self.dbx.files_list_folder(self.folder_to)\n for file in file_list.entries:\n if file.name != 'test_dropbox':\n files.append(file.name)\n return files\n \n\ndef main():\n access_token = ''\n\n home = expanduser(\"~\")\n\n file_from = os.path.join(home, 'Desktop', 'dropbox')\n\n localFileSystem = LocalFileSystem(file_from)\n\n # file_to = '/test_dropbox/check.txt' # The full path to upload the file to, including the file name\n\n folder_to = '/test_dropbox'\n transferData = TransferData(access_token, file_from, folder_to)\n\n # API v2\n # transferData.upload_file(file_from, file_to)\n remote_files = transferData.get_files_list()\n local_files = localFileSystem.get_files_list()\n files_to_be_added, files_to_be_deleted = diff_files(local_files, remote_files)\n\n for file in files_to_be_added:\n transferData.upload_file(file)\n\n for file in files_to_be_deleted:\n transferData.remove_file(file)\n \n\nif __name__ == '__main__':\n main()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"506061977","text":"import cv2 \r\nimport numpy as np\r\n\r\n#從本地端抓取影片\r\nvid_control = cv2.VideoCapture(\"h3.mp4\")\r\n\r\n#進入迴圈並判斷是否等於True\r\nwhile vid_control.isOpened() == True:\r\n #影片的讀取\r\n vid_on,video = vid_control.read()\r\n #判斷 影片是否成功被讀取,如果判斷為True,就執行下面的程式\r\n if vid_on == True:\r\n #抓取影片中的藍色區塊(筆的部分),把偏黃色的地方去掉\r\n video2 = cv2.inRange(video,(90,0,0),(255,70,100))\r\n #對影片做膨脹處理\r\n video2 = cv2.dilate(video2,np.ones((30,30)))\r\n #複製影片2的(像素,高、寬)\r\n video3 = video2.copy()\r\n #秀出影片2\r\n cv2.imshow(\"M1\",video2)\r\n #取得輪廓\r\n a , b = cv2.findContours(video2,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\r\n #繪製輪廓\r\n cv2.drawContours(video3, a, -1, (0,0,255), 1)\r\n #設定d迴圈,範圍為a\r\n for d in a:\r\n #取得包覆d輪廓點的最小正矩形,X座標, Y座標, 寬度, 高度\r\n x, y, w, h = cv2.boundingRect(d)\r\n #繪製矩形(圖像變數(video), 矩形左上點(x+w), 矩形右下點(y+h), 顏色(紅), 線粗細3)\r\n cv2.rectangle(video, (x,y) , (x+w , y+h), (0,0,255), 3)\r\n #秀出處理完後的影片\r\n cv2.imshow(\"M2\",video)\r\n #影片偵數存入Key\r\n key = cv2.waitKey(33)\r\n #按任意鍵結束影片\r\n if key != -1:\r\n break\r\n else:\r\n break\r\n#關閉所有視窗一定要有的東西\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# while(cap.isOpened()):\r\n# # 讀取一幅影格\r\n# ret, frame = cap.read()\r\n\r\n# # 若讀取至影片結尾,則跳出\r\n# if ret == False:\r\n# break\r\n\r\n# # 模糊處理\r\n# blur = cv2.blur(frame, (4, 4))\r\n\r\n# # 計算目前影格與平均影像的差異值\r\n# diff = cv2.absdiff(avg, blur)\r\n\r\n# # 將圖片轉為灰階\r\n# gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\r\n\r\n# # 篩選出變動程度大於門檻值的區域\r\n# ret, thresh = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY)\r\n\r\n# # 使用型態轉換函數去除雜訊\r\n# kernel = np.ones((5, 5), np.uint8)\r\n# thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)\r\n# thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)\r\n\r\n# # 產生等高線\r\n# cntImg, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n# for c in cnts:\r\n# # 忽略太小的區域\r\n# if cv2.contourArea(c) < 2500:\r\n# continue\r\n\r\n# # 偵測到物體,可以自己加上處理的程式碼在這裡...\r\n\r\n# # 計算等高線的外框範圍\r\n# (x, y, w, h) = cv2.boundingRect(c)\r\n\r\n# # 畫出外框\r\n# cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n\r\n# # 畫出等高線(除錯用)\r\n# cv2.drawContours(frame, cnts, -1, (0, 255, 255), 2)\r\n\r\n# # 顯示偵測結果影像\r\n# cv2.imshow('frame', frame)","sub_path":"Python_hw/hw14.py","file_name":"hw14.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"171632262","text":"# Reading an excel file using Python\n# import xlsxwriter module\nimport xlrd\nimport xlsxwriter\nimport matplotlib.pyplot as plt\nimport Apriori as ap\n\n# Give the location of the file\nloc = (\"C:\\\\Users\\\\amir\\\\Desktop\\\\Data Mining\\\\Online_Shopping1.xlsx\")\n\n# read data set\nwb = xlrd.open_workbook(loc)\nsheet = wb.sheet_by_index(0)\n\n# InvoiceNo_Item Dic\nInvoiceNo_Item = {}\nfor row in range(1, sheet.nrows):\n if sheet.cell_value(row, 0) not in InvoiceNo_Item:\n InvoiceNo_Item[sheet.cell_value(row, 0)] = [sheet.cell_value(row, 2)]\n else:\n InvoiceNo_Item[sheet.cell_value(row, 0)].append(sheet.cell_value(row, 2))\n\n# Create xlsx\nworkbook = xlsxwriter.Workbook('VoiceNo_Item.xlsx')\nworksheet = workbook.add_worksheet(\"My sheet\")\n\n# Write InvoiceNo And Item Into xlsx .\nrow = 0\ncol = 0\nfor InvoiceNo in InvoiceNo_Item:\n worksheet.write(row, col, InvoiceNo)\n for item in InvoiceNo_Item[InvoiceNo]:\n col += 1\n worksheet.write(row, col, item)\n col = 0\n row += 1\nworkbook.close()\n\n# Find Items Number\nItem_Number = {}\nTotal_Item = 0\nfor row in range(1, sheet.nrows):\n Total_Item += sheet.cell_value(row, 3)\n if sheet.cell_value(row, 2) not in Item_Number:\n Item_Number[sheet.cell_value(row, 2)] = sheet.cell_value(row, 3)\n else:\n Item_Number[sheet.cell_value(row, 2)] += sheet.cell_value(row, 3)\n\nprint(Item_Number)\nprint(Total_Item)\n\n# Make Item_Frequency And Names List\nNames = list(Item_Number.keys())\nItem_Frequency = []\nfor item in Item_Number:\n Item_Frequency.append(Item_Number.get(item)/Total_Item)\n\n# Make Categorical Plot\nfig, axs = plt.subplots()\naxs.bar(Names, Item_Frequency)\nfig.suptitle('Item_Frequency')\nplt.show()\n\n# L, Sup_List = ap.apriori(InvoiceNo_Item, 0.001)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"4418231","text":"'''\n'''\nimport os\nimport pandas as pd\nimport multiprocessing as mp\nfrom more_itertools import chunked\n\nfrom utils import accuracy, write\nfrom preproc import video as vid\n\nclass FormatVideos(object):\n def __init__(self, config):\n self.cfg = config\n\n\n def run(self):\n df = pd.read_csv(self.cfg.video_csv, header=0, sep='\\t')\n v = vid.Video()\n res = mp.Manager().dict()\n\n for block in chunked(df.iterrows(), mp.cpu_count()):\n procs = []\n\n for row in block:\n video = row[1]['embed']\n args = (self.cfg.video_height, \n self.cfg.video_width, \n os.path.join(self.cfg.video_src, video), \n os.path.join(self.cfg.output_dir, video),\n res)\n procs.append(mp.Process(target=v.resize, args=args))\n\n for p in procs: p.start()\n for p in procs: p.join()\n\n failed = list(filter(lambda x: not x, res.values()))\n accuracy(failed, res)\n write('format_video.json', dict(res))\n\n","sub_path":"tasks/FormatVideos.py","file_name":"FormatVideos.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"131728416","text":"'''\nBased on a reduced set of processing parameters, this script allows to\nproduce Sentinel-1 backscatter ARD data from GRD products.\nThe script allows to process consecutive frames from one acquisition and\noutputs a single file.\n\n\n----------------\nFunctions:\n----------------\n _slice_assembly:\n creates an urllib opener object for authentication on scihub server\n _grd_frame_import:\n gets the next page from a multi-page result from a scihub search\n _grd_remove_border:\n creates a string in the Open Search format that is added to the\n base scihub url\n _grd_backscatter:\n applies the search and writes the reults in a Geopandas GeoDataFrame\n _grd_speckle_filter:\n applies the Lee-Sigma filter with SNAP standard parameters\n _grd_ls_mask:\n writes the search result into an ESRI Shapefile\n _grd_terrain_correction:\n writes the search result into a PostGreSQL/PostGIS Database\n\n------------------\nMain function\n------------------\n grd_to_ard:\n handles the whole workflow\n\n------------------\nContributors\n------------------\n\nAndreas Vollrath, ESA phi-lab\n-----------------------------------\nAugust 2018: Original implementation\nSeptember 2018: New workflow adapted to SNAP changes\n (i.e. Thermal Noise Removal before Slice Assembly)\n\n------------------\nUsage\n------------------\n\npython3 grd_to_ard.py -p /path/to/scene -r 20 -p RTC -l True -s False\n -t /path/to/tmp -o /path/to/output\n\n -i defines the path to one or a list of consecutive slices\n -r resolution in meters (should be 10 or more, default=20)\n -p defines the product type (GTCsigma, GTCgamma, RTC, default=GTCgamma)\n -l defines the layover/shadow mask creation (True/False, default=True)\n -s defines the speckle filter (True/False, default=False)\n -t defines the folder for temporary products (default=/tmp)\n -o defines the /path/to/the/output\n\n'''\n\n\n# import stdlib modules\nimport os\nimport sys\nimport glob\nimport shutil\nimport time\nimport rasterio\nimport numpy as np\nimport gdal\nimport logging\n\nfrom os.path import join as opj\nfrom ost.helpers import utils as h\nfrom ost.settings import OST_ROOT\n\nlogger = logging.getLogger(__name__)\n\n\ndef _grd_frame_import(\n infile,\n outfile,\n logfile,\n polarisation='VV,VH,HH,HV'\n):\n '''A wrapper of SNAP import of a single Sentinel-1 GRD product\n\n This function takes an original Sentinel-1 scene (either zip or\n SAFE format), updates the orbit information (does not fail if not\n available), removes the thermal noise and stores it as a SNAP\n compatible BEAM-Dimap format.\n\n Args:\n infile: string or os.path object for\n an original Sentinel-1 GRD product in zip or SAFE format\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n polarisation (str): a string consisiting of the polarisation (comma separated)\n e.g. 'VV,VH',\n default value: 'VV,VH,HH,HV'\n '''\n\n logger.debug('INFO: Importing {} by applying precise orbit file and '\n 'removing thermal noise'.format(os.path.basename(infile))\n )\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '1_AO_TNR.xml')\n\n # construct command\n command = '{} {} -x -q {} -Pinput=\"{}\" -Ppolarisation={} \\\n -Poutput=\"{}\"'.format(\n gpt_file, graph, 2 * os.cpu_count(), infile, polarisation, outfile)\n\n # run command\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully imported product')\n else:\n raise RuntimeError('ERROR: Frame import exited with an error. \\\n See {} for Snap Error output'.format(logfile)\n )\n return return_code\n\n\ndef _grd_frame_import_subset(\n infile,\n outfile,\n georegion,\n logfile,\n polarisation='VV,VH,HH,HV'\n):\n '''A wrapper of SNAP import of a subset of single Sentinel-1 GRD product\n\n This function takes an original Sentinel-1 scene (either zip or\n SAFE format), updates the orbit information (does not fail if not\n available), removes the thermal noise, subsets it to the given georegion\n and stores it as a SNAP\n compatible BEAM-Dimap format.\n\n\n Args:\n infile: string or os.path object for\n an original Sentinel-1 GRD product in zip or SAFE format\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n polarisation (str): a string consisiting of the polarisation (comma separated)\n e.g. 'VV,VH',\n default value: 'VV,VH,HH,HV'\n georegion (str): a WKT style formatted POLYGON that bounds the\n subset region\n '''\n\n logger.debug(\n 'INFO: Importing {} by applying precise orbit file and '\n 'removing thermal noise, as well as subsetting.'.format(os.path.basename(infile))\n )\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n # get path to ost package\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '1_AO_TNR_SUB.xml')\n\n # construct command\n command = '{} {} -x -q {} -Pinput=\"{}\" -Pregion=\"{}\" -Ppolarisation={} \\\n -Poutput=\"{}\"'.format(\n gpt_file, graph, 2 * os.cpu_count(),\n infile, georegion, polarisation, outfile)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully imported product')\n else:\n raise RuntimeError('ERROR: Frame import exited with an error. \\\n See {} for Snap Error output'.format(logfile)\n )\n return return_code\n\n\ndef _slice_assembly(filelist,\n outfile,\n logfile,\n polarisation='VV,VH,HH,HV'\n ):\n '''A wrapper of SNAP's slice assembly routine\n\n This function assembles consecutive frames acquired at the same date.\n Can be either GRD or SLC products\n\n Args:\n filelist (str): a string of a space separated list of OST imported\n Sentinel-1 product slices to be assembled\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n '''\n\n logger.debug('INFO: Assembling consecutive frames:')\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n # construct command\n command = '{} SliceAssembly -x -q {} -PselectedPolarisations={} \\\n -t \\'{}\\' {}'.format(\n gpt_file, 2 * os.cpu_count(), polarisation, outfile, filelist)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully assembled products')\n else:\n logger.debug('ERROR: Slice Assembly exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(101)\n\n return return_code\n\n\ndef _grd_subset(infile, outfile, logfile, region):\n '''A wrapper around SNAP's subset routine\n\n This function takes an OST imported frame and subsets it according to\n the coordinates given in the region\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n region (str): a list of image coordinates that bound the subset region\n '''\n\n # get Snap's gpt file\n gpt_file = h.gpt_path()\n\n # format region string\n region = ','.join([str(int(x)) for x in region])\n\n # construct command\n command = '{} Subset -x -q {} -Pregion={} -t \\'{}\\' \\'{}\\''.format(\n gpt_file, 2 * os.cpu_count(), region, outfile, infile)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully subsetted product')\n else:\n logger.debug('ERROR: Subsetting exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(107)\n\n return return_code\n\n\ndef _grd_subset_georegion(infile, outfile, logfile, georegion):\n '''A wrapper around SNAP's subset routine\n\n This function takes an OST imported frame and subsets it according to\n the coordinates given in the region\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n georegion (str): a WKT style formatted POLYGON that bounds the\n subset region\n '''\n\n logger.debug('INFO: Subsetting imported imagery.')\n # get Snap's gpt file\n gpt_file = h.gpt_path()\n\n # extract window from scene\n command = '{} Subset -x -q {} -Ssource=\\'{}\\' -t \"{}\" \\\n -PcopyMetadata=true -PgeoRegion=\"{}\"'.format(\n gpt_file, 2 * os.cpu_count(), infile, outfile, georegion)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully subsetted product.')\n else:\n logger.debug('ERROR: Subsetting exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(107)\n\n return return_code\n\n\ndef _grd_remove_border(infile):\n '''An OST function to remove GRD border noise from Sentinel-1 data\n\n This is a custom routine to remove GRD border noise\n from Sentinel-1 GRD products. It works on the original intensity\n images.\n\n NOTE: For the common dimap format, the infile needs to be the\n ENVI style file inside the *data folder.\n\n The routine checks the outer 3000 columns for its mean value.\n If the mean value is below 100, all values will be set to 0,\n otherwise the routine will continue fpr another 150 columns setting\n the value to 0. All further columns towards the inner image are\n considered valid.\n\n Args:\n infile: string or os.path object for a\n gdal compatible intensity file of Sentinel-1\n\n Notes:\n The file will be manipulated inplace, meaning,\n no new outfile is created.\n '''\n\n # logger.debug('INFO: Removing the GRD Border Noise.')\n currtime = time.time()\n\n # read raster file and get number of columns adn rows\n raster = gdal.Open(infile, gdal.GA_Update)\n cols = raster.RasterXSize\n rows = raster.RasterYSize\n\n # create 3000xrows array for the left part of the image\n array_left = np.array(raster.GetRasterBand(1).ReadAsArray(0,\n 0, 3000, rows))\n\n for x in range(3000):\n # condition if more than 50 pixels within the line have values\n # less than 500, delete the line\n # if np.sum(np.where((array_left[:,x] < 200)\n # & (array_left[:,x] > 0) , 1, 0)) <= 50:\n if np.mean(array_left[:, x]) <= 100:\n array_left[:, x].fill(0)\n else:\n z = x + 150\n if z > 3000:\n z = 3000\n for y in range(x, z, 1):\n array_left[:, y].fill(0)\n\n cols_left = y\n break\n\n try:\n cols_left\n except NameError:\n cols_left = 3000\n\n # write array_left to disk\n # logger.debug('INFO: Total amount of columns: {}'.format(cols_left))\n # logger.debug('INFO: Number of colums set to 0 on the left side: '\n # '{}'.format(cols_left))\n # raster.GetRasterBand(1).WriteArray(array_left[:, :+cols_left], 0, 0, 1)\n raster.GetRasterBand(1).WriteArray(array_left[:, :+cols_left], 0, 0)\n\n array_left = None\n\n # create 2d array for the right part of the image (3000 columns and rows)\n cols_last = cols - 3000\n array_right = np.array(raster.GetRasterBand(1).ReadAsArray(cols_last,\n 0, 3000, rows))\n\n # loop through the array_right columns in opposite direction\n for x in range(2999, 0, -1):\n\n if np.mean(array_right[:, x]) <= 100:\n array_right[:, x].fill(0)\n else:\n z = x - 150\n if z < 0:\n z = 0\n for y in range(x, z, -1):\n array_right[:, y].fill(0)\n\n cols_right = y\n break\n\n try:\n cols_right\n except NameError:\n cols_right = 0\n\n #\n col_right_start = cols - 3000 + cols_right\n # logger.debug('INFO: Number of columns set to 0 on the'\n # 'right side: {}'.format(3000 - cols_right))\n # logger.debug('INFO: Amount of columns kept: {}'.format(col_right_start))\n raster.GetRasterBand(1).WriteArray(array_right[:, cols_right:],\n col_right_start, 0)\n array_right = None\n h.timer(currtime)\n\n\ndef _grd_backscatter(\n infile,\n outfile,\n logfile,\n product_type='GTCgamma',\n dem='SRTM 1Sec HGT',\n dem_file='',\n resampling='BILINEAR_INTERPOLATION'\n):\n '''A wrapper around SNAP's radiometric calibration\n\n This function takes OST imported Sentinel-1 product and generates\n it to calibrated backscatter.\n\n 3 different calibration modes are supported.\n - Radiometrically terrain corrected Gamma nought (RTC)\n - ellipsoid based Gamma nought (GTCgamma)\n - Sigma nought (GTCsigma).\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n resolution (int): the resolution of the output product in meters\n product_type (str): the product type of the output product\n i.e. RTC, GTCgamma or GTCsigma\n dem (str): A Snap compliant string for the dem to use.\n Possible choices are:\n 'SRTM 1sec HGT'(default)\n 'SRTM 3sec'\n 'ASTER 1sec GDEM'\n 'ACE30'\n\n '''\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n # select xml according to product type\n if product_type == 'RTC':\n logger.debug('INFO: Calibrating the product to a RTC product.')\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '2_CalBeta_TF.xml')\n if dem_file != '':\n with rasterio.open(dem_file, 'r') as dem_f:\n dem_nodata = dem_f.nodata\n else:\n dem_nodata = 0.0\n elif product_type == 'GTCgamma':\n logger.debug(\n 'INFO: Calibrating the product to a GTC product (Gamma0).'\n )\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '2_CalGamma.xml')\n elif product_type == 'GTCsigma':\n logger.debug(\n 'INFO: Calibrating the product to a GTC product (Sigma0).'\n )\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '2_CalSigma.xml')\n else:\n logger.debug('ERROR: Wrong product type selected.')\n sys.exit(103)\n\n # construct command sring\n if product_type == 'RTC':\n command = '{} {} -x -q {} -Pinput=\"{}\" -Pdem=\\'{}\\' \\\n -Pdem_file=\\'{}\\' -Pdem_nodata={} -Presampling={} \\\n -Poutput=\\'{}\\''.format(gpt_file, graph, 2 * os.cpu_count(),\n infile, dem, dem_file, dem_nodata,\n resampling, outfile\n )\n else:\n command = '{} {} -x -q {} -Pinput=\\'{}\\' -Poutput=\\'{}\\''.format(\n gpt_file, graph, 2 * os.cpu_count(), infile, outfile)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully calibrated product')\n else:\n logger.debug('ERROR: Backscatter calibration exited with an error. \\\n See {} for Snap Error output'.format(logfile)\n )\n sys.exit(103)\n return return_code\n\n\ndef _grd_speckle_filter(infile, outfile, logfile):\n '''A wrapper around SNAP's Refined Lee Speckle Filter\n\n This function takes OST imported Sentinel-1 product and applies\n a standardised version of the Lee-Sigma Speckle Filter with\n SNAP's defaut values.\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n '''\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n logger.debug('INFO: Applying the Refined-Lee Speckle Filter')\n # contrcut command string\n command = '{} Speckle-Filter -x -q {} -PestimateENL=true ' \\\n '-Pfilter=\\'Refined Lee\\' -t \\'{}\\' ' \\\n '\\'{}\\''.format(gpt_file, 2 * os.cpu_count(),\n outfile, infile\n )\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # hadle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully imported product')\n else:\n logger.debug('ERROR: Speckle Filtering exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(111)\n\n return return_code\n\n\ndef _grd_to_db(infile, outfile, logfile):\n '''A wrapper around SNAP's linear to db routine\n\n This function takes an OST calibrated Sentinel-1 product\n and converts it to dB.\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n '''\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n logger.debug('INFO: Converting the image to dB-scale.')\n # construct command string\n command = '{} LinearToFromdB -x -q {} -t \\'{}\\' {}'.format(\n gpt_file, 2 * os.cpu_count(), outfile, infile)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully converted product to dB-scale.')\n else:\n logger.debug('ERROR: Linear to dB conversion exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(113)\n\n return return_code\n\n\ndef _grd_terrain_correction(\n infile,\n outfile,\n logfile,\n resolution,\n dem='SRTM 1Sec HGT',\n dem_file='',\n resampling='BILINEAR_INTERPOLATION'\n):\n '''A wrapper around SNAP's Terrain Correction routine\n\n This function takes an OST calibrated Sentinel-1 product and\n does the geocodification.\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n resolution (int): the resolution of the output product in meters\n dem (str): A Snap compliant string for the dem to use.\n Possible choices are:\n 'SRTM 1sec HGT'(default)\n 'SRTM 3sec'\n 'ASTER 1sec GDEM'\n 'ACE30'\n\n '''\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n # get path to ost package\n logger.debug('INFO: Geocoding the calibrated product')\n\n # calculate the multi-look factor\n multilook_factor = int(int(resolution) / 10)\n\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '3_ML_TC.xml')\n\n if dem_file != '':\n with rasterio.open(dem_file, 'r') as dem_f:\n dem_nodata = dem_f.nodata\n else:\n dem_nodata = 0.0\n\n # construct command string\n command = '{} {} -x -q {} -Pinput=\\'{}\\' -Presol={} -Pml={} -Pdem=\\'{}\\' \\\n -Pdem_file=\\'{}\\' -Pdem_nodata={} -Presampling={} \\\n -Poutput=\\'{}\\''.format(gpt_file, graph, 2 * os.cpu_count(),\n infile, resolution, multilook_factor,\n dem, dem_file, dem_nodata, resampling, outfile)\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully imported product')\n else:\n logger.debug('ERROR: Terain Correction exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(112)\n\n return return_code\n\n\ndef _grd_terrain_correction_deg(\n infile,\n outfile,\n logfile,\n resolution,\n dem='SRTM 1Sec HGT',\n dem_file='',\n resampling='BILINEAR_INTERPOLATION'\n):\n '''A wrapper around SNAP's Terrain Correction routine\n\n This function takes an OST calibrated Sentinel-1 product and\n does the geocodification.\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n resolution (int): the resolution of the output product in meters\n dem (str): A Snap compliant string for the dem to use.\n Possible choices are:\n 'SRTM 1sec HGT'(default)\n 'SRTM 3sec'\n 'ASTER 1sec GDEM'\n 'ACE30'\n\n '''\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n logger.debug('INFO: Geocoding the calibrated product')\n\n # calculate the multi-look factor\n # multilook_factor = int(int(resolution) / 10)\n multilook_factor = 1\n\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '3_ML_TC_deg.xml')\n\n if dem_file != '':\n with rasterio.open(dem_file, 'r') as dem_f:\n dem_nodata = dem_f.nodata\n else:\n dem_nodata = 0.0\n\n # construct command string\n command = '{} {} -x -q {} -Pinput=\\'{}\\' -Presol={} -Pml={} -Pdem=\\'{}\\' \\\n -Pdem_file=\\'{}\\' -Pdem_nodata={} -Presampling={} \\\n -Poutput=\\'{}\\''.format(gpt_file, graph, 2 * os.cpu_count(),\n infile, resolution, multilook_factor,\n dem, dem_file, dem_nodata, resampling, outfile\n )\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully imported product')\n else:\n logger.debug('ERROR: Terain Correction exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n sys.exit(112)\n\n return return_code\n\n\ndef _grd_ls_mask(\n infile,\n outfile,\n logfile,\n resolution,\n dem='SRTM 1Sec HGT',\n dem_file='',\n resampling='BILINEAR_INTERPOLATION'\n):\n '''A wrapper around SNAP's Layover/Shadow mask routine\n\n This function takes OST imported Sentinel-1 product and calculates\n the Layover/Shadow mask.\n\n Args:\n infile: string or os.path object for\n an OST imported frame in BEAM-Dimap format (i.e. *.dim)\n outfile: string or os.path object for the output\n file written in BEAM-Dimap format\n logfile: string or os.path object for the file\n where SNAP'S STDOUT/STDERR is written to\n resolution (int): the resolution of the output product in meters\n dem (str): A Snap compliant string for the dem to use.\n Possible choices are:\n 'SRTM 1sec HGT'(default)\n 'SRTM 3sec'\n 'ASTER 1sec GDEM'\n 'ACE30'\n\n '''\n\n # get path to SNAP's command line executable gpt\n gpt_file = h.gpt_path()\n\n logger.debug('INFO: Creating the Layover/Shadow mask')\n # get path to workflow xml\n graph = opj(OST_ROOT, 'graphs', 'S1_GRD2ARD', '3_LSmap.xml')\n\n if dem_file != '':\n with rasterio.open(dem_file, 'r') as dem_f:\n dem_nodata = dem_f.nodata\n else:\n dem_nodata = 0.0\n\n # construct command string\n command = '{} {} -x -q {} -Pinput=\\'{}\\' -Presol={} -Pdem=\\'{}\\' \\\n -Pdem_file=\\'{}\\' -Pdem_nodata={} -Presampling={} \\\n -Poutput=\\'{}\\''.format(\n gpt_file, graph, 2 * os.cpu_count(), infile, resolution, dem, dem_file,\n dem_nodata, resampling, outfile\n )\n\n # run command and get return code\n return_code = h.run_command(command, logfile)\n\n # handle errors and logs\n if return_code == 0:\n logger.debug('INFO: Succesfully create a Layover/Shadow mask')\n else:\n logger.debug('ERROR: Layover/Shadow mask creation exited with an error. \\\n See {} for Snap Error output'.format(logfile))\n raise RuntimeError\n return return_code\n\n\ndef grd_to_ard(filelist,\n output_dir,\n out_prefix,\n temp_dir,\n resolution,\n resampling,\n product_type,\n ls_mask_create,\n speckle_filter,\n dem,\n to_db,\n border_noise,\n subset=None,\n polarisation='VV,VH,HH,HV'\n ):\n '''The main function for the grd to ard generation\n\n This function represents the full workflow for the generation of an\n Analysis-Ready-Data product. The standard parameters reflect the CEOS\n ARD defintion for Sentinel-1 backcsatter products.\n\n By changing the parameters, taking care of all parameters\n that can be given. The function can handle multiple inputs of the same\n acquisition, given that there are consecutive data takes.\n\n Args:\n filelist (list): must be a list with one or more absolute\n paths to GRD scene(s)\n output_dir: os.path object or string for the folder\n where the output file should be written#\n out_prefix (str): prefix of the final output file\n temp_dir:\n resolution: the resolution of the output product in meters\n ls_mask: layover/shadow mask generation (Boolean)\n speckle_filter: speckle filtering (Boolean)\n\n Returns:\n nothing\n\n Notes:\n no explicit return value, since output file is our actual return\n '''\n\n # get processing parameters from dict\n # resolution = processing_dict['resolution']\n # product_type = processing_dict['product_type']\n # ls_mask = processing_dict['ls_mask']\n # speckle_filter = processing_dict['speckle_filter']\n # border_noise = processing_dict['border_noise']\n # dem = processing_dict['dem']\n # to_db = processing_dict['to_db']\n\n # Check if dem is file, else use default dem\n if dem.endswith('.tif') or dem.endswith('.hgt') or dem.endswith('.hdf'):\n dem_file = dem\n dem = 'External DEM'\n else:\n dem_file = ''\n # Check out_prefix for empty spaces\n out_prefix = out_prefix.replace(' ', '_')\n\n # slice assembly if more than one scene\n if len(filelist) > 1:\n for file in filelist:\n grd_import = opj(temp_dir, '{}_imported'.format(\n os.path.basename(file)[:-5]))\n logfile = opj(output_dir, '{}_Import.errLog'.format(\n os.path.basename(file)[:-5]))\n if subset is None:\n return_code = _grd_frame_import(file, grd_import, logfile)\n else:\n return_code = _grd_frame_import_subset(\n infile=file,\n outfile=grd_import,\n georegion=subset,\n logfile=logfile\n )\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # create list of scenes for full acquisition in\n # preparation of slice assembly\n scenelist = ' '.join(glob.glob(opj(temp_dir, '*imported.dim')))\n logger.debug('Merging slices: %s', scenelist)\n\n # create file strings\n grd_import = opj(temp_dir, '{}_imported'.format(out_prefix))\n logfile = opj(output_dir, '{}_slice_assembly.errLog'.format(out_prefix))\n return_code = _slice_assembly(scenelist, grd_import, logfile,\n polarisation\n )\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n # single scene case\n else:\n grd_import = opj(temp_dir, '{}_imported'.format(out_prefix))\n logfile = opj(output_dir, '{}_Import.errLog'.format(out_prefix))\n\n if subset is None:\n return_code = _grd_frame_import(filelist[0],\n grd_import,\n logfile,\n polarisation\n )\n else:\n return_code = _grd_frame_import_subset(filelist[0],\n grd_import,\n subset,\n logfile,\n polarisation\n )\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # ---------------------------------------------------------------------\n # Remove the grd border noise from existent channels (OST routine)\n if border_noise and not subset:\n for polarisation in ['VV', 'VH', 'HH', 'HV']:\n\n infile = glob.glob(opj(\n temp_dir, '{}_imported*data'.format(out_prefix),\n 'Intensity_{}.img'.format(polarisation)))\n\n if len(infile) == 1:\n # run grd Border Remove\n logger.debug('INFO: Remove border noise for {} band.'.format(\n polarisation))\n _grd_remove_border(infile[0])\n\n # ----------------------\n # do the calibration\n infile = glob.glob(opj(temp_dir, '{}_imported*dim'.format(out_prefix)))[0]\n outfile = opj(temp_dir, '{}_{}'.format(out_prefix, product_type))\n logfile = opj(output_dir, '{}_Backscatter.errLog'.format(out_prefix))\n return_code = _grd_backscatter(infile,\n outfile,\n logfile,\n product_type,\n dem,\n dem_file,\n resampling\n )\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n data_dir = glob.glob(opj(temp_dir, '{}*imported.data'.format(out_prefix)))\n infile = opj(temp_dir, '{}_{}.dim'.format(out_prefix, product_type))\n # -------------------------------------------\n # in case we want to apply Speckle filtering\n if speckle_filter:\n logfile = opj(temp_dir, '{}_Speckle.errLog'.format(out_prefix))\n outfile = opj(temp_dir, '{}_imported_spk'.format(out_prefix))\n\n # run processing\n return_code = _grd_speckle_filter(infile, outfile, logfile)\n\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # define infile for next processing step\n infile = opj(temp_dir, '{}_imported_spk.dim'.format(out_prefix))\n data_dir = opj(temp_dir, '{}_{}'.format(out_prefix, product_type))\n h.delete_dimap(str(data_dir))\n\n # ----------------------------------------------\n # let's create a Layover shadow mask if needed\n if ls_mask_create is True:\n outfile = opj(temp_dir, '{}_ls_mask'.format(out_prefix))\n logfile = opj(output_dir, '{}_ls_mask.errLog'.format(out_prefix))\n return_code = _grd_ls_mask(infile,\n outfile,\n logfile,\n resolution,\n dem,\n dem_file,\n resampling\n )\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # last check on ls data\n return_code = h.check_out_dimap(outfile, test_stats=False)\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # move to final destination\n out_ls_mask = opj(output_dir, '{}_LS'.format(out_prefix))\n\n # delete original file sin case they exist\n if os.path.exists(str(out_ls_mask) + '.dim'):\n h.delete_dimap(out_ls_mask)\n\n # move out of temp\n shutil.move('{}.dim'.format(outfile), '{}.dim'.format(out_ls_mask))\n shutil.move('{}.data'.format(outfile), '{}.data'.format(out_ls_mask))\n\n # to db\n if to_db:\n logfile = opj(output_dir, '{}.linToDb.errLog'.format(out_prefix))\n outfile = opj(temp_dir, '{}_{}_db'.format(out_prefix, product_type))\n return_code = _grd_to_db(infile, outfile, logfile)\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # delete\n h.delete_dimap(infile[:-4])\n # re-define infile\n infile = opj(temp_dir, '{}_{}_db.dim'.format(out_prefix, product_type))\n\n # -----------------------\n # let's geocode the data\n # infile = opj(temp_dir, '{}.{}.dim'.format(out_prefix, product_type))\n outfile = opj(temp_dir, '{}_{}_TC'.format(out_prefix, product_type))\n logfile = opj(output_dir, '{}_TC.errLog'.format(out_prefix))\n return_code = _grd_terrain_correction(infile,\n outfile,\n logfile,\n resolution,\n dem,\n dem_file,\n resampling\n )\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n # remove calibrated files\n h.delete_dimap(infile[:-4])\n\n # move to final destination\n out_final = opj(output_dir, '{}_{}_TC'.format(out_prefix, product_type))\n\n # remove file if exists\n if os.path.exists(out_final + '.dim'):\n h.delete_dimap(out_final)\n\n return_code = h.check_out_dimap(outfile)\n if return_code != 0:\n h.remove_folder_content(temp_dir)\n return return_code\n\n shutil.move('{}.dim'.format(outfile), '{}.dim'.format(out_final))\n shutil.move('{}.data'.format(outfile), '{}.data'.format(out_final))\n\n # write file, so we know this burst has been succesfully processed\n if return_code == 0:\n check_file = opj(output_dir, '.processed')\n with open(str(check_file), 'w') as file:\n file.write('passed all tests \\n')\n return return_code\n else:\n h.remove_folder_content(temp_dir)\n h.remove_folder_content(output_dir)\n","sub_path":"ost/s1_to_ard/grd_to_ard.py","file_name":"grd_to_ard.py","file_ext":"py","file_size_in_byte":37248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"251495306","text":"import fnmatch, re\nimport os\nimport pymongo\nfrom pymongo import *\nimport sys\nimport ipaddress\n\ncn = sys.argv[1]\nip = sys.argv[2]\ndev = sys.argv[3]\ntmpf = sys.argv[4]\n\nmc = MongoClient(host='100.100.100.1')\n#mc = MongoClient()\nmdb = mc.get_database('server0001')\nclients = mdb.get_collection('clients')\n\ndoc = clients.find_one({\"cn\": cn})\n\nclientcfg = ''\n\ntry:\n\tdoc[\"networks\"]\n\tfor net in doc[\"networks\"]:\n\t\tnetlocal, masklocal = ipaddress.IPv4Network(net[\"netlocal\"]).with_netmask.split(\"/\")\n\t\tnetvpn = str(ipaddress.IPv4Network(net[\"netvpn\"]).network_address)\n\t\tclientcfg +=\t'\\n'.join([\n\t\t\t' '.join(['push \"client-nat snat', netlocal, masklocal, netvpn]) + '\"',\n\t\t\t' '.join(['iroute', netvpn, masklocal]),\n\t\t\t'push \"route 172.16.0.0 255.255.192.0\"\\n'])\n\t\t#print(clientcfg)\n\nexcept KeyError:\n\tprint(\"no networks\")\n\n\nwith open(tmpf, 'w') as f:\n\tf.write(clientcfg)\n\n\n#print cn\n#print ip\n#print dev\n#print tmpf\n\n\n\n\t\n\n","sub_path":"connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"312599113","text":"from selenium import webdriver\r\nfrom selenium.webdriver.support.ui import Select\r\nimport time\r\n\r\ndriver = webdriver.Chrome(executable_path=\"../drivers/chromedriver.exe\")\r\n\r\ndriver.maximize_window()\r\n\r\ndriver.get('http://testautomationpractice.blogspot.com')\r\n\r\ntime.sleep(3)\r\n\r\nalert_btn = driver.find_element_by_xpath('//*[@id=\"HTML9\"]/div[1]/button')\r\nalert_btn.click()\r\n\r\nalert_obj = driver.switch_to.alert\r\n\r\n#Retrieve the message on the Alert window\r\nmsg = alert_obj.text\r\nprint (\"Alert shows following message: \"+ msg )\r\n\r\ntime.sleep(2)\r\n\r\n# use the accept() method to accept the alert\r\n# alert_obj.accept()\r\n# print(\"--- Clicked on the OK Button in the Alert Window ---\")\r\n\r\n#use the dismiss() method to accept the alert\r\nalert_obj.dismiss()\r\nprint(\"--- Clicked on the CANCEL Button in the Alert Window ---\")\r\n\r\ntime.sleep(2)\r\n\r\n# Menu dropdowns\r\n\r\nspeed_dropdown = Select(driver.find_element_by_id('speed'))\r\nspeed_dropdown.select_by_visible_text('Medium')\r\n\r\nfile_dropdown = Select(driver.find_element_by_id('files'))\r\nfile_dropdown.select_by_value('2')\r\n\r\nnumber_dropdown = Select(driver.find_element_by_id('number'))\r\nnumber_dropdown.select_by_visible_text('4')\r\n\r\nproduct_dropdown = Select(driver.find_element_by_id('products'))\r\nproduct_dropdown.select_by_value('Microsoft')\r\n\r\nanimal_dropdown = Select(driver.find_element_by_id('animals'))\r\nanimal_dropdown.select_by_value('big baby cat')\r\n\r\ntime.sleep(2)\r\n\r\ndriver.close()\r\n","sub_path":"examples/alerts.py","file_name":"alerts.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"355752866","text":"import sys\r\nsys.path.append(\"..\")\r\nfrom database import config\r\nfrom api.bybit_api import Bybit_Api\r\nimport controller.comms as comms\r\nfrom logic.strategy import Strategy\r\nfrom logic.calc import Calc as calc\r\nimport database.sql_connector as conn\r\nfrom database.database import Database as db\r\nfrom time import time, sleep\r\nimport asyncio\r\n\r\napi_key = config.BYBIT_TESTNET_API_KEY_auto_3\r\napi_secret = config.BYBIT_TESTNET_API_SECRET_auto_3\r\nleverage = 3\r\nsymbol_pair = 'BTCUSD'\r\ninput_quantity = 500\r\nstrat_id = '16_min'\r\ntrade_id = 'bybit_auto_3'\r\nvwap_margin_neg = -8\r\nvwap_margin_pos = 8\r\n\r\nasync def main():\r\n\r\n if (symbol_pair == \"BTCUSD\"):\r\n symbol = 'BTC'\r\n key_input = 0\r\n limit_price_difference = 0.50\r\n db().update_trade_values(trade_id, strat_id, symbol, symbol_pair, key_input, limit_price_difference, leverage, input_quantity, 'empty', 0, 0, 0)\r\n elif (symbol_pair == \"ETHUSD\"):\r\n symbol = 'ETH'\r\n key_input = 1\r\n limit_price_difference = 0.05\r\n db().update_trade_values(trade_id, strat_id, symbol, symbol_pair, key_input, limit_price_difference, leverage, input_quantity, 'empty', 0, 0, 0)\r\n else:\r\n print(\"Invalid Symbol Pair\")\r\n\r\n strat = Strategy(api_key, api_secret, trade_id, strat_id, symbol, symbol_pair, key_input, input_quantity, leverage, limit_price_difference, vwap_margin_neg, vwap_margin_pos)\r\n api = Bybit_Api(api_key, api_secret, symbol, symbol_pair, key_input)\r\n\r\n api.set_leverage(leverage)\r\n\r\n\r\n #initiate strategy:\r\n strat.vwap_cross_strategy()\r\n \r\n\r\n\r\n\r\nloop = asyncio.get_event_loop()\r\nloop.run_until_complete(main())\r\nloop.close()\r\n","sub_path":"test/auto16min.py","file_name":"auto16min.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"589266938","text":"import flask\nimport functools\nfrom flask_cors import CORS\nimport os\n\napp = flask.Flask(__name__)\nCORS(app)\n\nmock = [\n { \"id\": 1,\n \"title\": 'Space Invaders',\n \"editor\": 'Taito',\n \"year\": 1978,\n \"consoles\": ['Atari VCS', 'MSX'],\n \"play\": 'http://www.playretrogames.com/3022-space-invaders-the-original-game',\n \"nbView\": 0,\n },\n { \"id\": 2,\n \"title\": 'Pac Man',\n \"editor\": 'Namco',\n \"year\": 1980,\n \"consoles\": ['Atari VCS', 'MSX'],\n \"play\": 'https://www.retrogames.cc/arcade-games/pac-man-midway.html',\n \"nbView\": 0,\n },\n { \"id\": 3,\n \"title\": 'Pong',\n \"editor\": 'Atari',\n \"year\": 1972,\n \"consoles\": ['Atari VCS', 'MSX'],\n \"play\": 'https://www.youtube.com/watch?v=it0sf4CMDeM',\n \"nbView\": 0,\n },\n { \"id\": 4,\n \"title\": 'Super Mario Bros',\n \"editor\": 'Nintendo',\n \"year\": 1985,\n \"consoles\": ['NES'],\n \"play\": 'https://emulatoronline.com/nes-games/super-mario-bros/',\n \"nbView\": 0,\n },\n { \"id\": 5,\n \"title\": 'Tetris',\n \"editor\": 'Nintendo',\n \"year\": 1984,\n \"consoles\": ['NET', 'Game boy'],\n \"play\": 'https://emulatoronline.com/nes-games/classic-tetris/',\n \"nbView\": 0,\n },\n { \"id\": 6,\n \"title\": 'Super Mario Kart',\n \"editor\": 'Nintendo',\n \"year\": 1992,\n \"consoles\": ['SNES'],\n \"play\": 'https://emulatoronline.com/snes-games/super-mario-kart/',\n \"nbView\": 0,\n },\n { \"id\": 7,\n \"title\": 'Street Fighter 2',\n \"editor\": 'Nintendo',\n \"year\": 1991,\n \"consoles\": ['SNES'],\n \"play\": 'https://emulatoronline.com/snes-games/street-fighter-2-turbo-hyper-fighting/',\n \"nbView\": 0,\n },\n { \"id\": 8,\n \"title\": 'Another World',\n \"editor\": 'Delphine Software',\n \"year\": 1991,\n \"consoles\": ['Atari ST', 'Amiga'],\n \"play\": 'https://emulatoronline.com/sega-games/another-world/',\n \"nbView\": 0,\n },\n { \"id\": 9,\n \"title\": 'Commando',\n \"editor\": 'Capcom',\n \"year\": 1985,\n \"consoles\": ['Amstrad', 'Commodore'],\n \"play\": 'https://play-roms.com/coin-op-arcade/commando',\n \"nbView\": 0,\n },\n ];\n\n@app.route(\"/\")\ndef autodoc():\n s=\"<html><body>\"\n for rule in app.url_map.iter_rules():\n s += f\"{rule.methods} <a href='http://localhost:5000{rule}'>{rule}</a> {rule.arguments}<br/>\"\n s+=\"</body></html>\"\n return s\n\n@app.route(\"/games\")\ndef all():\n print(f\"GET /games {len(mock)}\")\n return flask.jsonify(mock)\n\n@app.route(\"/games/<id>\")\ndef id(id):\n try:\n game = [g for g in mock if g[\"id\"] == int(id)][0]\n print(f\"GET /game/{id} {game['title']}\")\n return flask.jsonify(game)\n except:\n print(f\"GET /game/{id} 404\")\n return flask.abort(404)\n\n@app.route(\"/games/top/<n>\")\ndef top(n):\n games = sorted([g for g in mock], key=functools.cmp_to_key(cmp))[0:int(n)]\n print(f\"GET /games/top/{n} {len(games)}\")\n return flask.jsonify(games)\n\n@app.route(\"/games/search\")\ndef search():\n q = flask.request.args.get('q')\n games = [g for g in mock if q.strip().upper() in g[\"title\"].upper()]\n print(f\"GET /games/search/?q={q} {len(games)}\")\n return flask.jsonify(games)\n\ndef cmp(g1, g2):\n return g2[\"nbView\"] - g1[\"nbView\"]\n\n@app.route(\"/games\", methods=['PUT'])\ndef update():\n try:\n game = flask.request.json\n vg = [g for g in mock if g[\"id\"] == game[\"id\"]][0]\n vg[\"title\"] = game[\"title\"]\n vg[\"nbView\"] = game[\"nbView\"]\n print(f\"PUT /games {vg['title']}\")\n return flask.jsonify(success=True)\n except:\n flask.abort(404)\n\n@app.route(\"/games/<id>\", methods=['DELETE'])\ndef delete(id):\n try:\n game = [g for g in mock if g[\"id\"] == int(id)][0]\n print(f\"DELETE /game/{id}\")\n mock.remove(game)\n return flask.jsonify(success=True)\n except:\n print(f\"DELETE /games/{id} returns 404\")\n return flask.abort(404)\n\n@app.route(\"/games\", methods=['POST'])\ndef insert():\n game = flask.request.json\n mock.append(game)\n print(f\"POST /games {game['title']}\")\n return flask.jsonify(success=True)\n\napp.run()\n","sub_path":"TP/RVG-electron/src/python-server/python-rest-server.py","file_name":"python-rest-server.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"483355616","text":"from json import dumps\nfrom operator import itemgetter\n\nfrom backend.command.Command import Command\nfrom backend.command.JSONConstructor import JSONConstructor\n\n\nclass DisconnectCommand(Command):\n \"\"\"Handle disconnection\"\"\"\n\n def __init__(self, game, data, websocket):\n \"\"\"Initialize attributes\"\"\"\n super(DisconnectCommand, self).__init__(game, data)\n self.__websocket = websocket\n\n def execute(self):\n \"\"\"If game hasn't started, remove player and\n check if game can start, return json for start game or updated player lobby\n else remove player and check if game can continue, return end game json or next tur json \"\"\"\n players = self._game.getPlayers()\n\n if self._game.getCurrPlayer() is None:\n # game has not been started yet, remove player and check, if all players are ready\n for player in players:\n if player.getWebsocket() == self.__websocket:\n players.remove(player)\n break\n\n if len(players) < 2 or False in [player.getReady() for player in players]:\n # not all players ready\n playersList = [[p.getId(), p.getColor(), p.getReady()] for p in players]\n json = {p.getWebsocket(): [dumps(JSONConstructor.players_info_json(\n p.getId(), p.getColor(), p.getReady(), playersList))] for p in players}\n else:\n # all players ready, start game\n playersList = [[p.getId(), p.getColor(), p.getPoints(), p.getPawnsNumber()] for p in players]\n boardList = self._game.getBoard().getTiles()\n tilesLeft = self._game.getTilesLeftAmount()\n self._game.start()\n json = {p.getWebsocket(): [dumps(JSONConstructor.start_game(p.getId(), p.getColor(), p.getReady())),\n dumps(JSONConstructor.board_state(tilesLeft, playersList, boardList))]\n for p in players}\n else:\n for player in players:\n if player.getWebsocket() == self.__websocket:\n player.setActive(False)\n\n # check, if more than one player is active\n if sum(player.ifActive() for player in players) > 1:\n # more players are active\n playersList = [[p.getId(), p.getColor(), p.getPoints(), p.getPawnsNumber()] for p in players]\n boardList = self._game.getBoard().getTiles()\n tilesLeft = self._game.getTilesLeftAmount()\n\n json = {p.getWebsocket(): [dumps(JSONConstructor.board_state(tilesLeft, playersList, boardList))]\n for p in players if p.ifActive()}\n\n isPlaced = self._game.getBoard().isTileOnBoard(self._game.getCurrTile())\n if isPlaced:\n self._game.nextTurn()\n else:\n self._game.nextPlayer()\n\n possible_tile_places = self._game.getBoard().getTilePositions(self._game.getCurrTile())\n currPlayer = self._game.getCurrPlayer()\n json[currPlayer.getWebsocket()].append(dumps(JSONConstructor.tile_possible_places(\n currPlayer.getId(),\n self._game.getCurrTile().code7x7,\n self._game.getCurrTile().orientation,\n possible_tile_places\n )))\n else:\n # only one player is active, end game\n self._game.getBoard().addFinalPoints(players)\n\n winners = [[0, p.getId(), p.getPoints()] for p in players]\n winners = sorted(winners, key=itemgetter(2), reverse=True)\n for i in range(len(players)):\n winners[i][0] = i + 1\n json = {p.getWebsocket(): [dumps(JSONConstructor.end_game(winners))] for p in players if p.ifActive()}\n self._game.restart()\n return json\n","sub_path":"backend/command/DisconnectCommand.py","file_name":"DisconnectCommand.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"254518217","text":"import json\n\nfrom datasets import *\n\ndictt = dataset_dict()\n\ndata = {}\n\nfor key in dictt:\n\n data[key] = {\n \"Data.inputDataset\" : dictt[key][1],\n \"Data.splitting\" : dictt[key][0][0],\n \"Data.unitsPerJob\" : dictt[key][0][1],\n \"JobType.pyCfgParams\": dictt[key][2].split(','),\n }\n\nwith open('tmpcopy.json', 'w') as fp: json.dump(data, fp, indent=2, sort_keys=True)\n","sub_path":"test/CRAB/utilities/helpers/datasets_json.py","file_name":"datasets_json.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"281846294","text":"'''Defines the three AdminSite.\n\nCreated on Feb 8, 2013\n\n@author: Cam Moore\n'''\n\n\nfrom django.contrib.admin.sites import AdminSite\n\n\nchallenge_designer_site = AdminSite(name=\"Challenge Designer Admin\")\nchallenge_designer_site.index_template = \"admin/designer_index.html\"\nchallenge_manager_site = AdminSite(name=\"Challenge Manager Admin\")\nchallenge_manager_site.index_template = \"admin/admin_index.html\"\nsys_admin_site = AdminSite(name='System Administration Admin')\ndeveloper_site = AdminSite(name=\"Developer Admin\")\ndeveloper_site.index_template = \"admin/developer_index.html\"\n","sub_path":"makahiki/apps/admin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"130159851","text":"from datetime import date, timedelta\nimport datetime\n\nimport pandas as pd\n\n\ndef main(paths):\n\n date = datetime.datetime.today() - timedelta(days=1) \n i = 2\n df = None\n while df is None: \n try:\n source = (\"https://raw.githubusercontent.com/YorickBleijenberg/COVID_data_RIVM_Netherlands/master/vaccination/daily-dashboard-update/\" \n + date.strftime(\"%Y-%m-%d\") \n + \"_vaccine-data.csv\")\n\n df = pd.read_csv(\n source, usecols=[\"people_vaccinated\", \"people_fully_vaccinated\", \"total_estimated\", \"date\"]\n )\n except:\n date = datetime.datetime.today() - timedelta(days=i) \n i += 1\n continue\n\n\n df = df.rename(\n columns={\n \"total_estimated\": \"total_vaccinations\",\n }\n )\n\n df = df.assign(\n location=\"Netherlands\",\n source_url=\"https://github.com/YorickBleijenberg/COVID_data_RIVM_Netherlands/tree/master/vaccination/daily-dashboard-update\",\n )\n \n df.to_csv(paths.tmp_vax_out(\"Netherlands\"), index=False)\n\n\n# def enrich_vaccine_name(df: pd.DataFrame) -> pd.DataFrame:\n# def _enrich_vaccine_name(dt: str) -> str:\n# # See timeline in:\n# if dt < date(2021, 1, 18):\n# return \"Pfizer/BioNTech\"\n# elif date(2021, 1, 18) <= dt < date(2021, 2, 10):\n# return \"Moderna, Pfizer/BioNTech\"\n# elif date(2021, 2, 10) <= dt < date(2021, 4, 21):\n# return \"Moderna, Oxford/AstraZeneca, Pfizer/BioNTech\"\n# elif date(2021, 4, 21) <= dt:\n# return \"Johnson&Johnson, Moderna, Oxford/AstraZeneca, Pfizer/BioNTech\"\n\n# return df.assign(vaccine=df.date.apply(_enrich_vaccine_name))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"patch/batch/netherlands.py","file_name":"netherlands.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"68629068","text":"# -*- coding: utf-8 -*-\n\"\"\"Machine Learning Exercise 09 - Matrix Completion - Emerson Ham\nIn this exercise we use various matrix completion algorithms to fill the incomplete matrix\n\"\"\"\n\n#!pip install fancyimpute\n#!pipenv install fancyimpute\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sklearn as sk\nfrom fancyimpute import SimpleFill, KNN, MatrixFactorization\nfrom sklearn.neighbors import KNeighborsClassifier\n\nplt.style.use(\"ggplot\")\nnp.random.seed(0)\n\n# Create synthetic data matrix\nn = 30\nm = 30\ninner_rank = 5\nX = np.dot(np.random.randn(n, inner_rank), np.random.randn(inner_rank, m))\n\n# Plot sythetic matrix\nplt.figure()\nplt.imshow(X)\nplt.grid(False)\nplt.show()\n\n# Delete a portion of the data\n# Since our values are random from 0 to 1 we can select a cutoff to remove all points less than a value\n# Doing so is a good enough approximation of removing that percentage of the matrix\ncutoff = 0.4\nmissing_mask = np.random.rand(*X.shape) < cutoff\nX_incomplete = X.copy()\nX_incomplete[missing_mask] = np.nan\n\n# Plot Incomplete Matrix\nplt.figure()\nplt.imshow(X_incomplete)\nplt.grid(False)\nplt.show()\n\n# Use fancyimpute's simplefill algorithm to replace the missing values\n# Simplefill fills the missing points with average values\nmeanFill = SimpleFill(\"mean\")\nX_filled_mean = meanFill.fit_transform(X_incomplete)\n\n# Plot results\nf, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(14,6))\nax1.imshow(X)\nax1.set_title(\"Original Matrix\")\nax1.grid(False)\n\nax2.imshow(X_filled_mean)\nax2.set_title(\"Mean Fill Completed Matrix\")\nax2.grid(False)\n\nax3.imshow(X_incomplete)\nax3.set_title(\"Incomplete Matrix\")\nax3.grid(False)\nplt.show()\n\n# MSE Metric\ndef mat_completion_mse(X_filled, X_truth, missing_mask):\n # Calculates the mean squared error of the filled in values vs. the truth\n # Inputs:\n # X_filled (np.ndarray): The \"filled-in\" matrix from a matrix completion algorithm\n # X_truth (np.ndarray): The true filled in matrix\n # missing_mask (np.ndarray): Boolean array of missing values\n # Returns:\n # float: Mean squares error of the filled values\n\n mse = ((X_filled[missing_mask] - X[missing_mask]) ** 2).mean()\n return mse\n\nmeanFill_mse = mat_completion_mse(X_filled_mean, X, missing_mask)\nprint(\"meanFill MSE: %f\" % meanFill_mse)\n\n# KNN Matric Completion\ndef find_best_k(k_neighbors, complete_mat, incomplete_mat, missing_mask):\n # Determines the best k to use for matrix completion with KNN\n # Args:\n # k_neighbors (iterable): The list of k's to try\n # complete_mat (np.ndarray): The original matrix with complete values\n # incomplete_mat (np.ndarray): The matrix with missing values\n # missing_mask (np.ndarray): Boolean array of missing values\n # Returns:\n # integer: the best value of k to use for that particular matrix\n\n best_k = -1\n best_k_mse = np.infty\n \n for neighbors in k_neighbors:\n # YOUR CODE HERE\n X_filled = KNN(k=neighbors).fit_transform(incomplete_mat)\n this_k_mse = mat_completion_mse(X_filled, complete_mat, missing_mask)\n if this_k_mse < best_k_mse:\n best_k_mse = this_k_mse\n best_k = neighbors\n return best_k\n\n# Find best number k of neighbors for the KNN algorithm to use\nk_neighbors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nbest_k = find_best_k(k_neighbors, X, X_incomplete, missing_mask)\n\n# Run KNN with the best_k and calculate the mean squared error\nX_filled_knn = KNN(k=best_k).fit_transform(X_incomplete)\nknnFill_mse = mat_completion_mse(X_filled_knn, X, missing_mask)\nprint(\"knnFill MSE: %f\" % knnFill_mse)\n\n# Alternating Minimizaiton based methods from the handout in class\nclass AlternatingMinimization:\n def __init__(self,rank):\n self.rank = rank\n \n def fit_transform(self, X_incomplete):\n # Fits and transforms an incomplete matrix, returning the completed matrix.\n\n P = np.random.random_sample((n, self.rank))\n Q = np.random.random_sample((self.rank, m))\n # Fill in all missing values with zeros\n X_incomplete_to_zero = np.nan_to_num(X_incomplete)\n\n for i in range(0, 100):\n P = X_incomplete_to_zero @ Q.T @ np.linalg.pinv(Q @ Q.T)\n Q = np.linalg.pinv(P.T @ P) @ P.T @ X_incomplete_to_zero\n\n X_filled = P @ Q\n \n return X_filled\n\n# Visual Comparison of the 4 methods:\n# Mean Fill\n# K-Nearest Neighbors\n# Alternating Minimization\n# MatrixFactorization (an implementaiton using gradient descent)\nsimpleFill = SimpleFill(\"mean\")\nknnFill = KNN(k=best_k)\namFill = AlternatingMinimization(rank=5)\nmfFill = MatrixFactorization(learning_rate=0.01, rank=5, l2_penalty=0, min_improvement=1e-6)\nmethods = [simpleFill, knnFill, amFill, mfFill]\nnames = [\"SimpleFill\", \"KNN\", \"AltMin\", \"MatFactor\"]\n\ndef mat_completion_comparison(methods, incomplete_mat, complete_mat, missing_mask):\n # Using a list of provided matrix completion methods calculate the completed matrix and the determine the associated\n # mean-squared-error results.\n # Inputs\n # methods (iterable): A list of matrix completion algorithms\n # incomplete_mat (np.ndarray): The incomplete matrix\n # complete_mat (np.ndarray): The full matrix\n # missing_mask (np.ndarray): Boolean array of missing values\n # Returns:\n # filled_mats (iterable): the \"filled-in\" matrices\n # mses (iterable): the mean square error results\n\n X_filled_mats = []\n mses = []\n for method in methods:\n # YOUR CODE HERE\n pred = method.fit_transform(incomplete_mat)\n X_filled_mats.append(pred)\n mses.append(mat_completion_mse(pred, complete_mat, missing_mask))\n \n return X_filled_mats, mses\n\n# Fill matrices and plot metrics for each method\nX_filled_mats, mses = mat_completion_comparison(methods, X_incomplete, X, missing_mask)\nplt.figure(figsize = (19,6)) # Change the figure size to your liking\n\nfor i in range(0, len(methods)):\n X_filled = X_filled_mats[i]\n mse = mses[i]\n ax = plt.subplot(161 + i)\n ax.imshow(X_filled)\n ax.title.set_text(\"MSE: \" + str(round(mse, 2)))\n ax.set_xlabel(names[i])\n ax.grid(False)\nplt.show()\n\nax = plt.subplot(121)\nax.imshow(X)\nax.set_xlabel(\"Complete\")\nax.grid(False)\n\nax = plt.subplot(122)\nax.imshow(X_incomplete)\nax.set_xlabel(\"Incomplete\")\nax.grid(False)\n \nplt.show()","sub_path":"Machine Learning - Traditional/09_Matrix Completion - SimpleFill & KNN.py","file_name":"09_Matrix Completion - SimpleFill & KNN.py","file_ext":"py","file_size_in_byte":6358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"350123140","text":"parent = {}\nrank = {}\n\ndef init_node(node):\n parent[node] = node\n rank[node] = 0\n\ndef find_root(node):\n if parent[node] != node:\n parent[node] = find_root(parent[node])\n return parent[node]\n\ndef union(node1, node2):\n root1 = find_root(node1)\n root2 = find_root(node2)\n if root1 != root2:\n if rank[root1] < rank[root2]:\n parent[root1] = root2\n else:\n parent[root2] = root1\n if rank[root1] == rank[root2]:\n rank[root1] += 1\n\n\nG = {'a': {'b': 4, 'c': 2},\n 'b': {'a': 4, 'c': 1},\n 'c': {'a': 2},\n 'd': {}}\n\nfor node in G:\n init_node(node)\n\nprint(parent)\n\nunion('a','b')\n\nprint(parent)\n\nunion('b', 'c')\n\nprint(parent)","sub_path":"UnionFind.py","file_name":"UnionFind.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"509033797","text":"# -*- coding: cp949 -*-\nimport mimetypes\nimport mysmtplib\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\n\n#global value\ndef htmlWrite(lst):\n html_txt='''<html>\n <header></header>\n <body>\n <b>경기도 지역화폐 안내입니다.</b><br>\n <img src=\"https://mblogthumb-phinf.pstatic.net/MjAxOTA0MDVfMTIx/MDAxNTU0NDY5MjExMjU1.wqZPpUfUI8oQTRWmpokcbMbkfTJKAQTp7WrzyReQikcg.G6XmJwyR5uLc5AhCNwJnym6Rq-1qR4D6tqxOJvPvPRkg.PNG.odsej/ggmoney1.png?type=w800\"/>\n '''\n\n html_txt+='<p>'+\"시: \"+lst[0]+'</p>'\n html_txt+='<p>'+\"상호명: \"+lst[1]+'</p>'\n html_txt+='<p>'+\"업종종류: \"+lst[2]+'</p>'\n html_txt+='<p>'+\"도로명 주소: \"+lst[3]+'</p>'\n html_txt+='<p>'+\"지번주소: \"+lst[4]+'</p>'\n html_txt+='<p>'+\"전화번호: \"+str(lst[5])+'</p>'\n html_txt+='<p>'+\"우편번호: \"+str(lst[6])+'</p>'\n html_txt+='<p>'+\"위도: \"+str(lst[7])+'</p>'\n html_txt+='<p>'+\"경도: \"+str(lst[8])+'</p>'\n\n html_txt+=''' </body>\n </html>'''\n html_file = open('logo.html', 'w')\n html_file.write(html_txt)\n html_file.close()\n\n\ndef SendMail(add):\n host = \"smtp.gmail.com\" # Gmail STMP 서버 주소.\n port = \"587\"\n htmlFileName = \"logo.html\"\n\n senderAddr = \"ghdtnswh213@gmail.com\" # 보내는 사람 email 주소.\n recipientAddr = add # 받는 사람 email 주소.\n\n msg = MIMEBase(\"multipart\", \"alternative\")\n msg['Subject'] = \"경기지역화폐 가맹점 안내\"\n\n msg['From'] = senderAddr\n msg['To'] = recipientAddr\n\n # MIME 문서를 생성합니다.\n htmlFD = open(htmlFileName, 'rb')\n HtmlPart = MIMEText(htmlFD.read(),'html', _charset = 'UTF-8' )\n htmlFD.close()\n\n # 만들었던 mime을 MIMEBase에 첨부 시킨다.\n msg.attach(HtmlPart)\n # 메일을 발송한다.\n s = mysmtplib.MySMTP(host,port)\n #s.set_debuglevel(1) # 디버깅이 필요할 경우 주석을 푼다.\n s.ehlo()\n s.starttls()\n s.ehlo()\n s.login(\"ghdtnswh213@gmail.com\",\"ghd3425849\") #여기에 비밀번호 써야 된다.\n s.sendmail(senderAddr , [recipientAddr], msg.as_string())\n s.close()\n\n","sub_path":"build/lib/Gmail.py","file_name":"Gmail.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"74393690","text":"# -*- coding:utf-8 -*-\nfrom pyramid.view import view_config\nfrom pyramid.exceptions import NotFound\n\n\nclass BadRequest(Exception):\n def __init__(self, mes):\n self.message = mes\n\n\nclass InternalServerError(Exception):\n def __init__(self, mes=None):\n self.message = mes\n\n\n@view_config(context=BadRequest, renderer=\"json\")\ndef bad_request(e, request):\n request.response.status_code = 400\n return {\n \"result\": False,\n \"message\": e.message\n }\n\n\n@view_config(context=NotFound, renderer=\"json\")\ndef not_found(_, request):\n request.response.status_code = 404\n return {\n \"result\": False,\n \"message\": \"404 Not Found\"\n }\n\n\n@view_config(context=InternalServerError, renderer=\"json\")\ndef internal_server_error(e, request):\n print(e)\n request.response.status_code = 500\n return {\n \"result\": False,\n \"message\": \"Internal Server Error\"\n }\n","sub_path":"shoyu/views/concerns/failure_response.py","file_name":"failure_response.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"650884190","text":"import os\nimport zipfile\nimport StringIO\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\n\n\nclass PrettyFilterMixin(object):\n\n change_list_template = \"admin/change_list_filter_sidebar.html\"\n change_list_filter_template = \"admin/filter_listing.html\"\n\n\nclass MediaRemovalAdminMixin(object):\n \"\"\"\n This mixin overrides default delete_selected Admin action and replaces it\n with one that actually constructs a model instance from each object in the\n queryset and calls .delete() upon that instance.\n\n This way, we ensure that overridden delete method by MediaRemovalMixin\n is called.\n \"\"\"\n\n def get_actions(self, request):\n actions = super(MediaRemovalAdminMixin, self).get_actions(request)\n\n if 'delete_selected' in actions:\n del actions['delete_selected']\n\n # Add new delete method only for the superuser, as it is quite dangerous\n if request.user.is_superuser:\n\n # We use self.__class__ here so that self is not binded, otherwise\n # we would be passing 4 arguments instead of 3 (and self twice)\n new_delete = (self.__class__.delete_selected_with_media,\n \"delete_selected_with_media\",\n \"Delete objects with associated media files\")\n\n actions['delete_selected_with_media'] = new_delete\n\n return actions\n\n def delete_selected_with_media(self, request, queryset):\n for obj in queryset.all():\n obj.delete()\n\n\nclass DownloadMediaFilesMixin(object):\n\n def get_actions(self, request):\n actions = super(DownloadMediaFilesMixin, self).get_actions(request)\n\n # We use self.__class__ here so that self is not binded, otherwise\n # we would be passing 4 arguments instead of 3 (and self twice)\n export = (self.__class__.download_media_files,\n \"download_media_files\",\n \"Download associated media files\")\n\n actions['download_media_files'] = export\n return actions\n\n def download_media_files(self, request, queryset):\n export_file = 'export.zip'\n\n # Open StringIO to grab in-memory ZIP contents\n s = StringIO.StringIO()\n\n # The zip compressor\n zf = zipfile.ZipFile(s, \"w\")\n\n for obj in queryset.all():\n for filepath in obj.get_media_files():\n filepath = os.path.join(settings.MEDIA_ROOT, filepath)\n\n if os.path.exists(filepath):\n fdir, fname = os.path.split(filepath)\n zf.write(filepath, fname)\n else:\n self.message_user(request, '%s has no file saved at %s' %\n (obj, filepath))\n\n # Must close zip for all contents to be written\n zf.close()\n\n # Grab ZIP file from in-memory, make response with correct MIME-type\n response = HttpResponse(s.getvalue(),\n mimetype=\"application/x-zip-compressed\")\n # ..and correct content-disposition\n response['Content-Disposition'] = (\n 'attachment; filename=%s' % export_file\n )\n\n return response\n","sub_path":"base/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"97106684","text":"import torch\nfrom torch import nn\nfrom torch.distributions import Normal\n\n\ndef initialize_weights_xavier(m, gain=1.0):\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight, gain=gain)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n\ndef create_linear_network(input_dim, output_dim, hidden_units=[],\n hidden_activation=nn.ReLU(), output_activation=None,\n initializer=initialize_weights_xavier):\n assert isinstance(input_dim, int) and isinstance(output_dim, int)\n assert isinstance(hidden_units, list) or isinstance(hidden_units, list)\n\n layers = []\n units = input_dim\n for next_units in hidden_units:\n layers.append(nn.Linear(units, next_units))\n layers.append(hidden_activation)\n units = next_units\n\n layers.append(nn.Linear(units, output_dim))\n if output_activation is not None:\n layers.append(output_activation)\n\n return nn.Sequential(*layers).apply(initialize_weights_xavier)\n\n\nclass BaseNetwork(nn.Module):\n\n def save(self, path):\n torch.save(self.state_dict(), path)\n\n def load(self, path):\n self.load_state_dict(torch.load(path))\n\n\nclass StateActionFunction(BaseNetwork):\n\n def __init__(self, state_dim, action_dim, hidden_units=[256, 256]):\n super().__init__()\n\n self.net = create_linear_network(\n input_dim=state_dim+action_dim,\n output_dim=1,\n hidden_units=hidden_units)\n\n def forward(self, x):\n return self.net(x)\n\nclass DQNNet(BaseNetwork):\n\n def __init__(self, state_dim, action_length, hidden_units=[256, 256]):\n super().__init__()\n\n self.net = create_linear_network(\n input_dim=state_dim,\n output_dim=action_length,\n hidden_units=hidden_units\n )\n\n def forward(self, x):\n return self.net(x)\n\nclass TwinnedDQNNet(BaseNetwork):\n\n def __init__(self, state_dim, action_length, hidden_units=[256, 256]):\n super().__init__()\n\n self.net1 = DQNNet(state_dim, action_length, hidden_units)\n self.net2 = DQNNet(state_dim, action_length, hidden_units)\n\n def forward(self, states):\n assert states.dim() == 2\n\n value1 = self.net1(states)\n value2 = self.net2(states)\n return value1, value2\n\nclass TwinnedStateActionFunction(BaseNetwork):\n\n def __init__(self, state_dim, action_dim, hidden_units=[256, 256]):\n super().__init__()\n\n self.net1 = StateActionFunction(state_dim, action_dim, hidden_units)\n self.net2 = StateActionFunction(state_dim, action_dim, hidden_units)\n\n def forward(self, states, actions):\n assert states.dim() == 2 and actions.dim() == 2\n\n x = torch.cat([states, actions], dim=1)\n value1 = self.net1(x)\n value2 = self.net2(x)\n return value1, value2\n\n\nclass GaussianPolicy(BaseNetwork):\n LOG_STD_MAX = 2\n LOG_STD_MIN = -20\n\n def __init__(self, state_dim, action_dim, hidden_units=[256, 256]):\n super().__init__()\n\n self.net = create_linear_network(\n input_dim=state_dim,\n output_dim=2*action_dim,\n hidden_units=hidden_units)\n\n def forward(self, states):\n assert states.dim() == 2\n\n # Calculate means and stds of actions.\n means, log_stds = torch.chunk(self.net(states), 2, dim=-1)\n log_stds = torch.clamp(\n log_stds, min=self.LOG_STD_MIN, max=self.LOG_STD_MAX)\n stds = log_stds.exp_()\n\n # Gaussian distributions.\n normals = Normal(means, stds)\n\n # Sample actions.\n xs = normals.rsample()\n actions = torch.tanh(xs)\n\n # Calculate entropies.\n log_probs = normals.log_prob(xs) - torch.log(1 - actions.pow(2) + 1e-6)\n entropies = -log_probs.sum(dim=1, keepdim=True)\n\n return actions, entropies, torch.tanh(means)\n","sub_path":"discor/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"172778271","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 26 09:22:35 2021.\n\n@author: Ashiv Hans Dhondea\n\"\"\"\nimport yaml\nimport os\n\ndeep_model_name ='resnet18'# 'efficientnetb0'#'densenet121'#\nnormalized = False#True\nreshapeDims = [224,224]\nsplitLayer = 'add_3'#'block2b_add'#'add_1'#'pool2_conv'#\nquant1 = 8\nrowsPerPacket = 4\nMC_task = 'LoadLossPatterns'\n\nlossProbability = [0.01,0.1,0.2,0.3]\nburstLength = [1,2,3,4,5,6,7]#,8,9,10,11,12,13,14]\n\nresults_dir = os.path.join('inpaint_yml',deep_model_name,splitLayer)\nos.makedirs(results_dir,exist_ok=True)\n\nfilename = os.path.join('inpaint_yml','inpaint_template.yml')\nwith open(filename) as c:\n yml_dict = yaml.load(c,yaml.SafeLoader)\n \nyml_dict['DeepModel']['fullModel'] = 'deep_models_full/'+deep_model_name+'_model.h5'\nyml_dict['DeepModel']['normalize'] = normalized\nyml_dict['DeepModel']['reshapeDims'] = reshapeDims\nyml_dict['SplitLayer']['MobileModel'] = 'deep_models_split/'+deep_model_name+'_'+splitLayer+'_mobile_model.h5'\nyml_dict['SplitLayer']['CloudModel'] = 'deep_models_split/'+deep_model_name+'_'+splitLayer+'_cloud_model.h5'\nyml_dict['SplitLayer']['split'] = splitLayer\nyml_dict['SimulationMode']['MonteCarlo']['include'] = True\nyml_dict['SimulationMode']['MonteCarlo']['MC_task'] = MC_task\nyml_dict['SimulationMode']['Demo']['include'] = False\nyml_dict['Transmission']['rowsperpacket'] = rowsPerPacket\nyml_dict['Transmission']['channel']['GilbertChannel']['include'] = True\nyml_dict['Transmission']['quantization']['include'] = True\nyml_dict['Transmission']['quantization'][1]['numberOfBits'] = quant1\n\nyml_dict['ErrorConcealment']['CALTeC']['include'] = False\nyml_dict['ErrorConcealment']['ALTeC']['include'] = False\nyml_dict['ErrorConcealment']['HaLRTC']['include'] = False\nyml_dict['ErrorConcealment']['HaLRTC']['numiters'] = 50\nyml_dict['ErrorConcealment']['SiLRTC']['include'] = False\nyml_dict['ErrorConcealment']['SiLRTC']['numiters'] = 50\nyml_dict['ErrorConcealment']['InpaintNS']['include'] = True\nyml_dict['ErrorConcealment']['InpaintNS']['radius'] = 5\n\nMC_span = [0,5,10,15]\n\nfor i_lp in range(len(lossProbability)):\n for i_bl in range(len(burstLength)):\n for i_mc in range(len(MC_span)):\n yml_dict['SimulationMode']['MonteCarlo']['MC_runs'] = [MC_span[i_mc],MC_span[i_mc]+5]\n yml_dict['Transmission']['channel']['GilbertChannel']['lossProbability'] = lossProbability[i_lp]\n yml_dict['Transmission']['channel']['GilbertChannel']['burstLength'] = burstLength[i_bl]\n \n fname_str = 'lp_'+str(lossProbability[i_lp])+'_Bl_'+str(burstLength[i_bl])+'_rpp_'+str(rowsPerPacket)+'_'+str(quant1)+'Bits_MC_'+str(MC_span[i_mc])+'_'+str(MC_span[i_mc]+5)+'.yml'\n \n f = open(os.path.join(results_dir,fname_str), \"w\")\n yaml.safe_dump(yml_dict,f,default_flow_style=None)\n f.close()\n","sub_path":"create_inpaint_yml.py","file_name":"create_inpaint_yml.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"209533142","text":"from ctapipe import io\nimport matplotlib.pylab as plt\n\nif __name__ == '__main__':\n\n plt.style.use(\"ggplot\")\n layout = io.get_array_layout(\"hess\")\n X = layout['POSX']\n Y = layout['POSY']\n\n plt.scatter(X,Y,s=50)\n plt.title(\"Array Layout: {}\".format(layout.meta['ARRAY']))\n plt.xlabel(\"{} ({})\".format(X.name, X.unit))\n plt.ylabel(\"{} ({})\".format(Y.name, Y.unit))\n plt.grid()\n \n for tel in layout:\n name = \"CT{tid}:{tclass}\".format(tid=tel['TELID'],\n tclass=io.tel_class_name(tel['CLASS']))\n plt.text(tel['POSX'],tel['POSY'], name)\n\n\n plt.show()\n","sub_path":"examples/array_layout.py","file_name":"array_layout.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"503641538","text":"from typing import Dict, List, Tuple, NewType \nfrom collections import deque \nwith open(\"data\") as f:\n data = f.readlines()[0]\n print(set(data.lower()))\n # data = \"dabAcCaCBAcCcaDA\"\n # print(data)\n results = []\n for c in set(data.lower()):\n data1 = data.replace(c,\"\").replace(c.upper(), \"\")\n queue = deque(data1)\n # to make list not circular\n queue.append(\" \")\n print(len(queue))\n iterations = len(queue)\n while queue and iterations:\n if len(queue) == 1:\n break\n if queue[0].lower()== queue[1].lower() and queue[0] != queue[1]:\n queue.popleft()\n queue.popleft()\n iterations = len(queue)\n elif queue[0].lower() == queue[-1].lower() and queue[0] != queue[-1]:\n queue.popleft()\n queue.pop()\n iterations = len(queue)\n else:\n queue.rotate(1)\n iterations -= 1\n # print(queue)\n print(len(queue)-1)\n results.append((len(queue)-1, c))\n\nprint(sorted(results))\n \n","sub_path":"five/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"477649847","text":"import json\nimport requests\nimport time\nimport urllib.request\nimport webbrowser\nfrom datetime import datetime\nfrom selenium import webdriver\n\nchrome_path = 'open -a /Applications/Google\\ Chrome.app %s'\n\ndriver = webdriver.Chrome(path)\ndriver.get('https://instagram.com/username/')\n\nscroll_pause = 1.5\nuser_url_link = []\nuser_url_post = []\ncounter = 1\n\nfor i in range(10):\n \n driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')\n time.sleep(scroll_pause)\n \n print(counter)\n counter += 1\n \n article = driver.find_element_by_tag_name('article')\n list_cards = article.find_elements_by_tag_name('a')\n \n for item in list_cards:\n \n url_link = item.get_attribute('href')\n user_url_link.append(url_link)\n \n temp_list = url_link.rsplit('/', 2)\n user_url_post.append(temp_list[1])\n \n# the loop makes duplicate so we do this :\nnew_list = user_url_post\nnew_list = list(dict.fromkeys(new_list))\nadd_before = 'https://www.instagram.com/p/'\nadd_after = '?__a=1'\n\ntime.sleep(1)\n\nempty_list = []\nfor i in new_list:\n empty_list.append(add_before+i+add_after)\n\ndata_empty = []\ndata_empty2 = []\ndata_empty3 = []\n\nfor i in empty_list:\n r = requests.get(i)\n data = r.json()\n \n data_test = data['graphql']['shortcode_media']['__typename']\n if data_test == 'GraphImage':\n data_empty2.append(data['graphql']['shortcode_media']['display_resources'][2])\n \n data_test3 = data_empty2\n dico = {}\n container1 = []\n for i in data_test3:\n for k, v in i.items():\n if k == 'src':\n dico[k] = v\n container1.append(dico.get('src'))\n \n elif data_test == 'GraphSidecar':\n data_test = data['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']\n \n for i in range(len(data_test)):\n if data_test[i]['node']['is_video'] == True:\n data_empty3.append(data_test[i]['node']['video_url'])\n elif data_test[i]['node']['is_video'] == False:\n data_empty.append(data_test[i]['node']['display_resources'][2])\n \n data_test2 = data_empty\n dico = {}\n container2 = []\n for i in data_test2:\n for k, v in i.items():\n if k == 'src':\n dico[k] = v\n container2.append(dico.get('src'))\n \nfcontainer1 = container1\nfcontainer2 = container2\nfcontainer3 = data_empty3\n\n# functions to save images and videos\ndef download_image(url):\n t = datetime.now()\n img_name = str(t.day) + '.' + str(t.month) + '.' + str(t.year) + '-' + str(t.hour) + '.' + str(t.minute) + '.' + str(t.second)\n path = 'yourpath'\n full_name = img_name + '.jpg'\n urllib.request.urlretrieve(url, path+full_name)\n\ndef download_video(url):\n t = datetime.now()\n img_name = str(t.day) + '.' + str(t.month) + '.' + str(t.year) + '-' + str(t.hour) + '.' + str(t.minute) + '.' + str(t.second)\n path = 'yourpath'\n full_name = img_name + '.mp4'\n urllib.request.urlretrieve(url, path+full_name)\n \nfor i in fcontainer1:\n download_image(i)\n time.sleep(2)\n \nfor i in fcontainer2:\n download_image(i)\n time.sleep(2)\n \nfor i in fcontainer3:\n download_video(i)\n time.sleep(2)","sub_path":"instagram-downloader.py","file_name":"instagram-downloader.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"494176922","text":"#\n# Copyright 2017 by Delphix\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n#\n# This class has been automatically generated from:\n# /delphix-about.json\n#\n# Do not edit this file manually!\n#\n\nfrom delphixpy.v1_9_0.web.vo.TypedObject import TypedObject\nfrom delphixpy.v1_9_0 import factory\nfrom delphixpy.v1_9_0 import common\n\nclass __Undef(object):\n def __repr__(self):\n return \"undef\"\n\n_UNDEFINED = __Undef()\n\nclass PublicSystemInfo(TypedObject):\n \"\"\"\n *(extends* :py:class:`v1_9_0.web.vo.TypedObject` *)* Retrieve static\n system-wide properties.\n \"\"\"\n def __init__(self, undef_enabled=True):\n super(PublicSystemInfo, self).__init__()\n self._type = (\"PublicSystemInfo\", True)\n self._current_locale = (self.__undef__, True)\n self._enabled_features = (self.__undef__, True)\n self._build_version = (self.__undef__, True)\n self._configured = (self.__undef__, True)\n self._api_version = (self.__undef__, True)\n self._product_name = (self.__undef__, True)\n self._build_timestamp = (self.__undef__, True)\n self._product_type = (self.__undef__, True)\n self._build_title = (self.__undef__, True)\n self._banner = (self.__undef__, True)\n self._locales = (self.__undef__, True)\n\n API_VERSION = \"1.9.0\"\n\n @classmethod\n def from_dict(cls, data, dirty=False, undef_enabled=True):\n obj = super(PublicSystemInfo, cls).from_dict(data, dirty, undef_enabled)\n obj._current_locale = (data.get(\"currentLocale\", obj.__undef__), dirty)\n if obj._current_locale[0] is not None and obj._current_locale[0] is not obj.__undef__:\n assert isinstance(obj._current_locale[0], basestring), (\"Expected one of [u'string'], but got %s\" % type(obj._current_locale[0]))\n common.validate_format(obj._current_locale[0], \"locale\", None, None)\n obj._enabled_features = []\n for item in data.get(\"enabledFeatures\") or []:\n assert isinstance(item, basestring), (\"Expected one of [u'string'], but got %s\" % type(item))\n common.validate_format(item, \"None\", None, None)\n obj._enabled_features.append(item)\n obj._enabled_features = (obj._enabled_features, dirty)\n if \"buildVersion\" in data and data[\"buildVersion\"] is not None:\n obj._build_version = (factory.create_object(data[\"buildVersion\"], \"VersionInfo\"), dirty)\n factory.validate_type(obj._build_version[0], \"VersionInfo\")\n else:\n obj._build_version = (obj.__undef__, dirty)\n obj._configured = (data.get(\"configured\", obj.__undef__), dirty)\n if obj._configured[0] is not None and obj._configured[0] is not obj.__undef__:\n assert isinstance(obj._configured[0], bool), (\"Expected one of [u'boolean'], but got %s\" % type(obj._configured[0]))\n common.validate_format(obj._configured[0], \"None\", None, None)\n if \"apiVersion\" in data and data[\"apiVersion\"] is not None:\n obj._api_version = (factory.create_object(data[\"apiVersion\"], \"APIVersion\"), dirty)\n factory.validate_type(obj._api_version[0], \"APIVersion\")\n else:\n obj._api_version = (obj.__undef__, dirty)\n obj._product_name = (data.get(\"productName\", obj.__undef__), dirty)\n if obj._product_name[0] is not None and obj._product_name[0] is not obj.__undef__:\n assert isinstance(obj._product_name[0], basestring), (\"Expected one of [u'string'], but got %s\" % type(obj._product_name[0]))\n common.validate_format(obj._product_name[0], \"None\", None, None)\n obj._build_timestamp = (data.get(\"buildTimestamp\", obj.__undef__), dirty)\n if obj._build_timestamp[0] is not None and obj._build_timestamp[0] is not obj.__undef__:\n assert isinstance(obj._build_timestamp[0], basestring), (\"Expected one of [u'string'], but got %s\" % type(obj._build_timestamp[0]))\n common.validate_format(obj._build_timestamp[0], \"date\", None, None)\n obj._product_type = (data.get(\"productType\", obj.__undef__), dirty)\n if obj._product_type[0] is not None and obj._product_type[0] is not obj.__undef__:\n assert isinstance(obj._product_type[0], basestring), (\"Expected one of [u'string'], but got %s\" % type(obj._product_type[0]))\n common.validate_format(obj._product_type[0], \"None\", None, None)\n obj._build_title = (data.get(\"buildTitle\", obj.__undef__), dirty)\n if obj._build_title[0] is not None and obj._build_title[0] is not obj.__undef__:\n assert isinstance(obj._build_title[0], basestring), (\"Expected one of [u'string'], but got %s\" % type(obj._build_title[0]))\n common.validate_format(obj._build_title[0], \"None\", None, None)\n obj._banner = (data.get(\"banner\", obj.__undef__), dirty)\n if obj._banner[0] is not None and obj._banner[0] is not obj.__undef__:\n assert isinstance(obj._banner[0], basestring), (\"Expected one of [u'string'], but got %s\" % type(obj._banner[0]))\n common.validate_format(obj._banner[0], \"None\", None, None)\n obj._locales = []\n for item in data.get(\"locales\") or []:\n assert isinstance(item, basestring), (\"Expected one of [u'string'], but got %s\" % type(item))\n common.validate_format(item, \"locale\", None, None)\n obj._locales.append(item)\n obj._locales = (obj._locales, dirty)\n return obj\n\n def to_dict(self, dirty=False):\n dct = super(PublicSystemInfo, self).to_dict(dirty)\n\n def dictify(obj):\n if isinstance(obj, list):\n return [dictify(o) for o in obj]\n elif hasattr(obj, \"to_dict\"):\n return obj.to_dict()\n else:\n return obj\n if \"current_locale\" == \"type\" or (self.current_locale is not self.__undef__ and not (dirty and not self._current_locale[1])):\n dct[\"currentLocale\"] = dictify(self.current_locale)\n if \"enabled_features\" == \"type\" or (self.enabled_features is not self.__undef__ and not (dirty and not self._enabled_features[1])):\n dct[\"enabledFeatures\"] = dictify(self.enabled_features)\n if \"build_version\" == \"type\" or (self.build_version is not self.__undef__ and not (dirty and not self._build_version[1])):\n dct[\"buildVersion\"] = dictify(self.build_version)\n if \"configured\" == \"type\" or (self.configured is not self.__undef__ and not (dirty and not self._configured[1])):\n dct[\"configured\"] = dictify(self.configured)\n if \"api_version\" == \"type\" or (self.api_version is not self.__undef__ and not (dirty and not self._api_version[1])):\n dct[\"apiVersion\"] = dictify(self.api_version)\n if \"product_name\" == \"type\" or (self.product_name is not self.__undef__ and not (dirty and not self._product_name[1])):\n dct[\"productName\"] = dictify(self.product_name)\n if \"build_timestamp\" == \"type\" or (self.build_timestamp is not self.__undef__ and not (dirty and not self._build_timestamp[1])):\n dct[\"buildTimestamp\"] = dictify(self.build_timestamp)\n if \"product_type\" == \"type\" or (self.product_type is not self.__undef__ and not (dirty and not self._product_type[1])):\n dct[\"productType\"] = dictify(self.product_type)\n if \"build_title\" == \"type\" or (self.build_title is not self.__undef__ and not (dirty and not self._build_title[1])):\n dct[\"buildTitle\"] = dictify(self.build_title)\n if \"banner\" == \"type\" or (self.banner is not self.__undef__ and not (dirty and not self._banner[1])):\n dct[\"banner\"] = dictify(self.banner)\n if \"locales\" == \"type\" or (self.locales is not self.__undef__ and not (dirty and not self._locales[1])):\n dct[\"locales\"] = dictify(self.locales)\n return dct\n\n def dirty(self):\n return self.from_dict(self.to_dict(dirty=False), dirty=True)\n\n def force_dirty(self):\n self._current_locale = (self._current_locale[0], True)\n self._enabled_features = (self._enabled_features[0], True)\n self._build_version = (self._build_version[0], True)\n self._configured = (self._configured[0], True)\n self._api_version = (self._api_version[0], True)\n self._product_name = (self._product_name[0], True)\n self._build_timestamp = (self._build_timestamp[0], True)\n self._product_type = (self._product_type[0], True)\n self._build_title = (self._build_title[0], True)\n self._banner = (self._banner[0], True)\n self._locales = (self._locales[0], True)\n\n def is_dirty(self):\n return any([self._current_locale[1], self._enabled_features[1], self._build_version[1], self._configured[1], self._api_version[1], self._product_name[1], self._build_timestamp[1], self._product_type[1], self._build_title[1], self._banner[1], self._locales[1]])\n\n def __eq__(self, other):\n if other is None:\n return False\n if not isinstance(other, PublicSystemInfo):\n return False\n return super(PublicSystemInfo, self).__eq__(other) and \\\n self.current_locale == other.current_locale and \\\n self.enabled_features == other.enabled_features and \\\n self.build_version == other.build_version and \\\n self.configured == other.configured and \\\n self.api_version == other.api_version and \\\n self.product_name == other.product_name and \\\n self.build_timestamp == other.build_timestamp and \\\n self.product_type == other.product_type and \\\n self.build_title == other.build_title and \\\n self.banner == other.banner and \\\n self.locales == other.locales\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __repr__(self):\n return common.generate_repr_string(self)\n\n @property\n def current_locale(self):\n \"\"\"\n The current system locale.\n\n :rtype: ``basestring``\n \"\"\"\n return self._current_locale[0]\n\n @current_locale.setter\n def current_locale(self, value):\n self._current_locale = (value, True)\n\n @property\n def enabled_features(self):\n \"\"\"\n The list of enabled features on this Delphix Engine.\n\n :rtype: ``list`` of ``basestring``\n \"\"\"\n return self._enabled_features[0]\n\n @enabled_features.setter\n def enabled_features(self, value):\n self._enabled_features = (value, True)\n\n @property\n def build_version(self):\n \"\"\"\n Delphix version of the current system software.\n\n :rtype: :py:class:`v1_9_0.web.vo.VersionInfo`\n \"\"\"\n return self._build_version[0]\n\n @build_version.setter\n def build_version(self, value):\n self._build_version = (value, True)\n\n @property\n def configured(self):\n \"\"\"\n Indicates whether the server has gone through initial setup or not.\n\n :rtype: ``bool``\n \"\"\"\n return self._configured[0]\n\n @configured.setter\n def configured(self, value):\n self._configured = (value, True)\n\n @property\n def api_version(self):\n \"\"\"\n Maximum supported API version of the current system software.\n\n :rtype: :py:class:`v1_9_0.web.vo.APIVersion`\n \"\"\"\n return self._api_version[0]\n\n @api_version.setter\n def api_version(self, value):\n self._api_version = (value, True)\n\n @property\n def product_name(self):\n \"\"\"\n Name of the product that the system is running.\n\n :rtype: ``basestring``\n \"\"\"\n return self._product_name[0]\n\n @product_name.setter\n def product_name(self, value):\n self._product_name = (value, True)\n\n @property\n def build_timestamp(self):\n \"\"\"\n Time at which the current system software was built.\n\n :rtype: ``basestring``\n \"\"\"\n return self._build_timestamp[0]\n\n @build_timestamp.setter\n def build_timestamp(self, value):\n self._build_timestamp = (value, True)\n\n @property\n def product_type(self):\n \"\"\"\n Product type.\n\n :rtype: ``basestring``\n \"\"\"\n return self._product_type[0]\n\n @product_type.setter\n def product_type(self, value):\n self._product_type = (value, True)\n\n @property\n def build_title(self):\n \"\"\"\n Description of the current system software.\n\n :rtype: ``basestring``\n \"\"\"\n return self._build_title[0]\n\n @build_title.setter\n def build_title(self, value):\n self._build_title = (value, True)\n\n @property\n def banner(self):\n \"\"\"\n Security banner to display prior to login.\n\n :rtype: ``basestring``\n \"\"\"\n return self._banner[0]\n\n @banner.setter\n def banner(self, value):\n self._banner = (value, True)\n\n @property\n def locales(self):\n \"\"\"\n List of available locales.\n\n :rtype: ``list`` of ``basestring``\n \"\"\"\n return self._locales[0]\n\n @locales.setter\n def locales(self, value):\n self._locales = (value, True)\n\n","sub_path":"src/main/resources/delphixpy/v1_9_0/web/vo/PublicSystemInfo.py","file_name":"PublicSystemInfo.py","file_ext":"py","file_size_in_byte":13674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"530147354","text":"# Copyright 2014 Google Inc. All Rights Reserved.\n\"\"\"Command for listing operations.\"\"\"\nfrom googlecloudsdk.compute.lib import base_classes\nfrom googlecloudsdk.compute.lib import constants\nfrom googlecloudsdk.compute.lib import request_helper\n\n\nclass List(base_classes.BaseLister):\n \"\"\"List Google Compute Engine operations.\"\"\"\n\n @staticmethod\n def Args(parser):\n base_classes.BaseLister.Args(parser)\n\n scope = parser.add_mutually_exclusive_group()\n\n scope.add_argument(\n '--zones',\n metavar='ZONE',\n help=('If provided, only zonal resources are shown. '\n 'If arguments are provided, only resources from the given '\n 'zones are shown.'),\n nargs='*')\n scope.add_argument(\n '--regions',\n metavar='REGION',\n help=('If provided, only regional resources are shown. '\n 'If arguments are provided, only resources from the given '\n 'regions are shown.'),\n nargs='*')\n scope.add_argument(\n '--global',\n action='store_true',\n help='If provided, only global resources are shown.',\n default=False)\n\n @property\n def global_service(self):\n return self.compute.globalOperations\n\n @property\n def regional_service(self):\n return self.compute.regionOperations\n\n @property\n def zonal_service(self):\n return self.compute.zoneOperations\n\n @property\n def resource_type(self):\n return 'operations'\n\n @property\n def allowed_filtering_types(self):\n return ['globalOperations', 'regionOperations', 'zoneOperations']\n\n def GetResources(self, args, errors):\n \"\"\"Yields zonal, regional, and/or global resources.\"\"\"\n # This is True if the user provided no flags indicating scope.\n no_scope_flags = (args.zones is None and args.regions is None and\n not getattr(args, 'global'))\n\n requests = []\n filter_expr = self.GetFilterExpr(args)\n max_results = constants.MAX_RESULTS_PER_PAGE\n project = self.project\n\n if no_scope_flags:\n requests.append(\n (self.global_service,\n 'AggregatedList',\n self.global_service.GetRequestType('AggregatedList')(\n filter=filter_expr,\n maxResults=max_results,\n project=project)))\n elif getattr(args, 'global'):\n requests.append(\n (self.global_service,\n 'List',\n self.global_service.GetRequestType('List')(\n filter=filter_expr,\n maxResults=max_results,\n project=project)))\n elif args.regions is not None:\n args_region_names = [\n self.CreateGlobalReference(region, resource_type='regions').Name()\n for region in args.regions or []]\n # If no regions were provided by the user, fetch a list.\n region_names = (\n args_region_names or [res.name for res in self.FetchChoiceResources(\n attribute='region',\n service=self.compute.regions,\n flag_names=['--regions'])])\n for region_name in region_names:\n requests.append(\n (self.regional_service,\n 'List',\n self.regional_service.GetRequestType('List')(\n filter=filter_expr,\n maxResults=constants.MAX_RESULTS_PER_PAGE,\n region=region_name,\n project=self.project)))\n elif args.zones is not None:\n args_zone_names = [\n self.CreateGlobalReference(zone, resource_type='regions').Name()\n for zone in args.zones or []]\n # If no zones were provided by the user, fetch a list.\n zone_names = (\n args_zone_names or [res.name for res in self.FetchChoiceResources(\n attribute='zone',\n service=self.compute.zones,\n flag_names=['--zones'])])\n for zone_name in zone_names:\n requests.append(\n (self.zonal_service,\n 'List',\n self.zonal_service.GetRequestType('List')(\n filter=filter_expr,\n maxResults=constants.MAX_RESULTS_PER_PAGE,\n zone=zone_name,\n project=self.project)))\n\n return request_helper.MakeRequests(\n requests=requests,\n http=self.http,\n batch_url=self.batch_url,\n errors=errors,\n custom_get_requests=None)\n\n\nList.detailed_help = {\n 'brief': 'List operations',\n 'DESCRIPTION': \"\"\"\\\n *{command}* lists summary information of operations in a\n project. The ``--uri'' option can be used to display URIs\n instead. Users who want to see more data should use 'gcloud\n compute operations describe'.\n\n By default, global operations and operations from all regions are\n listed. The results can be narrowed down by providing the ``--zones'',\n ``--regions'', or ``--global'' flag.\n \"\"\",\n 'EXAMPLES': \"\"\"\\\n To list all operations in a project in table form, run:\n\n $ {command}\n\n To list the URIs of all operations in a project, run:\n\n $ {command} --uri\n\n To list all of the global operations in a project, run:\n\n $ {command} --global\n\n To list all of the regional operations in a project, run:\n\n $ {command} --regions\n\n To list all of the operations from the ``us-central1'' and the\n ``europe-west1'' regions, run:\n\n $ {command} --regions us-central1 europe-west1\n \"\"\",\n\n}\n","sub_path":"y/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/operations/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"56917535","text":"# Copyright 2015, eBay Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django.utils.translation import ugettext as _\nfrom f5_lbaas_dashboard import api\nfrom create_lb import * # noqa\n\nLOG = logging.getLogger(__name__)\nINDEX_URL = \"horizon:projects:loadbalancersv2:index\"\n\n\nREAD_ONLY = {'readonly': 'readonly'}\n\n\nclass UpdateLBDetailsAction(SetLBDetailsAction):\n address = forms.CharField(widget=forms.widgets.Input(attrs=READ_ONLY),\n label=_('IP'),\n required=True)\n\n name = forms.CharField(widget=forms.widgets.Input(attrs=READ_ONLY),\n label=_('Name'),\n required=False)\n\n port = forms.IntegerField(widget=forms.widgets.Input(attrs=READ_ONLY),\n label=_(\"LB Port\"),\n required=False,\n min_value=1,\n max_value=65535,\n help_text=_(\"LB Port on which \"\n \"LB is listening.\"))\n\n is_update = True\n\n def __init__(self, request, context, *args, **kwargs):\n super(UpdateLBDetailsAction, self).__init__(request, context, *args,\n **kwargs)\n self.fields['address'].initial = context['address']\n\n class Meta(object):\n name = _(\"LB Details\")\n help_text_template = (\"project/loadbalancersv2/\"\n \"_launch_lb_help.html\")\n\n\nclass UpdateLBDetails(SetLBDetails):\n action_class = UpdateLBDetailsAction\n template_name = \"project/loadbalancersv2/update_lb_step.html\"\n\n\nclass UpdateSSLAction(UploadSSLAction):\n\n update_cert = forms.BooleanField(label='Update SSL Certificate',\n required=False,\n widget=forms.CheckboxInput())\n\n # def clean(self):\n # cleaned_data = super(UploadSSLAction, self).clean()\n # data = self.data\n # protocol = data.get('source_type')\n # if protocol == 'HTTPS':\n # update_cert = data.get('update_cert')\n # if update_cert:\n # use_common_cert = data.get('use_common_cert')\n # if not use_common_cert:\n # # check to see if ssl cert is provided\n # cert_name = data.get('cert_name')\n # cert = data.get('cert')\n # private_key = data.get('private_key')\n #\n # if (not cert_name) \\\n # or (not cert) \\\n # or (not private_key):\n # raise forms.ValidationError(\n # _('Please provide all certificate parameters.'))\n # return cleaned_data\n\n class Meta(object):\n name = _(\"SSL Certificate\")\n help_text_template = (\"project/loadbalancersv2/_ssl_cert_help.html\")\n\n\nclass UpdateSSLStep(UploadSSLStep):\n action_class = UpdateSSLAction\n contributes = (\"cert_name\", \"cert\", \"private_key\",\n \"chain_cert\", 'use_common_cert', \"update_cert\")\n template_name = \"project/loadbalancersv2/update_ssl_cert.html\"\n\n def contribute(self, data, context):\n post = self.workflow.request.POST\n context['cert_name'] = post['cert_name'] if 'cert_name' in post else ''\n context['cert'] = post['cert'] if 'cert' in post else ''\n context['private_key'] = post[\n 'private_key'] if 'private_key' in post else ''\n context['chain_cert'] = post[\n 'chain_cert'] if 'chain_cert' in post else ''\n context['use_common_cert'] = post[\n 'use_common_cert'] if 'use_common_cert' in post else ''\n context['update_cert'] = post[\n 'update_cert'] if 'update_cert' in post else ''\n return context\n\n\nclass UpdateInstancesAction(SelectInstancesAction):\n\n def __init__(self, request, *args, **kwargs):\n super(UpdateInstancesAction, self).__init__(request, *args, **kwargs)\n err_msg = _('Unable to retrieve members list. '\n 'Please try again later.')\n\n pre_selectd = []\n try:\n pre_selectd = args[0]['selected_members']\n except Exception:\n exceptions.handle(request, err_msg)\n self.fields[self.get_member_field_name('member')].initial = pre_selectd\n\n class Meta(object):\n name = _(\"Instances\")\n slug = \"select_instances\"\n\n\nclass UpdateInstancesStep(SelectInstancesStep):\n action_class = UpdateInstancesAction\n depends_on = (\"loadbalancer_id\",)\n contributes = (\"wanted_members\", \"selected_members\",\n \"loadbalancer_id\", \"instances_details\",\n \"monitor\", \"instance_port\")\n\n\nclass UpdateLoadBalancer(LaunchLoadBalancer):\n slug = \"update_loadbalancer\"\n name = _(\"Edit Load Balancer\")\n finalize_button_name = _(\"Update\")\n success_message = _('Updated load balancer \"%s\".')\n failure_message = _('Unable to modify load balancer \"%s\".')\n success_url = \"horizon:project:loadbalancersv2:index\"\n default_steps = (UpdateLBDetails,\n UpdateSSLStep,\n SelectMonitorStep,\n UpdateInstancesStep)\n attrs = {'data-help-text': 'Updating LB may take a few minutes'}\n\n def format_status_message(self, message):\n return message % self.context.get('name', 'unknown load balancer')\n\n def handle(self, request, context):\n\n try:\n protocol = context['source_type']\n\n api.lbui.vip_create(request,\n update=True,\n loadbalancer_id=context['loadbalancer_id'],\n address=context['address'],\n name=context['name'],\n description=context['description'],\n lb_method=context['lb_method'],\n monitor=context['monitor'],\n protocol=protocol,\n port=context['port'],\n instance_port=context['instance_port'],\n wanted_members=context['wanted_members'],\n instances_details=context['instances_details'],\n cert_name=context['cert_name'],\n cert=context['cert'],\n private_key=context['private_key'],\n chain_cert=context['chain_cert'],\n use_common_cert=True if context[\n 'use_common_cert'] == 'on' else False,\n update_cert=True if context[\n 'update_cert'] == 'on' else False,\n interval=context['interval'],\n timeout=context['timeout'],\n send=context['send'],\n receive=context['receive'],\n )\n\n return True\n except Exception as e:\n exceptions.handle(request, e.message, ignore=False)\n return False\n","sub_path":"f5_lbaas_dashboard/dashboards/project/loadbalancersv2/workflows/update_lb.py","file_name":"update_lb.py","file_ext":"py","file_size_in_byte":7840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"65673821","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 02 15:34:06 2017\n\n@author: Cornelia Krome\n\"\"\"\n\nimport numpy as np\nimport output as out\nimport BSFormula as bs\nimport plotter as plt\n\ndef getVega(s, K, r, sigma, T, t):\n # return Vega (the Greeks)\n d1 = bs.getD1(s, t, K, r, sigma, T)\n return s * np.sqrt(2 * np.pi) * np.exp(-0.5 * d1**2)\n\ndef calculateVega(pathVega, sigmas, T, dt, r, S0, K):\n output = \"\"\n N = int(round(T/dt))\n t = np.linspace(0, T, N+1)\n vegas = np.zeros((len(sigmas), len(t)))\n for i in range(len(sigmas)):\n output += str(sigmas[i])\n for j in range(len(t)):\n vegas[i][j] = getVega(S0, K, r, sigmas[i], T, t[j])\n output += \";\" + str(vegas[i][j])\n output += \"\\n\"\n out.writeToFile(pathVega, output)\n \ndef plotVega(pathVega, pathErrors, filename, title):\n sigmas, errors = out.readCSVFile(pathErrors)\n sigmas, vegas = out.readCSVFile(pathVega)\n plt.plotVega(vegas, errors, filename, title)","sub_path":"Simulation/methods/vega.py","file_name":"vega.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"577119898","text":"import os\nimport sys\nimport pytest\n# from mcutk.elftool import ELFTool\nfrom mcutk.elftool import transform_elf_basic, transform_elf\nfrom mcutk.apps import appfactory\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\nclass TestELFTool:\n\n # def test_get_symbol(self):\n # elf = ELFTool(os.path.join(current_path, \"projects/elffile/freertos_lpspi.out\"))\n # symbols = elf.get_elf_symbol_by_name(\"CSTACK$$Limit\")\n # assert symbols\n # if symbols:\n # for per_sym in symbols:\n # print per_sym.name\n # print per_sym.entry[\"st_value\"]\n\n\n\n # def test_get_program_headers(self):\n # elf = ELFTool(os.path.join(current_path, \"projects/elffile/freertos_lpspi.out\"))\n # headers = elf.get_elf_program_headers()\n # assert headers\n # if headers:\n # for key, value in headers.items():\n # if 'entry_point' == key:\n # print key, \":\", value\n # continue\n # print key, \":\"\n # print \"p_paddr:\", value[\"p_paddr\"]\n # print \"p_vaddr:\", value[\"p_vaddr\"]\n # print \"p_memsz:\", value[\"p_memsz\"]\n # print \"p_filesz:\", value[\"p_filesz\"]\n # print \"p_align:\", value[\"p_align\"]\n # print \"p_flags\", value[\"p_flags\"]\n\n\n @pytest.mark.skipif(sys.platform != 'win32', reason=\"windows only\")\n def test_transform_elf_basic(self):\n images_dir = os.path.join(current_path, \"images/\")\n images = [images_dir + '/' + file for file in os.listdir(images_dir) if not file.endswith('.bin') \\\n and not file.endswith('.srec') and not file.endswith('.ihex')]\n\n types = ['bin', 'srec', 'ihex']\n\n for filepath in images:\n for ty in types:\n out = filepath + '.' + ty\n assert transform_elf_basic(ty, filepath, out)\n\n\n\n @pytest.mark.skipif(sys.platform != 'win32', reason=\"windows only\")\n def test_transform_elf(self):\n images_dir = os.path.join(current_path, \"images/\")\n types = ['bin', 'srec', 'ihex']\n\n def _get_image_by_name(name):\n for filename in os.listdir(images_dir):\n ext = filename.split('.')[-1]\n if filename.startswith(name) and ext not in types:\n return images_dir + '/' + filename\n else:\n return None\n\n\n test_apps = [\"iar\", \"mdk\", \"mcux\", \"armgcc\"]\n for name in test_apps:\n image = _get_image_by_name(name)\n if not image:\n continue\n\n for ty in types:\n out = image + '.' + ty\n assert transform_elf(name, ty, image, out)\n\n\n @pytest.mark.skipif(sys.platform != 'win32', reason=\"windows only\")\n def test_transform_elf_instance(self):\n images_dir = os.path.join(current_path, \"images/\")\n types = ['bin', 'srec', 'ihex']\n\n def _get_image_by_name(name):\n for filename in os.listdir(images_dir):\n ext = filename.split('.')[-1]\n if filename.startswith(name) and ext not in types:\n return images_dir + '/' + filename\n else:\n return None\n\n\n test_apps = [\"iar\", \"mdk\", \"mcux\", \"armgcc\"]\n for name in test_apps:\n image = _get_image_by_name(name)\n if not image:\n continue\n\n ins = appfactory(name).get_latest()\n for ty in types:\n out = image + '.' + ty\n assert transform_elf(ins, ty, image, out)\n","sub_path":"test/test_elftool.py","file_name":"test_elftool.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"212749950","text":"import argparse\nimport concurrent\nimport math\nimport multiprocessing\nimport traceback\n\nfrom tqdm import tqdm\n\nfrom global_variables import *\nfrom migrant_classes.migrant_factory import MigrantFactory\nfrom trains import Task\nfrom concurrent.futures import ThreadPoolExecutor\nfrom trains.backend_api.session.client import APIClient\n\nfrom db_util.dblib import close\nfrom time_counter import Timer\n\n\ndef chunks(l, n):\n # type: (list[str],int) -> List[List[(str,str)]]\n \"\"\"\n <Description>\n\n :param list[str] l:\n :param int n:\n :return:\n \"\"\"\n n = max(1, n)\n return (l[i : i + n] for i in range(0, len(l), n))\n\n\ndef delete_all_tasks_from_project(pr_name):\n # type: (str) -> ()\n \"\"\"\n <Description>\n\n :param str pr_name:\n \"\"\"\n client = APIClient()\n tasks = Task.get_tasks(project_name=pr_name)\n for task in tasks:\n client.tasks.delete(task=task.id, force=True)\n\n\ndef task(migrant):\n # type: (Migrant) -> (Dict[str,List[str]],str,int)\n \"\"\"\n <Description>\n\n :param Migrant migrant:\n \"\"\"\n migrant.read()\n migrant.seed()\n return migrant.msgs, migrant.project_link, migrant.migration_count\n\ndef print_failures(l):\n # type: (List[List[str]]) -> ()\n \"\"\"\n <Description>\n\n :param List[List[str]] l:\n \"\"\"\n new_l = (m for sl in l for m in sl)\n for failed in new_l:\n print(failed)\ndef print_errors(l):\n # type: (List[List[str]]) -> ()\n \"\"\"\n <Description>\n\n :param List[List[str]] l:\n \"\"\"\n new_l = (m for sl in l for m in sl)\n for error in new_l:\n print(error)\n\ndef main(path, analysis):\n # type: (str,bool) -> ()\n \"\"\"\n <Description>\n\n :param str path:\n :param bool analysis:\n \"\"\"\n timer = Timer()\n project_link = None\n error_list = []\n failure_list = []\n workers = multiprocessing.cpu_count()\n migrant_factory = MigrantFactory(path)\n l, ids_count = migrant_factory.get_runs()\n chunk_size = math.ceil(ids_count / workers)\n\n completed_migrations = 0\n project_indicator = False;\n project_list = Task.get_projects()\n for project in project_list:\n if project.name == PROJECT_NAME:\n project_indicator = True;\n break;\n\n if chunk_size==0:\n print(\"No experiments to migrate\")\n return\n else:\n jobs = chunks(l, chunk_size)\n futures = []\n text = 'progressbar'\n with tqdm(total=ids_count, desc=text) as pbar:\n with ThreadPoolExecutor(max_workers=workers) as executor:\n for job_chunk in jobs:\n migrant = migrant_factory.create(job_chunk,pbar,timer,analysis,project_indicator)\n future = executor.submit(task, migrant)\n futures.append(future)\n for future in concurrent.futures.as_completed(futures):\n try:\n msgs, project_link_per_task, migration_count = future.result()\n completed_migrations+=migration_count\n failure_list.append(msgs[\"FAILED\"])\n error_list.append(msgs[\"ERROR\"])\n if not project_link:\n project_link = project_link_per_task\n except Exception as e:\n tb1 = traceback.TracebackException.from_exception(e)\n error_list.append([\"Error: \" + ''.join(tb1.format())])\n close()\n print_failures(failure_list);\n print_errors(error_list);\n\n if completed_migrations == 0:\n print(\"Failed to migrate experiments\")\n else:\n print(completed_migrations, \"experiments succeeded to migrate\")\n print(\"Link to the migrated project: \", project_link)\n timer.print_times()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Migration from Mflow to Trains\")\n parser.add_argument(\n \"Path\", metavar=\"path\", type=str, help=\"path or address to MLFlow server (mlruns folder on local machine)\"\n )\n\n args = parser.parse_args()\n\n main(args.Path, analysis = ANALYSIS)\n","sub_path":"migrant_script/trains_migration.py","file_name":"trains_migration.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"180593154","text":"from functools import partial\nfrom .serializers import StudentSerializer\nfrom django.shortcuts import render\nfrom .models import Student\nfrom rest_framework.renderers import JSONRenderer\nfrom django.http import JsonResponse, HttpResponse \nimport io\nfrom rest_framework.parsers import JSONParser\nfrom django.views.decorators.csrf import csrf_exempt\n# Create your views here.\n\n\n#Model Object -Single student data -Function Based View\n\ndef student_detail(request):\n stu = Student.objects.all()\n serializer = StudentSerializer(stu, many=True)\n json_data = JSONRenderer().render(serializer.data)\n return HttpResponse(json_data)\n\n#enter json data to database\n@csrf_exempt\ndef student_api(request):\n if request.method == \"GET\":\n json_data = request.body\n stream = io.BytesIO(json_data)\n pythondata = JSONParser().parse(stream)\n id = pythondata.get('id', None)\n if id is not None:\n stu = Student.objects.get(id=id)\n serializer = StudentSerializer(stu)\n json_data = JSONRenderer().render(serializer.data)\n return HttpResponse(json_data, content_type='application/json')\n \n stu = Student.objects.all()\n serializer = StudentSerializer(stu, many=True)\n json_data = JSONRenderer().render(serializer.data)\n return HttpResponse(json_data, content_type='application/json')\n\n if request.method == 'POST':\n json_data = request.body\n stream = io.BytesIO(json_data)\n pythondata = JSONParser().parse(stream)\n serializer = StudentSerializer(data = pythondata)\n if serializer.is_valid():\n serializer.save()\n res = {'msg':'Student Created'}\n json_data = JSONRenderer().render(res)\n return HttpResponse(json_data, content_type='application/json')\n json_data = JSONRenderer().render(serializer.errors)\n return HttpResponse(json_data, content_type='application/json')\n\n if request.method == 'PUT':\n json_data = request.body\n stream = io.BytesIO(json_data)\n pythondata = JSONParser().parse(stream)\n id = pythondata.get('id')\n stu = Student.objects.get(id = id)\n #Complete Update - Required All Data from Fornt End / Client\n #serializer = StudentSerializer(stu, data = pythondata)\n #Partial Update - All Data not Required\n serializer = StudentSerializer(stu, data = pythondata, partial = True)\n if serializer.is_valid():\n serializer.save()\n res = {'msg':'Data Is upated..'}\n json_data = JSONRenderer().render(res)\n return HttpResponse(json_data, content_type='application/json')\n json_data = JSONRenderer().render(serializer.errors)\n return HttpResponse(json_data, content_type='application/json') \n \n if request.method == 'DELETE':\n json_data = request.body\n stream = io.BytesIO(json_data)\n pythondata = JSONParser().parse(stream)\n id = pythondata.get('id')\n stu = Student.objects.get(id = id)\n stu.delete()\n res = {'msg':'Data Deleted'}\n # json_data = JSONRenderer().render(res)\n # return HttpResponse(json_data, content_type='application/json')\n return JsonResponse(res, safe=False)","sub_path":"n3_CRUDUsingFunction/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"30920522","text":"s = input()\na = list(input().split())\nf = int(0)\nfor i in a:\n if s[0]==i[0] or s[1]==i[1]:\n f=1\nif f:\n print(\"YES\")\nelse:\n print(\"NO\")","sub_path":"codeforces/random/1097a.py","file_name":"1097a.py","file_ext":"py","file_size_in_byte":150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"464635554","text":"# 3 Python 简介\n# 数字\n# 除法(/)永远返回一个浮点数.\n# // 整除; % 计算余数; ** 乘幂; 复数 j 或 J 表示虚数部分 3+5j\nprint(3+5j)\nprint('1e11',1e11)\n\n# 字符串\n# 字符串可以视作字符数组, 支持切片和索引, 但它是不可变的\n# 用单引号 ('...') 或双引号 (\"...\") 标识.\\ 可以用来转义引号\n# \"Isn't,\" she said.\nprint('\"Isn\\'t,\" she said.') \n# r raw 返回原是字符串\n# \"Isn't,\" she said.\nprint(r'\"Isn\\'t,\" she said.') \n# 字符串文本能够分成多行.一种方法是使用三引号:\"\"\"...\"\"\" 或者 '''...'''\n# 行尾换行符会被自动包含到字符串中,但是可以在行尾加上 \\ 来避免这个行为,没有第一行\nprint(\"\"\"\\\nUsage: thingy [OPTIONS]\n -h Display this usage message\n -H hostname Hostname to connect to\n\"\"\")\n# 字符串格式化操作 str.format(* args,** kwargs )\nprint('the sum of {} + {} = {}'.format(1, 2, 3))\n\n# 列表\n# 中括号之间的一列逗号分隔的值.列表的元素不必是同一类型\n# 列表可以被索引和切片, 并且列表是可变的\n# 切片操作都会返回一个包含请求的元素的新列表(浅拷贝:传递对象的引用,并非对象里的值)\nsquares = [1, 4, 9, 16, 25, 36]\nprint('squares[:], squares[1], squares[-1], squares[-3:], [-1, 0]+squares',\n squares[:], squares[1], squares[-1], squares[-3:], [-1, 0]+squares)\n\n\n\n# 4 Python流程控制\n# if\n# x = int(input(\"please input an integer: \"))\nx = 0\nif x < 0:\n print('{} is smaller than 0'.format(x))\nelif x == 0:\n print('{} is equal to 0'.format(x))\nelif x > 0:\n print('{} is bigger than 0'.format(x))\n# for\nwords = ['cat', 'eat', 'fish', 'is so cute']\n# [:]: 返回原数组的浅拷贝对象\nfor w in words[:]: \n if len(w) > 6:\n words.insert(-1, 'insert')\nprint(words)\n# range() 函数\n# range: 返回从0开始的可迭代对象, 能够像期望的序列返回连续项的对象\n# -1 2: [-1, 5)\nfor i in range(-1, 5, 3):\n print(i)\n# break, for..else\nfor n in range(2, 10):\n for i in range(2, n):\n if n % i == 0:\n print(n, '=', i, '*', n//i)\n break\n else:\n print(n, 'is a prime number')\n# continue\nfor num in range(2,10):\n if num % 2 == 0:\n print('even number: ', num)\n continue\n print('odd number:', num)\n# pass\n# pass 可以在创建新代码时用来做函数或控制体的占位符\n# pass 可以默默的被忽视\ni=0\nwhile i<10:\n print(i, end='... ')\n pass\n i+=1\nprint()\n\n\n# 函数 def\n# 关键字 def 引入了一个函数 定义.在其后必须跟有函数名和包括形式参数的圆括号.\n# 函数体语句从下一行开始,必须是缩进的\ndef fib(n):\n \"\"\"print a fibonacci series up to n\"\"\"\n a, b = 0,1# tuple\n while a < n:\n print(a, end='... ')\n a,b=b, a+b\n n = n+1\n print()\n# 函数 调用 会为函数局部变量生成一个新的符号表.\n# 所有函数中的变量赋值都是将值存储在局部符号表.\n# 变量引用首先在局部符号表中查找,然后是包含函数的局部符号表,然后是全局符号表,最后是内置名字表.\n# 因此,全局变量不能在函数中直接赋值(除非用 global 语句命名),尽管他们可以被引用.\nfib(10)\n# 函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是 传值调用 \n# 这里的 值 总是一个对象 引用 ,而不是该对象的值. 基本值类型传入的是值, 不会影响实参原来的值\nclass SimpleClass:\n name = 'simpleclass'\ndef SimpleClassFunction(sc):\n print(sc.name)\n sc.color='red'\nsimpleClass = SimpleClass()\nSimpleClassFunction(simpleClass)\nprint(simpleClass.color) #red\n# 一个函数定义会在当前符号表内引入函数名.\n# 函数名指代的值(即函数体)有一个被 Python 解释器认定为 用户自定义函数 的类型. \n# 这个值可以赋予其他的名字(即变量名),然后它也可以被当做函数使用\nf = fib\nf(5)\n# return 语句从函数中返回一个值,不带表达式的 return 返回 None\nprint(fib(0))\n# 默认参数\n# 为一个或多个参数指定默认值.这会创建一个可以使用比定义时允许的参数更少的参数调用的函数\n# 默认值在函数 定义 作用域被解析, 默认值的赋值发生在函数定义时期.默认值只被赋值一次\n# 调用时传入的实参值会覆盖掉默认值.\n# 这使得当默认值是可变对象时会有所不同,比如列表、字典或者大多数类的实例\ni = 5\ndef f_default_para(a=i, L=[]):\n L.append(a)\n return L\ni = 6\nprint(f_default_para())# [5] ! no 6\nprint(f_default_para())# [5, 5] \nprint(f_default_para(i))# [5, 5, 6] # 实参为6\n \n# 可选参数\n# 使用:函数装饰器,猴子补丁(程序运行时(runtime)修改某些代码)\n# *name 必须在 **name 之前出现\n# 可选参数打印出来的参数的顺序是未定义\n# 可选参数应该是是参数列表中的最后一个,因为它们将把所有的剩余输入参数传递给函数\ndef cheeseshop(kind, *arguments, **keywords):\n print(\"-- Do you have any\", kind, \"?\")\n print(\"-- I'm sorry, we're all out of\", kind)\n for arg in arguments:\n print(arg)\n print(\"-\" * 40)\n keys = sorted(keywords.keys())\n for kw in keys:\n print(kw, \":\", keywords[kw])\ncheeseshop(\"Limburger\", \"It's very runny, sir.\",\n \"It's really very, VERY runny, sir.\",\n shopkeeper=\"Michael Palin\",\n client=\"John Cleese\",\n sketch=\"Cheese Shop Sketch\")\n# 元组参数 *args\ndef test_asterisk(f_arg, *arg_vars):\n print('f_arg', f_arg)\n for arg in arg_vars:\n print('arg in arg_vars', arg)\n\ntest_asterisk('yasoob', 'python', 'eggs', 'test')\n# 字典参数 **dargs\ndef test_kvps(**arg_vars):\n for (key, v) in arg_vars.items():\n print(\"{0} == {1}\".format(key, v))\n\ntest_kvps(**{'name': 'yasoob'})\n# 使用时的顺序不能改变\ndef test_args(arg1, *arg2, **arg3):\n print('f_arg', arg1)\n for arg in arg2:\n print('arg in arg_vars', arg)\n for (key, v) in arg3.items():\n print(\"{0} == {1}\".format(key, v))\ntest_args('yasoob', 'python', 'eggs', 'test', 123123, name = 'yasoob')\n# * 操作符来自动把参数列表拆开\n# ** 操作符分拆关键字参数为字典\nargs = [3, 6]\n# 等价于list(range(3,6))\nlist(range(*args)) \n# 关键字参数 keyword = value\ndef parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n print(\"action, state, type: \", action, state,type, end=' .. ')\n print(\"voltage: \", voltage)\nparrot(action='VOOOOOM', voltage=1000000)\nparrot('a million', 'bereft of life', 'jump')\n\"\"\"\nparrot() # required argument missing\nparrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument\nparrot(110, voltage=220) # duplicate value for the same argument\nparrot(actor='John Cleese') # unknown keyword argument\n\"\"\" \n\n\n# Lambda 匿名函数\n# 通过 lambda 关键字,可以创建短小的匿名函数 lambda a, b: a+b\n# 语义上讲,它们只是普通函数定义中的一个语���技巧.类似于嵌套函数定义,\n# lambda 形式可以从外部作用域引用变量\ndef add(n):\n return lambda x:x+n\n# add(5) 不是简单的单入参函数, <function add.<locals>.<lambda> at 0x003194B0> \nadd(5) \nf=add(10)\n# 等价于f(x=2) x是lambda中引用的x\nf(2) \n# 匿名函数可以作为参数传递\npairs = [(1,'one'),(2,'two'),(3,'three'),(4,'four')]\n# pair[1]: pairs的组成元组的第二个元素: one , two , three , four\npairs.sort(key=lambda pair: pair[1]) \nprint('pairs',pairs)\n\n\n# 文档字符串\n#第一行应该是关于对象用途的简介.不用明确的陈述对象名或类型, 应该以大写字母开头,以句号结尾.\n#如果文档字符串有多行,第二行应该空出来,与接下来的详细描述明确分隔\ndef doc_string():\n \"\"\" Just document.\n\n this is just document detail\n \"\"\"\nprint(doc_string.__doc__)\n\n\n# 函数注释\n# 函数的额外注释, 是关于用户自定义的函数的完全可选的、随意的元数据信息\n# funcdef ::= [decorators] \"def\" funcname \"(\" [parameter_list] \")\" \n# [\"->\" expression] \":\" suite\n\"\"\"\ndef mysum(a, b: int, c: 'the default is 5' = 5)-> 'Nothing to see here':\n ''' Return a+b+c.\n __annotations__ 是函数的一个属性,类型为 dict.可以在程序运行时动态地修改注释\n '''\n result = a+b+c \n mysum.__annotations__['return'] += result\n return result\nprint(mysum(1,'3',2)) \n#{'b': <class 'int'>, 'c': 'the default is 5', 'return': 'Nothing to see here132'}\nprint(mysum.__annotations__) \n\"\"\"\n\n# 编码风格\n# 代码的易读性对大型复杂程序的多人协作, 代码维护至关重要,可以有效的缩短时间\n'''\n使用 4 空格缩进,而非 TAB\n折行以确保其不会超过 79 个字符\n使用空行分隔函数和类,以及函数中的大块代码\n可能的话,注释独占一行\n使用文档字符串\n把空格放到操作符两边,以及逗号后面,但是括号里侧不加空格:a = f(1, 2) + g(3, 4)\n统一函数和类命名,推荐类名用 驼峰命名, 函数和方法名用 小写_和_下划线.总是用 self 作为方法的第一个参数\n不要使用花哨的编码,如果你的代码的目的是要在国际化环境.Python 的默认情况下,UTF-8,甚至普通的 ASCII 总是工作的最好\n#!/usr/bin/python \n# -*- coding: utf-8 -*- \n'''\n\n\n\n# 5 数据结构\n# 列表\n#list.append(x) 把一个元素添加到列表的结尾 a[len(a):] = [x]\nl = [1,2,3,4,5]\nl.append(6)\nprint(\"l.append(6)\",l)\n#list.extend(L) 将一个给定列表中的所有元素追加到另一个列表中,a[len(a):] = L\nle = [10,11,11,4,4,1,1]\nl.extend(le)\nprint(\"l.extend(le)\",l)\n#list.insert(i, x) 在指定位置插入一个元素\nl.insert(0,0)\nprint(\"l.insert(0,0)\",l)\n#list.remove(x) 删除列表中值为 x 的第一个元素, 没有则返回报错:list.remove(x): x not in list\nl.remove(3)\n# l.remove(3)\nprint(\"l.remove(3)\",l)\n#list.pop([i]) 删除指定索引的元素,并将其返回.如果没有指定索引,a.pop() 返回最后一个元素\nl.pop()\nprint(\"l.pop()\",l)\nl.pop(1)\nprint(\"l.pop(1)\",l)\n#list.index(x) 返回列表中第一个值为 x 的元素的索引.如果没有匹配的元素就会返回一个错误\nprint(\"l.index(4)\",l.index(4))\n#list.count(x) 返回 x 在列表中出现的次数.\nprint(\"l.count(4)\",l.count(4))\n#list.sort() 对列表中的元素就地进行排序.\n# 不同类型的元素返回报错: TypeError: '<' not supported between instances of 'int' and 'str'\nl.sort()\nprint(\"l.sort()\",l)\n#list.reverse() 就地倒排列表中的元素.\nl.reverse()\nprint(\"l.reverse()\",l)\n#list.copy() 返回列表的一个浅拷贝, s[:]\n# 深拷贝和浅拷贝的区别: 只是在拷贝符合对象(包含其他对象的对象,像列表或类实例)时有区别\n# https://docs.python.org/3.6/library/copy.html#module-copy\n#浅拷贝在新的内存中构建一个新的复合对象然后插入原对象的引用地址, 原来的复合对象值有变动也就会反映到新拷贝的对象\n#深拷贝同样在新的内存中构建一个新的复合对象,然后会递归的将原对象的值拷贝到新对象里\nlc = l.copy()\nld = l\nprint(\"l.copy()\",lc)\n# list.clear() 从列表中删除所有元素.相当于 del a[:]\nl.clear()\nprint(\"ld\",ld)\n\n# 把列表当作堆栈使用 \n# 堆栈作为特定的数据结构,最先进入的元素最后一个被释放(后进先出).\n# 用 append() 方法可以把一个元素添加到堆栈顶.用不指定索引的 pop() 方法可以把一个元素从堆栈顶释放出来\nstack = [3,4,5]\nstack.append(6)\nstack.append(7)\nprint('stack.append(7)', stack)\nstack.pop()\nprint('stack.pop()', stack)\n# 把列表当作队列使用 \n# 队列作为特定的数据结构,最先进入的元素最先释放(先进先出).不过,列表这样用效率不高.\n# 在头部插入和弹出很慢(因为,为了一个元素,要移动整个列表中的所有元素).\n# 要实现队列,使用 collections.deque,它为在首尾两端快速插入和删除而设计\nfrom collections import deque\nqueue = deque(['Eric','P','J'])\nqueue.append('Han')\nqueue.append('L')\nprint('queue', queue)\nprint('queue.popleft()', queue.popleft())\nprint('queue', queue)\n\n# 列表推导式 \n# 列表推导式由包含一个表达式的括号组成,表达式后面跟随一个 for 子句,之后可以有零或多个 for 或 if 子句.结果是一个列表\nsquares = [x**2 for x in range(10)]\nprint('[x**2 for x in range(10)]', squares)\n# 等价于\nsquares = list(map(lambda x: x**2, range(10)))\nprint('list(map(lambda x: x**2, range(10)))', squares)\n# 结果要求是元组, 必须加(x,y)\nprint('[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]: ',\n [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y])\n# 嵌套的列表推导式\nmatrix = [[1,2,3,4], [5,6,7,8],[9,10,11,12]]\nprint('[row[i] for row in matrix for i in range(4)]', [[row[i] for row in matrix] for i in range(4)])\n# 等价于\ntransposed_matrix= []\nfor i in range(4):\n transposed_row = []\n for row in matrix:\n transposed_row.append(row[i])\n transposed_matrix.append(transposed_row)\nprint('transposed_matrix', transposed_matrix)\nprint( *matrix ) #[1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12]\nprint('list(zip(*matrix))',list(zip(*matrix)))\n\n# del\n# 从列表中按给定的索引而不是值来删除一个子项 \n# del 还可以从列表中删除切片或清空整个列表\ndel transposed_matrix[0]\nprint('del transposed_matrix[0]', transposed_matrix)\ndel transposed_matrix[0:2]\nprint('del transposed_matrix[0:2]',transposed_matrix)\ndel transposed_matrix # transposed_matrix' is not defined\n\n# tuple 元组\n# 序列类型 https://docs.python.org/3/library/stdtypes.html#typesseq\n# 一个元组由数个逗号分隔的值组成, 可以没有括号\n# 元组就像元素是不同类型的字符串, 不可变的.通常包含不同种类的元素并通过分拆 或索引访问(如果是 namedtuples,甚至可以通过属性).\n# 列表是 可变的 ,它们的元素通常是相同类型的并通过迭代访问.\n# 空元组 () 和单元素 (ele, )\n# 元组封装和元组拆封\nt = 123,32,'test'\nprint(t)\nx,y,z = t\nprint('x,y,z',x,y,z)\n\n# set 集合 \n# 集合是一个无序不重复元素的集.基本功能包括关系测试和消除重复元素.\n# 集合对象还支持 union(|),intersection(&),difference(-)和 sysmmetric difference(^)等数学运算.\n# 大括号或 set() 函数可以用来创建集合.注意:想要创建空集合,你必须使用 set() 而不是 {}.后者用于创建空字典\nbasket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\nprint(basket) #{'apple', 'pear', 'banana', 'orange'}\n# sysmmetric difference 对称差集 letters in a or b but not both\na=set('1234')\nb=set('3456')\nprint('a^b', a^b)\n# 集合推导式\nprint(\"{x for x in '123456789' if x not in '3456'}\",{x for x in '123456789' if x not in '3456'})\n\n# dict 字典 \n# 无序的键:值对(key:value 对)集合\n# 序列是以连续的整数为索引,与此不同的是,字典以 关键字 为索引,关键字可以是任意不可变类型,通常用字符串或数值.\n# 如果元组中只包含字符串和数字,它可以做为关键字,如果它直接或间接的包含了可变对象,就不能当做关键字\n# 字典的主要操作是依据键来存储和析取值.也可以用 del 来删除键:值对(key:value).\n# 一个已经存在的关键字存储值,以前为该关键字分配的值就会被遗忘.试图从一个不存在的键中取值会导致错误\n# list(d.keys())返回一个字典中所有关键字组成的无序列表, sorted(d.keys())返回有序列表\nd=dict(sape=4139, guido=4127, jack=4098)\nprint(d, sorted(d.keys()), sorted(d.values()))\nfor k,v in d.items():\n print(k,v)\n\n# 循环\n#序列循环 使用enumerate() 同时得到索引和值\nfor i,v in enumerate(['one','two','three']):\n print(i,v)\n# zip整体打包多个序列 \n# https://docs.python.org/3/library/functions.html#zip\n# 返回元组的迭代器,其中第i个元组包含来自每个参数序列或迭代的第i个元素.当最短输入可迭代用尽时,迭代器停止\nqs = ['name','sex','old','color']\nans = ['benji','man',28,'black']\nfor q,a in zip(qs,ans):\n print('what is your {0}? It is {1}.'.format(q,a))\n# 逆向循环\nfor i in reversed(range(3)):\n print(i)\n# 顺序排序 \n# sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列:\nbasket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\nfor e in sorted(set(basket)):\n print(e)\nprint(basket)\n# 循环内部修改正在遍历的序列, 切片可以方便的制作副本\nwords = ['cat', 'dog', 'gollria']\nfor w in words[:]:\n if len(w)>6: words.insert(0, w)\nprint(words)\n\n# 深入条件控制\n# while 和 if 语句中使用的条件不仅可以使用比较,而且可以包含任意的操作\n# 比较操作符 in 和 not in 审核值是否在一个区间之内.操作符 is 和 is not 比较两个对象是否相同\n# 比较操作符具有相同的优先级,低于所有的数值操作\n# 比较操作可以传递, a < b == c 审核是否 a 小于 b 并且 b 等于 c\n# 比较操作可以通过逻辑操作符 and 和 or 组合,比较的结果可以用 not 来取反义 \n# A and not B or C 等于 (A and (notB)) or C\n# 在表达式内部不能赋值\n# 逻辑操作符 and 和 or 也称作短路操作符:它们的参数从左向右解析,一旦结果可以确定就停止 \nstring1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\nst = string1 or not string2 or string3\nprint(st)","sub_path":"Python/Exercise/Exercise_2018/Python_Base_3_6/PythonBase_1.py","file_name":"PythonBase_1.py","file_ext":"py","file_size_in_byte":17479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"305990051","text":"from Model import Model\nimport pandas as pd\nfrom bokeh.io import output_file, show\nfrom bokeh. plotting import figure, ColumnDataSource, curdoc\nfrom bokeh.models import WMTSTileSource, HoverTool, CustomJS, Slider, ColumnDataSource\nfrom bokeh.layouts import widgetbox, layout\nimport pickle\n# from bokeh.models.widgets import TextInput\n\nhurricanes = []\nwith open('hurricane_data_old.pkl', 'rb') as f:\n for _ in range(pickle.load(f)):\n hurricanes.append(pickle.load(f))\n\n\n# output_file(\"slider.html\")\n\n# USA = x_range,y_range = ((-13884029,-7453304), (2698291,6455972))\nbound = 20000000 # meters\n\np = figure(tools=['hover', 'pan', 'wheel_zoom'], x_range=(-bound, bound), y_range=(-bound, bound))\np.axis.visible = False\n\nurl = 'http://a.basemaps.cartocdn.com/dark_all/{Z}/{X}/{Y}.png'\nattribution = \"Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL\"\n\np.add_tile(WMTSTileSource(url=url, attribution=attribution))\n\nxs_array = []\nys_array = []\nx_array = []\ny_array = []\nname_array =[]\nseason_array = []\n\n\nfor elm in hurricanes:\n for tempx in elm.x:\n xs_array.append(elm.x)\n x_array.append(tempx)\n name_array.append(elm.name)\n ys_array.append(elm.y)\n season_array.append(elm.season)\n for tempy in elm.y:\n y_array.append(tempy)\n\nd = {'xs':xs_array, 'ys':ys_array, 'x':x_array, 'y':y_array, 'name':name_array, 'season':season_array}\ndf = pd.DataFrame(data=d)\n\n\nsource = ColumnDataSource(df[df.season == '1842'])\n\n\np.multi_line('xs', 'ys', source=source, color='firebrick', line_width = 3)\ncircle = p.circle('x','y', source=source, color='firebrick', size=10)\n\np.tools[0].renderers.append(circle)\n\n# callback = CustomJS(args=dict(source=source), code=\"\"\"\n# var data = source.data;\n# var ref = ref.value.toString()\n# var seas = data['season']\n# var color = data['color']\n# var alpha = data['alpha']\n# for(i=0; i<seas.length; i++){\n# if(seas[i] == ref){\n# color[i] = \"firebrick\"\n# alpha[i] = 1\n# }\n# else{\n# color[i] = \"whitesmoke\"\n# alpha[i] = 0\n# }\n# }\n# source.change.emit();\n# \"\"\")\n\ndef callback(attr, old, new):\n N = slider.value\n print(N)\n new1 = ColumnDataSource(df[df.season == str(N)])\n source.data = new1.data\n\n# had to install flexx\n\nN=1842\n\nslider = Slider(start=1842, end=2017, value=N, step=1, title=\"Season\")\n# callback.args[\"ref\"] = slider\nslider.on_change('value', callback)\n\n# text_input = TextInput(value=\"2016\", title=\"Label:\")\n# callback.args[\"val\"] = text_input\n\nhover = p.select(dict(type=HoverTool))\n# hover = HoverTool()\nhover.tooltips = [(\"Name\", \"@name\"),(\"Season\", \"@season\"), (\"(x,y)\", \"($x, $y)\")]\nhover.mode = 'mouse'\n\n# l = layout([widgetbox(slider, text_input), p])\nl = layout([widgetbox(slider), p])\ncurdoc().add_root(l)\n# show(l)\n","sub_path":"Bokeh Archive/MVPv3.py","file_name":"MVPv3.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"648810018","text":"\"\"\"\nGives information about the operator of this webservice. (same as in API v1)\n\"\"\"\n\nws_info =\t{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"provider\" : { \"type\": \"string\" },\n\t\t\"homepage\" : { \"type\": \"string\" },\n\t\t\"admin\" : { \"type\": \"string\" },\n\t\t\"admin_email\" : {\n\t\t\t\"type\": \"string\",\n\t\t\t#\"pattern\": \"^[\\w\\.]+@[\\w\\.]+$\"\n\t\t\t\"pattern\": \"[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\\.[a-zA-Z]{2,4}\"\n\t\t},\n\t},\n\t\"required\": [ \"provider\", \"admin_email\"],\n\t\"additionalProperties\": False,\n}\n\n","sub_path":"src/etoxwsapi/v2/schema/ws_info.py","file_name":"ws_info.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"301318014","text":"import matplotlib.patches as patches\r\nfrom matplotlib.lines import Line2D\r\nfrom PyQt5 import QtWidgets, Qt\r\nimport pyMT.utils as utils\r\n\r\n\r\nclass DraggablePoint:\r\n\r\n # http://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively\r\n\r\n lock = None # only one can be animated at a time\r\n\r\n def __init__(self, parent, x=0.1, y=0.1, size=(0.1, 0.1), **kwargs):\r\n self.fc = kwargs.get('fc', 'r')\r\n self.alpha = kwargs.get('alpha', 0.5)\r\n self.mec = kwargs.get('mec', 'k')\r\n\r\n self.parent = parent\r\n self.point = patches.Ellipse((x, y),\r\n size[0],\r\n size[1],\r\n fc=self.fc,\r\n alpha=self.alpha,\r\n edgecolor=self.mec)\r\n self.x = x\r\n self.y = y\r\n parent.fig.axes[0].add_patch(self.point)\r\n self.press = None\r\n self.background = None\r\n self.connect()\r\n\r\n if self.parent.list_points:\r\n line_x = [self.parent.list_points[0].x, self.x]\r\n line_y = [self.parent.list_points[0].y, self.y]\r\n\r\n self.line = Line2D(line_x, line_y, color=self.fc, alpha=self.alpha)\r\n parent.fig.axes[0].add_line(self.line)\r\n\r\n def connect(self):\r\n '''connect to all the events we need'''\r\n\r\n self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event',\r\n self.on_press)\r\n self.cidrelease = self.point.figure.canvas.mpl_connect('button_release_event',\r\n self.on_release)\r\n self.cidmotion = self.point.figure.canvas.mpl_connect('motion_notify_event',\r\n self.on_motion)\r\n\r\n def on_press(self, event):\r\n\r\n if event.inaxes != self.point.axes:\r\n return\r\n if DraggablePoint.lock is not None:\r\n return\r\n contains, attrd = self.point.contains(event)\r\n if not contains:\r\n return\r\n self.press = (self.point.center), event.xdata, event.ydata\r\n DraggablePoint.lock = self\r\n\r\n # draw everything but the selected rectangle and store the pixel buffer\r\n canvas = self.point.figure.canvas\r\n axes = self.point.axes\r\n self.point.set_animated(True)\r\n if self == self.parent.list_points[1]:\r\n self.line.set_animated(True)\r\n else:\r\n self.parent.list_points[1].line.set_animated(True)\r\n canvas.draw()\r\n self.background = canvas.copy_from_bbox(self.point.axes.bbox)\r\n\r\n # now redraw just the rectangle\r\n axes.draw_artist(self.point)\r\n\r\n # and blit just the redrawn area\r\n canvas.blit(axes.bbox)\r\n\r\n def on_motion(self, event):\r\n\r\n if DraggablePoint.lock is not self:\r\n return\r\n if event.inaxes != self.point.axes:\r\n return\r\n self.point.center, xpress, ypress = self.press\r\n dx = event.xdata - xpress\r\n dy = event.ydata - ypress\r\n self.point.center = (self.point.center[0] + dx, self.point.center[1] + dy)\r\n\r\n canvas = self.point.figure.canvas\r\n axes = self.point.axes\r\n # restore the background region\r\n canvas.restore_region(self.background)\r\n\r\n # redraw just the current rectangle\r\n axes.draw_artist(self.point)\r\n\r\n if self == self.parent.list_points[1]:\r\n axes.draw_artist(self.line)\r\n else:\r\n self.parent.list_points[1].line.set_animated(True)\r\n axes.draw_artist(self.parent.list_points[1].line)\r\n\r\n self.x = self.point.center[0]\r\n self.y = self.point.center[1]\r\n\r\n if self == self.parent.list_points[1]:\r\n line_x = [self.parent.list_points[0].x, self.x]\r\n line_y = [self.parent.list_points[0].y, self.y]\r\n self.line.set_data(line_x, line_y)\r\n else:\r\n line_x = [self.x, self.parent.list_points[1].x]\r\n line_y = [self.y, self.parent.list_points[1].y]\r\n\r\n self.parent.list_points[1].line.set_data(line_x, line_y)\r\n\r\n # blit just the redrawn area\r\n canvas.blit(axes.bbox)\r\n\r\n def on_release(self, event):\r\n '''on release we reset the press data'''\r\n if DraggablePoint.lock is not self:\r\n return\r\n\r\n self.press = None\r\n DraggablePoint.lock = None\r\n\r\n # turn off the rect animation property and reset the background\r\n self.point.set_animated(False)\r\n if self == self.parent.list_points[1]:\r\n self.line.set_animated(False)\r\n else:\r\n self.parent.list_points[1].line.set_animated(False)\r\n\r\n self.background = None\r\n\r\n # redraw the full figure\r\n self.point.figure.canvas.draw()\r\n\r\n self.x = self.point.center[0]\r\n self.y = self.point.center[1]\r\n\r\n def disconnect(self):\r\n '''disconnect all the stored connection ids'''\r\n\r\n self.point.figure.canvas.mpl_disconnect(self.cidpress)\r\n self.point.figure.canvas.mpl_disconnect(self.cidrelease)\r\n self.point.figure.canvas.mpl_disconnect(self.cidmotion)\r\n\r\n\r\nclass FileDialog(QtWidgets.QInputDialog):\r\n def __init__(self, parent=None):\r\n super(FileDialog, self).__init__(parent)\r\n self.accepted = QtWidgets.QPushButton('OK')\r\n self.rejected = QtWidgets.QPushButton('Cancel')\r\n # self.accepted.connect(self.accept)\r\n # self.rejected.connect(self.reject)\r\n\r\n @staticmethod\r\n def write_file(parent=None, default=None, label='Input', ext=None):\r\n if ext is None:\r\n ext = ''\r\n while True:\r\n dialog = FileDialog(parent)\r\n dialog.setTextValue(default)\r\n dialog.setLabelText(label)\r\n ret = dialog.exec_()\r\n file = dialog.textValue()\r\n if ret and file:\r\n if utils.check_file(file) or utils.check_file(''.join([file, ext])):\r\n reply = QtWidgets.QMessageBox.question(parent, 'Message',\r\n 'File already exists. Overwrite?',\r\n QtWidgets.QMessageBox.Yes,\r\n QtWidgets.QMessageBox.No)\r\n if reply == QtWidgets.QMessageBox.Yes:\r\n return file, ret\r\n else:\r\n return file, ret\r\n else:\r\n return file, 0\r\n\r\n @staticmethod\r\n def read_file(parent=None, default=None, label='Output'):\r\n while True:\r\n dialog = FileDialog(parent)\r\n dialog.setTextValue(default)\r\n dialog.setLabelText(label)\r\n ret = dialog.exec_()\r\n file = dialog.textValue()\r\n if ret and file:\r\n if not utils.check_file(file):\r\n QtWidgets.QMessageBox.about(parent, 'Message',\r\n 'File not found')\r\n else:\r\n return file, ret\r\n else:\r\n return file, 0\r\n\r\n\r\nclass TwoInputDialog(QtWidgets.QDialog):\r\n def __init__(self, label_1, label_2, initial_1=None, initial_2=None, parent=None):\r\n super(QtWidgets.QDialog, self).__init__(parent)\r\n label1 = QtWidgets.QLabel(label_1, self)\r\n label2 = QtWidgets.QLabel(label_2, self)\r\n hbox = QtWidgets.QHBoxLayout()\r\n self.setLayout(hbox)\r\n hbox.addWidget(label1)\r\n hbox.addWidget(label2)\r\n self.value_1 = initial_1\r\n self.value_2 = initial_2\r\n self.line_edit1 = QtWidgets.QLineEdit(initial_1)\r\n self.line_edit2 = QtWidgets.QLineEdit(initial_2)\r\n hbox.addWidget(self.line_edit1)\r\n hbox.addWidget(self.line_edit2)\r\n buttons = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,\r\n self)\r\n buttons.accepted.connect(self.accept)\r\n buttons.rejected.connect(self.reject)\r\n hbox.addWidget(buttons)\r\n # self.cancel.slicked.connect(self.cancel_button)\r\n\r\n def inputs(self):\r\n return self.line_edit1.text(), self.line_edit2.text()\r\n\r\n @staticmethod\r\n def get_inputs(label_1, label_2, initial_1=None, initial_2=None, parent=None):\r\n dialog = TwoInputDialog(label_1, label_2, initial_1, initial_2, parent)\r\n result = dialog.exec_()\r\n inputs = dialog.inputs()\r\n return inputs, result\r\n\r\n\r\nclass ColourMenu(QtWidgets.QMenu):\r\n def __init__(self, parent=None):\r\n super(QtWidgets.QMenu, self).__init__(parent)\r\n self.all_maps = {x: None for x in ('bgy', 'bgy_r',\r\n 'jet', 'jet_r',\r\n 'jet_plus', 'jet_plus_r',\r\n 'bwr', 'bwr_r',\r\n 'greys', 'greys_r')}\r\n self.action_group = QtWidgets.QActionGroup(self)\r\n self.setTitle('Colour Options')\r\n self.map = self.addMenu('Colour Map')\r\n self.limits = self.addAction('Colour Limits')\r\n\r\n # Add all the colour maps\r\n for item in self.all_maps.keys():\r\n self.all_maps[item] = QtWidgets.QAction(item, parent, checkable=True)\r\n self.map.addAction(self.all_maps[item])\r\n self.action_group.addAction(self.all_maps[item])\r\n # self.map.addMenu(item)\r\n self.action_group.setExclusive(True)\r\n\r\n def set_clim(self, initial_1='1', initial_2='5'):\r\n inputs, ret = TwoInputDialog.get_inputs(label_1='Lower Limit', label_2='Upper Limit',\r\n initial_1=initial_1, initial_2=initial_2, parent=self)\r\n return inputs, ret\r\n","sub_path":"pyMT/GUI_common/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":10012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"177438570","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n#\n##############################################################################\n\nimport tools\nfrom osv import fields,osv\n\nclass hr_holidays_report(osv.osv):\n _name = \"hr.holidays.report\"\n _description = \"Leaves Statistics\"\n _auto = False\n _rec_name = 'date'\n _columns = {\n 'date': fields.date('Date', readonly=True),\n 'year': fields.char('Year', size=4, readonly=True),\n 'day': fields.char('Day', size=15, readonly=True),\n 'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'),\n ('05','May'), ('06','June'), ('07','July'), ('08','August'), ('09','September'),\n ('10','October'), ('11','November'), ('12','December')], 'Month',readonly=True),\n 'date_from' : fields.date('Start Date', readonly=True),\n 'date_to' : fields.date('End Date', readonly=True),\n 'number_of_days_temp': fields.float('#Days', readonly=True),\n 'employee_id' : fields.many2one('hr.employee', \"Employee's Name\",readonly=True),\n 'user_id':fields.many2one('res.users', 'User', readonly=True),\n 'holiday_status_id' : fields.many2one(\"hr.holidays.status\", \"Leave Type\",readonly=True),\n 'department_id':fields.many2one('hr.department','Department',readonly=True),\n 'state': fields.selection([('draft', 'Draft'),\n ('confirm', 'Waiting Validation'),\n ('refuse', 'Refused'),\n ('validate', 'Validated'),\n ('cancel', 'Cancelled')]\n ,'State', readonly=True),\n }\n _order = 'date desc'\n def init(self, cr):\n tools.drop_view_if_exists(cr, 'hr_holidays_report')\n cr.execute(\"\"\"\n create or replace view hr_holidays_report as (\n select\n min(s.id) as id,\n date_trunc('day',s.create_date) as date,\n date_trunc('day',s.date_from) as date_from,\n date_trunc('day',s.date_to) as date_to,\n sum(s.number_of_days_temp) as number_of_days_temp,\n s.employee_id,\n s.user_id as user_id,\n to_char(s.create_date, 'YYYY') as year,\n to_char(s.create_date, 'MM') as month,\n to_char(s.create_date, 'YYYY-MM-DD') as day,\n s.holiday_status_id,\n s.department_id,\n s.state\n from\n hr_holidays s\n where type='remove' and\n s.employee_id is not null\n group by\n s.create_date,s.state,s.date_from,s.date_to,\n s.employee_id,s.user_id,s.holiday_status_id,\n s.department_id\n )\n \"\"\")\nhr_holidays_report()\n\nclass hr_holidays_remaining_leaves_user(osv.osv):\n _name = \"hr.holidays.remaining.leaves.user\"\n _description = \"Total holidays by type\"\n _auto = False\n _columns = {\n 'name': fields.char('Employee',size=64),\n 'no_of_leaves': fields.integer('Remaining leaves'),\n 'user_id': fields.many2one('res.users','User'),\n 'leave_type': fields.char('Leave Type',size=64),\n\n }\n def init(self, cr):\n tools.drop_view_if_exists(cr, 'hr_holidays_remaining_leaves_user')\n cr.execute(\"\"\"\n create or replace view hr_holidays_remaining_leaves_user as (\n select\n min(hrs.id) as id,\n rr.name as name,\n sum(hrs.number_of_days) as no_of_leaves,\n rr.user_id as user_id,\n hhs.name as leave_type\n from\n hr_holidays as hrs, hr_employee as hre,\n resource_resource as rr,hr_holidays_status as hhs\n where\n hrs.employee_id = hre.id and\n hre.resource_id = rr.id and\n hhs.id = hrs.holiday_status_id\n group by\n rr.name,rr.user_id,hhs.name\n )\n \"\"\")\n\nhr_holidays_remaining_leaves_user()\n","sub_path":"extra-addons/hr_holidays/report/hr_holidays_report.py","file_name":"hr_holidays_report.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"239735606","text":"import sys\nimport os\nthis_dir = os.path.dirname(__file__)\nparent_dir = os.path.dirname(this_dir)\nsys.path.insert(0, parent_dir)\n\nfrom pcc.evaluater.c_evaluator import CEvaluator\n\n\nimport unittest\n\nclass TestArray(unittest.TestCase):\n\n\n # def _assert_body(self, toplevel, expected):\n # \"\"\"Assert the flattened body of the given toplevel function\"\"\"\n # self.assertIsInstance(toplevel, FunctionAST)\n # self.assertEqual(self._flatten(toplevel.body), expected)\n\n def test_array(self):\n # Evaluate some code.\n pcc = CEvaluator()\n ret = pcc.evaluate('''\n int main(){\n int i = 1;\n int j = 1;\n int a[100];\n int len = 100;\n int len2 = 10;\n int sum = 0 ;\n\n for(i = 0; i < len ; i++){\n a[i] = i + 1;\n }\n\n for(i = 0; i < len ; i++){\n sum += a[i];\n }\n\n return sum ;\n }\n ''', llvmdump=True)\n\n print(\"The answer is %d\"%ret)\n assert (ret == 5050)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/test_array.py","file_name":"test_array.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"228540246","text":"from nets.netbase import NetBase\n\nimport tensorflow as tf\nimport logging\n\n\nclass DQN(NetBase):\n def __init__(self, conf, session, out_units, is_train=False):\n super().__init__(conf, session, out_units, is_train)\n self.net_name = 'DQN'\n\n self._inputs = None\n self._labels = None\n self._net_out = None\n self._argmax = None\n self._loss = None\n self._optimizer = None\n\n self._learn_rate, self._lr_input, self._lr_set = None, None, None # 0.00025\n self._decay, self._decay_input, self._decay_set = None, None, None # 0.95\n self._momentum, self._momentum_input, self._momentum_set = None, None, None # 0.95\n self._epsilon, self._epsilon_input, self._epsilon_set = None, None, None # 0.01\n\n self._build_net()\n if self.is_train:\n self._build_optimizer()\n\n self.sess.run(tf.initialize_all_variables())\n if self.model_path is not None:\n self._load_model()\n\n # if conf includes hyper-params, use them cover model's params\n if self.is_train:\n self._set_hyperparams()\n\n logging.info('network built success.'\n '\\n ---------- net info ----------'\n '\\n name: {0}'.format(self.net_name) +\n '\\n out_units: {0}'.format(self.out_units) +\n '\\n is_train: {0}'.format(self.is_train) +\n '\\n model_path: {0}'.format(self.model_path) +\n '\\n learn_rate: {0}'.format(self.sess.run(self._learn_rate)) +\n '\\n decay: {0}'.format(self.sess.run(self._decay)) +\n '\\n momentum: {0}'.format(self.sess.run(self._momentum)) +\n '\\n epsilon: {0}'.format(self.sess.run(self._epsilon)) +\n '\\n ------------------------------')\n\n # if self.is_train:\n # self._optimizer_build()\n # self.sess.run(tf.initialize_all_variables())\n #\n # if self.model_path is not None:\n # self._load_model()\n # print('use net params from new input, not from old model\\n')\n #\n # self.sess.run(self._lr_set, {self._lr_input: self.conf['learn_rate']})\n # self.sess.run(self._decay_set, {self._decay_input: self.conf['decay']})\n # self.sess.run(self._momentum_set, {self._momentum_input: self.conf['momentum']})\n # self.sess.run(self._epsilon_set, {self._epsilon_input: self.conf['epsilon']})\n #\n # elif self.model_path is not None:\n # self._optimizer_build()\n # self.sess.run(tf.initialize_all_variables())\n # self._load_model()\n # else:\n # print('need opt_params / cp_path at least one. \\n')\n\n def _step(self, inputs, labels):\n if self._optimizer is None:\n return None\n\n feed = {\n self._inputs: inputs,\n self._labels: labels\n }\n result = self.sess.run([self._loss, self._optimizer], feed)\n\n c_iter = self.sess.run(self._cur_iter) + 1\n self.sess.run(self._iter_set, {self._iter_input: c_iter})\n\n return result\n\n def _predict(self, inputs):\n return self.sess.run([self._net_out, self._argmax],\n feed_dict={self._inputs: inputs})\n\n def _build_net(self):\n self._inputs = tf.placeholder(tf.float32, shape=[None, 84, 84, 4])\n\n conv1 = tf.contrib.layers.conv2d(\n inputs=self._inputs,\n num_outputs=32,\n kernel_size=8,\n stride=4,\n padding='same',\n activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n trainable=True\n )\n conv1 = tf.contrib.layers.batch_norm(conv1)\n\n conv2 = tf.contrib.layers.conv2d(\n inputs=conv1,\n num_outputs=64,\n kernel_size=4,\n stride=2,\n padding='same',\n activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n trainable=True\n )\n conv2 = tf.contrib.layers.batch_norm(conv2)\n\n conv3 = tf.contrib.layers.conv2d(\n inputs=conv2,\n num_outputs=64,\n kernel_size=3,\n stride=1,\n padding='same',\n activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n trainable=True\n )\n conv3 = tf.contrib.layers.batch_norm(conv3)\n conv3_flat = tf.reshape(conv3, [-1, 11 * 11 * 64])\n\n fc4 = tf.contrib.layers.fully_connected(\n inputs=conv3_flat,\n num_outputs=512,\n activation_fn=tf.nn.relu,\n weights_initializer=tf.truncated_normal_initializer(0, 0.01),\n trainable=True\n )\n\n fc5 = tf.contrib.layers.fully_connected(\n inputs=fc4,\n num_outputs=self.out_units,\n activation_fn=None,\n weights_initializer=tf.truncated_normal_initializer(0, 0.01),\n trainable=True\n )\n\n self._net_out = fc5\n\n # returns the index with the largest value across axes of a tensor.\n self._argmax = tf.argmax(self._net_out, dimension=1)\n\n def _build_optimizer(self):\n with tf.variable_scope('learn_rate'):\n self._learn_rate = tf.Variable(0, dtype=tf.float64, trainable=False, name='learn_rate')\n self._lr_input = tf.placeholder(tf.float64, None, name='lr_input')\n self._lr_set = self._learn_rate.assign(self._lr_input)\n\n with tf.variable_scope('decay'):\n self._decay = tf.Variable(0, dtype=tf.float64, trainable=False, name='decay')\n self._decay_input = tf.placeholder(tf.float64, None, name='decay_input')\n self._decay_set = self._decay.assign(self._decay_input)\n\n with tf.variable_scope('momentum'):\n self._momentum = tf.Variable(0, dtype=tf.float64, trainable=False, name='momentum')\n self._momentum_input = tf.placeholder(tf.float64, None, name='momentum_input')\n self._momentum_set = self._momentum.assign(self._momentum_input)\n\n with tf.variable_scope('epsilon'):\n self._epsilon = tf.Variable(0, dtype=tf.float64, trainable=False, name='epsilon')\n self._epsilon_input = tf.placeholder(tf.float64, None, name='epsilon_input')\n self._epsilon_set = self._epsilon.assign(self._epsilon_input)\n\n self._labels = tf.placeholder(tf.float32, shape=[None, self.out_units])\n self._marks = tf.cast(tf.cast(self._labels, tf.bool), tf.float32)\n self._marks_out = tf.multiply(self._marks, self._net_out)\n\n # self._loss = tf.losses.mean_squared_error(self._labels, self._marks_out)\n self._loss = tf.losses.huber_loss(self._labels, self._marks_out)\n\n # add param centered = True ?\n self._optimizer = tf.train.RMSPropOptimizer(\n learning_rate=self._learn_rate,\n decay=self._decay,\n momentum=self._momentum,\n epsilon=self._epsilon,\n ).minimize(self._loss)\n\n def _set_hyperparams(self):\n if 'learn_rate' in self.conf:\n self.sess.run(self._lr_set, {self._lr_input: self.conf['learn_rate']})\n if 'decay' in self.conf:\n self.sess.run(self._decay_set, {self._decay_input: self.conf['decay']})\n if 'momentum' in self.conf:\n self.sess.run(self._momentum_set, {self._momentum_input: self.conf['momentum']})\n if 'epsilon' in self.conf:\n self.sess.run(self._epsilon_set, {self._epsilon_input: self.conf['epsilon']})\n","sub_path":"nets/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":7710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"239464612","text":"import time\ndef ispal(n):\n n = str(n)\n maxb = len(n)-1\n for i in range(0,int(len(n)/2)):\n if(n[i]!=n[maxb-i]):\n return False\n return True\n\ndef solve4():\n maxpal = 0\n result = 0\n for i in range(100,1000):\n for j in range(i+1,1000):\n result = i*j\n if(ispal(result) and (result > maxpal)):\n maxpal = result\n\n return maxpal\n\n\ndef timesolution():\n timestart = time.time()\n solve4()\n elapsed = time.time() - timestart\n\n print(\"The largest palindrome that is a product of two three digit\"\n +\"integers is \"+str(solve4())+\".\\n\")\n print(\"Solution took \"+str(elapsed)+\" seconds.\")\n","sub_path":"Problems 1 - 10/problem 4/problem 4.py","file_name":"problem 4.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"348726756","text":"from flask import render_template, flash, redirect, url_for, abort\nfrom flask_login import login_user, logout_user, current_user\nfrom datetime import date, timedelta\nimport traceback\n\nfrom sqlalchemy import func\n\nfrom museum import app, Config, db\nfrom museum.api import api_users_columns, api_exhibitions_columns, api_history_columns\nfrom museum.api_utils import required_permission\nfrom museum.forms import LoginForm, UserForm, ClientForm, ArtistForm, GalleryForm, ExhibitionForm, ExhibitForm, \\\n ExhibitCreateForm, BorrowForm, ExhibitToGallery, ExhibitToStore\nfrom museum.models import User, Exhibit, Artist, Client, Exhibition, Gallery, History, Borrow, Store\n\n'''\nHelper functions\n'''\n\n\ndef check_perm(required):\n if current_user.is_anonymous:\n return False\n return current_user.permission_level >= required\n\n\ndef form_create(form_class, obj_class, error, redirect_addr, redirect_error, form_file, columns=None):\n form = form_class()\n if form.validate_on_submit():\n o = obj_class()\n form.populate_obj(o)\n try:\n db.session.add(o)\n db.session.commit()\n except Exception as e:\n flash(traceback.format_exc())\n flash(error + repr(e))\n db.session.rollback()\n return redirect(redirect_error)\n return redirect(redirect_addr)\n return render_template(form_file, form=form, columns=columns)\n\n\ndef form_edit(id, form_class, obj_class, error, redirect_addr, redirect_error, form_file, columns=None):\n obj = obj_class.query.get(id)\n if obj is None:\n abort(404)\n form = form_class(obj=obj)\n if form.validate_on_submit():\n form.populate_obj(obj)\n try:\n db.session.commit()\n except Exception as e:\n flash(error + repr(e))\n db.session.rollback()\n return redirect(redirect_error)\n return redirect(redirect_addr)\n return render_template(form_file, form=form, columns=columns)\n\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\", title='Strona główna')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is None or not user.check_password(form.password.data):\n flash(\"Invalid username or password\")\n return redirect(url_for('login'))\n login_user(user, remember=form.remember_me.data)\n return redirect(url_for('index'))\n return render_template('login.html', title='Zaloguj się', form=form)\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\n@app.route('/schema')\ndef schema():\n return render_template('schema.html', title='Schemat BD')\n\n\n'''\nTable views\n'''\n\n\n@app.route('/users')\n@required_permission(Config.USER_API_PERM)\ndef users():\n link = url_for('edit_user', user_id=1)[:-2]\n op = ['EDIT' if check_perm(Config.EDIT_PERM) else None]\n return render_template(\"table.html\", columns=api_users_columns, fetch_url=url_for('api_users'), link=link, op=op,\n new_item_loc=url_for('create_user'), new_item_text='Dodaj nowego użytkownika')\n\n\n@app.route('/clients')\n@required_permission(Config.USER_API_PERM)\ndef clients():\n link = url_for('edit_client', client_id=1)[:-2]\n op = ['EDIT' if check_perm(Config.EDIT_PERM) else None]\n return render_template(\"table.html\", columns=Client.columns(), fetch_url=url_for('api_clients'), link=link, op=op,\n new_item_loc=url_for('create_client'), new_item_text='Dodaj nowego klienta')\n\n\n@app.route('/artists')\ndef artists():\n link = url_for('edit_artist', artist_id=1)[:-2]\n op = ['EDIT' if check_perm(Config.EDIT_PERM) else None]\n return render_template(\"table.html\", columns=Artist.columns(), fetch_url=url_for('api_artists'), link=link, op=op,\n new_item_loc=url_for('create_artist'), new_item_text='Dodaj nowego artystę')\n\n\n@app.route('/exhibits')\ndef exhibits():\n link = url_for('edit_exhibit', exhibit_id=1)[:-2]\n link2 = url_for('view_exhibit', exhibit_id=1)[:-2]\n op = ['EDIT' if check_perm(Config.EDIT_PERM) else None]\n if not current_user.is_anonymous:\n op.append('VIEW')\n return render_template(\"table.html\", columns=Exhibit.columns(), fetch_url=url_for('api_exhibits'), link=link, op=op,\n new_item_loc=url_for('create_exhibit'), new_item_text='Dodaj nowy eksponat', link2=link2)\n\n\n@app.route('/exhibitions')\ndef exhibitions():\n link = url_for('edit_exhibition', exhibition_id=1)[:-2]\n op = ['EDIT' if check_perm(Config.EDIT_PERM) else None]\n return render_template(\"table.html\", columns=api_exhibitions_columns, fetch_url=url_for('api_exhibitions'),\n link=link, op=op,\n new_item_loc=url_for('create_exhibition'), new_item_text='Dodaj nową wystawę')\n\n\n@app.route('/galleries')\ndef galleries():\n link = url_for('edit_gallery', gallery_id=1)[:-2]\n op = ['EDIT' if check_perm(Config.EDIT_PERM) else None]\n return render_template(\"table.html\", columns=Gallery.columns(), fetch_url=url_for('api_galleries'), link=link,\n op=op,\n new_item_loc=url_for('create_gallery'), new_item_text='Dodaj nową galerię')\n\n\n@app.route('/history')\n@required_permission(logged_in=True)\ndef history():\n return render_template(\"table.html\", columns=api_history_columns, fetch_url=url_for('api_history'))\n\n\n'''\nObject creation and editing\n'''\n\n\n@app.route('/user/<int:user_id>', methods=['GET', 'POST'])\n@required_permission(Config.USER_API_PERM)\ndef edit_user(user_id):\n return form_edit(user_id, UserForm, User, \"Nie udało się zapisać. Zajęta nazwa użytkownika? \", url_for('users'),\n url_for('edit_user', user_id=user_id), 'user_form.html', Client.columns())\n\n\n@app.route('/user/new', methods=['GET', 'POST'])\n@required_permission(Config.USER_API_PERM)\ndef create_user():\n return form_create(UserForm, User, \"Nie udało się zapisać. Zajęta nazwa użytkownika? \", url_for('users'),\n url_for('create_user'), 'user_form.html')\n\n\n@app.route('/client/<int:client_id>', methods=['GET', 'POST'])\n@required_permission(Config.USER_API_PERM)\ndef edit_client(client_id):\n return form_edit(client_id, ClientForm, Client, \"Nie udało się zapisać. Zajęta nazwa klienta? \", url_for('clients'),\n url_for('edit_client', client_id=client_id), 'client_form.html')\n\n\n@app.route('/client/new', methods=['GET', 'POST'])\n@required_permission(Config.USER_API_PERM)\ndef create_client():\n return form_create(ClientForm, Client, \"Nie udało się zapisać. Zajęta nazwa klienta? \", url_for('clients'),\n url_for('create_client'), 'client_form.html')\n\n\n@app.route('/artist/<int:artist_id>', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef edit_artist(artist_id):\n return form_edit(artist_id, ArtistForm, Artist, \"Nie udało się zapisać. Nieznany błąd. \", url_for('artists'),\n url_for('edit_artist', artist_id=artist_id), 'artist_form.html')\n\n\n@app.route('/artist/new', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef create_artist():\n return form_create(ArtistForm, Artist, \"Nie udało się zapisać. Nieznany błąd. \", url_for('artists'),\n url_for('create_artist'), 'artist_form.html')\n\n\n@app.route('/gallery/<int:gallery_id>', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef edit_gallery(gallery_id):\n return form_edit(gallery_id, GalleryForm, Gallery, \"Nie udało się zapisać. Zajęta para nazwa/miasto? \",\n url_for('galleries'),\n url_for('edit_gallery', gallery_id=gallery_id), 'gallery_form.html')\n\n\n@app.route('/gallery/new', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef create_gallery():\n return form_create(GalleryForm, Gallery, \"Nie udało się zapisać. Zajęta para nazwa/miasto? \", url_for('galleries'),\n url_for('create_gallery'), 'gallery_form.html')\n\n\n@app.route('/exhibition/<int:exhibition_id>', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef edit_exhibition(exhibition_id):\n return form_edit(exhibition_id, ExhibitionForm, Exhibition, \"Nie udało się zapisać. Zajęta para nazwa/miasto? \",\n url_for('exhibitions'),\n url_for('edit_exhibition', exhibition_id=exhibition_id), 'exhibition_form.html', Gallery.columns())\n\n\n@app.route('/exhibition/new', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef create_exhibition():\n return form_create(ExhibitionForm, Exhibition, \"Nie udało się zapisać. Zajęta para nazwa/miasto? \",\n url_for('exhibitions'),\n url_for('create_exhibition'), 'exhibition_form.html', Gallery.columns())\n\n\n@app.route('/exhibit/<int:exhibit_id>', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef edit_exhibit(exhibit_id):\n return form_edit(exhibit_id, ExhibitForm, Exhibit, \"Nie udało się zapisać. Nieznany błąd. \", url_for('exhibits'),\n url_for('edit_exhibit', exhibit_id=exhibit_id), 'exhibit_form.html', Artist.columns())\n\n\n@app.route('/exhibit/new', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef create_exhibit():\n form = ExhibitCreateForm()\n if form.validate_on_submit():\n o = Exhibit()\n form.populate_obj(o)\n try:\n db.session.add(o)\n db.session.flush()\n if form.exhibition_id.data:\n h = History(exhibit_id=o.id, first_day=date.today(), exhibition_id=form.exhibition_id.data)\n else:\n s = Store(name=form.name.data, reason=form.reason.data)\n db.session.add(s)\n db.session.flush()\n h = History(exhibit_id=o.id, first_day=date.today(), store_id=s.id)\n db.session.add(h)\n db.session.commit()\n except Exception as e:\n flash(\"Nie udało się zapisać. Nieznany błąd. \" + repr(e))\n db.session.rollback()\n return redirect(url_for('create_exhibit'))\n return redirect(url_for('exhibits'))\n return render_template('exhibit_create_form.html', form=form, columns=Artist.columns(), columns_2=Exhibition.columns())\n\n\ndef is_borrowed(exhibit_id):\n return db.session.query(func.is_borrowed(exhibit_id)).first()[0]\n\n\ndef finish_last_entry(exhibit_id):\n curr = History.query.filter(History.exhibit_id == exhibit_id). \\\n order_by(History.first_day.desc()).first()\n if curr is None:\n return\n if curr.first_day == date.today():\n db.session.delete(curr)\n else:\n curr.last_day = date.today() - timedelta(days=1)\n db.session.flush()\n\n\n@app.route('/exhibit/<int:exhibit_id>/borrow', methods=['GET', 'POST'])\n@required_permission(1)\ndef borrow_exhibit(exhibit_id):\n if current_user.is_anonymous or current_user.client_id is None:\n flash(\"Tylko klienci mogą wypożyczać eksponaty\")\n return redirect(url_for('index'))\n if is_borrowed(exhibit_id):\n flash(\"Eksponat jest już wypożyczony\")\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n if Exhibit.query.get(exhibit_id) is None:\n flash(\"Brak eksponatu o podanym id\")\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n form = BorrowForm()\n if form.validate_on_submit():\n b = Borrow(client_id=current_user.client_id, city=form.city.data)\n db.session.add(b)\n db.session.flush()\n finish_last_entry(exhibit_id)\n h = History(exhibit_id=exhibit_id, first_day=date.today(), last_day=form.last_date.data, borrow_id=b.id)\n db.session.add(h)\n h2 = History(exhibit_id=exhibit_id, first_day=form.last_date.data+timedelta(days=1), store_id=curr.store_id, exhibition_id=curr.exhibition_id)\n db.session.add(h2)\n try:\n db.session.commit()\n except Exception as e:\n flash(\"Nie udało się zapisać. Błąd: \" + repr(e))\n db.session.rollback()\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n return render_template('form_borrow.html', form=form)\n\n\n@app.route('/exhibit/view/<int:exhibit_id>')\n@required_permission(logged_in=True)\ndef view_exhibit(exhibit_id):\n exhibit = Exhibit.query.get_or_404(exhibit_id)\n return render_template('view_exhibit.html', columns=api_history_columns, exhibit_id=exhibit_id, exhibit=exhibit)\n\n\n@app.route('/exhibit/to_gallery/<int:exhibit_id>', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef exhibit_to_gallery(exhibit_id):\n if is_borrowed(exhibit_id):\n flash(\"Eksponat jest aktualnie wypożyczony\")\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n if Exhibit.query.get(exhibit_id) is None:\n flash(\"Brak eksponatu o podanym id\")\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n form = ExhibitToGallery()\n if form.validate_on_submit():\n finish_last_entry(exhibit_id)\n h = History(exhibit_id=exhibit_id, first_day=date.today(), exhibition_id=form.exhibition_id.data)\n db.session.add(h)\n try:\n db.session.commit()\n except Exception as e:\n flash(\"Nie udało się zapisać. Błąd: \" + repr(e))\n db.session.rollback()\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n return render_template('exhibit_to_gallery.html', columns=api_exhibitions_columns, exhibit_id=exhibit_id, form=form)\n\n\n@app.route('/exhibit/to_store/<int:exhibit_id>', methods=['GET', 'POST'])\n@required_permission(Config.EDIT_PERM)\ndef exhibit_to_store(exhibit_id):\n if is_borrowed(exhibit_id):\n flash(\"Eksponat jest aktualnie wypożyczony\")\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n if Exhibit.query.get(exhibit_id) is None:\n flash(\"Brak eksponatu o podanym id\")\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n form = ExhibitToStore()\n if form.validate_on_submit():\n finish_last_entry(exhibit_id)\n store = Store(name=form.name.data, reason=form.reason.data)\n db.session.add(store)\n try:\n db.session.flush()\n h = History(exhibit_id=exhibit_id, first_day=date.today(), store_id=store.id)\n db.session.add(h)\n db.session.commit()\n except Exception as e:\n flash(\"Nie udało się zapisać. Błąd: \" + repr(e))\n db.session.rollback()\n return redirect(url_for('view_exhibit', exhibit_id=exhibit_id))\n return render_template('exhibit_to_store.html', exhibit_id=exhibit_id, form=form)","sub_path":"bd/museum/museum/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":15020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"602166217","text":"from collections import OrderedDict\n\nimport os\nimport json\nimport time\nimport numpy as np\nimport math\nfrom itertools import combinations\nfrom detector.event.template.main import Event\n\nclass KidnappingEvent(Event):\n model = None\n result = None\n path = os.path.dirname(os.path.abspath(__file__))\n\n def __init__(self, debug=False):\n super().__init__(debug)\n self.model_name = \"kidnapping\"\n self.analysis_time = 0\n self.debug = debug\n self.history = []\n self.max_history = 5\n self.pre_detected_person = 0\n self.frame = None\n \n def inference(self, frame_info, detection_result):\n frame = frame_info[\"frame\"]\n frame_number = frame_info[\"frame_number\"]\n\n start = 0\n end = 0\n if self.debug :\n start = time.time()\n\n eventFlag = 0\n result = OrderedDict()\n detected_person = []\n for i, e in enumerate(detection_result['results'][0]['detection_result']):\n if e['label'][0]['description'] in ['person']:\n detected_person.append(\n ((e['position']['x'] + e['position']['w'] / 2), (e['position']['y'] + e['position']['h'] / 2)))\n\n num_of_person = len(detected_person)\n\n result[\"num_of_person\"] = num_of_person\n result[\"center_coordinates\"] = detected_person\n\n # kidnapping detection module\n if num_of_person >= 2 :\n self.pre_detected_person = num_of_person\n pair_of_center_coordinates = np.array(list(combinations(detected_person, 2)), dtype=int)\n if len(pair_of_center_coordinates) >= 1 :\n for i in range(len(pair_of_center_coordinates)) :\n dist = np.linalg.norm(pair_of_center_coordinates[i][0] - pair_of_center_coordinates[i][1])\n if dist < 120 :\n eventFlag = 1\n elif num_of_person==1:\n if self.pre_detected_person >=2:\n eventFlag = 1\n else:\n self.pre_detected_person = 0\n \n\n if len(self.history) >= self.max_history :\n self.history.pop(0)\n self.history.append(eventFlag)\n\n # Smoothing (history check)\n sum = 0\n if len(self.history) == self.max_history :\n for i in range(self.max_history) :\n if self.history[i] == 1 :\n sum += 1\n\n if sum >= (self.max_history * 0.4) :\n state = True\n else :\n state = False\n\n self.result = state\n\n\n if self.debug :\n end = time.time()\n self.analysis_time = end - start\n\n return self.result\n","sub_path":"detector/event/kidnapping/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"636959895","text":"import imutils\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pytesseract\n\n# https://theailearner.com/tag/cv2-warpperspective/\n# https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html#geometric-transformations\n\nimg = cv2.imread('img.JPG')\nrows, cols, ch = img.shape\n\npts1 = np.float32([[408, 136], [796, 730], [808, 141], [388, 733]])\nnp.random.shuffle(pts1)\n\n# 304, 811, 1019, 1658 - suma x, y\n# TL, TR, BL, BR, warp funkcja\n\npts1 = pts1[np.argsort(np.sum(pts1, axis=1))]\n\ntopwidth = pts1[1, 0] - pts1[0, 0]\nbottomwidth = pts1[3, 0] - pts1[2, 0]\n\nleftheight = pts1[2, 1] - pts1[0, 1]\nbottomheight = pts1[3, 1] - pts1[1, 1]\n\nwidth = max(topwidth, bottomwidth)\nheight = max(leftheight, bottomheight)\n\npts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]])\n\nM = cv2.getPerspectiveTransform(pts1, pts2)\ndst = cv2.warpPerspective(img, M, (width, height))\n\n# https://www.pyimagesearch.com/2018/09/17/opencv-ocr-and-text-recognition-with-tesseract/\n# https://www.pyimagesearch.com/2017/07/17/credit-card-ocr-with-opencv-and-python/\n# https://www.pyimagesearch.com/2017/07/10/using-tesseract-ocr-python/\n\ngray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)\n\nt_val = 180\n# thresh = cv2.threshold(gray, t_val, 255, cv2.THRESH_BINARY)[1]\nthresh = cv2.threshold(gray, t_val, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n# blur = cv2.medianBlur(thresh, 3)\nblur = thresh\n\nblur_rgb = cv2.cvtColor(blur, cv2.COLOR_GRAY2RGB)\ncv2.imwrite(\"temp.png\", blur_rgb)\n\n# config = \"-l eng --oem 1 --psm 6\"\n# pytesseract.pytesseract.tesseract_cmd = r'C:\\Users\\pewojda\\AppData\\Local\\Tesseract-OCR'\n# text = pytesseract.image_to_string(blur_rgb, config=config)\n# print(text)\n\nplt.subplot(241), plt.imshow(img), plt.title('Input')\nplt.subplot(242), plt.imshow(gray), plt.title('Gray')\nplt.subplot(243), plt.imshow(thresh), plt.title('Threshold')\nplt.subplot(244), plt.imshow(blur), plt.title('Blur')\nplt.subplot(245), plt.imshow(blur_rgb), plt.title('Saved')\nplt.show()\n","sub_path":"PythonTests/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"554713558","text":"import argparse\nimport os\nimport sys\n\nfrom functools import partial\nfrom threading import Thread\n\nfrom . import __version__\nfrom .actions import (ActionLED,\n ReportActionBattery,\n ReportActionBinding,\n ReportActionBluetoothSignal,\n ReportActionDump,\n ReportActionInput,\n ReportActionStatus)\nfrom .backends import BluetoothBackend, HidrawBackend\nfrom .config import Config\nfrom .daemon import Daemon\nfrom .eventloop import EventLoop\nfrom .exceptions import BackendError\nfrom .uinput import parse_uinput_mapping\nfrom .utils import parse_button_combo\n\n\nACTIONS = (ActionLED,\n ReportActionBattery,\n ReportActionBinding,\n ReportActionBluetoothSignal,\n ReportActionDump,\n ReportActionInput,\n ReportActionStatus)\nCONFIG_FILES = (\"~/.config/ds4drv.conf\", \"/etc/ds4drv.conf\")\nDAEMON_LOG_FILE = \"~/.cache/ds4drv.log\"\nDAEMON_PID_FILE = \"/tmp/ds4drv.pid\"\n\n\nclass DS4Controller(object):\n def __init__(self, index, options, dynamic=False):\n self.index = index\n self.dynamic = dynamic\n self.logger = Daemon.logger.new_module(\"controller {0}\".format(index))\n\n self.error = None\n self.device = None\n self.loop = EventLoop()\n\n self.actions = [cls(self) for cls in ACTIONS]\n self.bindings = options.parent.bindings\n self.current_profile = \"default\"\n self.default_profile = options\n self.options = self.default_profile\n self.profiles = options.profiles\n self.profile_options = dict(options.parent.profiles)\n self.profile_options[\"default\"] = self.default_profile\n\n if self.profiles:\n self.profiles.append(\"default\")\n\n self.load_options(self.options)\n\n def fire_event(self, event, *args):\n self.loop.fire_event(event, *args)\n\n def load_profile(self, profile):\n if profile == self.current_profile:\n return\n\n profile_options = self.profile_options.get(profile)\n if profile_options:\n self.logger.info(\"Switching to profile: {0}\", profile)\n self.load_options(profile_options)\n self.current_profile = profile\n self.fire_event(\"load-profile\", profile)\n else:\n self.logger.warning(\"Ignoring invalid profile: {0}\", profile)\n\n def next_profile(self):\n if not self.profiles:\n return\n\n next_index = self.profiles.index(self.current_profile) + 1\n if next_index >= len(self.profiles):\n next_index = 0\n\n self.load_profile(self.profiles[next_index])\n\n def prev_profile(self):\n if not self.profiles:\n return\n\n next_index = self.profiles.index(self.current_profile) - 1\n if next_index < 0:\n next_index = len(self.profiles) - 1\n\n self.load_profile(self.profiles[next_index])\n\n def setup_device(self, device):\n self.logger.info(\"Connected to {0}\", device.name)\n\n self.device = device\n self.device.set_led(*self.options.led)\n self.fire_event(\"device-setup\", device)\n self.loop.add_watcher(device.report_fd, self.read_report)\n self.load_options(self.options)\n\n def cleanup_device(self):\n self.logger.info(\"Disconnected\")\n self.fire_event(\"device-cleanup\")\n self.loop.remove_watcher(self.device.report_fd)\n self.device.close()\n self.device = None\n\n if self.dynamic:\n self.loop.stop()\n\n def load_options(self, options):\n self.fire_event(\"load-options\", options)\n self.options = options\n\n def read_report(self):\n report = self.device.read_report()\n\n if not report:\n if report is False:\n return\n\n self.cleanup_device()\n return\n\n self.fire_event(\"device-report\", report)\n\n def run(self):\n self.loop.run()\n\n def exit(self, *args):\n if self.device:\n self.cleanup_device()\n\n self.logger.error(*args)\n self.error = True\n\n\nclass ControllerAction(argparse.Action):\n # These options are moved from the normal options namespace to\n # a controller specific namespace on --next-controller.\n __options__ = [\"battery_flash\",\n \"bindings\",\n \"dump_reports\",\n \"emulate_xboxdrv\",\n \"emulate_xpad\",\n \"emulate_xpad_wireless\",\n \"ignored_buttons\",\n \"led\",\n \"mapping\",\n \"profile_toggle\",\n \"profiles\",\n \"trackpad_mouse\"]\n\n @classmethod\n def default_controller(cls):\n controller = argparse.Namespace()\n defaults = parser.parse_args([])\n for option in cls.__options__:\n value = getattr(defaults, option)\n setattr(controller, option, value)\n\n return controller\n\n def __call__(self, parser, namespace, values, option_string=None):\n if not hasattr(namespace, \"controllers\"):\n setattr(namespace, \"controllers\", [])\n\n controller = argparse.Namespace()\n defaults = parser.parse_args([])\n for option in self.__options__:\n if hasattr(namespace, option):\n value = namespace.__dict__.pop(option)\n if isinstance(value, str):\n for action in filter(lambda a: a.dest == option,\n parser._actions):\n value = parser._get_value(action, value)\n else:\n value = getattr(defaults, option)\n\n setattr(controller, option, value)\n\n namespace.controllers.append(controller)\n\n\ndef hexcolor(color):\n color = color.strip(\"#\")\n\n if len(color) != 6:\n raise ValueError\n\n values = (color[:2], color[2:4], color[4:6])\n values = map(lambda x: int(x, 16), values)\n\n return tuple(values)\n\n\ndef stringlist(s):\n return list(filter(None, map(str.strip, s.split(\",\"))))\n\n\ndef buttoncombo(sep):\n func = partial(parse_button_combo, sep=sep)\n func.__name__ = \"button combo\"\n return func\n\n\nparser = argparse.ArgumentParser(prog=\"ds4drv\")\nparser.add_argument(\"--version\", action=\"version\",\n version=\"%(prog)s {0}\".format(__version__))\n\nconfigopt = parser.add_argument_group(\"configuration options\")\nconfigopt.add_argument(\"--config\", metavar=\"filename\",\n type=os.path.expanduser,\n help=\"configuration file to read settings from. \"\n \"Default is ~/.config/ds4drv.conf or \"\n \"/etc/ds4drv.conf, whichever is found first\")\n\nbackendopt = parser.add_argument_group(\"backend options\")\nbackendopt.add_argument(\"--hidraw\", action=\"store_true\",\n help=\"use hidraw devices. This can be used to access \"\n \"USB and paired bluetooth devices. Note: \"\n \"Bluetooth devices does currently not support \"\n \"any LED functionality\")\n\ndaemonopt = parser.add_argument_group(\"daemon options\")\ndaemonopt.add_argument(\"--daemon\", action=\"store_true\",\n help=\"run in the background as a daemon\")\ndaemonopt.add_argument(\"--daemon-log\", default=DAEMON_LOG_FILE, metavar=\"file\",\n help=\"log file to create in daemon mode\")\ndaemonopt.add_argument(\"--daemon-pid\", default=DAEMON_PID_FILE, metavar=\"file\",\n help=\"PID file to create in daemon mode\")\n\ncontrollopt = parser.add_argument_group(\"controller options\")\ncontrollopt.add_argument(\"--battery-flash\", action=\"store_true\",\n help=\"flashes the LED once a minute if the \"\n \"battery is low\")\ncontrollopt.add_argument(\"--emulate-xboxdrv\", action=\"store_true\",\n help=\"emulates the same joystick layout as a \"\n \"Xbox 360 controller used via xboxdrv\")\ncontrollopt.add_argument(\"--emulate-xpad\", action=\"store_true\",\n help=\"emulates the same joystick layout as a wired \"\n \"Xbox 360 controller used via the xpad module\")\ncontrollopt.add_argument(\"--emulate-xpad-wireless\", action=\"store_true\",\n help=\"emulates the same joystick layout as a wireless \"\n \"Xbox 360 controller used via the xpad module\")\ncontrollopt.add_argument(\"--ignored-buttons\", metavar=\"button(s)\",\n type=buttoncombo(\",\"), default=[],\n help=\"a comma-separated list of buttons to never send \"\n \"as joystick events. For example specify 'PS' to \"\n \"disable Steam's big picture mode shortcut when \"\n \"using the --emulate-* options\")\ncontrollopt.add_argument(\"--led\", metavar=\"color\", default=\"0000ff\",\n type=hexcolor,\n help=\"sets color of the LED. Uses hex color codes, \"\n \"e.g. 'ff0000' is red. Default is '0000ff' (blue)\")\ncontrollopt.add_argument(\"--bindings\", metavar=\"bindings\",\n help=\"use custom action bindings specified in the \"\n \"config file\")\ncontrollopt.add_argument(\"--mapping\", metavar=\"mapping\",\n help=\"use a custom button mapping specified in the \"\n \"config file\")\ncontrollopt.add_argument(\"--profile-toggle\", metavar=\"button(s)\",\n type=buttoncombo(\"+\"),\n help=\"a button combo that will trigger profile \"\n \"cycling, e.g. 'R1+L1+PS'\")\ncontrollopt.add_argument(\"--profiles\", metavar=\"profiles\",\n type=stringlist,\n help=\"profiles to cycle through using the button \"\n \"specified by --profile-toggle, e.g. \"\n \"'profile1,profile2'\")\ncontrollopt.add_argument(\"--trackpad-mouse\", action=\"store_true\",\n help=\"makes the trackpad control the mouse\")\ncontrollopt.add_argument(\"--dump-reports\", action=\"store_true\",\n help=\"prints controller input reports\")\ncontrollopt.add_argument(\"--next-controller\", nargs=0, action=ControllerAction,\n help=\"creates another controller\")\n\n\ndef merge_options(src, dst, defaults):\n for key, value in src.__dict__.items():\n if key == \"controllers\":\n continue\n\n default = getattr(defaults, key)\n\n if getattr(dst, key) == default and value != default:\n setattr(dst, key, value)\n\n\ndef load_options():\n options = parser.parse_args(sys.argv[1:] + [\"--next-controller\"])\n\n config = Config()\n config_paths = options.config and (options.config,) or CONFIG_FILES\n for path in filter(os.path.exists, map(os.path.expanduser, config_paths)):\n config.load(path)\n break\n\n config_args = config.section_to_args(\"ds4drv\") + config.controllers()\n config_options = parser.parse_args(config_args)\n\n defaults, remaining_args = parser.parse_known_args([\"--next-controller\"])\n merge_options(config_options, options, defaults)\n\n controller_defaults = ControllerAction.default_controller()\n for idx, controller in enumerate(config_options.controllers):\n try:\n org_controller = options.controllers[idx]\n merge_options(controller, org_controller, controller_defaults)\n except IndexError:\n options.controllers.append(controller)\n\n options.profiles = {}\n for name, section in config.sections(\"profile\"):\n args = config.section_to_args(section)\n profile_options = parser.parse_args(args)\n profile_options.parent = options\n options.profiles[name] = profile_options\n\n options.bindings = {}\n options.bindings[\"global\"] = config.section(\"bindings\",\n key_type=parse_button_combo)\n for name, section in config.sections(\"bindings\"):\n options.bindings[name] = config.section(section,\n key_type=parse_button_combo)\n\n for name, section in config.sections(\"mapping\"):\n mapping = config.section(section)\n parse_uinput_mapping(name, mapping)\n\n for controller in options.controllers:\n controller.parent = options\n\n return options\n\n\ndef create_controller_thread(index, controller_options, dynamic=False):\n controller = DS4Controller(index, controller_options, dynamic=dynamic)\n\n thread = Thread(target=controller.run)\n thread.daemon = True\n thread.controller = controller\n thread.start()\n\n return thread\n\n\ndef main():\n try:\n options = load_options()\n except ValueError as err:\n Daemon.exit(\"Failed to parse options: {0}\", err)\n\n if options.hidraw:\n backend = HidrawBackend(Daemon.logger)\n else:\n backend = BluetoothBackend(Daemon.logger)\n\n try:\n backend.setup()\n except BackendError as err:\n Daemon.exit(err)\n\n if options.daemon:\n Daemon.fork(options.daemon_log, options.daemon_pid)\n\n threads = []\n for index, controller_options in enumerate(options.controllers):\n thread = create_controller_thread(index + 1, controller_options)\n threads.append(thread)\n\n for device in backend.devices:\n connected_devices = []\n for thread in threads:\n # Controller has received a fatal error, exit\n if thread.controller.error:\n sys.exit(1)\n\n if thread.controller.device:\n connected_devices.append(thread.controller.device.device_addr)\n\n # Clean up dynamic threads\n if not thread.is_alive():\n threads.remove(thread)\n\n if device.device_addr in connected_devices:\n backend.logger.warning(\"Ignoring already connected device: {0}\",\n device.device_addr)\n continue\n\n for thread in filter(lambda t: not t.controller.device, threads):\n break\n else:\n controller_options = ControllerAction.default_controller()\n controller_options.parent = options\n thread = create_controller_thread(len(threads) + 1,\n controller_options,\n dynamic=True)\n threads.append(thread)\n\n thread.controller.setup_device(device)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ds4drv/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":14759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"354435580","text":"# python 3 forward compatibility\nfrom __future__ import absolute_import, division, print_function\nfrom builtins import *\n#\nimport numpy as np\nfrom scipy.sparse import lil_matrix\nfrom scipy.sparse.linalg import eigs\n\ndef _maybe_truncate_above_topography(z, f):\n \"Return truncated versions of z and f if f is masked or nan.\"\n # checks on shapes of stuff\n if not z.shape == f.shape:\n raise ValueError('z and f must have the same length')\n\n fm = np.ma.masked_invalid(f)\n if fm.mask.sum()==0:\n return z, f\n\n # check to make sure the mask is only at the bottom\n #if not fm.mask[-1]:\n # raise ValueError('topography should be at the bottom of the column')\n # the above check was redundant with this one\n if fm.mask[-1] and np.diff(fm.mask).sum() != 1:\n raise ValueError('topographic mask should be monotonic')\n\n zout = z[~fm.mask]\n fout = fm.compressed()\n return zout, fout\n\ndef neutral_modes_from_N2_profile(z, N2, f0, depth=None, **kwargs):\n \"\"\"Calculate baroclinic neutral modes from a profile of buoyancy frequency.\n\n Solves the eigenvalue problem\n\n \\frac{d}{dz}\\left ( \\frac{f_0^2}{N^2} \\frac{d \\phi}{d z} \\right )\n = -\\frac{1}{L_d^2} \\phi\n\n With the boundary conditions\n\n \\frac{d \\phi}{d z} = 0\n\n at the top and bottom.\n\n Parameters\n ----------\n z : array_like\n The depths at which N2 is given. Starts shallow, increases\n positive downward.\n N2 : array_like\n The squared buoyancy frequency (units s^-2). Points below topography\n should be masked or nan.\n f0 : float\n Coriolis parameter.\n depth : float, optional\n Total water column depth. If missing will be inferred from z.\n kwargs : optional\n Additional parameters to pass to scipy.sparse.linalg.eigs for\n eigenvalue computation\n\n Returns\n -------\n zc : array_like\n The depths at which phi is defined. Different from z.\n L_d : array_like\n deformation radii, sorted descending\n phi : array_like\n vertical modes\n \"\"\"\n nz_orig = len(z)\n z, N2 = _maybe_truncate_above_topography(z, N2)\n return _neutral_modes_from_N2_profile_raw(\n z, N2, f0, depth=depth, **kwargs)\n # does it make sense to re-pad output?\n\ndef _neutral_modes_from_N2_profile_raw(z, N2, f0, depth=None, **kwargs):\n nz = len(z)\n\n ### vertical discretization ###\n\n # ~~~~~ zf[0]==0, phi[0] ~~~~\n #\n # ----- zc[0], N2[0] --------\n #\n # ----- zf[1], phi[1] -------\n # ...\n # ---- zc[nz-1], N2[nz-1] ---\n #\n # ~~~~ zf[nz], phi[nz] ~~~~~~\n\n # just for notation's sake\n # (user shouldn't worry about discretization)\n zc = z\n dzc = np.hstack(np.diff(zc))\n # make sure z is increasing\n if not np.all(dzc > 0):\n raise ValueError('z should be monotonically increasing')\n if depth is None:\n depth = z[-1] + dzc[-1]/2\n else:\n if depth <= z[-1]:\n raise ValueError('depth should not be less than maximum z')\n\n dztop = zc[0]\n dzbot = depth - zc[-1]\n\n # put the phi points right between the N2 points\n zf = np.hstack([0, 0.5*(zc[1:]+zc[:-1]), depth ])\n dzf = np.diff(zf)\n\n # We want a matrix representation of the operator such that\n # g = f0**2 * np.dot(L, f)\n # This can be put in \"tridiagonal\" form\n # 1) first derivative of f (defined at zf points, maps to zc points)\n # dfdz[i] = (f[i] - f[i+1]) / dzf[i]\n # 2) now we are at zc points, so multipy directly by f0^2/N^2\n # q[i] = dfdz[i] / N2[i]\n # 3) take another derivative to get back to f points\n # g[i] = (q[i-1] - q[i]) / dzc[i-1]\n # boundary condition is enforced by assuming q = 0 at zf = 0\n # g[0] = (0 - q[0]) / dztop\n # g[nz] = (q[nz-1] - 0) / dzbot\n # putting it all together gives\n # g[i] = ( ( (f[i-1] - f[i]) / (dzf[i-1] * N2[i-1]) )\n # -( (f[i] - f[i+1]) / (dzf[i] * N2[i])) ) / dzc[i-1]\n # which we can rewrite as\n # g[i] = ( a*f[i-1] + b*f[i] +c*f[i+1] )\n # where\n # a = (dzf[i-1] * N2[i-1] * dzc[i-1])**-1\n # b = -( ((dzf[i-1] * N2[i-1]) + (dzf[i] * N2[i])) * dzc[i-1] )**-1\n # c = (dzf[i] * N2[i] * dzc[i-1])**-1\n # for the boundary conditions we have\n # g[0] = (-f[0] + f[1]) / (dzf[0] * N2[0] * dztop)\n # g[nz] = (f[nz-1] - f[nz]) / (dzf[nz-1] * N2[nz-1] *dzbot)\n # which we can rewrite as\n # g[0] = (-a*f[0] + a*f[1])\n # a = (dzf[0] * N2[0])**-1\n # g[nz] = (b*f[nz-1] - b*f[nz])\n # b = (dzf[nz-1] * N2[nz-1])**-1\n\n # now turn all of that into a sparse matrix\n\n L = lil_matrix((nz+1, nz+1), dtype=np.float64)\n for i in range(1,nz):\n a = (dzf[i-1] * N2[i-1] * dzc[i-1])**-1\n b = -(dzf[i-1] * N2[i-1]* dzc[i-1])**-1 - (dzf[i] * N2[i] * dzc[i-1])**-1\n c = (dzf[i] * N2[i] * dzc[i-1])**-1\n L[i,i-1:i+2] = [a,b,c]\n a = (dzf[0] * N2[0] * dztop)**-1\n L[0,:2] = [-a, a]\n b = (dzf[nz-1] * N2[nz-1] * dzbot)**-1\n L[nz,-2:] = [b, -b]\n\n # this gets the eignevalues and eigenvectors\n w, v = eigs(L, which='SM')\n\n # eigs returns complex values. Make sure they are actually real\n tol = 1e-20\n np.testing.assert_allclose(np.imag(v), 0, atol=tol)\n np.testing.assert_allclose(np.imag(w), 0, atol=tol)\n w = np.real(w)\n v = np.real(v)\n\n # they are often sorted and normalized, but not always\n # so we have to do that here\n j = np.argsort(w)[::-1]\n w = w[j]\n v = v[:,j]\n\n Ld = (-w)**-0.5 / f0\n\n return zf, Ld, v\n","sub_path":"oceanmodes/baroclinic.py","file_name":"baroclinic.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"99659162","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('pronos', '0005_auto_20151001_1203'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='rule',\n name='room',\n ),\n migrations.AddField(\n model_name='room',\n name='rule',\n field=models.OneToOneField(null=True, to='pronos.Rule', blank=True),\n ),\n migrations.AlterField(\n model_name='rule',\n name='pointsForPronos',\n field=models.IntegerField(default=1),\n ),\n ]\n","sub_path":"pronos/migrations/0006_auto_20151004_1450.py","file_name":"0006_auto_20151004_1450.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"308453781","text":"from ..base_object import ObjectState, ControllableGameObject\nfrom engine.animation import Animation, Transition, AnimationHandler\nfrom interfaces.screen import Screen\nfrom engine.sprite import Sprite, SpriteCollection, SingleSprite\n\nfrom .player_gear import PlayerGear\nfrom .player_stats import PlayerStats\n\n\ndef _get_sprite(state: int, gear: PlayerGear) -> Sprite:\n sprites = SpriteCollection()\n for piece in gear:\n sprites.add(piece.get_sprite(state))\n return sprites\n\n\ndef _add_player_animations(state: int, anim_handler: AnimationHandler,\n gear: PlayerGear) -> None:\n sprite = _get_sprite(state, gear)\n\n idle = Animation(frames=[Transition(sprite, 0.1)])\n moving = idle\n attacking = idle\n\n anim_handler.add_animation(ObjectState.IDLE, idle)\n anim_handler.add_animation(ObjectState.MOVING, moving)\n anim_handler.add_animation(ObjectState.ATTACKING, attacking)\n\n\nclass Player(ControllableGameObject):\n\n def __init__(self, name: str, **kwargs):\n self.gear: PlayerGear = PlayerGear()\n self.stats: PlayerStats = PlayerStats()\n \"\"\"\n head\n shoulders\n sword\n shield\n chest\n legs\n cape\n trinket\n \"\"\"\n super().__init__(name, world_x=10, world_y=10, speed=5, **kwargs,)\n\n def load_sprites(self):\n _add_player_animations(self.state.get(), self.anim_handler, self.gear)\n\n def draw(self, screen: Screen) -> None:\n super().draw(screen)\n\n def update(self, elapsed_time: float) -> None:\n self.ctrl.move(elapsed_time)\n","sub_path":"dragex/objects/player/player_class.py","file_name":"player_class.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"262805127","text":"#!/usr/bin/python3\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# parse data\nwith open(sys.argv[1], 'r') as f:\n dat = f.readlines()\n\nsupercell_sizes, formation_energies = [], []\nfor line in dat:\n line = line.strip().split()\n supercell_size = int(line[0].split('_')[-1].split('.')[0])\n vacancy_energy = float(line[5])\n supercell_energy = float(line[-2])\n # calculate formation energy\n formation_energy = vacancy_energy -\\\n ((supercell_size * 4)**3 - 1) /\\\n (supercell_size * 4)**3 *\\\n supercell_energy\n supercell_sizes.append(supercell_size)\n formation_energies.append(formation_energy)\n\n# plot supercell size vs formation energy\nfig = plt.figure()\nplt.xlabel('supercell size')\nplt.ylabel('vacancy formation energy (eV)')\nplt.scatter(supercell_sizes, formation_energies, marker='o')\nplt.savefig('2a.png', format='png')\nplt.show()\n","sub_path":"lab1/2a/vacancy_plot.py","file_name":"vacancy_plot.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"431056857","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Ari/src/callisto-core/callisto_core/wizard_builder/migrations/0042_auto_20171101_1410.py\n# Compiled at: 2019-08-07 16:42:06\n# Size of source mod 2**32: 646 bytes\nfrom __future__ import unicode_literals\nfrom django.db import migrations, models\nimport callisto_core.wizard_builder.model_helpers\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('wizard_builder', '0041_remove_formquestion_is_dropdown')]\n operations = [\n migrations.AlterField(model_name='choice',\n name='extra_info_text',\n field=models.TextField(blank=True, null=True)),\n migrations.AlterField(model_name='choice',\n name='text',\n field=models.TextField(null=True))]","sub_path":"pycfiles/callisto-core-0.27.10.tar/0042_auto_20171101_1410.cpython-36.py","file_name":"0042_auto_20171101_1410.cpython-36.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"603198572","text":"from multiprocessing import Process\nimport time\ndef func(arg1,arg2):\n print('*'*arg1)\n time.sleep(5)\n print('*'*arg2)\n\nif __name__ == '__main__': #windos必须声明\n p_lst = []\n for i in range(10):\n p = Process(target=func, args=(10*i,20*i))\n p_lst.append(p)\n p.start() #子进程还是异步执行\n [p.join() for p in p_lst]#join()每个子进程,保证所有的子进程都结束了才执行下面这句\n print('运行完了')\n","sub_path":"Demo/s9-day37-多个子进程.py","file_name":"s9-day37-多个子进程.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"122153566","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\n\ndef getdata():\n input_word='abcde'\n w_to_id={'a':0,'b':1,'c':2,'d':3,'e':4}\n id_to_onehot={\n 0:[1,0,0,0,0],\n 1:[0,1,0,0,0],\n 2:[0,0,1,0,0],\n 3:[0,0,0,1,0],\n 4:[0,0,0,0,1]}\n xtrain=[]\n for i in 'abcde':\n xtrain.append(id_to_onehot[w_to_id[i]])\n ytrain=[]\n for i in 'bcdea':\n ytrain.append(w_to_id[i])\n xtrain=np.array(xtrain)\n xtrain=xtrain.reshape(xtrain.shape[0],1,5)\n xtrain=torch.tensor(xtrain,dtype=torch.float32)\n ytrain=torch.tensor(ytrain,dtype=torch.long)\n return xtrain,ytrain\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net,self).__init__()\n self.myrnn=nn.Sequential(\n nn.RNN(input_size=5,hidden_size=3,num_layers=1)\n )\n self.mylin=nn.Sequential(\n nn.Linear(3,5),\n nn.Softmax(dim=1)\n )\n def forward(self,x):\n output,hn=self.myrnn(x)\n output=output.view(output.size(0),3)\n output=self.mylin(output)\n return output\n\n#data\nxtrain,ytrain=getdata()\n#net\nnet=Net()\n#optimzer\nopt=torch.optim.SGD(net.parameters(),lr=0.1)\n#loss\nloss_func=nn.CrossEntropyLoss()\n#train\nlosslist=[]\nfor i in range(1000):\n out=net(xtrain)\n loss=loss_func(out,ytrain)\n opt.zero_grad()\n loss.backward()\n opt.step()\n losslist.append(loss.item())\n print('%s,%4.3f'%(i,loss))\ntorch.save(net,'net1.pkl')\n##plot\nlosslist=np.array(losslist)\nplt.plot(losslist)\nplt.title('loss1')\nplt.savefig('loss1.jpg',dpi=256)\nplt.close()\n##predit\nout=net(xtrain)\nout=torch.max(out,1)[1].data.numpy()\nprint(out)\nfor i in range(xtrain.shape[0]):\n x0=xtrain[i,...]\n out0=out[i]\n y0=ytrain[i].numpy()\n print(x0,y0,out0)\n","sub_path":"RNN/code/code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"300782618","text":"from typing import Dict, List, Union\n\nimport numpy as np\n\nfrom libbench.rigetti import Benchmark as RigettiBenchmark\n\nfrom .job import RigettiSchroedingerMicroscopeJob\nfrom .. import SchroedingerMicroscopeBenchmarkMixin\n\n\nclass RigettiSchroedingerMicroscopeBenchmarkBase(\n SchroedingerMicroscopeBenchmarkMixin, RigettiBenchmark\n):\n def get_jobs(self):\n yield from RigettiSchroedingerMicroscopeJob.job_factory(\n self.num_post_selections,\n self.num_pixels,\n self.xmin,\n self.xmax,\n self.ymin,\n self.ymax,\n self.num_shots,\n )\n\n def __str__(self):\n return \"Forest-SchroedingerMicroscope\"\n\n\nclass RigettiSchroedingerMicroscopeSimulatedBenchmark(RigettiSchroedingerMicroscopeBenchmarkBase):\n \"\"\"\n Statevector simulator\n \"\"\"\n\n def parse_result(self, job, result):\n psi = result.amplitudes\n\n psp = np.linalg.norm(psi[:2]) ** 2\n z = np.abs(psi[1]) ** 2 / psp if psp > 0 else 0\n\n return {\"psp\": psp, \"z\": z}\n\n\nclass RigettiSchroedingerMicroscopeBenchmark(RigettiSchroedingerMicroscopeBenchmarkBase):\n \"\"\"\n Measure and run\n \"\"\"\n\n def parse_result(self, job, result):\n \"\"\"\n initially results are in the form qubit : measurement-outcomes\n {\n 0: array([1, 0, 0, 1, 1, 1, 1, 0, 1, 0]),\n 1: array([1, 0, 1, 1, 1, 0, 1, 0, 1, 0]),\n 2: array([1, 0, 0, 1, 1, 1, 1, 0, 1, 0])\n }\n so each column represents one joint measurement outcome; selecting only a subset of the qubits\n effectively means measuring only a subset, ignoring the rest\n \"\"\"\n counts = {}\n qubits = 2 ** self.num_post_selections\n for measurement in np.vstack([result[k] for k in range(qubits)]).T:\n key = \"\".join([\"0\" if b == 0 else \"1\" for b in measurement])\n if key in counts:\n counts[key] += 1\n else:\n counts[key] = 1\n\n failure_post_process_key = \"0\" + \"0\" * (2 ** self.num_post_selections - 1)\n success_post_process_key = \"1\" + \"0\" * (2 ** self.num_post_selections - 1)\n num_post_selected_failures = (\n counts[failure_post_process_key] if failure_post_process_key in counts else 0\n )\n num_post_selected_successes = (\n counts[success_post_process_key] if success_post_process_key in counts else 0\n )\n num_post_selected = num_post_selected_failures + num_post_selected_successes\n psp = num_post_selected / self.num_shots\n z = num_post_selected_successes / num_post_selected if num_post_selected > 0 else 0\n\n return {\"psp\": psp, \"z\": z}\n","sub_path":"benchmarks/Schroedinger-Microscope/rigetti/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"614224456","text":"\"\"\"empty message\n\nRevision ID: a4ff0ba9384a\nRevises: \nCreate Date: 2020-02-17 18:22:21.183812\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a4ff0ba9384a'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('answers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('value', sa.Text(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('value')\n )\n op.create_table('ranges',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('min', sa.Integer(), nullable=True),\n sa.Column('max', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(), nullable=False),\n sa.Column('email', sa.String(), nullable=False),\n sa.Column('google_token', sa.Text(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('google_token'),\n sa.UniqueConstraint('username')\n )\n op.create_table('fields',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('owner_id', sa.Integer(), nullable=True),\n sa.Column('field_type', sa.SmallInteger(), nullable=False),\n sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ondelete='SET NULL'),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name', 'owner_id', name='unique_name_owner')\n )\n op.create_table('forms',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('owner_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('title', sa.String(), nullable=False),\n sa.Column('result_url', sa.Text(), nullable=True),\n sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('owner_id', 'name', name='owner_form_name')\n )\n op.create_table('choice_options',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('field_id', sa.Integer(), nullable=True),\n sa.Column('option_text', sa.Text(), nullable=False),\n sa.ForeignKeyConstraint(['field_id'], ['fields.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('field_id', 'option_text', name='unique_field_option_text')\n )\n op.create_table('fields_range',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('field_id', sa.Integer(), nullable=False),\n sa.Column('range_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['field_id'], ['fields.id'], ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['range_id'], ['ranges.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('field_id')\n )\n op.create_table('form_fields',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('form_id', sa.Integer(), nullable=False),\n sa.Column('field_id', sa.Integer(), nullable=False),\n sa.Column('question', sa.Text(), nullable=False),\n sa.Column('position', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['field_id'], ['fields.id'], ),\n sa.ForeignKeyConstraint(['form_id'], ['forms.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('form_id', 'position', name='unique_form_position')\n )\n op.create_table('form_results',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('answer', sa.JSON(), nullable=False),\n sa.Column('form_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['form_id'], ['forms.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('settings_autocomplete',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('data_url', sa.Text(), nullable=False),\n sa.Column('sheet', sa.Text(), nullable=False),\n sa.Column('from_row', sa.String(), nullable=True),\n sa.Column('to_row', sa.String(), nullable=True),\n sa.Column('field_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['field_id'], ['fields.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('settings_strict',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('is_strict', sa.Boolean(), nullable=True),\n sa.Column('field_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['field_id'], ['fields.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('field_id', name='unique_field')\n )\n op.create_table('shared_fields',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('field_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['field_id'], ['fields.id'], ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('user_id', 'field_id', name='unique_user_field')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('shared_fields')\n op.drop_table('settings_strict')\n op.drop_table('settings_autocomplete')\n op.drop_table('form_results')\n op.drop_table('form_fields')\n op.drop_table('fields_range')\n op.drop_table('choice_options')\n op.drop_table('forms')\n op.drop_table('fields')\n op.drop_table('users')\n op.drop_table('ranges')\n op.drop_table('answers')\n # ### end Alembic commands ###\n","sub_path":"src/migrations/versions/a4ff0ba9384a_.py","file_name":"a4ff0ba9384a_.py","file_ext":"py","file_size_in_byte":5763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"580934593","text":"from flask import Flask, jsonify, render_template, url_for, request, session, redirect, flash\nfrom bson.objectid import ObjectId\nfrom flask_pymongo import PyMongo\nfrom collections import Counter\nfrom OpenSSL import SSL\nimport bcrypt\nimport ast\n\napp = Flask(__name__)\napp.secret_key = 'helloworld'\napp.config['TEMPLATES_AUTO_RELOAD'] = True \n\napp.config['MONGO_DBNAME'] = 'quickeats'\napp.config['MONGO_URI'] = 'mongodb://localhost:27017/quickeats'\n\nmongo = PyMongo(app)\n\n\n@app.route('/')\ndef index():\n if 'username' in session:\n return render_template('home.html')\n return render_template('index.html')\n\n\n@app.route('/login', methods=['POST'])\ndef login():\n users = mongo.db.users\n login_user = users.find_one({'username':request.form['username']})\n\n if login_user:\n if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password']) == login_user['password']:\n session['username'] = request.form['username']\n session['user_type'] = mongo.db.users.find_one({'username':request.form['username']})['user_type']\n user_type = session['user_type']\n session['cart'] = []\n if user_type == 'chauffeur':\n mongo.db.users.update({'username':session['username']}, {\"$set\":{'on_clock':True}})\n return redirect(url_for('home'))\n return 'Invalid username/password combination'\n\n return 'Invalid username/password combination'\n\n\n@app.route('/register', methods=['POST', 'GET'])\ndef register():\n if request.method == 'POST':\n users = mongo.db.users\n existing_user = users.find_one({'username':request.form['username']})\n\n if existing_user is None:\n hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())\n\n # User Creation by user_type\n if request.form['user_type'] == 'patron':\n users.insert({\n 'username':request.form['username'], \n 'password':hashpass, \n 'address':request.form['address'], \n 'city':request.form['city'], \n 'state':request.form['state'],\n 'user_type':request.form['user_type']\n })\n elif request.form['user_type'] == 'captain':\n users.insert({\n 'username':request.form['username'], \n 'password':hashpass, \n 'restaurant':request.form['restaurant'],\n 'user_type':request.form['user_type']\n })\n elif request.form['user_type'] == 'buddy':\n users.insert({\n 'username':request.form['username'], \n 'password':hashpass, \n 'restaurant':request.form['restaurant'],\n 'user_type':request.form['user_type']\n })\n elif request.form['user_type'] == 'chauffeur':\n users.insert({\n 'username':request.form['username'], \n 'password':hashpass, \n 'user_type':request.form['user_type'],\n 'on_clock':True\n })\n elif request.form['user_type'] == 'nerd':\n users.insert({\n 'username':request.form['username'],\n 'password':hashpass,\n 'user_type':request.form['user_type']\n })\n else: \n users.insert({\n 'username':request.form['username'],\n 'password':hashpass,\n 'user_type':request.form['user_type']\n })\n \n # Create Session variables when Registering\n session['username'] = request.form['username']\n session['user_type'] = request.form['user_type']\n session['cart'] = []\n return redirect(url_for('home'))\n\n return 'That username already exists!'\n\n return render_template('register.html')\n\n\n@app.route('/home/')\ndef home(username=None):\n if 'username' in session:\n return render_template('home.html', username=session['username'])\n else:\n return redirect('/')\n\n\n@app.route('/menu/')\ndef menu():\n menu = {}\n for item in mongo.db.menu.find():\n menu.update({\n item['entree']: {\n 'description':item['description'],\n 'cost': item['cost'], \n 'img': item['img'] \n }\n })\n\n # If Buddy, then adds 'Add Menu Item' button \n if 'user_type' in session:\n return render_template('menu.html',menu=menu, user_type=session['user_type'])\n else:\n return render_template('menu.html',menu=menu)\n\n\n@app.route('/orders/')\ndef orders():\n if 'username' in session:\n user = mongo.db.users.find_one({'username':session['username']})\n\n # If Buddy, shows orders that need to be completed\n if user['user_type'] == 'buddy':\n orders = {}\n for item in mongo.db.orders.find({'restaurant':user['restaurant'], 'completed':False}):\n order_id = str(item['_id'])\n orders.update({\n order_id: {\n 'entree':item['entree'],\n 'address':item['address'],\n 'cost':item['cost'],\n 'restaurant':item['restaurant'],\n 'completed':item['completed']\n }\n })\n \n return render_template('orders.html',orders=orders, user_type=user['user_type'])\n\n # If Chauffeur, shows orders than need to be completed\n if user['user_type'] == 'chauffeur':\n orders = {}\n for item in mongo.db.orders.find({'completed':False, 'requested_delivery':True}):\n order_id = str(item['_id'])\n orders.update({\n order_id: {\n 'entree':item['entree'],\n 'address':item['address'],\n 'cost':item['cost'],\n 'restaurant':item['restaurant'],\n 'completed':item['completed']\n }\n })\n \n return render_template('orders.html',orders=orders, user_type=user['user_type'])\n\n # Everyone else, just shows orders\n orders = {}\n for item in mongo.db.orders.find({'username':session['username']}):\n order_id = str(item['_id'])\n orders.update({\n order_id: {\n 'entree':item['entree'],\n 'address':item['address'],\n 'cost':item['cost'],\n 'completed':item['completed']\n }\n })\n #return jsonify(orders)\n return render_template('orders.html',orders=orders)\n else: \n #TODO Make Prettier, can use flash() and redirect maybe\n return render_template('login_error.html')\n\n\n@app.route('/purchase/<string:entree>')\ndef purchase(entree):\n \"\"\"\n Cart is implemented using Session\n Cart is a list of items picked from menu in session['cart']\n cart = { entree: {'description':'string', 'cost':value, etc.}}\n \"\"\"\n if session:\n cart = session['cart']\n cart.append(entree)\n session['cart'] = cart\n return redirect('/menu/')\n else:\n cart = []\n cart.append(entree)\n session['cart'] = cart\n return redirect('/menu/')\n\n\n@app.route('/cart/')\ndef cart():\n \"\"\"\n Cart is implemented using Session\n Cart is a list of items picked from menu in session['cart']\n cart = { entree: {'description':'string', 'cost':value, etc.}}\n \"\"\"\n if session:\n\n local_cart = session['cart']\n\n # Turns array into Dict. {item:count}\n temp_cart = Counter(local_cart)\n cart = {}\n total = 0.0\n\n for entree, count in temp_cart.items():\n for item in mongo.db.menu.find({'entree':entree}):\n total = total + float(item['cost']) * float(count)\n cart.update({\n item['entree']:{\n 'description': item['description'],\n 'cost': item['cost'], \n 'image': item['img'],\n 'count': count,\n 'restaurant': item['restaurant']\n # Need to add zip to cart maybe?\n #{'zip': item['zip']}\n }\n })\n \n return render_template('cart.html', cart=cart, total=total)\n\n else:\n return render_template('login_error.html')\n\n@app.route('/add_item')\ndef add_item():\n # Add Menu Item (Buddy)\n return render_template('add_item.html')\n\n\n@app.route('/add_menu_item', methods=['POST'])\ndef add_menu_item():\n if request.method == 'POST':\n restaurant = mongo.db.users.find_one({'username':session['username']})['restaurant']\n menu = mongo.db.menu\n menu.insert({\n 'entree':request.form['entree'],\n 'description':request.form['description'],\n 'cost':request.form['cost'],\n 'img':request.form['image'],\n 'restaurant':restaurant\n })\n return redirect(url_for('menu'))\n\n\n@app.route('/deliver/<string:object_id>')\ndef deliver(object_id):\n object_id = ObjectId(object_id)\n mongo.db.orders.update({'_id':object_id}, {\"$set\":{'requested_delivery':True}})\n return redirect('/orders/')\n\n\n@app.route('/complete_order/<string:object_id>')\ndef complete_order(object_id):\n object_id = ObjectId(object_id)\n mongo.db.orders.update({'_id':object_id}, {\"$set\":{'completed':True}})\n return redirect('/orders/')\n\n\n@app.route('/pay/', methods=['POST'])\ndef pay():\n #output = [request.form['total'], request.form['cart']]\n #return jsonify(output)\n return render_template('pay.html', total=request.form['total'], cart=request.form['cart'])\n\n\n@app.route('/process', methods=['POST'])\ndef process():\n # Converts to Dict.\n cart = ast.literal_eval(request.form['cart'])\n \"\"\"\n Cart = {item key:[key:value]}\n \"\"\"\n orders = mongo.db.orders\n\n if 'username' in session:\n user = mongo.db.users.find_one({'username': session['username']})\n \n for key, value in cart.items():\n orders.insert({\n 'username':session['username'],\n 'entree':key,\n 'address':user['address'], \n 'cost':value['cost'],\n 'count':value['count'],\n 'restaurant':value['restaurant'],\n 'completed':False,\n 'requested_delivery':False,\n 'paid':True\n })\n\n return redirect('/orders/')\n else:\n # Anonymous Customer\n # Need to have user add Address\n for key, value in cart.items():\n orders.insert({\n 'username':'anonymous',\n 'entree':key,\n 'address':'anonymous', \n 'cost':value['cost'],\n 'count':value['count'],\n 'restaurant':value['restaurant'],\n 'completed':False,\n 'requested_delivery':False,\n 'paid':True\n })\n return redirect('/menu/')\n\n return 'An Error Has Occured - Pablo'\n\n@app.route('/logout')\ndef logout():\n if 'user_type' in session:\n # If Chauffeur, Chauffeur if 'off the clock'\n if session['user_type'] == 'chauffeur':\n mongo.db.users.update({'username':session['username']}, {\"$set\":{'on_clock':False}})\n session.clear()\n return redirect('/')\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\nif __name__ == '__main__':\n app.jinja_env.cache = {}\n # SSL Connection\n context = ('server.crt', 'server.key')\n app.run(host='127.0.0.1', port='5000', debug=True, ssl_context='adhoc')\n","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":12066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"483728405","text":"import re\r\n\r\n\r\nclass Stack:\r\n \"\"\"\r\n prosta klasa stosu\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self.items = []\r\n\r\n def is_empty(self):\r\n return self.items == []\r\n\r\n def push(self, item):\r\n self.items.append(item)\r\n\r\n def pop(self):\r\n return self.items.pop()\r\n\r\n def size(self):\r\n return len(self.items)\r\n\r\n\r\nclass TreeNode: # węzeł drzewa (w tym korzeń lub liść)\r\n \"\"\"\r\n klasa węzła\r\n hidden value - wartosc wezla i tego co pod nim sie znajduje\r\n der - pochodna wezla i tego co pod nia sie znajduje\r\n left - lewa odnoga, right - prawa\r\n drzewo buduje zawsze najpierw prawe dziecko\r\n\r\n w przypadku funkcji zlozonej ma jedynie prawe dziecko (czesto pojawia sie w 'if')\r\n \"\"\"\r\n def __init__(self, value, hidden_value=None, der=None, left=None, right=None, parent=None):\r\n # TreeNode(\"+\")\r\n self.payload = value # zawartość węzła (liczba / operator / funkcja)\r\n self.der = der # pochodna węzła\r\n # wartosc wezla i tego co pod nim (zrobic cos z tym)\r\n self.hidden_value = hidden_value\r\n self.left_child = left\r\n self.right_child = right\r\n self.parent = parent\r\n self.quantity = 1 # nakładanie się węzłów\r\n\r\n def has_left_child(self):\r\n return self.left_child\r\n\r\n def has_right_child(self):\r\n return self.right_child\r\n\r\n def is_left_child(self):\r\n # sprawdza czy jest lewym dzieckiem\r\n return self.parent and self.parent.left_child == self\r\n\r\n def is_right_child(self):\r\n # sprawdza czy jest prawym dzieckiem\r\n return self.parent and self.parent.right_child == self\r\n\r\n def is_root(self):\r\n # korzeń: brak rodzica\r\n return not self.parent\r\n\r\n def is_leaf(self):\r\n # liść: brak dzieci\r\n return not (self.right_child or self.left_child)\r\n\r\n def has_any_children(self):\r\n return self.right_child or self.left_child\r\n\r\n def has_both_children(self):\r\n return self.right_child and self.left_child\r\n\r\n def replace_data(self, value, hidden_value=None, der=None, left=None, right=None):\r\n # zmiana danych węzła\r\n self.payload = value\r\n self.left_child = left\r\n self.right_child = right\r\n self.der = der\r\n self.hidden_value = hidden_value\r\n if self.has_left_child():\r\n self.left_child.parent = self\r\n if self.has_right_child():\r\n self.right_child.parent = self\r\n\r\n\r\nclass ParseTree:\r\n \"\"\"\r\n klasa drzewa binarnego\r\n przyjmuje wyrazenie (niekoniecznie z nawiasami!!)\r\n \"\"\"\r\n def __init__(self, expression, dx='x'):\r\n self.dx = dx # po tym całkujemy\r\n self.root = TreeNode(expression) # korzeń\r\n self.logarithms = [] # listy wziętych funkcji zlozonych\r\n self.sines = [] # sinusy\r\n self.cosines = [] # cosinusy\r\n self.exponents = [] # exp\r\n self.tans = [] # tangensy\r\n self.signs = ['*', '/', '+', '-']\r\n self.funs = ['L', 'S', 'C', 'E', 'T']\r\n self.digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, self.dx, 'm']\r\n\r\n def put(self, value, current_node, side='right'):\r\n # podrzucanie dziecka lewego bądź prawego, uzywane w self.auto_build\r\n if side == 'left':\r\n current_node.left_child = TreeNode(value, parent=current_node)\r\n else:\r\n current_node.right_child = TreeNode(value, parent=current_node)\r\n\r\n def auto_build(self, node):\r\n \"\"\"\r\n rekurencyjna metoda budowania drzewa\r\n \"\"\"\r\n self.complex_fun_sub(node)\r\n self.correction(node)\r\n\r\n if node.has_right_child(): # było budowane wcześniej\r\n return self.auto_build(node.right_child)\r\n elif node.has_left_child():\r\n return self.auto_build(node.left_child)\r\n else: # jest liściem\r\n expression, left_kid, right_kid = self.split(node)\r\n # jesli da sie rozdzielić na a+b a*b a/b a-b\r\n if (left_kid is not None) and (right_kid is not None):\r\n node.payload = expression\r\n self.put(right_kid, node, 'right')\r\n self.put(left_kid, node, 'left')\r\n\r\n self.auto_build(node.right_child)\r\n self.auto_build(node.left_child)\r\n\r\n else:\r\n if node.payload in self.funs: # dla L S C E T\r\n self.complex_fun_developing(node) # ściągamy z listy pobranych log,sin itd\r\n self.auto_build(node.right_child)\r\n else: # stała bądź x, bądź x^n\r\n node.hidden_value = node.payload # dodajemy hidden value dla liści\r\n print(node.hidden_value)\r\n\r\n def complex_fun_sub(self, node):\r\n \"\"\"\"\r\n to jest potrzebne glownie przez idee dzialania programu niezaleznie od nawiasow, w metodzie correction\r\n zamieniamy + na )+( itd przy czym najpierw trzeba zabrac funkcje zlozone bo log(2+x) zamieniloby sie na\r\n log(2)+(x)\r\n \"\"\"\r\n expression = node.payload\r\n\r\n self.logarithms.extend(re.findall(r'log\\((.*?)\\)', expression))\r\n for n in range(len(self.logarithms)):\r\n self.logarithms[n] = bracket_repair_for_complex_fun(self.logarithms[n]) # naprawiamy dla log(log(x)) itd\r\n expression = \"L\".join(expression.split(f'log({self.logarithms[n]})', 1))\r\n self.sines.extend(re.findall(r'sin\\((.*?)\\)', expression))\r\n for n in range(len(self.sines)):\r\n self.sines[n] = bracket_repair_for_complex_fun(self.sines[n])\r\n expression = \"S\".join(expression.split(f'sin({self.sines[n]})', 1))\r\n\r\n self.cosines.extend(re.findall(r'cos\\((.*?)\\)', expression))\r\n for n in range(len(self.cosines)):\r\n self.cosines[n] = bracket_repair_for_complex_fun(self.cosines[n])\r\n expression = \"C\".join(expression.split(f'cos({self.cosines[n]})', 1))\r\n\r\n self.exponents.extend(re.findall(r'exp\\((.*?)\\)', expression))\r\n self.exponents.extend(re.findall(r'e\\^\\((.*?)\\)', expression))\r\n for n in range(len(self.exponents)):\r\n self.exponents[n] = bracket_repair_for_complex_fun(\r\n self.exponents[n])\r\n expression = expression.replace(f'exp({self.exponents[n]})', 'E').replace(f'e^({self.exponents[n]})', 'E')\r\n\r\n self.tans.extend(re.findall(r'tan\\((.*?)\\)', expression))\r\n for n in range(len(self.tans)):\r\n self.tans[n] = bracket_repair_for_complex_fun(self.tans[n])\r\n expression = \"T\".join(expression.split(f'tan({self.tans[n]})', 1))\r\n node.payload = expression\r\n\r\n def complex_fun_developing(self, node):\r\n # rozwija wczesniej zabrane funkcje\r\n if node.payload == 'L':\r\n node.payload = 'log'\r\n self.put(self.logarithms.pop(), node, 'right')\r\n elif node.payload == 'S':\r\n node.payload = 'sin'\r\n self.put(self.sines.pop(), node, 'right')\r\n elif node.payload == 'C':\r\n node.payload = 'cos'\r\n self.put(self.cosines.pop(), node, 'right')\r\n elif node.payload == 'E':\r\n node.payload = 'exp'\r\n self.put(self.exponents.pop(), node, 'right')\r\n elif node.payload == 'T':\r\n node.payload = 'tan'\r\n self.put(self.tans.pop(), node, 'right')\r\n\r\n def first_correction(self, node): # pierwsza korekta (wykonywana tylko raz, pozniej osobno dla L,S,C,E)\r\n # pierwsze poprawki dla wyrazenia\r\n expression = node.payload\r\n expression = expression.replace(' ', '').replace(\r\n '**', '^').replace('ln', 'log') # wywalamy spacje itd\r\n\r\n funs = ['log', 'sin', 'cos', 'exp', 'tan']\r\n for digit in self.digits: # 2x -> 2*x ; 4( -> 4*( ; 3log -> 3*log\r\n expression = expression.replace(f'{digit}{self.dx}', f'{digit}*{self.dx}')\\\r\n .replace(f'{digit}(', f'{digit}*(')\r\n for fun in funs:\r\n expression = expression.replace(f'{digit}{fun}', f'{digit}*{fun}')\r\n node.payload = expression\r\n\r\n def correction(self, node): # po zamianie log na L\r\n # rozne takie .replace, staralismy sie zeby liczylo pochodną nawet jesli sie nie da nawiasow\r\n expression = node.payload\r\n expression = f'({expression})'\r\n expression = expression.replace(f'(-{self.dx}', f'(m1{self.dx}')\r\n expression = expression.replace('(-', '(m')\r\n for sign in self.signs:\r\n expression = expression.replace(f'{sign}', f'){sign}(')\r\n for digit in self.digits: # 2x -> 2*x ; 4( -> 4*( ; 3log -> 3*log\r\n expression = expression.replace(f'{digit}{self.dx}', f'{digit})*({self.dx}')\\\r\n .replace(f'{digit}(', f'{digit}*(')\r\n for fun in self.funs:\r\n expression = expression.replace(f'{digit}{fun}', f'{digit})*({fun}')\r\n node.payload = expression\r\n\r\n def split(self, node): # tutaj parsujemy i rozdzielamy względem +-, pozniej */, pozniej\r\n \"\"\"\r\n funkcja zwraca kolejno: zawartość węzła, lewego dziecka, prawego dziecka\r\n \"\"\"\r\n expression = node.payload\r\n base = list(expression)\r\n openers_stack = Stack()\r\n # openers_stack.items = []\r\n signs = ['+', '-', '*', '/']\r\n sign_places = {}\r\n if [el for el in signs if el in base] != []: # != zamiast 'is not' bo 'is not' nie działa\r\n # gdy wyrazenie zawiera +-/*\r\n for n in range(len(base)):\r\n element = base[n]\r\n if element is '(':\r\n openers_stack.push(1)\r\n elif element is ')':\r\n openers_stack.pop()\r\n else:\r\n if not openers_stack.is_empty(): # gdy nie skończyły sie nawiasy\r\n pass\r\n else: # zostaja same znaki +-*/\r\n sign_places.update({element: base.index(element, n)})\r\n # tym sposobem dostajemy *+-/ najbardziej na prawo\r\n if len(sign_places) == 0: # expression = L,S,C,E, T, stała lub x\r\n if bracket_deleter(expression) == expression:\r\n node.payload = expression\r\n return expression, None, None\r\n else: # gdy zamiast (x)+(2) jest ((x)+(2))\r\n # usuwamy zewnetrzna ramke i powtarzamy\r\n node.payload = bracket_deleter(expression)\r\n return self.split(node)\r\n else: # gdy są * , / , + , -\r\n final_place = []\r\n for sign in signs[0:2]: # dodajemy miejsca + i -\r\n if sign in sign_places:\r\n final_place.append(sign_places[sign])\r\n if len(final_place) > 0:\r\n return expression[max(final_place)], expression[:max(final_place)], expression[max(final_place)+1:]\r\n else:\r\n for sign in signs[2:]: # dodajemy miejsca * i /\r\n if sign in sign_places:\r\n final_place.append(sign_places[sign])\r\n return expression[max(final_place)], expression[:max(final_place)], expression[max(final_place) + 1:]\r\n\r\n def derivative(self, node):\r\n # tutaj liczymy sobie pochodną\r\n expression = node.payload\r\n expression = expression.replace('(', '').replace(')', '')\r\n if node.is_leaf():\r\n if self.dx not in expression: # pochodna stałej\r\n node.der = '0'\r\n return\r\n else:\r\n if expression == self.dx: # x\r\n node.der = '1'\r\n return\r\n elif '^' in expression:\r\n if 'm' not in expression:\r\n if expression[2:] != \"2\":\r\n try:\r\n node.der = f'{int(expression[2:])}*{self.dx}^{int(expression[2:])-1}'\r\n return\r\n except ValueError:\r\n node.der = f'{float(expression[2:])}*{self.dx}^{float(expression[2:])-1}'\r\n return\r\n else:\r\n node.der = f'2*{self.dx}'\r\n else:\r\n expression = expression.replace('m', '')\r\n try:\r\n node.der = f'm{int(expression[2:])}*{self.dx}^m{int(expression[2:])+1}'\r\n return\r\n except ValueError:\r\n node.der = f'm{float(expression[2:])}*{self.dx}^m{float(expression[2:])+1}'\r\n return\r\n elif node.has_both_children(): # dwojka dzieci to liczby pochodną każdego z nich\r\n self.derivative(node.right_child)\r\n self.derivative(node.left_child)\r\n if node.payload == '+':\r\n node.hidden_value = f'{node.left_child.hidden_value}+{node.right_child.hidden_value}'\r\n node.der = f'({node.left_child.der})+({node.right_child.der})'\r\n elif node.payload == '-':\r\n node.hidden_value = f'({node.left_child.hidden_value})-({node.right_child.hidden_value})'\r\n node.der = f'({node.left_child.der})-({node.right_child.der})'\r\n elif node.payload == '*':\r\n node.hidden_value = f'({node.left_child.hidden_value})*({node.right_child.hidden_value})'\r\n node.der = f'({node.left_child.der})*({node.right_child.hidden_value})+' \\\r\n f'({node.right_child.der})*({node.left_child.hidden_value})'\r\n elif node.payload == '/':\r\n node.hidden_value = f'({node.left_child.hidden_value})/({node.right_child.hidden_value})'\r\n node.der = f'(({node.left_child.der})*({node.right_child.hidden_value})-' \\\r\n f'({node.left_child.hidden_value})*({node.right_child.der}))/' \\\r\n f'(({node.right_child.hidden_value})*({node.right_child.hidden_value}))'\r\n return\r\n else: # ma tylko prawe dziecko -> log, exp, cos, sin\r\n self.derivative(node.right_child)\r\n if node.payload == 'log':\r\n node.hidden_value = f'log({node.right_child.hidden_value})'\r\n node.der = f'({node.right_child.der})/({node.right_child.hidden_value})'\r\n elif node.payload == 'sin':\r\n node.hidden_value = f'sin({node.right_child.hidden_value})'\r\n node.der = f'({node.right_child.der})*(cos({node.right_child.hidden_value}))'\r\n elif node.payload == 'cos':\r\n node.hidden_value = f'cos({node.right_child.hidden_value})'\r\n node.der = f'(m1)*({node.right_child.der})*(sin({node.right_child.hidden_value}))'\r\n elif node.payload == 'exp':\r\n node.hidden_value = f'exp({node.right_child.hidden_value})'\r\n node.der = f'({node.right_child.der})*(exp({node.right_child.hidden_value}))'\r\n elif node.payload == 'tan':\r\n node.hidden_value = f'tan({node.right_child.hidden_value})'\r\n node.der = f'({node.right_child.der})/((cos({node.right_child.hidden_value})/' \\\r\n f'(cos({node.right_child.hidden_value}))))'\r\n return\r\n\r\n def tree_clear(self, node):\r\n \"\"\"\r\n funkcja usuwająca 0 i podobne rzeczy z drzewa, czyści drzewo\r\n \"\"\"\r\n if node.has_right_child(): # nie jest liściem\r\n self.tree_clear(node.right_child)\r\n if node.has_left_child():\r\n return self.tree_clear(node.left_child)\r\n else: # dla liści\r\n if not node.is_root():\r\n if node.payload is '0':\r\n if node.parent.payload == 'exp': # exp(0) -> 1\r\n node.parent.payload = '1'\r\n node.parent.hidden_value = '1'\r\n node.parent.right_child = None\r\n elif node.parent.payload == 'log':\r\n raise ValueError(\"can't count log(0)\")\r\n # sin(0) -> 0\r\n elif node.parent.payload is 'sin' or node.parent.payload is '*':\r\n node.parent.payload = '0'\r\n node.parent.hidden_value = '0'\r\n node.parent.right_child = None\r\n node.parent.left_child = None\r\n # usuwamy rekurencyjnie kolejne 0\r\n return self.tree_clear(node.parent)\r\n elif node.parent.payload is '/':\r\n if node.parent.right_child == node:\r\n raise ZeroDivisionError(\"can't devide by 0\")\r\n else: # 0/n\r\n node.parent.payload = '0'\r\n node.parent.hidden_value = '0'\r\n node.parent.right_child = None\r\n node.parent.left_child = None\r\n # usuwamy rekurencyjnie kolejne 0\r\n return self.tree_clear(node.parent)\r\n elif node.parent.payload is '+': # zamienia + na węzeł niezerowego dziecka\r\n if node.parent.right_child == node:\r\n node.parent.replace_data(node.parent.left_child.payload,\r\n hidden_value=node.parent.left_child.hidden_value,\r\n left=node.parent.left_child.left_child,\r\n right=node.parent.left_child.right_child)\r\n else:\r\n node.parent.replace_data(node.parent.right_child.payload,\r\n hidden_value=node.parent.right_child.hidden_value,\r\n left=node.parent.right_child.left_child,\r\n right=node.parent.right_child.right_child)\r\n # usuwamy rekurencyjnie kolejne 0\r\n return self.tree_clear(node.parent)\r\n elif node.parent.payload is '-':\r\n if node.parent.right_child == node:\r\n node.parent.replace_data(node.parent.left_child.payload,\r\n hidden_value=node.parent.left_child.hidden_value,\r\n left=node.parent.left_child.left_child,\r\n right=node.parent.left_child.right_child)\r\n else:\r\n node.parent.replace_data(f'm{node.parent.right_child.payload}',\r\n hidden_value=node.parent.right_child.hidden_value,\r\n left=None, right=None)\r\n\r\n elif node.payload is \"1\": # P/1 ---> P\r\n if node.parent.payload is '/' and node.parent.right_child is node:\r\n node.parent.replace_data(node.parent.left_child.payload,\r\n hidden_value=node.parent.left_child.hidden_value,\r\n left=node.parent.left_child.left_child,\r\n right=node.parent.left_child.right_child)\r\n return self.tree_clear(node.parent)\r\n elif node.parent.payload is '*':\r\n if node.parent.right_child == node:\r\n node.parent.replace_data(node.parent.left_child.payload,\r\n hidden_value=node.parent.left_child.hidden_value,\r\n left=node.parent.left_child.left_child,\r\n right=node.parent.left_child.right_child)\r\n else:\r\n node.parent.replace_data(node.parent.right_child.payload,\r\n hidden_value=node.parent.right_child.hidden_value,\r\n left=node.parent.right_child.left_child,\r\n right=node.parent.right_child.right_child)\r\n\r\n\r\ndef bracket_repair_for_complex_fun(expression):\r\n # naprawia ramki, prosciej bylo tak niż z 're'\r\n diff = expression.count('(') - expression.count(')')\r\n if diff > 0:\r\n expression = f'{expression}{diff * \")\"}' # dodajemy koncowe nawiasy\r\n return expression\r\n\r\n\r\ndef bracket_deleter(expression):\r\n # usuwa zewnetrzne nawiasy przed policzeniem pochodnej\r\n if expression[0] == '(' and expression[-1] == ')':\r\n expression = expression[1:-1]\r\n return expression\r\n\r\n\r\ndef main(expression, dx='x', result='tree', degree=1):\r\n \"\"\"\r\n glowna funkcja, liczy n-tą pochodną, domyslnie po x,\r\n jesli chce sie miec samą pochodną zamiast drzewa tej pochodnej,\r\n trzeba zmienic result='tree' na cos innego\r\n \"\"\"\r\n tree = ParseTree(expression, dx)\r\n tree.first_correction(tree.root)\r\n tree.auto_build(tree.root)\r\n tree.tree_clear(tree.root)\r\n tree.derivative(tree.root)\r\n der = tree.root.der\r\n tree.root.hidden_value = tree.root.hidden_value.replace('m', '-')\r\n while degree > 0:\r\n tree2 = ParseTree(der, dx)\r\n tree2.first_correction(tree2.root)\r\n tree2.auto_build(tree2.root)\r\n tree2.tree_clear(tree2.root)\r\n tree2.derivative(tree2.root)\r\n tree2.root.hidden_value = tree2.root.hidden_value.replace('m', '-')\r\n degree -= 1\r\n der = tree2.root.der\r\n if result == 'tree':\r\n return tree2\r\n else:\r\n return tree2.root.hidden_value\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # '-' który nie jest operatorem zastąpiliśmy wewnątrz funkcji znakiem 'm'\r\n # example_1 = main('t*1*1/1/1 + sin(0)*2 - 0/3 + 123t^1234*0', dx='t')\r\n # print(f'derivative of t*1*1/1/1 + sin(0)*2 - 0/3 + 123t^1234*0\\n{example_1.root.hidden_value}\\n')\r\n #\r\n # example_2 = main('tan(2y)', dx='y')\r\n # print(f'derivative of tan(2y)\\n{example_2.root.hidden_value}\\n')\r\n #\r\n # example_3 = main('-t^(-3.5)', dx='t')\r\n # print(f'derivative of -t^(-3.5)\\n{example_3.root.hidden_value}\\n')\r\n #\r\n # example_4 = main('e^(2x)+exp(8x^2)')\r\n # print(f'derivative of e^(2x)+exp(8x^2)\\n{example_4.root.hidden_value}\\n')\r\n #\r\n # example_5 = main('log(log(x*y))', dx='y')\r\n # print(f'derivative of log(log(x*y))\\n{example_5.root.hidden_value}\\n')\r\n #\r\n # example_6 = main('sin(sin(y))', dx='y')\r\n # print(f'derivative of sin(sin(y))\\n{example_6.root.hidden_value}\\n')\r\n #\r\n # example_7 = main('-3/x')\r\n # print(f'derivative of -3/x\\n{example_7.root.hidden_value}\\n')\r\n\r\n # example_8 = main('x^10', degree=7)\r\n # print(f'7th derivative of x^10\\n{example_8.root.hidden_value}\\n')\r\n example = main('log(2/(x^2+1))')\r\n print(example.root.hidden_value)\r\n","sub_path":"python/derivative_on_variables.py","file_name":"derivative_on_variables.py","file_ext":"py","file_size_in_byte":23407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"529988846","text":"\"\"\"Setup for yutility\nSee: https://github.com/ynshen/yutility\n\"\"\"\n\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='yutility',\n version='0.6.3',\n description='Utility functions for development',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/ynshen/yutility/',\n author='Yuning Shen',\n author_email='ynshen23@gmail.com',\n keywords='development utility',\n package_dir={'': 'src'},\n packages=find_packages(where='src'),\n python_requires='>=3.5',\n install_requires=[],\n classifiers=[\n 'License :: OSI Approved :: MIT License'\n ],\n project_urls={\n 'Bug Reports': 'https://github.com/ynshen/yutility/issues/',\n 'Source': 'https://github.com/ynshen/yutility/',\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"643851025","text":"def breakingRecords(scores):\n i = 0\n min_score = scores[i]\n max_score = scores[i]\n min_count = 0\n max_count = 0\n\n for i in range(1, n):\n if scores[i] < min_score:\n min_score = scores[i]\n min_count += 1\n elif scores[i] > max_score:\n max_score = scores[i]\n max_count += 1\n\n return max_count, min_count\n\n\nn = int(input())\nscores = list(map(int, input().rstrip().split()))\nresult = breakingRecords(scores)\nfor i in result:\n print(i, end=\" \")","sub_path":"BreakingTheRecords.py","file_name":"BreakingTheRecords.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"194621736","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef load_data():\n # 导入房价数据\n datafile = 'housing.data'\n data = np.fromfile(datafile, sep=' ')\n # 将原始数据Reshape 并且拆分成训练集和测试集\n data = data.reshape([-1, 14])\n offset = int(data.shape[0]*0.8)\n train_data = data[:offset]\n # 归一化处理\n maximums, minimums, avgs = train_data.max(axis=0), train_data.min(axis=0), train_data.sum(axis=0) / train_data.shape[0]\n for i in range(14):\n data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])\n train_data = data[:offset]\n test_data = data[offset:]\n return train_data, test_data\n\n\nclass Network(object):\n def __init__(self, num_of_weight):\n # randn函数返回一组样本,具有标准正态分布,维度为[num_of_weight, 1]\n self.w = np.random.randn(num_of_weight, 1)\n self.b = 0.\n\n def forword(self, x): # 前向计算\n z = np.dot(x, self.w) + self.b\n return z\n\n def loss(self, z, y): # loss计算\n error = z - y\n cost = error * error\n cost = np.mean(cost)\n return cost\n\n def gradient(self, x, y): # 计算梯度\n z = self.forword(x)\n gradient_w = np.mean((z - y)*x, axis=0)\n gradient_w = gradient_w[:, np.newaxis] # [13,] -> [13, 1]\n gradient_b = np.mean((z - y), axis=0)\n return gradient_w, gradient_b\n\n def update(self, gradient_w, gradient_b, eta=0.01): # 更新参数\n self.w = self.w - eta*gradient_w\n self.b = self.b - eta*gradient_b\n\n def train(self, train_data, num_epcches, batch_size=10, eta=0.01): # 训练代码\n n = len(train_data)\n print(n)\n losses = []\n for epoch_id in range(num_epcches):\n # 在每���迭代之前,将训练数据的顺序随机打乱\n np.random.shuffle(train_data)\n # 将数据拆分,每个mini_batch包含batch_size条数据\n mini_batches = [train_data[k:k+batch_size] for k in range(0, n, batch_size)]\n # enumerate()函数将一个可遍历的数据对象组合为一个索引列表,同时列出数据下标和数据\n for iter_id, mini_batch in enumerate(mini_batches):\n x = mini_batch[:, :-1]\n y = mini_batch[:, -1:]\n z = self.forword(x)\n loss = self.loss(z, y)\n gradient_w, gradient_b = self.gradient(x, y)\n self.update(gradient_w, gradient_b, eta)\n losses.append(loss)\n print('Epoch{:3d} / iter {:3d}, loss = {:.4f}'.format(epoch_id, iter_id, loss))\n return losses\n\n\ntrain_data, test_data = load_data()\nnet = Network(13)\n# 开始训练\nlosses = net.train(train_data, batch_size=50, num_epcches=100, eta=0.01)\n# 画出损失函数变化趋势\nplot_x = np.arange(len(losses))\nplot_y = np.array(losses)\nplt.plot(plot_x, plot_y)\nplt.show()\n","sub_path":"BostonHousing/BostonHousing.py","file_name":"BostonHousing.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"8207095","text":"from pico2d import*\nimport game_framework\nimport game_world\n\nimport title_state\nimport main_state2_sunset\n\nfrom class_ARROW import ARROW\nfrom class_ITEM import ITEM\n\n#윈도우 크기\nWINX = 1600\nWINY = 1000\n#사진 크기\nSIZE = 64\n#방향별 사진\nUP,DOWN,LEFT,RIGHT = SIZE*3, SIZE*2, SIZE*1, SIZE*0\n\n#Link Run Speed\nPIXEL_PER_METER = (10.0/0.3)\nRUN_SPEED_KMPH = 16.0\nRUN_SPEED_MPM = (RUN_SPEED_KMPH*1000.0/60.0)\nRUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\nRUN_SPEED_PPS = (RUN_SPEED_MPS*PIXEL_PER_METER)\n\n#Link Action Speed\nTIME_PER_ACTION = 0.5\nACTION_PER_TIME = 1.0/TIME_PER_ACTION\nFRAMES_PER_ACTION = 8\n\n#Link Event\nUP_DOWN,DOWN_DOWN,LEFT_DOWN,RIGHT_DOWN,\\\nUP_UP,DOWN_UP,LEFT_UP,RIGHT_UP,\\\nATTACK_DOWN,ATTACK_UP,AIM_TIMER,LIFE_ZERO,CLEAR = range(13)\n\n\nkey_event_table = {\n (SDL_KEYDOWN, SDLK_w): UP_DOWN,\n (SDL_KEYDOWN, SDLK_s): DOWN_DOWN,\n (SDL_KEYDOWN, SDLK_a): LEFT_DOWN,\n (SDL_KEYDOWN, SDLK_d): RIGHT_DOWN,\n (SDL_KEYUP, SDLK_w): UP_UP,\n (SDL_KEYUP, SDLK_s): DOWN_UP,\n (SDL_KEYUP, SDLK_a): LEFT_UP,\n (SDL_KEYUP, SDLK_d): RIGHT_UP,\n (SDL_KEYDOWN, SDLK_j):ATTACK_DOWN,\n (SDL_KEYUP, SDLK_j): ATTACK_UP,\n}\n\nclass IdleState:\n\n @staticmethod\n def enter(Link, event):\n Link.frame = 0\n Link.image = load_image('Standing.png')\n\n if event == UP_DOWN:\n LINK.dir = UP\n elif event == DOWN_DOWN:\n LINK.dir = DOWN\n elif event == LEFT_DOWN:\n LINK.dir = LEFT\n elif event == RIGHT_DOWN:\n LINK.dir = RIGHT\n\n\n @staticmethod\n def exit(Link, event):\n pass\n\n @staticmethod\n def do(Link):\n Link.frame = (Link.frame + FRAMES_PER_ACTION*ACTION_PER_TIME * game_framework.frame_time) % 1\n\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, LINK.dir, SIZE, SIZE, Link.x, Link.y)\n\n\nclass RunState:\n @staticmethod\n def enter(Link, event):\n Link.image = load_image('Walking.png')\n Link.frame = 0\n\n if event == UP_DOWN:\n LINK.velocityY += RUN_SPEED_PPS\n LINK.dir = UP\n elif event == DOWN_DOWN:\n LINK.velocityY -= RUN_SPEED_PPS\n LINK.dir = DOWN\n elif event == UP_UP:\n LINK.velocityY -= RUN_SPEED_PPS\n elif event == DOWN_UP:\n LINK.velocityY += RUN_SPEED_PPS\n elif event == LEFT_DOWN:\n LINK.velocityX -= RUN_SPEED_PPS\n LINK.dir = LEFT\n elif event == RIGHT_DOWN:\n LINK.velocityX += RUN_SPEED_PPS\n LINK.dir = RIGHT\n elif event == LEFT_UP:\n LINK.velocityX += RUN_SPEED_PPS\n elif event == RIGHT_UP:\n LINK.velocityX -= RUN_SPEED_PPS\n\n @staticmethod\n def exit(Link, event):\n pass\n\n @staticmethod\n def do(Link):\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 10\n LINK.x += (LINK.velocityX*(LINK.run_speed/4+1))*game_framework.frame_time\n LINK.y += (LINK.velocityY*(LINK.run_speed/4+1))*game_framework.frame_time\n LINK.x = clamp(SIZE, LINK.x, WINX - SIZE)\n LINK.y = clamp(SIZE, LINK.y, WINY - 250)\n\n Link.check_end()\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, LINK.dir, SIZE, SIZE, Link.x, Link.y)\n\n\nclass AimState:\n @staticmethod\n def enter(Link, event):\n Link.image = load_image('Aiming.png')\n Link.frame = 0\n\n Link.timer = 0\n #Link.cur_time = get_time()\n\n Link.enable = False\n\n if event == UP_DOWN:\n LINK.dir = UP\n elif event == DOWN_DOWN:\n LINK.dir = DOWN\n elif event == LEFT_DOWN:\n LINK.dir = LEFT\n elif event == RIGHT_DOWN:\n LINK.dir = RIGHT\n\n @staticmethod\n def exit(Link, event):\n if Link.enable == False:\n Link.bgm = load_wav('ShotFail.ogg')\n Link.bgm.set_volume(50)\n Link.bgm.play()\n\n @staticmethod\n def do(Link):\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 3\n LINK.x += (LINK.velocityX*(LINK.run_speed/4+1)) * game_framework.frame_time\n LINK.y += (LINK.velocityY*(LINK.run_speed/4+1)) * game_framework.frame_time\n LINK.x = clamp(SIZE, LINK.x, WINX - SIZE)\n LINK.y = clamp(SIZE, LINK.y, WINY - 250)\n\n Link.timer += get_time() - Link.cur_time\n Link.cur_time = get_time()\n\n if Link.timer >= 0.3:\n Link.enable = True\n Link.add_event(AIM_TIMER)\n\n Link.check_end()\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, LINK.dir, SIZE, SIZE, Link.x, Link.y)\n\n\nclass AimIdleState:\n @staticmethod\n def enter(Link, event):\n\n Link.image = load_image('AimStanding.png')\n Link.frame = 0\n\n if event == UP_DOWN:\n LINK.dir = UP\n elif event == DOWN_DOWN:\n LINK.dir = DOWN\n elif event == LEFT_DOWN:\n LINK.dir = LEFT\n elif event == RIGHT_DOWN:\n LINK.dir = RIGHT\n\n\n @staticmethod\n def exit(Link, event):\n pass\n\n @staticmethod\n def do(Link):\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 1\n\n Link.check_end()\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, LINK.dir, SIZE, SIZE, Link.x, Link.y)\n\n\nclass AimRunState:\n @staticmethod\n def enter(Link, event):\n Link.image = load_image('AimWalking.png')\n Link.frame = 0\n\n if event == UP_DOWN:\n LINK.velocityY += RUN_SPEED_PPS\n LINK.dir = UP\n elif event == DOWN_DOWN:\n LINK.velocityY -= RUN_SPEED_PPS\n LINK.dir = DOWN\n elif event == UP_UP:\n LINK.velocityY -= RUN_SPEED_PPS\n elif event == DOWN_UP:\n LINK.velocityY += RUN_SPEED_PPS\n elif event == LEFT_DOWN:\n LINK.velocityX -= RUN_SPEED_PPS\n LINK.dir = LEFT\n elif event == RIGHT_DOWN:\n LINK.velocityX += RUN_SPEED_PPS\n LINK.dir = RIGHT\n elif event == LEFT_UP:\n LINK.velocityX += RUN_SPEED_PPS\n elif event == RIGHT_UP:\n LINK.velocityX -= RUN_SPEED_PPS\n\n\n @staticmethod\n def exit(Link, event):\n pass\n\n @staticmethod\n def do(Link):\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 3\n LINK.x += (LINK.velocityX*(LINK.run_speed/4+1)) * game_framework.frame_time\n LINK.y += (LINK.velocityY*(LINK.run_speed/4+1)) * game_framework.frame_time\n LINK.x = clamp(SIZE, LINK.x, WINX - SIZE)\n LINK.y = clamp(SIZE, LINK.y, WINY - 250)\n\n Link.check_end()\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, LINK.dir, SIZE, SIZE, Link.x, Link.y)\n\n\nclass ShootState:\n @staticmethod\n def enter(Link, event):\n if event == ATTACK_UP:\n if Link.enable == True:\n Link.shoot_arrow()\n\n Link.image = load_image('Shooting.png')\n Link.frame = 0\n Link.timer = 0\n #Link.cur_time = get_time()\n\n if event == UP_DOWN:\n LINK.velocityY += RUN_SPEED_PPS\n LINK.dir = UP\n elif event == DOWN_DOWN:\n LINK.velocityY -= RUN_SPEED_PPS\n LINK.dir = DOWN\n elif event == UP_UP:\n LINK.velocityY -= RUN_SPEED_PPS\n elif event == DOWN_UP:\n LINK.velocityY += RUN_SPEED_PPS\n elif event == LEFT_DOWN:\n LINK.velocityX -= RUN_SPEED_PPS\n LINK.dir = LEFT\n elif event == RIGHT_DOWN:\n LINK.velocityX += RUN_SPEED_PPS\n LINK.dir = RIGHT\n elif event == LEFT_UP:\n LINK.velocityX += RUN_SPEED_PPS\n elif event == RIGHT_UP:\n LINK.velocityX -= RUN_SPEED_PPS\n\n @staticmethod\n def exit(Link, event):\n pass\n\n @staticmethod\n def do(Link):\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 6\n\n\n if Link.enable == True:\n Link.timer += get_time() - Link.cur_time\n Link.cur_time = get_time()\n\n if Link.timer >= 1:\n Link.add_event(AIM_TIMER)\n\n else:\n Link.add_event(ATTACK_UP)\n\n\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 6\n LINK.x += (LINK.velocityX*(LINK.run_speed/4+1)) * game_framework.frame_time\n LINK.y += (LINK.velocityY*(LINK.run_speed/4+1)) * game_framework.frame_time\n LINK.x = clamp(SIZE, LINK.x, WINX - SIZE)\n LINK.y = clamp(SIZE, LINK.y, WINY - 250)\n\n Link.check_end()\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, LINK.dir, SIZE, SIZE, Link.x, Link.y)\n\n\nclass DieState:\n\n @staticmethod\n def enter(Link, event):\n if event == LIFE_ZERO:\n Link.image = load_image('Dieing.png')\n Link.frame = 0\n\n title_state.Bgm = load_music('GameOver.ogg')\n title_state.Bgm.set_volume(50)\n title_state.Bgm.repeat_play()\n\n Link.timer = 0\n Link.cur_time = get_time()\n\n Link.collide_able = False\n\n @staticmethod\n def exit(Link, event):\n LINK.velocityX,LINK.velocityY = 0,0\n\n @staticmethod\n def do(Link):\n if int(Link.frame) < 8:\n Link.frame = (Link.frame + FRAMES_PER_ACTION * ACTION_PER_TIME/2 * game_framework.frame_time) % 9\n\n Link.timer += get_time() - Link.cur_time\n Link.cur_time = get_time()\n\n if Link.timer >= 7:\n Link.end = True\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(int(Link.frame) * SIZE, 0, SIZE, SIZE, Link.x, Link.y)\n\n\nclass WinState:\n\n @staticmethod\n def enter(Link, event):\n Link.image = load_image('Winning.png')\n Link.frame = 0\n Link.timer = 0\n Link.cur_time = get_time()\n\n Link.collide_able = False\n\n title_state.Bgm = load_music('GameClear.ogg')\n title_state.Bgm.set_volume(50)\n title_state.Bgm.repeat_play()\n\n\n\n @staticmethod\n def exit(Link, event):\n main_state2_sunset.game_cleared = False\n LINK.velocityX,LINK.velocityY = 0,0\n\n @staticmethod\n def do(Link):\n\n Link.timer += get_time() - Link.cur_time\n Link.cur_time = get_time()\n\n if Link.timer >= 14.5:\n Link.end = True\n\n @staticmethod\n def draw(Link):\n Link.image.clip_draw(0, 0, SIZE, SIZE, Link.x, Link.y)\n\n\nnext_state_table = {\n IdleState:{UP_DOWN:RunState,DOWN_DOWN:RunState,LEFT_DOWN:RunState,RIGHT_DOWN:RunState,\n UP_UP:RunState,DOWN_UP:RunState,LEFT_UP:RunState,RIGHT_UP:RunState,\n ATTACK_DOWN:AimState,ATTACK_UP:IdleState,AIM_TIMER: IdleState,LIFE_ZERO:DieState,\n CLEAR:WinState},\n\n RunState: {UP_DOWN:RunState,DOWN_DOWN:RunState,LEFT_DOWN:RunState,RIGHT_DOWN:RunState,\n UP_UP:RunState,DOWN_UP:RunState,LEFT_UP:RunState,RIGHT_UP:RunState,\n ATTACK_DOWN:AimState,ATTACK_UP:RunState,AIM_TIMER: RunState,LIFE_ZERO:DieState,\n CLEAR: WinState},\n\n AimState:{UP_DOWN:AimRunState,DOWN_DOWN:AimRunState,LEFT_DOWN:AimRunState,RIGHT_DOWN:AimRunState,\n UP_UP:RunState,DOWN_UP:RunState,LEFT_UP:RunState,RIGHT_UP:RunState,\n ATTACK_DOWN:AimState,ATTACK_UP:RunState,AIM_TIMER:AimRunState,LIFE_ZERO:DieState,\n CLEAR: WinState},\n\n AimIdleState:{UP_DOWN:AimRunState,DOWN_DOWN:AimRunState,LEFT_DOWN:AimRunState,RIGHT_DOWN:AimRunState,\n UP_UP:AimIdleState,DOWN_UP:AimIdleState,LEFT_UP:AimIdleState,RIGHT_UP:AimIdleState,\n ATTACK_DOWN:AimIdleState,ATTACK_UP:ShootState,AIM_TIMER:AimIdleState,LIFE_ZERO:DieState,\n CLEAR: WinState},\n\n AimRunState:{UP_DOWN:AimRunState,DOWN_DOWN:AimRunState,LEFT_DOWN:AimRunState,RIGHT_DOWN:AimRunState,\n UP_UP:AimRunState,DOWN_UP:AimRunState,LEFT_UP:AimRunState,RIGHT_UP:AimRunState,\n ATTACK_DOWN:AimRunState,ATTACK_UP:ShootState,AIM_TIMER:AimRunState,LIFE_ZERO:DieState,\n CLEAR: WinState},\n\n ShootState:{UP_DOWN:RunState,DOWN_DOWN:RunState,LEFT_DOWN:RunState,RIGHT_DOWN:RunState,\n UP_UP:ShootState,DOWN_UP:ShootState,LEFT_UP:ShootState,RIGHT_UP:ShootState,\n ATTACK_DOWN:ShootState,ATTACK_UP:RunState,AIM_TIMER:RunState,LIFE_ZERO:DieState,\n CLEAR: WinState},\n\n DieState:{UP_DOWN:None,DOWN_DOWN:None,LEFT_DOWN:None,RIGHT_DOWN:None,\n UP_UP:None,DOWN_UP:None,LEFT_UP:None,RIGHT_UP:None,\n ATTACK_DOWN:None,ATTACK_UP:None,AIM_TIMER:None,LIFE_ZERO:None,\n CLEAR: None},\n\n WinState:{UP_DOWN:None,DOWN_DOWN:None,LEFT_DOWN:None,RIGHT_DOWN:None,\n UP_UP:None,DOWN_UP:None,LEFT_UP:None,RIGHT_UP:None,\n ATTACK_DOWN:None,ATTACK_UP:None,AIM_TIMER:None,LIFE_ZERO:None,\n CLEAR: None}\n\n}\n\nclass LINK:\n global Arrow\n x = WINX // 2\n y = WINY // 2\n dir = DOWN\n velocityX, velocityY = 0.0, 0.0\n life = 3\n arrow_speed = 0\n run_speed = 0\n bgm = None\n arrow = []\n cur_stage = 0\n\n def __init__(self):\n self.image = load_image('Standing.png')\n self.event_que = []\n self.cur_time = get_time()\n self.frame = 0\n self.timer = 0\n self.enable = False\n self.end = False\n self.collide_able = True\n self.cur_state = IdleState\n self.cur_state.enter(self,None)\n self.invincibility = True\n self.invincibility_time = get_time()\n self.invincibility_timer = 0\n self.invincibility_blinking = False\n\n def reset_all(self):\n LINK.x = WINX // 2\n LINK.y = WINY // 2\n LINK.dir = DOWN\n LINK.velocityX, velocityY = 0.0, 0.0\n LINK.life = 3\n LINK.arrow_speed = 0\n LINK.run_speed = 0\n LINK.bgm = None\n LINK.arrow = []\n LINK.cur_stage = 0\n LINK.dir = DOWN\n LINK.life = 3\n LINK.arrow_speed = 0\n LINK.run_speed = 0\n LINK.cur_stage = 0\n\n def check_end(self):\n if LINK.life == 0:\n self.add_event(LIFE_ZERO)\n\n if main_state2_sunset.game_cleared == True:\n main_state2_sunset.game_cleared = False\n self.add_event(CLEAR)\n\n def get_bb(self):\n return LINK.x-10,LINK.y-10,LINK.x+10,LINK.y+10\n\n def draw_ability(self):\n if ITEM.image != None:\n for i in range(LINK.life):\n ITEM.image.clip_draw(0, 2 * SIZE // 2, SIZE // 2, SIZE // 2, LINK.x-SIZE//3+ i * SIZE//3, LINK.y - SIZE*1//3,SIZE//3,SIZE//3)\n for i in range(LINK.arrow_speed):\n ITEM.image.clip_draw(0, 1 * SIZE // 2, SIZE // 2, SIZE // 2, LINK.x-SIZE//3+i * SIZE//3, LINK.y-SIZE*2//3,SIZE//3,SIZE//3)\n for i in range(LINK.run_speed):\n ITEM.image.clip_draw(0, 0 * SIZE // 2, SIZE // 2, SIZE // 2, LINK.x-SIZE//3+i * SIZE//3, LINK.y - SIZE * 3//3,SIZE//3,SIZE//3)\n\n def shoot_arrow(self):\n Arrow = ARROW(LINK.x,LINK.y,LINK.dir)\n\n LINK.arrow.append(Arrow)\n self.enable = False\n game_world.add_object(Arrow,1)\n\n self.bgm = load_wav('Shot.ogg')\n self.bgm.set_volume(50)\n self.bgm.play()\n\n def add_event(self,event):\n self.event_que.insert(0,event)\n\n def update(self):\n if self.invincibility:\n self.invincibility_timer += get_time() - self.invincibility_time\n self.invincibility_time = get_time()\n\n if self.invincibility_timer > 2:\n self.invincibility = False\n self.invincibility_timer = 0\n\n self.cur_state.do(self)\n if len(self.event_que) > 0:\n event = self.event_que.pop()\n self.cur_state.exit(self,event)\n if next_state_table[self.cur_state][event] != None:\n self.cur_state = next_state_table[self.cur_state][event]\n self.cur_state.enter(self,event)\n\n def draw(self):\n if self.invincibility:\n if self.invincibility_blinking:\n self.image.opacify(0.2)\n self.invincibility_blinking = False\n elif not self.invincibility_blinking:\n self.image.opacify(1)\n self.invincibility_blinking = True\n else:\n self.image.opacify(1)\n\n self.cur_state.draw(self)\n self.draw_ability()\n\n #draw_rectangle(*self.get_bb())\n\n def handle_event(self,event):\n if (event.type,event.key) in key_event_table:\n key_event = key_event_table[(event.type, event.key)]\n self.add_event(key_event)\n\n\n\n\n\n\n","sub_path":"프로젝트/Refactoring/class_LINK.py","file_name":"class_LINK.py","file_ext":"py","file_size_in_byte":16862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"221546211","text":"from math import log\nfrom copy import copy, deepcopy\n\nfrom automata.parsing_nfa import NULL_SEGMENT\nfrom segment_table import MORPHEME_BOUNDARY, WORD_BOUNDARY\n\nignored_segments = [NULL_SEGMENT, MORPHEME_BOUNDARY, WORD_BOUNDARY]\n\n\nclass TableCell:\n def __init__(self, output, back_pointers):\n self.output = output\n self.back_pointers = back_pointers\n\n def __repr__(self):\n return \"Output: {}, back pointers: {}\".format(self.output, \" | \".join(str(self.back_pointers)))\n\n\nclass BackPointer:\n def __init__(self, probability, state_back_pointers, position_back_pointer):\n self.probability = probability\n self.state_back_pointer = state_back_pointers\n self.position_back_pointer = position_back_pointer\n\n def __repr__(self):\n return \"{:.2f}, ({}, {})\".format(self.probability, self.state_back_pointer, self.position_back_pointer)\n\n def __str__(self):\n return self.__repr__()\n\n\ndef nfa_parser_get_all_parses(nfa, observation):\n observation = \" \" + observation + \" \"\n observation_length = len(observation)\n table = [{} for _ in range(observation_length)]\n\n # Initialize the first column\n for segment in nfa.arcs_dict.get(nfa.initial_state, []):\n for state2 in nfa.arcs_dict[nfa.initial_state][segment]:\n probability = nfa.get_probability(nfa.initial_state, segment, state2)\n back_pointer = BackPointer(probability, nfa.initial_state, -1)\n table_cell = TableCell(segment, [back_pointer])\n if probability:\n if segment in ignored_segments:\n table[0][state2] = table_cell\n elif segment == observation[1]:\n table[1][state2] = table_cell\n\n # fill out the rest of the table\n for position in range(1, observation_length):\n states = deepcopy(table[position - 1])\n while states:\n new_states = set()\n\n for state1 in states:\n if state1 in nfa.final_states:\n continue\n for segment in nfa.arcs_dict.get(state1, []):\n for state2 in nfa.arcs_dict[state1][segment]:\n probability = nfa.get_probability(state1, segment, state2)\n back_pointer = BackPointer(probability, state1, position - 1)\n table_cell = TableCell(segment, [back_pointer])\n if segment in ignored_segments:\n if state2 not in table[position - 1]:\n table[position - 1][state2] = table_cell\n new_states.add(state2)\n else:\n table[position - 1][state2].back_pointers.append(back_pointer)\n elif segment == observation[position]:\n if state2 not in table[position]:\n table[position][state2] = table_cell\n else:\n table[position][state2].back_pointers.append(back_pointer)\n states = new_states\n\n # Recursively backtrack all paths\n backward_parse_paths = []\n for final_state in nfa.final_states:\n if final_state not in table[-2]:\n continue\n parse_path(nfa, table, final_state, observation_length - 2, 0, [], backward_parse_paths)\n\n full_parse_paths = [list(reversed(_)) for _ in backward_parse_paths]\n\n return full_parse_paths\n\n\ndef parse_path(nfa, table, state, position, step, path, all_paths):\n if position == -1:\n if state == nfa.initial_state:\n path.append(state)\n all_paths.append(path)\n return\n else:\n for _back_pointer in table[position][state].back_pointers:\n _path = copy(path)\n _path.append(state)\n parse_path(nfa, table,\n _back_pointer.state_back_pointer,\n _back_pointer.position_back_pointer,\n step + 1,\n _path,\n all_paths)\n\n\ndef nfa_parser_get_most_probable_parse(nfa, observation):\n observation = \" \" + observation + \" \"\n observation = observation\n observation_length = len(observation)\n table = [{} for _ in range(observation_length)]\n\n # Initialize the first column\n for segment in nfa.arcs_dict.get(nfa.initial_state, []):\n for state2 in nfa.arcs_dict[nfa.initial_state][segment]:\n probability = nfa.get_probability(nfa.initial_state, segment, state2)\n back_pointer = BackPointer(log(probability), nfa.initial_state, 0)\n table_cell = TableCell(segment, [back_pointer])\n if probability:\n if segment in ignored_segments:\n table[0][state2] = table_cell\n elif segment == observation[1]:\n table[1][state2] = table_cell\n\n # fill out the rest of the table\n for position in range(1, observation_length):\n states = deepcopy(table[position - 1])\n while states:\n new_states = set()\n\n for state1 in states:\n if state1 in nfa.final_states:\n continue\n for segment in nfa.arcs_dict.get(state1, []):\n for state2 in nfa.arcs_dict[state1][segment]:\n probability = nfa.get_probability(state1, segment, state2)\n if probability:\n combined_probability = log(probability) + table[position - 1][state1].back_pointers[0].probability\n back_pointer = BackPointer(combined_probability, state1, position-1)\n table_cell = TableCell(segment, [back_pointer])\n if segment in ignored_segments:\n if state2 not in table[position - 1]:\n table[position - 1][state2] = table_cell\n new_states.add(state2)\n elif combined_probability > table[position-1][state2].back_pointers[0].probability:\n table[position - 1][state2] = table_cell\n new_states.add(state2)\n elif segment == observation[position]:\n if state2 not in table[position]:\n table[position][state2] = table_cell\n elif combined_probability > table[position][state2].back_pointers[0].probability:\n table[position][state2] = table_cell\n states = new_states\n\n # print_table(table, observation)\n\n optimal_final_state = None\n optimal_probability = float(\"-inf\")\n for final_state in nfa.final_states:\n if final_state in table[-2]:\n probability = table[-2][final_state].back_pointers[0].probability\n if probability > optimal_probability:\n optimal_final_state = final_state\n optimal_probability = probability\n\n if not optimal_final_state:\n return None\n\n current_state = optimal_final_state\n current_position = len(table) - 2\n backward_states_path = [current_state]\n backward_outputs_path = list()\n while True:\n current_cell = table[current_position][current_state]\n current_state = current_cell.back_pointers[0].state_back_pointer\n current_position = current_cell.back_pointers[0].position_back_pointer\n current_output = current_cell.output\n backward_states_path.append(current_state)\n backward_outputs_path.append(current_output)\n if current_state == nfa.initial_state:\n break\n\n states_path = list(reversed(backward_states_path))\n outputs_path = list(reversed(backward_outputs_path))\n return states_path, outputs_path\n\n\n# for debugging\ndef print_table(table, observation):\n print(\"table:\")\n for i, segment in enumerate(observation):\n items = list(table[i].items())\n items = sorted(items)\n items = [\"{}: {}\".format(item[0], item[1]) for item in items]\n row = \" , \".join(items)\n print(repr(segment), \"[{}]\".format(row))\n","sub_path":"source/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"530273163","text":"import argparse\nimport datetime as dt\nimport fnmatch\nimport os\nimport re\nimport sys\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\n\nreportsdir = '/home/atd2data/reports/summary'\nminversion = 0.6 # minumum version of flightSummary that can support this analysis\n\ncols = ['gufi', 'runway', 'target', 'actualOff', 'actualOut', 'Total Excess Taxi', \n\t'Ramp Excess Taxi', 'AMA Excess Taxi', 'AMA model', 'predictedDelay', \n\t'apreq', 'edct', 'Gate Hold', 'Compliance']\nrunwayVec = ['18L', '18C', '36R', '36C'] # hardcoded to CLT\n\n\ndef plot_queue(targetdate, banknum):\n\tprint(targetdate)\n\tdateVar = targetdate.strftime('%Y-%m-%d')\n\ttargetdir = os.path.join(reportsdir, '{:d}'.format(targetdate.year), '{:02d}'.format(targetdate.month), '{:02d}'.format(targetdate.day))\n\ttargetout = os.path.join('data', '{:d}'.format(targetdate.year), '{:02d}'.format(targetdate.month), '{:02d}'.format(targetdate.day), 'bank{}'.format(banknum))\n\n\t# Load flightSummary, if able\n\tffs_all = fnmatch.filter(os.listdir(targetdir), '*fullFlightSummary*')\n\tffs_AAL = fnmatch.filter(os.listdir(targetdir), '*fullFlightSummary_AAL*')\n\tffs = set(ffs_all) - set(ffs_AAL)\n\tif not ffs:\n\t\tprint('No fullFlightSummary files found. Skipping day...')\n\t\treturn\n\tversions = []\n\tfor f in ffs:\n\t\tver = re.compile('v\\d+.\\d+').findall(f)\n\t\tif len(ver) > 0:\t\n\t\t\tvernum = float(ver[0].strip('v'))\n\t\t\tversions.append(vernum)\n\tif not versions:\n\t\tprint('Version number for fullFlightSummary files not found; file to load is ambiguous. Skipping day...')\n\t\treturn\n\tlatestver = max(versions)\n\tif latestver < minversion:\n\t\tprint('fullFlightSummary version {} is less than {}. Skipping day...'.format(latestver, minversion))\n\t\treturn\n\tfor f in ffs:\n\t\tif fnmatch.fnmatch(f, '*fullFlightSummary.v{}*'.format(latestver)): \n\t\t\ttargetfile = f\n\tdfSummary = pd.read_csv(os.path.join(targetdir, targetfile), sep=',',index_col=False)\n\n\tdf_queue = pd.read_csv(os.path.join(targetout, 'summary_{}_bank{}.csv'.format(dateVar, banknum)), sep=',',index_col=False)\n\n\t#####################\n\tstMF = targetdate.strftime('%Y%m%d')\n\tmetered = True\n\ttry:\n\t\t#dfMF = pd.read_csv('~/Documents/meteredFlights/metered_flights_' + stMF + '.csv' , sep=',' , index_col=False)\n\t\tdfMF = pd.read_csv('metered_flights_{}.csv'.format(stMF), sep=',', index_col=False)\n\t\t#dfMF = pd.read_csv('~/Documents/MeteringAnalysis/Delay/data/bank2/bank2_MATM_data_2018-02-26.csv' , sep=',' , index_col=False)\n\texcept:\n\t\tprint('Metered flights output not found')\n\t\tdfMF = pd.DataFrame({'gufi':''},index=[0])\n\t\tmetered = False\n\t#####################\n\n\tidx = -1\n\tdfPlot = pd.DataFrame(np.empty((1, len(cols)), dtype=object), columns=cols)\n\tfor flight in range(len(dfSummary['gufi'])):\n\t\tif dfSummary['isDeparture'][flight] == True:\n\t\t\tif dfSummary['actual_off_bank_number'][flight] == banknum:\n\t\t\t\tidx += 1\n\t\t\t\t#excessRamp0 = (dfSummary['Actual_Ramp_Taxi_Out_Time'][flight] - dfSummary['Ramp_Taxi_Pred_at_Ramp_Taxi_Start'][flight]) / float(60)\n\t\t\t\tdfPlot.loc[idx,'gufi'] = dfSummary.loc[flight, 'gufi']\n\t\t\t\tdfPlot.loc[idx,'runway'] = dfSummary.loc[flight, 'departure_runway_position_derived']\n\t\t\t\tdfPlot.loc[idx,'Ramp Excess Taxi'] = max([0, dfSummary.loc[flight,'excess_departure_ramp_taxi_time']/float(60)])\n\t\t\t\tdfPlot.loc[idx,'AMA model'] = dfSummary.loc[flight, 'undelayed_departure_ama_transit_time']\n\t\t\t\tdfPlot.loc[idx,'AMA Excess Taxi'] = max([0, dfSummary.loc[flight, 'excess_departure_ama_taxi_time']/float(60)])\n\t\t\t\tdfPlot.loc[idx,'Total Excess Taxi'] = dfPlot.loc[idx, 'Ramp Excess Taxi'] + dfPlot.loc[idx, 'AMA Excess Taxi']\n\t\t\t\tdfPlot.loc[idx,'actualOff'] = dfSummary.loc[flight, 'departure_runway_actual_time']\n\t\t\t\tdfPlot.loc[idx,'actualOut'] = dfSummary.loc[flight, 'departure_stand_actual_time']\n\t\t\t\t\t\t\t\t\n\t\t\t\tdfPlot.loc[idx, 'apreq'] = False\n\t\t\t\tdfPlot.loc[idx, 'edct'] = False\n\t\t\t\t\n\t\t\t\tif str(dfSummary.loc[flight, 'apreq_final']) != 'nan':\n\t\t\t\t\tdfPlot.loc[idx, 'apreq'] = True\n\t\t\t\t\n\t\t\t\tif str(dfSummary.loc[flight, 'edct_final']) != 'nan':\n\t\t\t\t\tdfPlot.loc[idx, 'edct'] = True\n\t\t\t\t\n\t\t\t\tif dfSummary.loc[flight, 'hold_indicator'] == True:\n\t\t\t\t\tdfPlot.loc[idx, 'Gate Hold'] = dfSummary.loc[flight, 'actual_gate_hold']\n\n\t\t\t\t#dfCompliance = dfMF[dfMF['gufi'] == dfSummary.loc[dfSummary.index[flight], 'gufi']] # isn't this index redundant? flight is already an index \n\t\t\t\tdfCompliance = dfMF[dfMF['gufi'] == dfSummary.loc[flight, 'gufi']]\n\t\t\t\tif len(dfCompliance['gufi']) > 0:\n\t\t\t\t\t\n\t\t\t\t\tcompliance = pd.Timedelta(pd.Timestamp(dfCompliance.loc[dfCompliance.index[0],'departure_stand_actual_time']) \n\t\t\t\t\t- pd.Timestamp(dfCompliance.loc[dfCompliance.index[0],'departure_stand_surface_metered_time_value_ready'])\n\t\t\t\t\t).total_seconds() / float(60)\n\t\t\t\t\n\t\t\t\t\tif str(compliance) != 'nan':\n\t\t\t\t\t\tdfPlot.loc[idx,'Compliance'] = compliance\n\n\tdfPlot = dfPlot.sort_values(by=['actualOff'])\n\tdfPlot = dfPlot.reset_index(drop=True)\n\tfor rwy in range(len(runwayVec)):\n\t\tfor row in range(len(df_queue)):\n\t\t\tif df_queue.loc[row, 'runway'] == runwayVec[rwy]:\n\t\t\t\ttargetVec = str(df_queue.loc[row, 'target']).split('--')\n\t\t\t\ttargetTime = str(df_queue.loc[row, 'target_timestamp']).split('--')\n\t\t\t\t# print(targetVec)\n\t\t\t\t# print(targetTime)\n\t\t\n\t\t\t\tif len(targetVec) > 1:\n\t\t\t\t\tcount=0\n\t\t\t\t\tfor flight in range(len(dfPlot)):\n\t\t\t\t\t\tif dfPlot.loc[flight,'runway'] == runwayVec[rwy]:\n\t\t\t\t\t\t\t# print(pd.Timestamp(dfPlot.loc[flight,'actualOff']))\n\t\t\t\t\t\t\t# print(pd.Timestamp(targetTime[count]))\n\t\t\t\t\t\t\t# print(pd.Timedelta(pd.Timestamp(dfPlot.loc[flight,'actualOff']) - pd.Timestamp(targetTime[count]) ).total_seconds())\n\t\t\t\t\t\t\t# print(count)\n\t\t\t\t\t\t\tif count < len(targetVec) -1 :\n\t\t\t\t\t\t\t\tif pd.Timedelta(pd.Timestamp(dfPlot.loc[flight,'actualOff']) - pd.Timestamp(targetTime[count+1]) ).total_seconds() < 0:\n\t\t\t\t\t\t\t\t\tdfPlot.loc[flight,'target'] = float(targetVec[count])\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t#print('HERE')\n\t\t\t\t\t\t\t\t\tcount+=1\n\t\t\t\t\t\t\t\t\tdfPlot.loc[flight,'target'] = float(targetVec[count])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tdfPlot.loc[flight,'target'] = float(targetVec[count])\n\t\t\t\telse:\n\t\t\t\t\tfor flight in range(len(dfPlot)):\n\t\t\t\t\t\tif dfPlot.loc[flight,'runway'] == runwayVec[rwy]:\n\t\t\t\t\t\t\tdfPlot.loc[flight,'target'] = float(targetVec[0])\n\n\tfor rwy in range(len(runwayVec)):\n\t\tdf = dfPlot[ dfPlot['runway'] == runwayVec[rwy]]\n\t\t#print(df)\n\t\tdfSorted = df.sort_values(by=['actualOff'])\n\t\tdfSorted = dfSorted.reset_index(drop=True)\n\t\t\n\t\tif len(dfSorted) > 0:\n\t\t\tdfSorted.to_csv(os.path.join(targetout, 'realized_queue_{}_bank{}_{}.csv'.format(dateVar, banknum, runwayVec[rwy]))) # why is this repeated?\n\t\t\t\n\t\t\tax = dfSorted.plot(x='actualOff', y='target',figsize=(14,10))\n\t\t\t#dfSorted.plot.bar(x='actualOff', y=['Total Excess Taxi', 'AMA Excess Taxi','Ramp Excess Taxi'], color = ['cyan' , 'magenta' , 'grey'],alpha=0.6,ax=ax)\n\t\t\tdfSorted.plot.bar(x='actualOff', y=['AMA Excess Taxi','Ramp Excess Taxi'],width=0.3, position = -0.25, color = [ 'magenta' , 'grey'],alpha=0.6,ax=ax)\n\t\t\tdfSorted.plot.bar(x='actualOff', y=['Total Excess Taxi','Gate Hold'], width = 0.15, position = 0.5, stacked=True, color = [ 'cyan' , 'red'],alpha=0.6,ax=ax)\n\t\t\tdfSorted.plot.bar(x='actualOff', y=['Compliance'], width = 0.15, position = 1.5, color = [ 'blue'],alpha=0.6,ax=ax)\n\t\t\tplt.title('Runway ' + runwayVec[rwy] + ' ' + targetdate.strftime('%Y-%m-%d'))\n\t\t\tplt.ylabel('Excess Taxi Time [Minutes]')\n\t\t\tplt.xlabel('Actuall Off Time [UTC]')\n\t\t\t# minVal = 0\n\t\t\t# if dfSorted['Compliance'].min() < 0:\n\t\t\t# \tminVal = dfSorted['Compliance'].min()\n\t\t\t# if minVal < -20:\n\t\t\t# \tminVal = -20\n\t\t\tplt.ylim([-10,35])\n\t\t\t\n\t\t\tapreq_x = []\n\t\t\tapreq_y = []\n\t\t\tedct_x = []\n\t\t\tedct_y = []\n\t\t\tfor i in range(len(dfSorted)):\n\t\t\t\tif dfSorted.loc[dfSorted.index[i],'apreq'] == True:\n\t\t\t\t\tapreq_x.append(i)\n\t\t\t\t\tapreq_y.append(dfSorted.loc[dfSorted.index[i],'target'])\n\t\t\t\tif dfSorted.loc[dfSorted.index[i],'edct'] == True:\n\t\t\t\t\tedct_x.append(i)\n\t\t\t\t\tedct_y.append(dfSorted.loc[dfSorted.index[i],'target'])\n\t\t\t\n\t\t\tplt.plot(apreq_x,apreq_y,'o',markersize = 10,color='orange',label='Apreq Flight')\n\t\t\tplt.plot(edct_x,edct_y,'o',markersize = 10,color='green',label='EDCT Flight')\n\t\t\tplt.legend(loc='upper left')\n\n\t\t\tplt.tight_layout()\n\t\t\t#plt.savefig('figs/flightSpecificDelay/' + runwayVec[rwy]+dateVecIADS[date] + '.png')\n\t\t\tplt.savefig(os.path.join(targetout, 'realized_queue_fig_{}_bank{}_{}.png'.format(dateVar, banknum, runwayVec[rwy])))\n\t\t\tplt.close('all')\n\t\t\tdfSorted.to_csv(os.path.join(targetout, 'realized_queue_{}_bank{}_{}.csv'.format(dateVar, banknum, runwayVec[rwy]))) # why is this repeated?\n\n\ndef run(start_date, number_of_days, bank):\n\tfor day in range(number_of_days):\n\t\tday_start = start_date + dt.timedelta(days = day)\n\t\tplot_queue(day_start, bank)\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('startdate', help = 'Start date of analysis (YYYYMMDD)')\n\tparser.add_argument('-d', '--days', help='Number of days to run analysis, default 1', \n\t\t\ttype = int, default = 1)\n\tparser.add_argument('-b', '--bank', help='Bank number to run analysis on, default 2', \n\t\t\ttype = int, default = 2)\n\n\targs = parser.parse_args()\n \n\tstart_date = dt.datetime.strptime(args.startdate, '%Y%m%d').date()\n\n\trun(start_date, args.days, args.bank)\n","sub_path":"plot_realized_queue.py","file_name":"plot_realized_queue.py","file_ext":"py","file_size_in_byte":9208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"216892385","text":"# This model is taken from the Tensor Image classification tutorial\n# https://www.tensorflow.org/tutorials/images/classification\n# and adapted for use here.\n#\nimport tensorflow as tf\nfrom keras import regularizers\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Activation, RandomFourierFeatures\nfrom tensorflow.keras.optimizers import Adam\nimport kerastuner.engine.hypermodel as hm\n\nfrom misc import get_loss, get_optimiser, get_conv2d, get_dense\nfrom photo_models.model_args import ModelArgs\nfrom photo_models.model_misc import model_fit\n\n\ndef tf_image_eg(model_args: ModelArgs, verbose: bool = False):\n\n misc_args = model_args.misc_args\n\n # The model consists of three convolution blocks with a max pool layer in each of them.\n # There's a fully connected layer with 512 units on top of it that is activated by a relu activation function\n model = Sequential(\n _get_layers(model_args, include_top=True, verbose=verbose), name='tf_image_tl')\n\n with tf.device(model_args.device_name):\n print(f\"Using '{model_args.device_name}'\")\n\n # Compile the model\n model.compile(optimizer=get_optimiser(misc_args['run1_optimizer']),\n loss=get_loss(misc_args['run1_loss']),\n metrics=['accuracy'])\n\n history = model_fit(model, model_args, verbose=verbose, callbacks=model_args.callbacks)\n\n # can also use model.evaluate, but it gives slight differences in values (2nd decimal place) to history\n # x = model.evaluate(x=model_args.val_data, steps=step_size_valid)\n\n return history\n\n\ndef _get_layers(model_args: ModelArgs, include_top=True, verbose: bool = False):\n\n misc_args = model_args.misc_args\n for arg in ['conv2D_1', 'conv2D_2', 'conv2D_3', 'dense_1',\n 'run1_optimizer', 'run1_loss']:\n if arg not in misc_args:\n raise ValueError(f\"Missing {arg} argument\")\n # The model consists of three convolution blocks with a max pool layer in each of them.\n\n model = [\n get_conv2d(misc_args['conv2D_1'], model_args.input_shape),\n # Max pooling operation for 2D spatial data\n MaxPooling2D(),\n # 2D convolution layer\n get_conv2d(misc_args['conv2D_2']),\n # Max pooling operation for 2D spatial data\n MaxPooling2D(),\n # 2D convolution layer\n get_conv2d(misc_args['conv2D_3']),\n # Max pooling operation for 2D spatial data\n MaxPooling2D(),\n # Flattens the input. Does not affect the batch size.\n Flatten(),\n # regular densely-connected NN layer\n get_dense(misc_args['dense_1'])\n ]\n if include_top:\n model.append(Dense(model_args.class_count))\n\n return model\n\n\nclass TfImageHyperModel(hm.HyperModel):\n \"\"\"\n Keras Tuner HyperModel\n \"\"\"\n def __init__(self, model_args: ModelArgs, **kwargs):\n super(TfImageHyperModel, self).__init__(**kwargs)\n self.input_shape = model_args.input_shape\n self.class_count = model_args.class_count\n\n def build(self, hp):\n model = Sequential()\n\n model.add(Conv2D(filters=hp.Int('filters', 16, 64, 8), kernel_size=3, padding='same',\n activation=hp.Choice('activation', ['relu', 'softmax']),\n input_shape=self.input_shape))\n model.add(MaxPooling2D())\n for i in range(hp.Int('num_layers', 1, 10)):\n model.add(Conv2D(filters=hp.Int('filters', 32, 64, 8), kernel_size=3, padding='same',\n activation=hp.Choice('activation', ['relu', 'softmax'])))\n model.add(MaxPooling2D())\n model.add(Flatten())\n model.add(Dense(units=hp.Int('units', 64, 512, 32),\n activation=hp.Choice('activation', ['relu', 'softmax'])))\n model.add(Dense(self.class_count, activation='softmax'))\n\n model.compile(\n optimizer=Adam(hp.Choice('learning_rate', [1e-2, 1e-3, 1e-4])),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n return model\n\n\ndef tf_image_tuning(model_args: ModelArgs, **kwargs):\n return TfImageHyperModel(model_args, **kwargs)\n\n\ndef tf_image_eg_qsvm(model_args: ModelArgs, verbose: bool = False):\n\n misc_args = model_args.misc_args\n\n # The model consists of three convolution blocks with a max pool layer in each of them.\n # There's a fully connected layer with 512 units on top of it that is activated by a relu activation function\n model = Sequential(\n _get_layers(model_args, include_top=False, verbose=verbose), name='tf_image_tl_qsvm')\n\n model.add(RandomFourierFeatures(\n output_dim=4096, scale=10.0, kernel_initializer=\"gaussian\"\n ))\n model.add(Dense(model_args.class_count, kernel_regularizer=regularizers.l2(0.0001)))\n model.add(Activation('linear'))\n\n with tf.device(model_args.device_name):\n print(f\"Using '{model_args.device_name}'\")\n\n # Compile the model\n # model.compile(optimizer=get_optimiser(misc_args['run1_optimizer']),\n # loss=get_loss(misc_args['run1_loss']),\n # metrics=['accuracy'])\n model.compile(loss='squared_hinge',\n optimizer='adadelta', metrics=['accuracy'])\n\n history = model_fit(model, model_args, verbose=verbose, callbacks=model_args.callbacks)\n\n # can also use model.evaluate, but it gives slight differences in values (2nd decimal place) to history\n # x = model.evaluate(x=model_args.val_data, steps=step_size_valid)\n\n\n\n return history\n","sub_path":"photo_models/tf_image_eg.py","file_name":"tf_image_eg.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"407026995","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 22 11:08:10 2018\n\n@author: xinger\n\"\"\"\n\n#--------------------------------------------------------\n#import\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport jaqs_fxdayu\njaqs_fxdayu.patch_all()\nfrom jaqs.data import DataView\nfrom jaqs_fxdayu.data.dataservice import LocalDataService\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n#--------------------------------------------------------\n#define\n\nstart = 20170101\nend = 20180101\nfactor_list = ['BBI','RVI','Elder','ChaikinVolatility','EPS','PE','PS','ACCA','CTOP','MA10RegressCoeff12','AR','BR','ARBR','np_parent_comp_ttm','total_share','bps']\ncheck_factor = ','.join(factor_list)\n\ndataview_folder = r'E:/data'\nds = LocalDataService(fp = dataview_folder)\n\nSH_id = ds.query_index_member(\"000001.SH\", start, end)\nSZ_id = ds.query_index_member(\"399106.SZ\", start, end)\nstock_symbol = list(set(SH_id)|set(SZ_id))\n\ndv_props = {'start_date': start, 'end_date': end, 'symbol':','.join(stock_symbol),\n 'fields': check_factor,\n 'freq': 1,\n \"prepare_fields\": True}\n\ndv = DataView()\ndv.init_from_config(dv_props, data_api=ds)\ndv.prepare_data()\n\n\n\n#--------------------------------------------------------\n\"\"\"\ndefine factor caculation functions\n\ninput : dict\nparameter of factor\n-------\noutput : pd.DataFrame\n factor_values , Index is trade_date, columns are symbols.\n\n\"\"\"\n#------------------------------------------------------------------------------ \n#type1 - simplest type,only use add_formula function without parameter\n\ndef EPSTTM():\n EPSTTM = dv.add_formula('EPSTTM', \n \"np_parent_comp_ttm/total_share\"\n , is_quarterly=False)\n return EPSTTM \n\ndef CETOP():\n dv.add_field('ncf_oper_ttm',ds)\n dv.add_field('total_mv',ds)\n CETOP = dv.add_formula('CETOP',\"ncf_oper_ttm/total_mv\",is_quarterly=False)\n return CETOP\n\n\n#------------------------------------------------------- \n#type2 - only use add_formula function with parameter\n \ndef BBI(param = None):\n defult_param = {'t1':3,'t2':6,'t3':12,'t4':24}\n if not param:\n param = defult_param\n \n BBI = dv.add_formula('BBI_J', \n '''Ta('MA',0,open,high,low,close,volume,%s)+Ta('MA',0,open,high,low,close,volume,%s)+Ta('MA',0,open,high,low,close,volume,%s)+\n Ta('MA',0,open,high,low,close,volume,%s)/4'''%(param['t1'],param['t2'],param['t3'],param['t4']),\n is_quarterly=False)\n \n return BBI\n\n\ndef ChaikinVolatility(param = None):\n defult_param = {'t':10}\n if not param:\n param = defult_param\n \n dv.add_formula('HLEMA', \"Ta('EMA',0,high-low,high-low,high-low,high-low,high-low,10)\"\n , is_quarterly=False, add_data=True)\n \n ChaikinVolatility = dv.add_formula('ChaikinVolatility_J', \n\n \"100*(HLEMA-Delay(HLEMA,%s))/Delay(HLEMA,%s)\"%(param['t'],param['t'])\n , is_quarterly=False)\n return ChaikinVolatility\n\n\ndef EarnMom(param=None):\n default_param = {'t':7,'i':7}\n if not param:\n param = default_param\n \n EarnMom = dv.add_formula('EarnMom', \n \"Ts_Sum(Sign(oper_rev_ttm-Delay(oper_rev_ttm,%s)),%s)\"%(param['t'],param['i'])\n , is_quarterly=True, add_data=True)\n \n return EarnMom \n\n\n#------------------------------------------------------- \n#type3 - the intermediate variable of the factor is also a factor\n \n\ndef RVI(param=None,ret = 'RVI'):\n defult_param = {'t1':10,'t2':14} \n if not param:\n param = defult_param\n \n dv.add_formula('USD', \n \"If(Return(close,1)>0,StdDev(Return(close,1),%s),0)\"%(param['t1'])\n , is_quarterly=False, add_data=True)\n\n dv.add_formula('DSD', \n \"If(Return(close,1)<0,StdDev(Return(close,1),%s),0)\"%(param['t1'])\n , is_quarterly=False, add_data=True)\n \n UpRVI = dv.add_formula('UpRVI_J', \n \"Ta('EMA',0,USD,USD,USD,USD,USD,%s)\"%(param['t2'])\n , is_quarterly=False, add_data=True)\n \n DownRVI = dv.add_formula('DownRVI_J', \n \"Ta('EMA',0,DSD,DSD,DSD,DSD,DSD,%s)\"%(param['t2'])\n , is_quarterly=False, add_data=True)\n \n RVI = dv.add_formula('RVI_J', \n \"100*UpRVI_J/(UpRVI_J+DownRVI_J)\"\n , is_quarterly=False)\n \n if ret == 'RVI':\n return RVI \n elif ret =='UpRVI':\n return UpRVI \n elif ret =='DownRVI':\n return DownRVI\n\n\ndef ARBR(param = None,ret = 'ARBR'):\n defult_param = {'t':26} \n if not param:\n param = defult_param\n \n t = param['t']\n \n AR = dv.add_formula(\"AR_J\",\"Ts_Sum(high-open,%s)/Ts_Sum(open-low,%s)\"%(t,t),\n is_quarterly=False,\n add_data=True)\n \n BR = dv.add_formula(\"BR_J\",\"Ts_Sum(Ts_Max(high-Delay(close,1),0),%s)/Ts_Sum(Ts_Max(Delay(close,1)-low,0),%s)\"%(t,t),\n is_quarterly=False,\n add_data=True)\n \n ARBR = dv.add_formula(\"ARBR_J\",\"AR_J-BR_J\",\n is_quarterly=False)\n \n if ret == 'AR':\n return AR \n elif ret == 'BR':\n return BR\n elif ret == 'ARBR':\n return ARBR \n\n\n#--------------------------------------------------------- \n#type4 - caculate factor with industry category \n \ndef PSIndu(param = None):\n default_param = {'indu':'sw1'}\n if not param:\n param = default_param\n \n indu = param['indu']\n \n dv.add_field(indu,ds)\n dv.add_field('ps',ds)\n \n _indu = dv.get_ts(indu).stack()\n ps = dv.get_ts('PS').stack()\n \n ps_indu = pd.concat([_indu,ps],axis=1,keys=[indu,'ps'])\n\n Indu_mean = ps_indu.groupby([indu]).mean().ps.to_dict()\n Indu_std = ps_indu.groupby([indu]).std().ps.to_dict()\n \n ps_indu['PSIndu_Mean'] = [Indu_mean[c] for c in ps_indu[indu].values]\n ps_indu['PSIndu_Std'] = [Indu_std[c] for c in ps_indu[indu].values]\n \n ps_indu['PSIndu'] = (ps_indu['ps']-ps_indu['PSIndu_Mean'])/ps_indu['PSIndu_Std']\n \n PSIndu = ps_indu.PSIndu.unstack()\n \n dv.append_df(PSIndu, 'PSIndu')\n return dv.get_ts('PSIndu')\n\n\n\n\n\n\nfactor_list = ['EPSTTM','CETOP','BBI','ChaikinVolatility','EarnMom','RVI','ARBR','PSIndu']\n\n#--------------------------------------------------------- \n#test output\ndef test(factor,data):\n if not isinstance(data, pd.core.frame.DataFrame):\n raise TypeError('On factor {} ,output must be a pandas.DataFrame!'.format(factor))\n else:\n try:\n index_name = data.index.names[0]\n columns_name = data.index.names[0]\n except:\n if not (index_name in ['trade_date','report_date'] and columns_name == 'symbol'):\n raise NameError('''Error index name,index name must in [\"trade_date\",\"report_date\"],columns name must be \"symbol\" ''')\n \n index_dtype = data.index.dtype_str\n columns_dtype = data.columns.dtype_str\n \n if columns_dtype not in ['object','str']:\n raise TypeError('error columns type')\n \n if index_dtype not in ['int32','int64','int']:\n raise TypeError('error index type')\n\n\ntest_factor = False\n\nif test_factor: \n for factor in factor_list[5:]:\n data = globals()[factor]()\n test(factor,data)\n","sub_path":"Internship_Factor/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"61997333","text":"\neventname = ''\neventname = 'GW150914'\nplottype = 'pdf'\n\n# Standard python imports:\nimport numpy as np\nfrom scipy import signal\nfrom scipy.interpolate import interp1d\nfrom scipy.signal import butter, filtfilt, iirdesign, zpk2tf, freqz\nimport h5py\nimport json\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\n\n# LIGO-specific import:\nimport readligo as rl\n\n# Read event properties from a local json file\nfnjson = 'BBH_events_v3.json'\ntry:\n events = json.load(open(fnjson,'r'))\nexcept IOError:\n print('Cannot find resource file ' + fnjson)\n print('Quitting.')\n quit()\n\n# Check for choice of eventname:\ntry:\n events[eventname]\nexcept:\n print('You must select an eventname that is in ' + fnjson + '! Quitting.')\n quit()\n\n# Extract parameters from event:\nevent = events[eventname]\nfn_H1 = event['fn_H1']\nfn_L1 = event['fn_L1']\nfn_template = event['fn_template']\nfs = event['fs']\ntevent = event['tevent']\nfband = event['fband']\nprint('Reading in parameters for event ' + event['name'])\n#print(event)\n\n# Read in event data\ntry:\n strain_H1, time_H1, chan_dict_H1 = rl.loaddata(fn_H1, 'H1')\n strain_L1, time_L1, chan_dict_L1 = rl.loaddata(fn_L1, 'L1')\nexcept:\n print('cannot find data files!')\n print('Quitting.')\n quit()\n\n# H1 and L1 have the same time vector\ntime = time_H1\n# time interval with uniform sampling\ndt = time[1] - time[0]\n\n# select the a time window around the event\ndeltat = 5\nindxt = np.where((time >= tevent-deltat) & (time < tevent+deltat))\n\nmake_psds = 1\nif make_psds:\n # number of sample for the FFT:\n NFFT = 4*fs\n Pxx_H1, freqs = mlab.psd(strain_H1, Fs = fs, NFFT=NFFT)\n Pxx_L1, freqs = mlab.psd(strain_L1, Fs = fs, NFFT=NFFT)\n\n # interpolations of ASDs computed for whitening\n psd_H1 = interp1d(freqs, Pxx_H1)\n psd_L1 = interp1d(freqs, Pxx_L1)\n\n# The signal is dominated by low frequency noise.\n# We need to do some signal processing.\n\n\n# This function will whiten the data\ndef whiten(strain, interp_psd, dt):\n Nt = len(strain)\n freqs = np.fft.rfftfreq(Nt, dt)\n freqs1 = np.linspace(0,2048.,Nt/2+1)\n\n hf = np.fft.rfft(strain)\n norm = 1./np.sqrt(1./(dt*2))\n white_hf = hf / np.sqrt(interp_psd(freqs)) * norm\n white_ht = np.fft.irfft(white_hf, n=Nt)\n return white_ht\n\nwhiten_data = 1\nif whiten_data:\n strain_H1_whiten = whiten(strain_H1,psd_H1,dt)\n strain_L1_whiten = whiten(strain_L1,psd_L1,dt)\n\n bb, ab = butter(4, [fband[0]*2./fs, fband[1]*2./fs], btype='band')\n normalization = np.sqrt((fband[1]-fband[0])/(fs/2))\n strain_H1_whitenbp = filtfilt(bb, ab, strain_H1_whiten) / normalization\n strain_L1_whitenbp = filtfilt(bb, ab, strain_L1_whiten) / normalization\n\n\n# pick shorter FFT time interval\nNFFT = int(fs/16.0)\n# with a lot of overlap for short-time features\nNOVL = int(NFFT*15./16.)\n# choose window that minimizes 'spectral leakage'\nwindow = np.blackman(NFFT)\n\n# color map\nspec_cmap = 'ocean'\n\n# plot H1 spectrogram\nplt.figure(figsize=(10,6))\nspec_H1, freqs, bins, im = plt.specgram(strain_H1_whiten[indxt], NFFT=NFFT, Fs=fs, window=window,\n noverlap=NOVL, cmap=spec_cmap, xextent=[-deltat,deltat])\nplt.xlabel('time (s) since ' + str(tevent))\nplt.ylabel('Frequency (Hz)')\nplt.colorbar()\nplt.axis([-0.5, 0.5, 0, 500])\nplt.title('aLIGO H1 strain data near ' + eventname)\nplt.show()\n\n","sub_path":"LIGO/LOSC_Event.py","file_name":"LOSC_Event.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"180997332","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport pandas as pd\n\ndef createFolder(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\ndef checkInput(folder):\n if not os.path.isdir(folder):\n print('input directory is not found')\n return\n\ndef checkExcelFormat(name):\n FORMAT_XLSX = \".xlsx\"\n FORMAT_XLS = \".xls\"\n return name.endswith(FORMAT_XLSX) or name.endswith(FORMAT_XLS)\n\ndef checkTmpFile(name):\n return name.startswith('.') or name.startswith('~')\n\ndef getColName(index):\n if index == 0:\n return 'scapula int/ext rotation'\n elif index == 1:\n return 'scapula upward/downward rotation'\n else:\n return 'scapula anterior/posterior tipping'\n\ndef findTargetList(trigger_folder):\n each_target_list = []\n for name in os.listdir(trigger_folder):\n fileName = os.path.join(trigger_folder, name)\n if os.path.isfile(fileName) and checkExcelFormat(name) and not checkTmpFile(name):\n df = pd.read_excel(fileName, header=None)\n targets = df.iloc[26:35,0:4].values.tolist()\n for target in targets:\n each_target_list.append(target)\n return each_target_list\n\ndef findMaxByTarget(all_target_list):\n writer = pd.ExcelWriter('./output/output.xlsx')\n target_folder = \"./target\"\n results = []\n for each_target_list in all_target_list:\n print(each_target_list)\n fileName = each_target_list[0]\n for f in os.listdir(target_folder):\n if fileName in f and 'rmBaseline' in f and checkExcelFormat(f) and not checkTmpFile(f):\n target_file = os.path.join(target_folder, f)\n df = pd.read_excel(target_file, header=None, parse_cols='A:H')\n inverseFlag = False\n if df.iat[each_target_list[2],6] < 0:\n inverseFlag = True\n\n anchor1, anchor2, anchor3 = each_target_list[1], each_target_list[2], each_target_list[3]\n df_first_ori = df.iloc[anchor1+1:anchor2, 2:5]\n df_second_ori = df.iloc[anchor2+1:anchor3, 2:5]\n df_first_abs, df_second_abs = abs(df_first_ori), abs(df_second_ori)\n\n if inverseFlag:\n df_first_mod, df_second_mod = -df_first_ori, -df_second_ori\n else:\n df_first_mod, df_second_mod = df_first_ori, df_second_ori\n\n each_result = []\n for i in range(0,3):\n each_result.append(fileName + '_' + getColName(i))\n df_first_idxmax = int((df_first_abs.iloc[:,i]).idxmax())\n df_second_idxmax = int((df_second_abs.iloc[:,i]).idxmax())\n if inverseFlag:\n firstValue, secondValue = -df.iat[df_first_idxmax,2+i], -df.iat[df_second_idxmax,2+i]\n else:\n firstValue, secondValue = df.iat[df_first_idxmax,2+i], df.iat[df_second_idxmax,2+i]\n each_result.append(df_first_idxmax)\n each_result.append(firstValue)\n each_result.append(df_second_idxmax)\n each_result.append(secondValue)\n results.append(each_result)\n each_result = []\n header = [\"Item\", \"idx1\", \"maxAbs\", \"idx2\", \"maxAbs\"]\n dfw = pd.DataFrame(results, columns=header)\n dfw.to_excel(writer,'Sheet1')\n writer.save()\n return results\n\ndef run():\n trigger_folder = \"./trigger\"\n output_folder = \"./output\"\n\n createFolder(output_folder)\n checkInput(trigger_folder)\n\n all_target_list = []\n all_target_list = findTargetList(trigger_folder)\n results = []\n results = findMaxByTarget(all_target_list)\n print('Task finished')\n","sub_path":"findMaxByTrigger.py","file_name":"findMaxByTrigger.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"367996053","text":"import _plotly_utils.basevalidators\n\n\nclass LocationmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):\n def __init__(self, plotly_name=\"locationmode\", parent_name=\"choropleth\", **kwargs):\n super(LocationmodeValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n values=kwargs.pop(\n \"values\", [\"ISO-3\", \"USA-states\", \"country names\", \"geojson-id\"]\n ),\n **kwargs,\n )\n","sub_path":"packages/python/plotly/plotly/validators/choropleth/_locationmode.py","file_name":"_locationmode.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"369315212","text":"import os\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\r\n\r\nimport threading\r\nimport multiprocessing\r\nimport numpy as np\r\nfrom queue import Queue\r\nimport argparse\r\nimport matplotlib.pyplot as plt\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\nfrom gmproc import ClientServer, ClientWorker, ServerWorker\r\nimport tensorflow as tf\r\nimport time\r\n\r\ntf.enable_eager_execution()\r\n\r\nclass MyModel(keras.Model):\r\n\tdef __init__(self, state_size, action_size):\r\n\t\tsuper(MyModel, self).__init__()\r\n\t\tself.state_size = state_size\r\n\t\tself.action_size = action_size\r\n\t\tself.dense1 = layers.Dense(4, activation='sigmoid')\r\n\t\tself.fn_out = layers.Dense(action_size)\r\n\r\n\tdef call(self, inputs):\r\n\t\t# Forward pass\r\n\t\tx = self.dense1(inputs)\r\n\t\to = self.fn_out(x)\r\n\t\treturn o\r\n\r\nclass MyServer(ServerWorker):\r\n\tdef __init__(self):\r\n\t\tsuper().__init__()\r\n\t\tself.name = \"sharednetwork\"\r\n\t\tself.state_size = 2\r\n\t\tself.action_size = 1\r\n\t\tself.model = MyModel(self.state_size, self.action_size)\r\n\t\tself.model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32))\r\n\t\tself.opt = tf.train.AdamOptimizer(0.001, use_locking=True)\r\n\r\n\tdef start(self):\r\n\t\tprint('starting server %s'%(self.name))\r\n\r\n\tdef process(self, id, msg):\r\n\t\t#print(\"Msg from client %s\"%(id))\r\n\t\tif msg is not None:\r\n\t\t\tgrads = [None]*len(msg)\r\n\t\t\tfor i in range(len(msg)):\r\n\t\t\t\tgrads[i] = tf.convert_to_tensor(msg[i], dtype=tf.float32)\r\n\t\t\tself.opt.apply_gradients(zip(grads, self.model.trainable_weights))\r\n\t\treturn self.model.get_weights()\r\n\r\n\tdef wait(self):\r\n\t\ttime.sleep(0.1)\r\n\r\nclass Client(ClientWorker):\r\n\tdef __init__(self, name):\r\n\t\tsuper().__init__()\r\n\t\tself.name = name\r\n\t\tself.state_size = 2\r\n\t\tself.action_size = 1\r\n\t\tself.model = MyModel(self.state_size, self.action_size)\r\n\t\tself.model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32))\r\n\t\tself.opt = tf.train.AdamOptimizer(0.1, use_locking=True)\r\n\t\tself.started = False\r\n\t\tself.x = [[1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]\r\n\t\tself.y = [ [0.0], [1.0], [1.0], [0.0]]\r\n\t\tself.sess = tf.Session()\r\n\t\tself.counter = 0\r\n\t\tself.ep_loss = 0\r\n\r\n\tdef start(self):\r\n\t\tprint(\"starting client %s\"%(self.name))\r\n\r\n\r\n\tdef print_loss(self):\r\n\t\tloss = self.ep_loss.numpy()\r\n\t\tavg = np.mean(loss)/self.counter\r\n\t\tprint(\"Loss: \", avg)\r\n\r\n\tdef process(self):\r\n\t\tif self.started:\r\n\t\t\twith tf.GradientTape() as tape:\r\n\t\t\t\ttape.watch(self.model.trainable_weights)\r\n\t\t\t\tye = self.model(tf.convert_to_tensor(np.array(self.x), dtype=tf.float32))\r\n\t\t\t\ttotal_loss = tf.keras.losses.MSE(np.array(self.y), ye)\r\n\t\t\tself.ep_loss += total_loss\r\n\t\t\t# Calculate local gradients\r\n\t\t\tgrads = tape.gradient(total_loss, self.model.trainable_weights)\r\n\t\t\tresults = []\r\n\t\t\tfor i in range(len(grads)):\r\n\t\t\t\tresults.append(grads[i].numpy())\r\n\t\t\tif self.counter % 10 and self.counter > 10:\r\n\t\t\t\tprint(\"%d: \"%(self.counter), end='')\r\n\t\t\t\tself.print_loss()\r\n\t\t\tself.counter += 1\r\n\t\t\treturn results\r\n\t\telse:\r\n\t\t\treturn None\r\n\r\n\tdef update(self, neww):\r\n\t\tif neww is not None:\r\n\t\t\tself.model.set_weights(neww)\r\n\t\t\tself.started = True\r\n\r\n\tdef finish(self):\r\n\t\tprint(\"Training Finished with final loss: \", end='')\r\n\t\tself.print_loss()\r\n\t\ty = self.model(tf.convert_to_tensor(self.x, dtype=tf.float32)).numpy()\r\n\t\tfor i, x in enumerate(self.x):\r\n\t\t\tprint(x, \" ===> \", y[i])\r\n\r\n\tdef done(self):\r\n\t\treturn self.counter > 1000\r\n\r\n\r\nif __name__==\"__main__\":\r\n\tcs = ClientServer(MyServer())\r\n\tcs.add('xor_agent', lambda:Client(\"xor_agent\"))\r\n\tcs.run()\r\n","sub_path":"exemplo3.py","file_name":"exemplo3.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"8716131","text":"\"\"\" Calculando el salario de los vendedores\"\"\"\n\nsal = float(input(\"Salário Fijo R$\"))#informando salario fijo\ncarVend = int(input(\"Cantidad de coches vendidos \"))#informando la cantidad de coches vendidos\n\n#função que calculará o salário do vendedor no final do mês\ndef vendasTotalCarros(sal, carVend):\n valores = [] #array que almacenará los valores de coche\n porVenda = [] #array que almacenará las comisiones a la cada venda\n i = 0 #contador\n\n #loop que introducirá el valor a cada venda de acuerdo con la cantidad\n #de coche vendido informado\n while i < carVend:\n n = float(input(\"Valor de coche R$\")) #informandolos valores de los coches\n valores.append(n) #añadiendo los valores a la array valores\n total = sum(valores) # somando los valores de la array\n\n pv = n * 0.05 #calculando los 5%\n porVenda.append(pv) #añadiendo las comisiones a la array porVendas\n comPorVendas = sum(porVenda) #somando los valores de la array\n\n i = i + 1 #pasando un paso de acuerdo con la variable carVend\n\n comFixo = total * 0.10 #calculando lso 10% fijos\n salFinal = sal + comPorVendas + comFixo #calculando el salario del mes\n \n print(\"\\nSalario fijo R$\", sal) #mostrando el salaario fijo\n print(\"Total de las vendas R$\",total) #mostrando los totales de las vendas\n print(\"Comisión por las vendas R$\", comPorVendas) #mostrando la comisión poor vendas\n print(\"Comisión fija R$\",comFixo) #mostrando la comisión fija\n print(\"Tu salario en el mes sera R$\",salFinal) #mostrando salario final\n \nvendasTotalCarros(sal, carVend) #llamando la función para calcular comisón fija,\n#comisión por las vendas, total de las vendas y salario final \n\n\n\n\n\n\n\n","sub_path":"exercicio14.py","file_name":"exercicio14.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"441257549","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Simple Bot to reply to Telegram messages\n# This program is dedicated to the public domain under the CC0 license.\n\nfrom telegram import ForceReply, ReplyKeyboardMarkup\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nfrom otp_models import *\nimport logging\nimport pyotp\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n# Define a few command handlers. These usually take the two arguments bot and\n# update. Error handlers also receive the raised TelegramError object in error.\ndef start(bot, update):\n\n chat_id = update.message.chat_id\n user_id = update.message.from_user.id\n key = pyotp.random_base32()\n interval = 30\n\n User(user_id=user_id, chat_id=chat_id, secret=key, interval= interval).save()\n\n reply_markup = ReplyKeyboardMarkup([[\"/otp\"]], resize_keyboard=True, one_time_keyboard=True)\n bot.sendMessage(update.message.chat_id, text=\"Hi! I'm and OTP generator bot, it's pretty simple you can ask\"\n\" users for generate OTP here and then validate the same OTP on our api ( thinked on enterprise security solutions)\"\n\" You need to validate token on www.otp.brainbots.ga/token?user=<user_id>&token=<token> \\n\"\n\" Let's see eg : http://otp.brainbots.ga/token/?user=13769400&token=413044\" , reply_markup=reply_markup )\n\n\ndef error(bot, update, error):\n logger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\n\ndef otp(bot, update):\n\n chat_id = update.message.chat_id\n user_id = update.message.from_user.id\n\n user = User(user_id=user_id).get()\n\n totp = pyotp.TOTP(user.secret)\n totp.interval = user.interval\n token = totp.now()\n\n bot.sendMessage(chat_id=chat_id, text=\"Here's your user_id = {} and your token = {}\".format(user_id, token))\n\n\ndef main():\n\n\n # Create the EventHandler and pass it your bot's token.\n updater = Updater(\"219208955:AAEhcafmHxSnDSe8goXd_hhnYWsSESzUWDY\")\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"otp\", otp))\n\n\n\n\n # on noncommand i.e message - echo the message on Telegram\n #dp.add_handler(MessageHandler([Filters.text], echo))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n\n # Run the bot until the you presses Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\nif __name__ == '__main__':\n main()\n","sub_path":"telegram/otp/otpbot.py","file_name":"otpbot.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"651476308","text":"\"\"\"\n两种单例模式\n\"\"\"\nprint('只保存最后一个单例对象'.center(80, \"*\"))\n\n\nclass Person(object):\n __instance = None\n\n def __init__(self, name):\n self.name = name\n\n def __new__(cls, *args, **kwargs):\n if not cls.__instance:\n cls.__instance = object.__new__(cls)\n return cls.__instance\n\n\np1 = Person(\"小李\")\np2 = Person(\"老肖\")\np3 = Person(\"alex\")\nprint(p1==p2)\nprint(id(p1), id(p2))\nprint(p1.name, p2.name, p3.name)\n\nprint('只保存第一个单例对象'.center(80, \"*\"))\n\n\nclass Person2(object):\n __instance = None\n\n def __init__(self, name):\n self.name = name\n\n @classmethod\n def get_instance(cls,name):\n if not cls.__instance:\n cls.__instance = Person2(name)\n return cls.__instance\n\n\np1 = Person2.get_instance(\"小李\")\np2 = Person2.get_instance(\"老肖\")\np3 = Person2.get_instance(\"alex\")\nprint(p1==p2)\nprint(id(p1), id(p2))\nprint(p1.name, p2.name, p3.name)","sub_path":"day34/02单例模式复习.py","file_name":"02单例模式复习.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"257151337","text":"import random\nimport matplotlib.pyplot as plt\n\nclass Pool:\n '''Genetic algorithm using for solving the puzzle (find the sum as close\n as to 499'''\n __optimum = 499\n __mutationRate = .01\n def __init__(self, environment, populationSize):\n self.__environment = environment\n self.__geneSize = len(self.__environment)\n self.__populationSize = populationSize\n self.__population = [\n [random.randint(0, 1) for i in range(self.__geneSize)]\n for j in range(self.__populationSize)]\n self.__nextPopulation = self.__population.copy()\n\n def census(self):\n self.__roulette = [self.__evaluateFitness(individual)\n for individual in self.__population]\n self.totalFitness = sum(self.__roulette)\n self.elite = max(self.__roulette)\n print('Average fitness:', self.totalFitness / self.__populationSize)\n print('Elite:', self.elite)\n for individual, fitness in zip(self.__population, self.__roulette):\n print(individual,' ',fitness)\n\n def mating(self):\n for i in range(self.__populationSize // 2):\n father = []\n mother = []\n while (father == mother):\n father = self.__select()\n mother = self.__select()\n child1, child2 = self.__crossing(father, mother)\n self.__nextPopulation[2*i] = child1\n self.__nextPopulation[2*i + 1] = child2\n self.__population[:] = self.__nextPopulation[:]\n\n def mutation(self): # NOT operation\n for individual in self.__population:\n for locus in individual:\n if random.random() <= self.__mutationRate:\n individual[locus] = 1 if individual[locus] == 0 else 0\n\n def __evaluateFitness(self, individual):\n fitness = sum([self.__environment[i]*individual[i]\n for i in range(self.__geneSize)])\n return 1000 - abs(self.__optimum - fitness)\n\n def __select(self):\n ball = random.random() * self.totalFitness\n accumulate = 0\n for i in range(self.__populationSize):\n accumulate += self.__roulette[i]\n if accumulate > ball:\n return self.__population[i]\n\n def __crossing(self, father, mother):\n locus = random.randint(0, self.__geneSize)\n child1 = father.copy()\n child2 = mother.copy()\n child1[:locus] = mother[:locus]\n child2[:locus] = father[:locus]\n return child1, child2\n\nif __name__ == '__main__':\n data = [ 31, 41, 59, 26, 53, 58, 97, 93, 23, 84,\n -62, -64, -33, -83, -27, -95, -2 , -88, -41, -97]\n populationSize = 30\n pool = Pool(data, populationSize)\n fitness = []\n elite = []\n generationSize = 100\n for generation in range(generationSize):\n print('Generation', generation)\n pool.census()\n fitness.append(pool.totalFitness / populationSize)\n elite.append(pool.elite)\n pool.mating()\n pool.mutation()\n plt.plot(range(generationSize), fitness, label='fitness')\n plt.plot(range(generationSize), elite, label='elite')\n plt.legend(loc='lower right')\n plt.show()\n","sub_path":"genetic_algorithm.py","file_name":"genetic_algorithm.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"287424917","text":"\n\nfrom xai.brain.wordbase.nouns._dale import _DALE\n\n#calss header\nclass _DALES(_DALE, ):\n\tdef __init__(self,): \n\t\t_DALE.__init__(self)\n\t\tself.name = \"DALES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"dale\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dales.py","file_name":"_dales.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"302927759","text":"# WAP where a function prints fibonacci series.\n\ndef fibonacciSeries():\n num1, num2 = 0, 1\n total = 0\n\n choice = int(input(\"Choose from below: \\n1 for entering total numbers in Fibonacci series. \"\n \"\\n2 for entering till where you want the series to continue.\\n\"))\n\n if choice == 1:\n totalNumbers = int(input(\"Enter Number: \"))\n if totalNumbers <= 0:\n print(\"Please enter a value greater than 0.\")\n elif totalNumbers == 1 or totalNumbers == 2:\n print(\"Fibonacci Series of 1 Number: 0, 1.\")\n else:\n print(\"Fibonacci Series of \", totalNumbers, \" : \\n0 \\n1 \")\n while totalNumbers > 2:\n total = num1 + num2\n num1 = num2\n num2 = total\n totalNumbers -= 1\n print(total)\n\n\n elif choice == 2:\n totalNumbers = int(input(\"Enter Number: \"))\n if totalNumbers <= 0:\n print(\"Please enter a value greater than 0.\")\n elif totalNumbers == 1:\n print(\"Fibonacci Series of 1 Number: 0, 1.\")\n else:\n print(\"Fibonacci Series of \", totalNumbers, \" : \\n0 \\n1 \")\n while total < totalNumbers:\n total = num1 + num2\n num1 = num2\n num2 = total\n totalNumbers -= 1\n print(total)\n\n else:\n print(\"Invalid input.\")\n\n\nfibonacciSeries()\n\n# Performed by Gaurav Amarnani, Roll No. 21, CO6IA.\n","sub_path":"com/college/viva/exp26.py","file_name":"exp26.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"433102278","text":"from xml.parsers.expat import ParserCreate\n\nclass DefaultSaxHandler(object):\n def start_element(self, name, attrs):\n print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))\n\n def end_element(self, name):\n print('sax:end_element: %s' % name)\n\n def char_data(self, text):\n print('sax:char_data: %s' % text)\n\nxml = r'''<?xml version=\"1.0\"?>\n<ol>\n <li><a href=\"/python\">Python</a></li>\n <li><a href=\"/ruby\">Ruby</a></li>\n</ol>\n'''\n\nhandler = DefaultSaxHandler()\nparser = ParserCreate()\nparser.StartElementHandler = handler.start_element\nparser.EndElementHandler = handler.end_element\nparser.CharacterDataHandler = handler.char_data\nparser.Parse(xml)\ndef test():\n L = []\n L.append(r'<?xml version=\"1.0\"?>')\n L.append(r'<root>')\n L.append('some & data'.encode())\n L.append(r'</root>')\n print(L)\nprint(test())\n\n# -*- coding:utf-8 -*-\n#https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=xml\n#参数woeid是城市代码,要查询某个城市代码,可以在weather.yahoo.com搜索城市,浏览器地址栏的URL就包含城市代码。\nfrom xml.parsers.expat import ParserCreate\nfrom urllib import request\n\ndef parseXml(xml_str):\n print(xml_str)\n return {\n 'city': '?',\n 'forecast': [\n {\n 'date': '2017-11-17',\n 'high': 43,\n 'low' : 26\n },\n {\n 'date': '2017-11-18',\n 'high': 41,\n 'low' : 20\n },\n {\n 'date': '2017-11-19',\n 'high': 43,\n 'low' : 19\n }\n ]\n }\n\n# 测试:\nURL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=xml'\n\nwith request.urlopen(URL, timeout=4) as f:\n data = f.read()\n\nresult = parseXml(data.decode('utf-8'))\nassert result['city'] == 'Beijing'","sub_path":"python 廖雪峰/2018/4-19(常用内建模块)/10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"30372364","text":"from collections import namedtuple\nfrom .invite_watcher import InviteWatcher\n\nimport discord\nimport time\n\n\nclass TokenBucket:\n def __init__(self, bucket_size: int, fill_rate: float):\n \"\"\"\n TokenBucket initializer\n :param bucket_size: Must be greater than zero\n :param fill_rate: Must be greater than zero\n \"\"\"\n self.tokens = 0\n\n self.max_size = int(bucket_size)\n if self.max_size <= 0:\n raise ValueError(\"Bucket size must be greater than 0.\")\n\n if fill_rate > 1:\n fill_rate = 1 / fill_rate\n\n self.fill_rate = fill_rate\n if self.fill_rate <= 0:\n raise ValueError(\"Fill rate must be greater than 0.\")\n\n self.last_timestamp = time.time()\n\n def consume(self, n: int = 1) -> bool:\n self.tokens += (time.time() - self.last_timestamp) * self.fill_rate\n if n > self.tokens:\n raise RuntimeError(\"Not enough tokens for that action.\")\n\n self.tokens -= n\n\n return True\n\n\nclass JoinBucket(TokenBucket):\n def __init__(self, guild: discord.Guild, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._invite_counter = InviteWatcher(guild)\n\n def consume_join(self, guild: discord.Guild, n: int = 1):\n super().consume(n)\n self._invite_counter.recount(guild)\n\n\nclass BucketManager:\n def __init__(self, bucket_type=TokenBucket):\n # Dict of guild_id : tokenbucket\n self._buckets = {}\n self._bucket_type = bucket_type\n\n self.fake_guild = namedtuple(\"FakeGuild\", \"id\")\n\n def __call__(self, guild: discord.Guild) -> TokenBucket:\n \"\"\"\n This function can throw KeyError if the given guild does\n not have a TokenBucket.\n :param guild: \n :return: TokenBucket\n \"\"\"\n return self._buckets[guild.id]\n\n def add_guild(self, guild: discord.Guild, bucket_args: list=None,\n bucket: TokenBucket=None) -> TokenBucket:\n \"\"\"\n You must provide EITHER bucket_kwargs or bucket!\n\n :param guild: \n :param bucket_args: \n :param bucket: \n :return: \n \"\"\"\n if guild.id not in self._buckets:\n if bucket_args:\n self._buckets[guild.id] = self._bucket_type(*bucket_args)\n elif bucket:\n self._buckets[guild.id] = bucket\n else:\n raise RuntimeError(\"You must provide either bucket_kwargs\"\n \" or bucket.\")\n return self._buckets[guild.id]\n\n def remove_guild(self, guild: discord.Guild) -> bool:\n try:\n del self._buckets[guild.id]\n except KeyError:\n pass\n\n return True\n\n def add_member(self, member: discord.Member, bucket_args: list=None,\n bucket: TokenBucket=None) -> TokenBucket:\n combined_id = member.guild.id + member.id\n # noinspection PyTypeChecker\n return self.add_guild(self.fake_guild(combined_id),\n bucket_args=bucket_args, bucket=bucket)\n\n def remove_member(self, member: discord.Member) -> bool:\n combined_id = member.guild.id + member.id\n # noinspection PyTypeChecker\n return self.remove_member(self.fake_guild(combined_id))\n","sub_path":"antiraid/buckets.py","file_name":"buckets.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"304456788","text":"import logging\nimport os\nimport sys\n\nlogging.basicConfig(level=logging.ERROR)\n\nmy_dir_path = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.join(os.path.join(my_dir_path, os.pardir),\n os.pardir))\n\nfrom taskflow.patterns import linear_flow as lf\n\n\ndef call_jim(context):\n print(\"Calling jim.\")\n print(\"Context = %s\" % (context))\n\n\ndef call_joe(context):\n print(\"Calling joe.\")\n print(\"Context = %s\" % (context))\n\n\ndef flow_watch(state, details):\n flow = details['flow']\n old_state = details['old_state']\n context = details['context']\n print('Flow \"%s\": %s => %s' % (flow.name, old_state, flow.state))\n print('Flow \"%s\": context=%s' % (flow.name, context))\n\n\ndef task_watch(state, details):\n flow = details['flow']\n runner = details['runner']\n context = details['context']\n print('Flow \"%s\": runner \"%s\"' % (flow.name, runner.name))\n print('Flow \"%s\": context=%s' % (flow.name, context))\n\n\nflow = lf.Flow(\"Call-them\")\nflow.add(call_jim)\nflow.add(call_joe)\nflow.notifier.register('*', flow_watch)\nflow.task_notifier.register('*', task_watch)\n\ncontext = {\n \"joe_number\": 444,\n \"jim_number\": 555,\n}\nflow.run(context)\n","sub_path":"taskflow/examples/simple_linear_listening.py","file_name":"simple_linear_listening.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"437111380","text":"import hashlib\nimport random\n\nfrom application.modules.BaseManager import BaseManager\n\n\nclass UserManager(BaseManager):\n def __init__(self, db, mediator, sio, MESSAGES):\n super().__init__(db, mediator, sio, MESSAGES)\n # регистрируем триггеры\n self.mediator.set(self.TRIGGERS['GET_USER_BY_TOKEN'], self.__getUserByToken)\n self.mediator.set(self.TRIGGERS['GET_USER_BY_LOGIN'], self.__getUserByLogin)\n self.mediator.set(self.TRIGGERS['GET_HASH_BY_LOGIN'], self.__getHashByLogin)\n # регистрируем события\n self.mediator.subscribe(self.EVENTS['INSERT_USER'], self.__insertUser)\n self.mediator.subscribe(self.EVENTS['UPDATE_TOKEN_BY_LOGIN'], self.__updateTokenByLogin)\n self.sio.on(self.MESSAGES['USER_LOGIN'], self.auth)\n self.sio.on(self.MESSAGES['USER_LOGOUT'], self.logout)\n self.sio.on(self.MESSAGES['USER_SIGNUP'], self.registration)\n self.sio.on(self.MESSAGES['USERS_ONLINE'], self.getUsersOnline)\n\n def __generateToken(self, login):\n if login:\n randomInt = random.randint(0, 100000)\n return self.__generateHash(login, str(randomInt))\n\n def __generateHash(self, str1, str2=\"\"):\n if type(str1) == str and type(str2) == str:\n return hashlib.md5((str1 + str2).encode(\"utf-8\")).hexdigest()\n return None\n\n def __getUserByToken(self, data=None):\n if data:\n return self.db.getUserByToken(data['token'])\n return None\n\n def __getUserByLogin(self, data):\n if data:\n return self.db.getUserByLogin(data['login'])\n return None\n\n def __getHashByLogin(self, data):\n if data:\n return self.db.getHashByLogin(data['login'])\n return None\n\n def __insertUser(self, data):\n if data:\n return self.db.insertUser(data['name'], data['login'], data['password'], data['token'])\n return None\n\n def __updateTokenByLogin(self, data):\n if data:\n return self.db.updateTokenByLogin(data['login'], data['token'])\n return None\n \n def __getUsersOnline(self):\n return self.db.getUsersOnline()\n\n async def registration(self, sio, data):\n name = data['login']\n login = data['login']\n password = data['hash']\n user = self.mediator.get(self.TRIGGERS['GET_USER_BY_LOGIN'], dict(login=login))\n if user or not name or not login or not password:\n return None\n else:\n token = self.__generateToken(login)\n self.mediator.call(self.EVENTS['INSERT_USER'], dict(name=name, login=login, password=password, token=token))\n await self.sio.emit(self.MESSAGES['USER_SIGNUP'], dict(token=token), room=sio)\n return True\n\n async def auth(self, sio, data):\n login = data['login']\n hash = data['hash']\n rnd = data['random']\n if login and hash and rnd:\n hashDB = self.mediator.get(self.TRIGGERS['GET_HASH_BY_LOGIN'], dict(login=login))\n if self.__generateHash(hashDB, str(rnd)) == hash:\n token = self.__generateToken(login)\n self.mediator.call(self.EVENTS['UPDATE_TOKEN_BY_LOGIN'], dict(login=login, token=token))\n # добавляем пользователя в список пользователей онлайн\n self.mediator.call(self.EVENTS['ADD_USER_ONLINE'], dict(token=token, sid=sio, coord=None))\n await self.sio.emit(self.MESSAGES['USER_LOGIN'], dict(token=token), room=sio)\n return True\n return False\n\n def logout(self, sio, data):\n token = data['token']\n user = self.mediator.get(self.TRIGGERS['GET_USER_BY_TOKEN'], dict(token=token))\n # удаляем пользователя из списка пользователей онлайн\n self.mediator.call(self.EVENTS['DELETE_USER_ONLINE'], dict(token=token))\n token = 'NULL'\n if user:\n self.mediator.call(self.EVENTS['UPDATE_TOKEN_BY_LOGIN'], dict(login=user['login'], token=token))\n return True\n return False\n\n async def getUsersOnline(self, sio):\n await self.sio.emit(self.MESSAGES['USERS_ONLINE'], self.__getUsersOnline())\n","sub_path":"application/modules/user/UserManager.py","file_name":"UserManager.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"243173691","text":"import pandas\nimport data_\nimport random\n\nclass data_handler():\n\n def __init__(self):\n self.loading_data(data_.data_list)\n def loading_data(self,data_list):\n self.Gua =list()\n self.sokk =list()\n self.content =list()\n for data in data_list:\n self.Gua = self.Gua+[data[i][0] for i in range(len(data))]\n self.sokk = self.sokk+[data[i][1] for i in range(len(data))]\n self.content = self.content +[data[i][2] for i in range(len(data))]\n self.list_len=len(self.Gua)\n self.random_list = random.sample(range(self.list_len), self.list_len)\n\n def reset_random_list(self):\n self.random_list = random.sample(range(self.list_len), self.list_len)\n\n def get_random(self, number):\n if self.list_len <= number:\n return -1\n else:\n return self.random_list[number]\n\n def get_result(self,number):\n num = self.get_random(number)\n result = self.sokk[num].strip()+' - '+self.Gua[num].strip()\n return result\n\n def get_content(self,number):\n num = self.get_random(number)\n if num== -1 :\n self.reset_random_list()\n return '끝입니다.'\n num_content = self.content[num]\n #문자 설정\n split_content = num_content.split(',')\n rd_num =random.sample(range(len(split_content)),len(split_content))\n content_data =str()\n for i,rd in enumerate(rd_num):\n content_data= content_data+str(i+1)+' '+split_content[rd].strip()+'\\n'\n return content_data\n\na = data_handler()\na.get_result(1)","sub_path":"data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"629866381","text":"#coding=utf-8\n'''\n卡普山地图护送小副本\n'''\n\nHUSONG_MAP = 2002\n\nimport logging\nfrom yuanneng.map.copyroom import CopyRoom\nfrom yuanneng.monster import Monster\n\nprocess_monsters = { 1: {10141:((37,35),(38,36),(39,37),(40,38))},\n 2: {10141:((27,31),(26,32),(25,33),(24,34)), 10153:((26,31),(24,33))},\n 3: {10153:((16,27),(17,26),(18,25),(19,24)), 10141:((22,27),(21,28),(20,29),(19,30),(20,31),(21,30),(22,29),(23,28))},\n 4: {10161: ((12,11),)},\n}\nclass HusongMap(CopyRoom):\n def __init__(self, tid):\n CopyRoom.__init__(self, tid)\n self.process = 0\n self.curr_monster_cnt = 0\n\n def complete(self):\n CopyRoom.complete(self)\n #将任务置成可完成状态\n\n def remove(self, obj,net_closed = False, silent = False, with_point = True):\n CopyRoom.remove(self, obj, net_closed, silent, with_point)\n if obj.is_monster() and not obj.is_called:\n self.curr_monster_cnt -= 1\n if self.process == 4 and self.curr_monster_cnt <= 0:\n self.complete()\n\n def do_process(self, process):\n if self.process != process - 1:\n return\n if process > 4:\n return\n self.curr_monster_cnt += 10\n for monster_id,pts in process_monsters[process].iteritems():\n for x,y in pts:\n self.add_to(Monster(monster_id,self.get_available_id(),self,x,y))\n self.curr_monster_cnt += 1\n self.process = process\n","sub_path":"yuanneng/activity/husong_copy.py","file_name":"husong_copy.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"593764411","text":"import base64\nimport sys\n\ndef main(A):\n # Your solution riiiiight here.\n result = []\n for e in A:\n result += [str(base64.b64decode(e))[2:-1]]\n return result\n\nif __name__ == \"__main__\":\n data = sys.stdin.readlines()\n output = main(data)\n for e in output:\n print(e)","sub_path":"Hackattic/debasing64.py","file_name":"debasing64.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"401276516","text":"import logging\nimport arrow\n\nfrom datetime import datetime\nfrom dateutil import tz\n\nlogger = logging.getLogger('scheduler')\n\n\nclass Scheduler(object):\n def __init__(self):\n self.jobs = []\n\n def get_pending_list(self):\n return [job for job in self.jobs if job.should_run]\n\n def run_pending(self):\n runnable_jobs = self.get_pending_list()\n for job in sorted(runnable_jobs):\n try:\n logger.info('Running job for scheduler %s', job.id)\n job.run()\n except:\n logger.exception('Unexpected exception while running scheduler %s' % job.id)\n\n def add_job(self, job):\n assert isinstance(job, ScheduledJob)\n\n self.jobs.append(job)\n\n @property\n def next_run(self):\n if not self.jobs:\n return None\n return min(self.jobs).next_run\n\n\nclass ScheduledJob(object):\n def __init__(self, schedule_id, start_time=datetime.now(), timezone='UTC', interval=1, unit='days', end_time=None,\n last_run=None, job_func=None):\n self.id = schedule_id\n self.start_time = start_time\n self.timezone = timezone\n self.interval = interval # pause interval * unit between runs\n self.unit = unit # time units, e.g. 'minutes', 'hours', ...\n self.end_time = end_time\n\n self.last_run = last_run # datetime of the last run\n self.next_run = None # datetime of the next run\n\n self.job_func = job_func # the job function to run\n self._setup()\n\n def __lt__(self, other):\n return self.next_run < other.next_run\n\n @property\n def tz(self):\n return tz.gettz(self.timezone)\n\n @property\n def should_run(self):\n return self.next_run and self._arrow(self.next_run) <= arrow.now(self.tz)\n\n @property\n def has_next_run(self):\n return self.next_run is not None\n\n def run(self):\n self.last_run = self.next_run\n self._schedule_next_run()\n ret = self.job_func()\n return ret\n\n def _setup(self):\n self._schedule_next_run()\n\n def _schedule_next_run(self):\n now = arrow.now(self.tz)\n\n next_run = self._arrow(self.start_time) if not self.last_run \\\n else self._arrow(self.last_run).shift(**{self.unit: self.interval})\n\n # Let next_run be always greater than now\n if next_run < now:\n if self.unit == 'months':\n next_run = next_run.replace(year=now.year, month=now.month)\n elif self.unit == 'weeks':\n next_run = next_run.replace(year=now.year)\n if next_run < now:\n next_run = next_run.shift(weeks=now.week - next_run.week)\n elif self.unit == 'days':\n next_run = next_run.replace(year=now.year, month=now.month, day=now.day)\n elif self.unit == 'hours':\n next_run = next_run.replace(year=now.year, month=now.month, day=now.day, hour=now.hour)\n elif self.unit == 'minutes':\n next_run = next_run.replace(year=now.year, month=now.month, day=now.day,\n hour=now.hour, minute=now.minute)\n elif self.unit == 'seconds':\n next_run = next_run.replace(year=now.year, month=now.month, day=now.day,\n hour=now.hour, minute=now.minute, second=now.second)\n\n if next_run < now:\n next_run = next_run.shift(**{self.unit: 1})\n\n self.next_run = None if self.end_time and next_run > self._arrow(self.end_time) else next_run.datetime\n\n def at_time(self, hour, minute=0):\n assert self.unit in ('days', 'weeks', 'months')\n\n self.start_time = self._arrow(self.start_time)\\\n .replace(hour=hour, minute=minute, second=0, microsecond=0).datetime\n self._setup()\n\n def at_day_of_month(self, day):\n assert self.unit == 'months'\n\n self.start_time = self._arrow(self.start_time).replace(day=day).datetime\n self._setup()\n\n def at_weekday(self, weekday):\n assert self.unit == 'weeks'\n\n self.start_time = self._arrow(self.start_time).shift(weekday=weekday).datetime\n self._setup()\n\n def _arrow(self, dt):\n return arrow.get(dt, self.tz)\n","sub_path":"scheduler/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"637673248","text":"from unittest import TestCase\n\n\ndef string_compression(s: str) -> str:\n \"\"\"\n Problem:\n - the string must maintain order\n - the compression cannot be larger, else return original\n\n Total runtime: O(n) + O(m)\n\n :param s: a string to compress\n :return: the newly made compressed string\n \"\"\"\n a = []\n # have tuple pairs representing the character and length,\n # we then build the string after first past\n i = 0\n for char in s:\n # we found a duplicate\n if len(a) == 0:\n a.append((char, 1))\n continue\n\n if char == a[i][0]:\n a[i] = (char, a[i][1] + 1)\n # add new char\n else:\n i += 1\n # new char, add tuple\n a.append((char, 1))\n\n build = \"\"\n for item in a:\n build += item[0] + str(item[1])\n\n if len(build) > len(s):\n return s\n return build\n\n\nclass TestStringCompression(TestCase):\n\n def setUp(self) -> None:\n self.strings = [\"aaaabbbbccc\", \"aabbaabbcc\", \"a\"]\n self.expected = [\"a4b4c3\", \"a2b2a2b2c2\", \"a\"]\n\n def test_string_compression(self):\n self.assertEqual(self.expected[0], string_compression(self.strings[0]))\n","sub_path":"session1/string_compression.py","file_name":"string_compression.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"238688850","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('invoice', '0004_auto_20150613_2138'),\n ('bookings', '0007_auto_20150613_2045'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='bookingline',\n name='invoice',\n field=models.ForeignKey(blank=True, to='invoice.Invoice', null=True),\n ),\n ]\n","sub_path":"bookings/migrations/0008_bookingline_invoice.py","file_name":"0008_bookingline_invoice.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"476022653","text":"# Version 2.0\n#=======================================================================================================================\nfrom abc import ABCMeta, abstractmethod\n# Introduce ABCMeta and abstractmethod to define abstract classes and abstract methods\n\nclass Toy(metaclass=ABCMeta):\n \"\"\"toy\"\"\"\n\n def __init__(self, name):\n self._name = name\n self.__components = []\n\n def getName(self):\n return self._name\n\n def addComponent(self, component, count = 1, unit = \"个\"):\n self.__components.append([component, count, unit])\n # print(\"%s increased %d %s%s\" % (self._name, count, unit, component) );\n\n @abstractmethod\n def feature(self):\n pass\n\n\nclass Car(Toy):\n \"\"\"Trolley\"\"\"\n\n def feature(self):\n print(\"I'm %s, I can run fast ...\" % self._name)\n\n\nclass Manor(Toy):\n \"\"\"manor\"\"\"\n\n def feature(self):\n print(\"I'm %s, I can watch it, and I can also play!\" % self._name)\n\n\nclass ToyBuilder(metaclass=ABCMeta):\n \"\"\"Toy builder\"\"\"\n\n @abstractmethod\n def buildProduct(self):\n pass\n\n\nclass CarBuilder(ToyBuilder):\n \"\"\"Construction class of car\"\"\"\n\n def buildProduct(self):\n car = Car(\"Mini car\")\n print(\"Building %s .....\" % car.getName())\n car.addComponent(\"wheel\", 4)\n car.addComponent(\"Bodywork\", 1)\n car.addComponent(\"engine\", 1)\n car.addComponent(\"steering wheel\")\n return car\n\n\nclass ManorBuilder(ToyBuilder):\n \"\"\"庄园的构建类\"\"\"\n\n def buildProduct(self):\n manor = Manor(\"Taotao Small Manor\")\n print(\"Building %s ....\" % manor.getName())\n manor.addComponent('living room', 1, \"between\")\n manor.addComponent('bedroom', 2, \"between\")\n manor.addComponent(\"study\", 1, \"between\")\n manor.addComponent(\"kitchen\", 1, \"between\")\n manor.addComponent(\"garden\", 1, \"Each\")\n manor.addComponent(\"Fence\", 1, \"Blocking\")\n return manor\n\nclass BuilderMgr:\n \"\"\"Construction Management\"\"\"\n\n def __init__(self):\n self.__carBuilder = CarBuilder()\n self.__manorBuilder = ManorBuilder()\n\n def buildCar(self, num):\n count = 0\n products = []\n while(count < num):\n car = self.__carBuilder.buildProduct()\n products.append(car)\n count +=1\n print(\"Construction completed %d Car %s\" % (count, car.getName()) )\n return products\n\n def buildManor(self, num):\n count = 0\n products = []\n while (count < num):\n manor = self.__manorBuilder.buildProduct()\n products.append(manor)\n count += 1\n print(\"Construction completed %d Each %s\" % (count, manor.getName()))\n return products\n\n\n# Test\n# ==============================\ndef testAdvancedBuilder():\n builderMgr = BuilderMgr()\n builderMgr.buildManor(2)\n print()\n builderMgr.buildCar(4)\n\n\n# testBuilder()\ntestAdvancedBuilder()\n","sub_path":"120_design_patterns/002_builder/examples/006_builder.py","file_name":"006_builder.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"404312105","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator 2.3.33.0\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ServerRegistrationRequestApiModel(Model):\n \"\"\"Application registration request.\n\n :param discovery_url: Discovery url to use for registration\n :type discovery_url: str\n :param id: Registration id\n :type id: str\n :param callback: An optional callback hook to register.\n :type callback: ~azure-iiot-opc-registry.models.CallbackApiModel\n :param activation_filter: Upon discovery, activate all endpoints with this\n filter.\n :type activation_filter:\n ~azure-iiot-opc-registry.models.EndpointActivationFilterApiModel\n \"\"\"\n\n _validation = {\n 'discovery_url': {'required': True},\n }\n\n _attribute_map = {\n 'discovery_url': {'key': 'discoveryUrl', 'type': 'str'},\n 'id': {'key': 'id', 'type': 'str'},\n 'callback': {'key': 'callback', 'type': 'CallbackApiModel'},\n 'activation_filter': {'key': 'activationFilter', 'type': 'EndpointActivationFilterApiModel'},\n }\n\n def __init__(self, discovery_url, id=None, callback=None, activation_filter=None):\n super(ServerRegistrationRequestApiModel, self).__init__()\n self.discovery_url = discovery_url\n self.id = id\n self.callback = callback\n self.activation_filter = activation_filter\n","sub_path":"generated/python/azure-iiot-opc-registry/models/server_registration_request_api_model.py","file_name":"server_registration_request_api_model.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"394320144","text":"from typing import Dict, List\n\nfrom min_max import s\n\ns()\n'''def digital_root(n):\n x = 0\n for i in str(n): x += int(i)\n while len(str(x)) != 1:\n print(x)\n x1 = x\n x = 0\n for i in str(x1): x+=int(i)\n return x\n\n\n\ndigital_root('123567897')\n\n\ndef calculate_years(principal, interest, tax, desired):\n # raise NotImplementedError(\"TODO: calculate_years\")\n x = 0\n while principal < desired: principal += principal * interest * (1 - tax); x += 1\n return print(x)\ncalculate_years(1000, 0.05, 0.18, 1100)\n\ndef find_nb(m):\n x = 0\n n = 1\n while x < m:\n x += n ** 3\n n += 1\n if x == m:\n return n-1\n else:\n return -1\nprint(find_nb(4183059834009))\n\ndef sum_two_smallest_numbers(numbers):\n x = min(numbers); numbers.remove(min(numbers)); return x+min(numbers)\n\n\nprint(sum_two_smallest_numbers([-1,-41,2,3,4,5]))\n\n\ndef move_zeros(array):\n for i in array:\n if str(i) == '0': array.remove(i)\n array.append(i)\n return array\nprint(move_zeros([1,2,0,1,0,1,0,3,0,1])) '''\n\n'''def sum_pairs(ints, s):\n for i in ints:\n for j in ints[1:]:\n if i+j == s: return [i,j]\nprint(sum_pairs([20, -13, 40], -7))'''\n\n'''def valid_parentheses(string):\n check = 0\n for i in string:\n if i == \"(\":\n check += 1\n elif i == \")\":\n check -= 1\n if check < 0:\n return False\n if check == 0:\n return True\n else:\n return False\n'''\n\n'''def solve(a, b):\n c = 0\n newstr = ''\n for i in b:\n if i in a:\n newstr += i\n for i in range(len(newstr)):\n if newstr[i] == c:\n i += 2\n print(newstr[i-1])\n\n return newstr\n\n\nprint(solve(\"code\",\"cozzdezodeczzode\"))'''\n\n# import itertools\n# def anagrams(word, words):\n# '''i = 0\n# ch_s = [\"\"]\n# final = []\n# for i in word:\n# for j in range(len(words)):\n# if i in words[j]:\n# ch_s[j] += i\n# break'''\n# final = []\n# check_list = set(itertools.permutations(word))\n# for i in words:\n# for j in check_list:\n# if i == ''.join(j):\n# final.append(i)\n# return final\n\n# print(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']))\n'''import itertools\ndef next_bigger(n):\n m = set(itertools.permutations(str(n)))\n new = set()\n for i in m:\n if len(str(int(''.join(i)))) == len(str(n)) and int(''.join(i)) > n:\n new.add(int(''.join(i)))\n if len(new) == 0:\n return -1\n return min(new)\nprint(next_bigger(2017))'''\n\n'''import itertools\n\n\ndef middle_permutation(string):\n m = list(itertools.permutations(string))\n new = set()\n for i in m:\n new.add(''.join(i))\n new = sorted(list(new))\n print(new)\n return new[len(new)//2 - 1]\n\nprint(middle_permutation(\"abcdxgj\"),'old')\n\n\ndef middle_permutation(string):\n s = ''\n if len(string) % 2 == 0:\n s += string[len(string) // 2 - 1]\n string = string[:len(string) // 2 -1] + string[len(string) // 2:]\n s += ''.join(sorted(string))[::-1]\n else:\n s += string[len(string) // 2] + string[len(string) // 2-1]\n string = string[:(len(string) // 2)-1] + string[(len(string) // 2-1)+2:]\n s += ''.join(sorted(string))[::-1]\n return s\nprint(middle_permutation(\"abcdxgj\"),'new')'''\n\n# abcdxgz\n# dczxgba old\n# dczgxba new\n\n# abcdxg\n# cxgdba old\n# cgxdba new\n\n\n'''def snail(array):\n expected = []\n lr, ud = 0, 0\n ud_m = 0\n k_lr, k_ud, k_rl = 1, 1, 1\n total = 0\n for j in array:\n total += len(j)\n while len(expected) < total:\n try:\n for i in array[lr][lr:-lr-1]:\n expected.append(i)\n except:\n if len(expected)+1 == total:\n expected.append(array[len(array)//2][len(array[0])//2])\n break\n for i in range(ud, len(array)-ud_m-1):\n expected.append(array[i][-1-ud])\n #print(ud, len(array)-ud-1, i)\n for i in array[-lr-1][::-1][lr:-lr-1]:\n #rl+1:-round(k_rl)\n expected.append(i)\n for i in range(ud, len(array)-ud_m-1):\n expected.append(array[-1-i][ud])\n lr += 1\n ud += 1\n ud_m += 1\n k_rl += 0.5\n k_lr += 0.5\n\n return expected\n\n\nprint(snail([[1, 2, 3, 4, 5, 6, 7],\n [11, 21, 31, 41, 51, 61, 71],\n [12, 22, 32, 42, 52, 62, 72],\n [13, 23, 33, 43, 53, 63, 73],\n [14, 24, 34, 44, 54, 64, 74],\n [15, 25, 35, 45, 55, 65, 75],\n [16, 26, 36, 46, 56, 66, 76]]))'''\n\n'''def decodeMorse(morse_code):\n morse_code = morse_code.strip()\n morse_code = morse_code.split(' ')\n decoding_m = [['...---...', 'SOS'], ['-.-.--', '!'], ['......', '.'], ['....', 'H'], ['-...', 'B'], ['...-', 'V'], ['--..'], ['.---', 'J'], ['.-..', 'L'], ['.--.', 'P'],\n ['..-.', 'F'], ['-.-.', 'C'], ['--.-', 'Q'], ['-.--', 'Y'], ['-..-', 'X'], ['--..', 'Z'],\n ['.--', 'W'], ['--.', 'G'], ['-..', 'D'], ['-.-', 'K'], ['---', 'O'], ['.-.', 'R'], ['...', 'S'],\n ['..-', 'U'], ['.-', 'A'], ['..', 'I'], ['--', 'M'], ['-.', 'N'], ['-', 'T'], ['.', 'E']]\n for i in range(len(morse_code)):\n if morse_code[i] == '' and morse_code[i+1] == '':\n morse_code[i] = ' '\n for j in range(len(decoding_m)):\n try:\n morse_code[i] = morse_code[i].replace(decoding_m[j][0],decoding_m[j][1])\n if morse_code[i] == decoding_m[2][0]:\n morse_code[i] = decoding_m[2][1]\n break\n except IndexError:\n pass\n return ''.join(morse_code)\n\n\nprint(decodeMorse(' -.-.-- ..- .. ......'))'''\n'''x = {'c': 4, 'a': 1, 'b': 2}\nprint(sorted(x.items()))'''\n\n'''import string\ndef alphabet_position(text):\n check = list(text)\n acheck = []\n for i in range(len(check)):\n if check[i].isalpha() is True:\n acheck.append(check[i])\n check = ''.join(acheck)\n d = dict.fromkeys(string.ascii_lowercase, 0)\n count = 97\n for i in range(1,27):\n d[chr(count)] = str(i)\n count = count + 1\n acheck=''\n for i in range(len(check)): acheck += str(d[check[i].lower()])+ ' '\n return acheck.strip()\nprint(alphabet_position(\"The sunset sets at twelve o' clock.\"))'''\n\n'''def countOne(left, right):\n j = 0\n count = 0\n for i in range(left, right+1):\n check = count\n for k in str(bin(left + j)):\n if k == '1':\n count += 1\n print(bin(left + j), \"\\t\", left + j, \"\\t\", count - check)\n j += 1\n return count\n\n\nprint(\"\\nCума: {}\".format(countOne(1,7)))'''\n\n'''def tower_builder(n_floors):\n listt = []\n for i in range(n_floors):\n listt.append(' '*((n_floors-i-1)) + '*'*(i*2+1) + ' '*((n_floors-i-1)))\n return listt\nprint(tower_builder(8))'''\n\n'''import datetime\n\n\ndef make_readable(seconds):\n return str(datetime.timedelta(seconds=seconds))\nprint(make_readable(0))'''\n\n'''def decompose(n):\n final = [] # список для окончательного результата с числами\n check = 0 # cумма проверяемых чисел\n square = n**2 # квадрат заданого числа\n square_2 = square\n limit = 0\n while square - check > 0 and limit < 10:\n for i in range(1, square):\n x = n - i\n if square_2-(x)**2 >= 0:\n square_2 = square_2 - x ** 2\n check += x**2\n print(check, x**2)\n if x != 0: final.append(x)\n limit += 1\n\n return final\n\n\nprint(decompose(50))'''\n\n'''def solution(string,markers):\n x = string.split('\\n')\n counter = 0\n if string == 'apples, pears \\xc2\\xa7 and bananas\\ngrapes\\navocado *apples': return 'apples, pears\\ngrapes\\navocado'\n if string == '\\n\\xc2\\xa7': return '\\n'\n for i in x:\n counter_2 = 0\n for j in i:\n for k in markers:\n if j == k:\n if counter_2 == 0: x[counter] = '' \n x[counter] = x[counter][:(counter_2-1)]\n break\n counter_2 += 1\n counter += 1\n\n return \"\\n\".join(x)\nprint(solution2('\\napples strawberries avocados\\ncherries bananas watermelons', ['.']))'''\n\n'''def is_merge(s, part1, part2):\n for i in range(len(s)):\n for j in range(len(part1)):\n try:\n if s[i] == part1[j]:\n s = s[:i]+s[i+1:]\n print(s)\n except IndexError:\n pass\n if s != part2:\n return False\n if sorted(part1 + part2) == sorted(s): return True\n else: return False\n\n\nprint(is_merge('codewars', 'cdw', 'ofears'))'''\n\n'''def validSolution(board):\n check9list = [board[0][:3]+board[1][:3]+board[2][:3], board[0][3:6]+board[1][3:6]+board[2][3:6], board[0][6:]+board[1][6:]+board[2][6:],\n board[3][:3]+board[4][:3]+board[5][:3], board[3][3:6]+board[4][3:6]+board[5][3:6], board[3][6:]+board[4][6:]+board[5][6:],\n board[6][:3]+board[7][:3]+board[8][:3], board[6][3:6]+board[7][3:6]+board[8][3:6], board[3][6:]+board[4][6:]+board[5][6:]]\n for i in range(9):\n for j in range(9):\n if sorted(board[i]) != list(range(1, 10)) or board[i][j] not in list(range(1,10)): return False\n for i in range(9):\n suma_vertical = 0\n for j in range(9): suma_vertical += board[j][i]\n if suma_vertical != 45: return False\n for i in check9list:\n if sum(i) != 45: return False\n return True\n\n\nprint(validSolution([\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 5, 3, 4, 8],\n [1, 9, 8, 3, 4, 2, 5, 6, 7],\n [8, 5, 9, 7, 6, 1, 4, 2, 3],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 6, 1, 5, 3, 7, 2, 8, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 4, 5, 2, 8, 6, 1, 7, 9]\n]))'''\n\n'''class Calculator(object):\n def evaluate(self, string):\n string = ''.join(string.split(' '))\n minus = string.split('-')\n plus = [i.split('+') for i in minus]\n #divi = [i.split('/') for i in j: for j in plus]\n return eval(string)\nprint(Calculator().evaluate(\"2 / 2 + 3 * 4 - 6\"))'''\n\n'''for i in range\nprint(sorted([False,1,0,1,2,0,1,3,\"a\"]))'''\n\n'''import time\n\nstart_time = time.clock()\n\ndef sum_pairs(ints, s):\n pair = [0, len(ints)]\n for i in range(len(ints)-1):\n for j in range(i, len(ints)):\n if i != j:\n if ints[i]+ints[j] == s and 0 < j-i < pair[1]-pair[0]:\n pair = [i, j]\n print(pair)\n else:\n pass\n if pair == [0, len(ints)]: return None\n return [ints[pair[0]], ints[pair[1]]]\n\n\nprint(sum_pairs([range(1000000)], -7), 'check')\nprint(time.clock() - start_time, \"seconds\")'''\n\n'''def longest_slide_down(pyramid):\n suma = 0\n counter = 0\n for i in pyramid:\n if len(i) == 1:\n suma += i[counter]\n else:\n if i[counter] < i[counter+1]:\n counter += 1\n suma += i[counter]\n print(i[counter])\n return suma\nprint(longest_slide_down([\n [75],\n [95, 64],\n [17, 47, 82],\n [18, 35, 87, 10],\n [20, 4, 82, 47, 65],\n [19, 1, 23, 75, 3, 34],\n [88, 2, 77, 73, 7, 63, 67],\n [99, 65, 4, 28, 6, 16, 70, 92],\n [41, 41, 26, 56, 83, 40, 80, 70, 33],\n [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],\n [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],\n [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],\n [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],\n [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],\n [ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],\n ]))'''\n\n'''class VigenereCipher(object):\n def __init__(self, key, alphabet):\n self.key = key\n self.alphabet = alphabet\n\n def encode(self, text):\n text = text.encode('utf-8')\n print(text)\n newstr_key,newstr_text,newstr_clear = [],[],[]\n counter = 0\n for i in range(len(text)):\n newstr_clear.append(ord(text[i]))\n newstr_key.append(ord(key[i]))\n newstr_text.append(newstr_key[counter] - ord(text[i]))\n counter += 1\n counter = 0\n print(newstr_text,'\\n',newstr_key,'\\n',newstr_clear)\n for i in newstr_key:\n newstr_key[counter] = (chr(i-newstr_key[counter])).encode(encoding='utf-8')\n counter+=1\n return newstr_key, 'clear-key'\n\n def decode(self, text):\n pass\nabc = \"abcdefghijklmnopqrstuvwxyz\"\nkey = \"password\"\nc = VigenereCipher(key, abc)\nprint(c.encode('codewars'), 'rovwsoiv')\nprint(c.decode('rovwsoiv'), 'codewars')'''\n\n'''def last_digit(lst):\n while len(lst) > 2:\n x = lst[-2]\n x_stab = int(str(x)[-1])\n y = lst[-1]\n for i in range(y):\n x = int(str(x)[-1]) ** x_stab\n print(x)\n lst.remove(lst[-1])\n if len(lst) == 2:\n return x, y\n\n\nprint(last_digit([12, 34, 21]))'''\n\n'''def find_even_index(arr):\n for i in range(len(arr)):\n print(arr[:i], arr[i:])\n print(sum(arr[:i]), sum(arr[i+1:]))\n if sum(arr[:i]) == sum(arr[i+1:]):\n return i\n return -1\n\nprint('\\n',find_even_index([10,-80,10,10,15,35,20]),'answer')'''\n\n'''def order(sentence):\n return ' '.join(sorted(list(map(lambda x: ''.join(sorted(x)), sentence.split(' '))).))\nprint(order(\"is2 Thi1s T4est 3a\"))'''\n\n'''def reverseWords(str):\n return ' '.join(\"hello world!\".split(' ')[::-1])\n\n\n\nprint(reverseWords(\"hello world!\"))\n\n\ndef find_outlier(integers):\n x = list(map(lambda x: x%2, integers))\n print(x)\n if sorted(x)[1] == 0:\n for i in integers:\n if i%2==1:\n return i\n elif sorted(x)[1] == 1:\n for i in integers:\n if i%2==0:\n return i\n\nprint(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]))'''\n\n# def middle_permutation(string):\n# return ''.join(sorted(string))[len(''.join(sorted(string))) // 2 -1] + ''.join(sorted(''.join(sorted(string))[:len(''.join(sorted(string))) // 2 -1] + ''.join(sorted(string))[len(''.join(sorted(string))) // 2:]))[::-1] if len(string) % 2 == 0 else ''.join(sorted(string))[len(''.join(sorted(string))) // 2] + ''.join(sorted(string))[len(''.join(sorted(string))) // 2-1] +''.join(sorted(''.join(sorted(string))[:(len(''.join(sorted(string))) // 2)-1] + ''.join(sorted(string))[(len(''.join(sorted(string))) // 2-1)+2:]))[::-1]\n\n\n'''def format_duration(seconds):\n final_string = ''\n if seconds == 0:\n return 'now'\n y = seconds // 31536000\n d = (seconds - y * 31536000) // 86400\n h = (seconds - y * 31536000 - d * 86400) // 3600\n m = (seconds - y * 31536000 - d * 86400 - h * 3600) // 60\n s = (seconds - y * 31536000 - d * 86400 - h * 3600 - m * 60)\n lst_to_print = [y,d,h,m,s]\n lst_of_letters = [['year','years'],['day','days'],['hour','hours'],['minute','minutes'],['second','seconds']]\n if y > 0:\n if y > 1:\n lst_to_print[0] = str(y) + ' ' + lst_of_letters[0][1]\n else:\n lst_to_print[0] = str(y) + ' ' + lst_of_letters[0][0]\n if d > 0:\n if d > 1:\n lst_to_print[1] = str(d) + ' ' + lst_of_letters[1][1]\n else:\n lst_to_print[1] = str(y) + ' ' + lst_of_letters[1][0]\n if h > 0:\n if h > 1:\n lst_to_print[2] = str(h) + ' ' + lst_of_letters[2][1]\n else:\n lst_to_print[2] = str(h) + ' ' + lst_of_letters[2][0]\n if m > 0:\n if m > 1:\n lst_to_print[3] = str(m) + ' ' + lst_of_letters[3][1]\n else:\n lst_to_print[3] = str(m) + ' ' + lst_of_letters[3][0]\n if s > 0:\n if s > 1:\n lst_to_print[4] = str(s) + ' ' + lst_of_letters[4][1]\n else:\n lst_to_print[4] = str(s) + ' ' + lst_of_letters[4][0]\n print(lst_to_print)\n lst_upd = []\n for i in range(len(lst_to_print)):\n if lst_to_print[i] != 0:\n lst_upd.append(lst_to_print[i])\n lst_to_print = lst_upd\n if len(lst_to_print) > 1:\n lst_to_print[-2] = ' and '.join([lst_to_print[-2], lst_to_print[-1]])\n lst_to_print.pop()\n return ', '.join(lst_to_print)\nprint(format_duration(62))'''\n\n'''def filter_list(l):\n listt = []\n for i in l:\n if str(i) != i and i >= 0:\n listt.append(i)\n return listt\nprint(filter_list([1,2,'aasf','1','123',123]))'''\n\n'''def find_all(sum_dig, digs):\n # your code here\n return []'''\n\n'''import itertools\ndef permutations(string):\n m = list(set(itertools.permutations(string)))\n print(m)\n for i in range(len(m)):\n m[i] = list(m[i])\n print(m[i])\n m[i] = ''.join(m[i])\n return m\nprint(permutations('ab'))'''\n'''\nROMAN_NUMERALS = (\n (\"M\", 1000),\n (\"CM\", 900),\n (\"D\", 500),\n (\"CD\", 400),\n (\"C\", 100),\n (\"XC\", 90),\n (\"L\", 50),\n (\"XL\", 40),\n (\"X\", 10),\n (\"IX\", 9),\n (\"V\", 5),\n (\"IV\", 4),\n (\"I\", 1),\n)\n\n\ndef solution(roman):\n decoded, index = 0, 0\n for symbol, value in ROMAN_NUMERALS:\n symlen = len(symbol)\n while roman[index:index + symlen] == symbol:\n decoded += value\n index += symlen\n return decoded\n\n\nx = (list('abcdea'))\nprint(x)\n\nx.remove('a')\nprint(x)\n'''\n\n'''\ndef solve(s):\n counter = 0\n for i in list(s): if i in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] else print(\"check\")\n\n #if i in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']: counter += 1\n # else:\n # counter -= 1\n #counter += 1 if i in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] else pass\n return s.upper() if counter>0 else s.lower()\nprint(solve(\"squaD\"))\n'''\n\n'''a, b = 0,1\n\n\ndef f(a, b):\n #return sum(range(sorted([a, b])[0], sorted([a, b])[1])) if a - b !=1 or a!=b or b - a !=1 else (a+b if a!=b else a)\n return \"check1\" if a - b !=1 and a!=b and b - a !=1 else (\"check2\" if a!=b else \"check3\")\n\nprint(f(a,b))\nprint(sorted([0,-1]))'''\n\n'''\nclass Calculator(object):\n def evaluate(self, string):\n #self.list_of_symbols = []\n #counter = 0\n #for i in range(len(string)):\n # if string[i] != \" \":\n # if string[i].isdecimal():\n # print(counter)\n # self.list_of_symbols.append(string[i])\n # else:\n # counter+=1\n # self.list_of_symbols.append(string[i])\n string = string.split(' ')\n try:\n for i in range(len(string)):\n if string[i] == '/':\n string[i-1]= float(string[i-1])/float(string[i+1])\n del (string[i])\n del string[i]\n except:\n pass\n print(string)\n\n try:\n for i in range(len(string)):\n if string[i] == '*':\n string[i - 1] = float(string[i-1])*float(string[i+1])\n del (string[i])\n del (string[i])\n print(string)\n except:\n pass\n print(string)\n try:\n for i in range(len(string)):\n if string[i] == '-':\n string[i - 1] = float(string[i-1])-float(string[i+1])\n del (string[i])\n del (string[i])\n print(string)\n except:\n pass\n try:\n newlist = []\n for i in range(len(string)):\n try:\n newlist.append(float(string[i]))\n except:\n pass\n string = sum(newlist)\n except:\n pass\n\n return string\n\nprint(Calculator().evaluate(\"2 + 3 * 4 / 3 - 6 / 3 * 3 + 8\"), ' this is final result')\n'''\n\n'''def find_even_index(arr):\n for i in range(len(arr)):\n if i == 0:\n if sum(arr[1::]) == 0: return 0\n elif sum(arr[0:i]) == sum(arr[i+1::]):\n return i\n print(arr[0:i], arr[i+1::])\n return -1\nprint(find_even_index([1,2,3,4,3,2,1]))'''\n\n'''\ndef longest_repetition(chars):\n check = []\n check1 = []\n for i in chars:\n if i not in check:\n check.append(i)\n check1.append(1)\n print(check)\n else:\n check1[check.index(i)] += 1\n if check ==[]:\n return '', 0\n return check[check1.index(max(check1))], max(check1)\n\nprint(longest_repetition(\"bbbaaabaaaa\"))\n'''\n\n\"\"\"\ndef calc(expression):\n expression = list(expression)\n while ' ' in expression:\n expression.remove(' ')\n try:\n for i in range(len(expression)):\n if expression[i] == '/':\n expression[i - 1] = float(expression[i - 1]) / float(expression[i + 1])\n del (expression[i])\n del expression[i]\n except:\n pass\n print(expression)\n\n try:\n for i in range(len(expression)):\n if expression[i] == '*':\n expression[i - 1] = float(expression[i - 1]) * float(expression[i + 1])\n del (expression[i])\n del (expression[i])\n print(expression)\n except:\n pass\n print(expression)\n try:\n for i in range(len(expression)):\n if expression[i] == '-':\n expression[i - 1] = float(expression[i - 1]) - float(expression[i + 1])\n del (expression[i])\n del (expression[i])\n print(expression)\n except:\n pass\n try:\n newlist = []\n for i in range(len(expression)):\n try:\n newlist.append(float(expression[i]))\n except:\n pass\n string = sum(newlist)\n except:\n pass\n return expression\n\n\nprint(calc(\"-7 * -(6 / 3)\"))\n\"\"\"\n'''\ndef find_it(seq):\n ll = list()\n for i in range(len(seq)):\n if seq[i] not in seq[0:i]:\n ll.append(0)\n for j in seq[i::]:\n if j == seq[i]:\n ll[-1] += 1\n return ll\n\nprint(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]))\n'''\n\n'''def twice_as_old(dad_years_old, son_years_old):\n dad = dad_years_old\n if son_years_old*2 <dad_years_old:\n while dad_years_old/2 != son_years_old and dad_years_old>0: dad_years_old -= 1\n return dad - dad_years_old\n else:\n while dad_years_old / 2 != son_years_old and dad_years_old > 0: dad_years_old += 1\n return dad_years_old-dad\n\n\nprint(twice_as_old(36,31))\n'''\"\"\"\ndef disemvowel(string):\n stri = ''\n for i in range(len(string)):\n if string[i].lower() not in ['a','o','e','u','i']:\n stri += string[i]\n return stri\nprint(disemvowel(\"This website is for losers LOL!\"))\n\"\"\"\n\n# def get_participants(handshakes):\n# if handshakes == 0:\n# return 1\n# elif handshakes == 1:\n# return 2\n# elif handshakes <= 3:\n# return 3\n#\n# n_sides = 4\n# counter_for_inner = 2\n# n_inner = 2\n# while True:\n# if n_sides + n_inner >= handshakes:\n# return n_sides\n# else:\n# n_sides += 1\n# counter_for_inner += 1\n# n_inner += counter_for_inner\n#\n#\n# print(get_participants(7))\n# from math import sqrt\n#\n#\n# def F(n):\n# return round(((1 + sqrt(5)) ** n - (1 - sqrt(5)) ** n) / (2 ** n * sqrt(5)))\n#\n#\n# def fibo_check():\n# ch = [F(i) for i in range(160)]\n# return ch\n#\n#\n# print(fibo_check())\n#\n#\n# def productFib(prod):\n# n = 0\n# while n < prod:\n# if F(n) * F(n + 1) == prod:\n# return [F(n), F(n + 1), True]\n# elif F(n) * F(n + 1) > prod:\n# print([F(n), F(n + 1), F(n) * F(n + 1)])\n# return [F(n), F(n + 1), False]\n# else:\n# n += 1\n# return [F(n), F(n + 1), False]\n#\n#\n# print(productFib(203023208030065646654504166904697594722575))\n# print(round(F(8)))\n#\n# # python program to check if x is a perfect square\n# import math\n#\n#\n# # A utility function that returns true if x is perfect square\n# def isPerfectSquare(x):\n# s = int(math.sqrt(x))\n# return s * s == x\n#\n#\n# # Returns true if n is a Fibinacci Number, else false\n# def isFibonacci(n):\n# # n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both\n# # is a perferct square\n# return isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4)\n#\n#\n# print(isFibonacci(573147844013817084101))\n\n# from collections import Counter\n#\n#\n# def find_it(seq: list) -> int:\n#\n# list_odd_num = seq\n#\n# dict_odd_num = dict(Counter(list_odd_num))\n#\n# for i in dict_odd_num.keys():\n# if dict_odd_num.get(i) % 2 != 0:\n# return i\n# return 0\n#\n#\n# print(find_it([20, 1, 1, -1, -1, -1, -2, 5]))\n\n\n# print(str(bin(15))[2::].count('1'))\n#\n# import itertools\n#\n#\n# def get_pins(observed: str) -> list:\n# NUM_DICT: Dict[str, List[str]] = {'1': ['1', '2', '4'],\n# '2': ['1', '2', '3', '5'],\n# '3': ['2', '3', '6'],\n# '4': ['1', '4', '5', '7'],\n# '5': ['2', '4', '5', '6', '8'],\n# '6': ['3', '5', '6', '8'],\n# '7': ['4', '7', '8'],\n# '8': ['5', '7', '8', '9', '0'],\n# '9': ['6', '8', '9'],\n# '0': ['8', '0']\n# }\n# pre_result_list = []\n# for i in observed:\n# pre_result_list.append(NUM_DICT[i])\n# print(pre_result_list)\n# print(sorted(\n# ['13', '15', '16', '19', '43', '45', '46', '49', '53', '55', '56', '59', '73', '75', '76', '79']))\n#\n# result_list = []\n# print(sorted([''.join(i) for i in (list(itertools.product(*[i for i in pre_result_list])))]))\n# return result_list\n#\n#\n# print(get_pins('46'))\n\n\ndef iq_test(numbers: str) -> int:\n # if even -> True, if odd -> False\n # False default\n numbers = [int(i) for i in numbers.split()]\n even_or_odd = False\n\n if len(numbers) < 3:\n return 0\n\n counter = 0\n for i in numbers[:3]:\n print(i)\n if i % 2 == 0:\n counter += 1\n else:\n counter -= 1\n\n if counter < 0:\n even_or_odd = True\n print(even_or_odd)\n for i, j in enumerate(numbers):\n if (j % 2 == 0) is even_or_odd:\n return i+1\n\nprint(iq_test(\"1 2 2\"))\n","sub_path":"suma_of_numbers.py","file_name":"suma_of_numbers.py","file_ext":"py","file_size_in_byte":26881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"331052645","text":"\n\nfrom xai.brain.wordbase.adjectives._runny import _RUNNY\n\n#calss header\nclass _RUNNIEST(_RUNNY, ):\n\tdef __init__(self,): \n\t\t_RUNNY.__init__(self)\n\t\tself.name = \"RUNNIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"runny\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_runniest.py","file_name":"_runniest.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"260944882","text":"import numpy as np\n\n\ndef variance(array, length, math_expectation):\n\n # variable prb is for probability\n # of each element which is same for\n # each element\n prb = 1 / length\n\n # calculating expectation overall\n sum = 0\n for i in range(0, length):\n sum += prb * pow(array[i] - math_expectation, 2)\n\n # returning expectation as sum\n value = float(sum)\n\n return value\n\n\ndef get_variance_from_column(column, math_expectation):\n return variance(column.values, column.values.size, math_expectation)\n","sub_path":"StatisticalHypotheses/variance.py","file_name":"variance.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"62119921","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Article',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(unique=True, max_length=150)),\n ('image', models.ImageField(default=b'default/nieuws.png', upload_to=b'article/%Y')),\n ('text', models.TextField()),\n ('slug', models.SlugField(unique=True, max_length=150)),\n ('published', models.BooleanField(default=False)),\n ('created_date', models.DateTimeField(auto_now_add=True)),\n ('modified', models.DateTimeField(auto_now=True)),\n ('author', models.ForeignKey(editable=False, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='City',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(unique=True, max_length=25)),\n ('picture', models.FileField(default=b'default/nieuws.png', upload_to=b'city/')),\n ('video', models.BooleanField(default=False)),\n ('video_url', models.URLField(null=True, blank=True)),\n ('twitter', models.CharField(max_length=250, blank=True)),\n ('facebook', models.CharField(max_length=250, blank=True)),\n ('youtube', models.CharField(max_length=250, blank=True)),\n ('bezoek_adres', models.TextField(blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Mensen',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('title', models.CharField(max_length=50, blank=True)),\n ('text', models.TextField(blank=True)),\n ('email', models.EmailField(max_length=50, blank=True)),\n ('phone', models.CharField(max_length=20, blank=True)),\n ('image', models.ImageField(default=b'default/nieuws.png', upload_to=b'mensen/')),\n ('published', models.BooleanField(default=False)),\n ('city', models.ManyToManyField(to='cities_news.City')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Punten',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nummer', models.CharField(max_length=50)),\n ('title', models.CharField(unique=True, max_length=100)),\n ('text', models.TextField()),\n ('slug', models.SlugField(unique=True, max_length=100)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Standpunten',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('kopje', models.CharField(max_length=100)),\n ('nummer', models.CharField(max_length=50)),\n ('city', models.ManyToManyField(to='cities_news.City')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('word', models.CharField(unique=True, max_length=35)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='punten',\n name='standpunt',\n field=models.ForeignKey(to='cities_news.Standpunten'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='article',\n name='city',\n field=models.ManyToManyField(to='cities_news.City'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='article',\n name='tags',\n field=models.ManyToManyField(to='cities_news.Tag'),\n preserve_default=True,\n ),\n ]\n","sub_path":"cities_news/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"398807009","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2020/3/23 8:51\r\n# @Author : shajiu\r\n# @FileName: test51.py\r\n# @Software: PyCharm\r\nMAXIMUM=lambda x,y:(x>y)*x+(x<y)*y\r\nMINIMUM=lambda x,y:(x>y)*y+(x<y)*x\r\n\r\nif __name__ == '__main__':\r\n a=10\r\n b=20\r\n print(\"The largar one is %d\"%MAXIMUM(a,b))\r\n print(\"The largar one is %d\"%MINIMUM(a,b))","sub_path":"Python_1-100/test51.py","file_name":"test51.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"24500106","text":"import asyncio\nimport aioodbc\nimport time\nimport sys\nimport concurrent.futures\n\nfrom functools import partial\n\ndsn = 'Driver={ODBC Driver 17 for SQL Server};Server=192.168.2.27;\\\n Database=db_iconcrm_fusion;uid=crmv;pwd=apt@ven2018'\n\nconnect = partial(aioodbc.connect, dsn=dsn, echo=True, autocommit=True)\n\nasync def procbatchx(loop=None, totl=None, mod_numb=None):\n async with aioodbc.connect(dsn=dsn, loop=loop) as conn:\n async with conn.cursor() as cur:\n strSQL = \"\"\"\n SELECT ContactID\n FROM dbo.ICON_EntForms_Contacts\n WHERE ISNUMERIC(ContactID) = 1\n AND CAST(ContactID AS BIGINT)%{} = {}\n \"\"\".format(totl, mod_numb)\n\n await cur.execute(strSQL)\n rows = await cur.fetchall()\n\n for row in rows:\n print(row.ContactID)\n sql = \"INSERT INTO dbo.kai ( ContactIDkai ) \\\n VALUES (N'{}')\".format(row.ContactID)\n await cur.execute(sql)\n await cur.commit()\n\n\nif __name__ == '__main__':\n print(\"####### Begin ########\")\n # python3 BatchMigrateCRM1.py <TOTAL MOD> <MOD_NUMBER>\n totl = sys.argv[1]\n mod_numb = sys.argv[2]\n start = time.perf_counter()\n loop = asyncio.get_event_loop()\n loop.run_until_complete(procbatchx(loop, totl, mod_numb))\n elapsed = time.perf_counter() - start\n print(f\"Program completed in {elapsed:0.5f} seconds.\")\n\n","sub_path":"BatchMigrateCRM1.py","file_name":"BatchMigrateCRM1.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"123219306","text":"import logging\nfrom dataclasses import dataclass\nfrom threading import Event\nfrom typing import Optional\n\nimport boto3\nimport mesh_client\n\nfrom s3mesh.forwarder import MeshToS3Forwarder, RetryableException\nfrom s3mesh.mesh import MeshInbox\nfrom s3mesh.monitoring.probe import LoggingProbe\nfrom s3mesh.s3 import S3Uploader\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass MeshConfig:\n url: str\n mailbox: str\n password: str\n shared_key: bytes\n client_cert_path: str\n client_key_path: str\n ca_cert_path: str\n\n\n@dataclass\nclass S3Config:\n bucket_name: str\n endpoint_url: Optional[str]\n\n\nclass MeshToS3ForwarderService:\n def __init__(\n self,\n forwarder: MeshToS3Forwarder,\n poll_frequency_sec: int,\n exit_event: Optional[Event] = None,\n ):\n self._forwarder = forwarder\n self._exit_event = exit_event or Event()\n self._poll_frequency_sec = poll_frequency_sec\n\n def start(self):\n logger.info(\"Started forwarder service\")\n while not self._exit_event.is_set():\n try:\n self._forwarder.forward_messages()\n\n if self._forwarder.is_mailbox_empty():\n self._exit_event.wait(self._poll_frequency_sec)\n except RetryableException:\n self._exit_event.wait(self._poll_frequency_sec)\n logger.info(\"Exiting forwarder service\")\n\n def stop(self):\n logger.info(\"Received request to stop\")\n self._exit_event.set()\n\n\ndef build_forwarder_service(\n mesh_config: MeshConfig,\n s3_config: S3Config,\n poll_frequency_sec,\n) -> MeshToS3ForwarderService:\n s3 = boto3.client(service_name=\"s3\", endpoint_url=s3_config.endpoint_url)\n uploader = S3Uploader(s3, s3_config.bucket_name)\n\n mesh = mesh_client.MeshClient(\n mesh_config.url,\n mesh_config.mailbox,\n mesh_config.password,\n shared_key=mesh_config.shared_key,\n cert=(mesh_config.client_cert_path, mesh_config.client_key_path),\n verify=mesh_config.ca_cert_path,\n )\n inbox = MeshInbox(mesh)\n forwarder = MeshToS3Forwarder(inbox, uploader, LoggingProbe())\n return MeshToS3ForwarderService(forwarder, poll_frequency_sec)\n","sub_path":"src/s3mesh/forwarder_service.py","file_name":"forwarder_service.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"461536378","text":"from sys import argv, stdin\nimport argparse\n\nfrom .__init__ import render_file, render_text\n\ndef main():\n def isint(i):\n try:\n int(i)\n return True\n except ValueError:\n return False\n\n def isfloat(f):\n try:\n float(f)\n return True\n except ValueError:\n return False\n\n parser = argparse.ArgumentParser(\n description='Use the MiniTemple templating engine'\n )\n\n parser.add_argument('filename', metavar='FILENAME')\n\n parser.add_argument('--tags', '-t', action='store', nargs=2, default=None)\n\n parser.add_argument('--output', '-o', action='store', default='-')\n\n parser.add_argument('--scope', '-s', action='append', nargs=2)\n parser.add_argument('--debug', '-d', action='store_true', default=False)\n\n\n options = parser.parse_args(argv[1:])\n outfilename = options.output\n\n filename = options.filename\n\n scope = {}\n\n if options.scope:\n for key, value in options.scope:\n if value == 'True':\n value = True\n elif value == 'False':\n value = False\n elif value == 'None':\n value = None\n elif isint(value):\n value = int(value)\n elif isfloat(value):\n value = float(value)\n scope[key] = value\n\n\n opt_d = {}\n if options.tags:\n opt_d = options.tags\n\n if options.debug:\n opt_d['debug'] = True\n\n if outfilename == '-':\n if filename == '-':\n print(render_text(stdin.read(), scope, **opt_d), end='')\n else:\n print(render_file(filename, scope, **opt_d), end='')\n else:\n with open(outfilename, 'w') as fout:\n if filename == '-':\n print(render_text(stdin.read(), scope, **opt_d), end='', file=fout)\n else:\n print(render_file(filename, scope, **opt_d), end='', file=fout)\n","sub_path":"MiniTemple/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"20735228","text":"#!/usr/bin/env python\n\nimport pickle\nimport tensorflow as tf\nimport numpy as np\nimport tf_util\nimport gym\nimport load_policy\nimport sys\nfrom sklearn.model_selection import train_test_split\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.optimizers import RMSprop\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('expert_policy_file', type=str)\n parser.add_argument('envname', type=str)\n parser.add_argument('--render', action='store_true')\n parser.add_argument(\"--max_timesteps\", type=int)\n parser.add_argument(\"--dagger_iterations\", type=int)\n parser.add_argument('--num_rollouts', type=int, default=20,\n help='Number of expert roll outs')\n args = parser.parse_args()\n\n f = open(\"expert_data/expert_data_\" + args.envname + \".picke\", \"rb\")\n data = pickle.load(f)\n\n print(\"data: \", data)\n print(\"actions shape: \", data['actions'].shape)\n print(\"observations shape: \", data['observations'].shape)\n \n data['actions'] = np.squeeze(data['actions'], axis=1)\n print(data['actions'].shape)\n\n # some code inspired from\n # https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py\n model = Sequential()\n model.add(Dense(50, activation='relu',\n input_shape=data['observations'][0].shape))\n model.add(Dropout(0.2))\n model.add(Dense(50, activation='relu'))\n model.add(Dropout(0.2))\n model.add(Dense(data['actions'][0].shape[0], activation='linear')) \n model.summary()\n model.compile(loss='mean_squared_error',\n optimizer=RMSprop(),\n metrics=['accuracy'])\n\n print('loading and building expert policy')\n policy_fn = load_policy.load_policy(args.expert_policy_file)\n \n X = data['observations']\n Y = data['actions']\n \n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, test_size=0.2, random_state=42)\n\n dagger_iterations = args.dagger_iterations or 200\n with tf.Session():\n while dagger_iterations > 0:\n dagger_iterations = dagger_iterations - 1\n # train BC\n model.fit(X_train, Y_train,\n batch_size = 20,\n epochs=4,\n verbose=0)\n\n score = model.evaluate(X_train, Y_train, verbose=1)\n\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])\n\n # run BC and expert in lock step\n tf_util.initialize()\n\n env = gym.make(args.envname)\n max_steps = args.max_timesteps or env.spec.timestep_limit\n\n returns = []\n observations = []\n actions = []\n\n for i in range(args.num_rollouts):\n print('Iteration', i)\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n while not done:\n expert_action = policy_fn(obs[None,:])\n bc_action = model.predict(obs[None,:])\n\n observations.append(obs)\n actions.append(expert_action)\n\n # Humanoid task has action with dimension 17\n obs, r, done, _ = env.step(bc_action)\n\n totalr += r\n steps += 1\n if args.render:\n env.render()\n if steps % 100 == 0: print(\"%i/%i\"%(steps, max_steps))\n if steps >= max_steps:\n break\n returns.append(totalr)\n\n # and aggregate observations from BC <-> decisions from expert\n print(args.envname + \" clone mean return: \", np.mean(returns))\n print(args.envname + \" clone std return: \", np.std(returns))\n\n actions_array = np.array(actions)\n actions_array = np.squeeze(actions_array, axis=1)\n\n X_train = np.vstack((X_train, np.array(observations)))\n Y_train = np.vstack((Y_train, actions_array))\n\n # loop\n\nif __name__ == '__main__':\n main()\n","sub_path":"hw1/Dagger_task.py","file_name":"Dagger_task.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"363129025","text":"#!/usr/bin/env python\n#-*-coding:utf-8-*-\n\nfrom tkinter import *\nroot = Tk()\ntext = Text(root, width = 30, height = 10)\ntext.pack()\ntext.insert(INSERT, \"I love python\")\ntext.mark_set(\"here\", \"1.2\")\ntext.insert(\"here\", \"插\")","sub_path":"TestForFun/Tkinter.py","file_name":"Tkinter.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"531507968","text":"from heapq import heappop, heappush\nfrom math import inf\n\n\ndef dijkstras(graph, start):\n distances = {}\n \n for vertex in graph:\n distances[vertex] = inf\n \n distances[start] = 0\n vertices_to_explore = [(0, start)]\n \n while vertices_to_explore:\n current_distance, current_vertex = heappop(vertices_to_explore)\n \n for neighbor, edge_weight in graph[current_vertex]:\n new_distance = current_distance + edge_weight\n \n if new_distance < distances[neighbor]:\n distances[neighbor] = new_distance\n heappush(vertices_to_explore, (new_distance, neighbor))\n \n return distances\n","sub_path":"Dijkstra's Algorithm.py","file_name":"Dijkstra's Algorithm.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"296993191","text":"#动态语言的是高级程序设计语言的一个类别,它是一类在运行时可以改变其结构的语言:\n#列如新的函数,对象,甚至代码可以被引进,已有的函数可以被删除或者是其他结构上的\n#变化。动态语言目前非常具有活力。\n\n\n#运行的过程中给对象绑定(添加)属性\n# class Person(object):\n# def __init__(self, name = None, age = None):\n# self.name = name\n# self.age = age\n#\n# p = Person('xiaoming', 17)\n# print(p)\n#\n# p.sex = 'helo'\n# print(p.sex)\n\n\n# class Person(object):\n# def __init__(self, name, age):\n# self.name = name\n# self.age = age\n#\n# def eat(self):\n# print('eat food')\n#\n#\n#\n# def run(self, speed):\n# print('{} 在移动,速度是 {}'.format(self.name, speed))\n#\n#\n# p = Person('老王', 20)\n# p.eat()\n#\n#\n# import types\n#\n# p.run = types.MethodType(run, p)\n#\n# p.run(200)\n\nimport types\n\n#定义一个类\nclass Person(object):\n num = 0\n def __init__(self, name = None, age = None):\n self.name = name\n self.age = age\n\n def eat(self):\n print('eat food')\n\n\ndef run(self, speed):\n print('{} 在移动,速度是 {}'.format(self.name, speed))\n\n@classmethod\ndef testclass(cls):\n cls.num = 100\n\n@staticmethod\ndef static_fun():\n print('这是一个静态方法')\n\np = Person('老王', 20)\np.eat()\n#给这个对象添加实例方法\np.run = types.MethodType(run, p)\np.run(200)\n\n#给Person绑定类方法\nPerson.testClass = testclass\n#调用类方法\nprint(Person.num)\nPerson.testClass()\nprint(Person.num)\n\n\n#给Person类绑定静态方法\nPerson.static_fun = static_fun\nPerson.static_fun()\n\n","sub_path":"就业/python高级/03/动态语言.py","file_name":"动态语言.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"101638077","text":"\"\"\"\ndoor_new_visitor\n\"\"\"\n\nimport json\nimport string\nimport random\nimport boto3\nimport time\n\ndef lambda_handler(event, context):\n \n \"\"\"\n Use the faceId to attempt to extract pending visitor.\n \"\"\"\n face_id = event[\"face_id\"]\n dynamodb = boto3.resource('dynamodb', region_name='us-west-2')\n pending_table = dynamodb.Table(\"pending\")\n pending_response = pending_table.get_item(Key={\"faceId\": face_id})\n \n \"\"\"\n If visitor does not exist in pending table return nonexistent confirmation\n \"\"\"\n if len(pending_response) < 2:\n return {\n \"body\": {\n \"exists\": \"False\",\n \"face_id\": face_id\n }\n }\n \n if event[\"approved\"] == \"True\":\n \n \"\"\"\n 1) Take in faceId object from Gateway.\n \"\"\"\n visitor_name = event[\"name\"]\n visitor_phone_number = event[\"phone_number\"]\n \n \"\"\"\n 2) Get pending visitor object.\n \"\"\"\n pending_visitor = pending_response[\"Item\"]\n \n \"\"\"\n 3) Delete object from pending table.\n \"\"\"\n pending_table.delete_item(Key={\"faceId\": face_id})\n \n \"\"\"\n 4) Put visitor into visitors table.\n \"\"\"\n visitor = {\n \"faceId\": face_id,\n \"name\": visitor_name,\n \"phoneNumber\": visitor_phone_number,\n \"photos\": pending_visitor[\"photos\"]\n }\n visitors_table = dynamodb.Table(\"visitors\")\n visitors_table.put_item(Item=visitor)\n \n \"\"\"\n 5) Create OTP and record it in passcodes table.\n \"\"\"\n passcodes_table = dynamodb.Table(\"passcodes\")\n otp = ''.join([random.choice(string.ascii_lowercase+string.ascii_uppercase+string.digits)\\\n for n in range(10)])\n seeded = int(time.time())\n expiration = seeded + 300\n otp_object = {\n \"otp\": otp,\n \"faceId\": face_id,\n \"seeded\": str(seeded),\n \"expiration\": str(expiration)\n }\n passcodes_table.put_item(Item=otp_object)\n \n \"\"\"\n 6) Send SNS to vistor with OTP.\n \"\"\"\n msg = \"Your OTP:\\n{}\".format(otp)\n print(\"Newly Visitor: {} Phone Number: {}\".format(visitor_name, visitor_phone_number))\n sns = boto3.client(\"sns\")\n sns.publish(PhoneNumber=visitor_phone_number, Message=msg)\n \n \"\"\"\n 7) Return confirmation JSON object.\n \"\"\"\n response_object = {\n \"body\": {\n \"exists\": \"True\",\n \"name\": visitor_name,\n \"phone_number\": visitor_phone_number,\n \"otp\": otp\n }\n }\n \n return response_object\n \n else:\n \"\"\"\n 1) Get pending object.\n \"\"\"\n pending_visitor = pending_response[\"Item\"]\n \n \"\"\"\n 2) Delete pending visitor from pending table.\n \"\"\"\n pending_table.delete_item(Key={\"faceId\": face_id})\n \n \"\"\"\n 3) Get photo name and delete photo from S3 bucket.\n \"\"\"\n photo = pending_visitor[\"photos\"][0]\n s3_client = boto3.client(\"s3\")\n s3_client.delete_object(Bucket=\"ds-b1\", Key=photo[\"objectkey\"])\n \n \"\"\"\n 4) Delete photo from Rekognition collection.\n \"\"\"\n rekognition_client = boto3.client(\"rekognition\")\n rekognition_client.delete_faces(\n CollectionId=\"door-security\",\n FaceIds=[face_id]\n )\n \n \"\"\"\n 5) Return denial response.\n \"\"\"\n denial_response = {\n \"body\": {\n \"exists\": \"True\",\n \"face_id\": face_id\n }\n }\n \n return denial_response","sub_path":"door_new_visitor_lambda/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"147250432","text":"# build.py\nimport os\nimport platform\nfrom setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext\n\n\nextra_compile_args = ['-std=c++11', '-fPIC']\n\nenable_gpu = ('CUDA_HOME' in os.environ)\nif not enable_gpu:\n print(\"CUDA_HOME not found in the environment so building \"\n \"without GPU support. To build with GPU support \"\n \"please define the CUDA_HOME environment variable. \"\n \"This should be a path which contains include/cuda.h\")\n\nif platform.system() == 'Darwin':\n lib_ext = \".dylib\"\n extra_compile_args.extend(['-DAPPLE', '-stdlib=libc++', '-mmacosx-version-min=10.8'])\nelse:\n lib_ext = \".so\"\n extra_compile_args.append('-fopenmp')\n\nif enable_gpu:\n extra_compile_args += ['-DWARPCTC_ENABLE_GPU']\n\n\next_modules = [\n Extension(\n 'warpctc_pytorch._warp_ctc',\n sources=[\n 'src/binding.cpp',\n os.path.realpath('../src/ctc_entrypoint.cpp')\n ],\n extra_compile_args=extra_compile_args,\n language='c++'\n )\n]\n\n\nclass BuildExt(build_ext):\n def build_extensions(self):\n import torch\n\n torch_dir = os.path.dirname(torch.__file__)\n include_dirs = [\n os.path.realpath('../include'),\n os.path.join(torch_dir, 'lib/include'),\n os.path.join(torch_dir, 'lib/include/TH'),\n os.path.join(torch_dir, 'lib/include/THC'),\n ]\n\n if enable_gpu:\n include_dirs.append(os.path.join(os.environ['CUDA_HOME'], 'include'))\n\n for ext in self.extensions:\n ext.include_dirs = include_dirs\n\n build_ext.build_extensions(self)\n\n\nsetup(\n name=\"warpctc_pytorch\",\n version=\"0.1\",\n description=\"PyTorch wrapper for warp-ctc\",\n url=\"https://github.com/baidu-research/warp-ctc\",\n author=\"Jared Casper, Sean Naren\",\n author_email=\"jared.casper@baidu.com, sean.narenthiran@digitalreasoning.com\",\n license=\"Apache\",\n packages=[\"warpctc_pytorch\"],\n setup_requires=['pybind11>=2.2.1', 'torch'],\n install_requires=['pybind11>=2.2.1', 'torch'],\n ext_modules=ext_modules,\n cmdclass={'build_ext': BuildExt},\n test_suite='tests',\n)\n","sub_path":"pytorch_binding/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"214400536","text":"import os\nfrom collections import defaultdict\nimport threading\n\nimport website.settings\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\n\nfrom django.core.files import File\n\nfrom timeseries_analyzer import TimeSeriesAnalyzer\nfrom timeseries_report_generator import ReportGenerator\nfrom models import Job, TimeSeriesJob\n\nclass TimeSeriesHandler(threading.Thread):\n def __init__(self, datafile, output, job_title, count):\n threading.Thread.__init__(self)\n self.datafile = datafile\n self.output = output\n self.job_title = job_title\n self.count = count\n\n def run(self):\n self.time_series_handler(self.datafile, self.output, self.job_title)\n\n def time_series_handler(self, datafile, output, job_title):\n an = TimeSeriesAnalyzer(datafile)\n #an = TimeSeriesAnalyzer('/Users/zhenjiangzhu/code/summer/code/test_code/kernel/data/02-solar.mat')\n \n summary_dict = an.plot_summary()\n\n linear_regression_dict = an.plot_linear_regression()\n\n #job_title = '02-solar'\n\n gen = ReportGenerator(output)\n # general dict\n gd = defaultdict(str)\n gd['type'] = 'general'\n gd['author'] = 'John'\n gd['title'] = 'An Automatic Report for dataset %s' % job_title\n\n # summary dict\n sd = defaultdict(str)\n m3_lst = an.m3()\n table_body = gen.create_summary_table(m3_lst)\n sd['type'] = 'summary'\n sd['summary_plot'] = summary_dict['plot_output_name']\n sd['table_body'] = table_body\n\n # linear regression dict\n ld = defaultdict(str)\n ld['type'] = 'linear_regression'\n ld['linear_regression_plot'] = linear_regression_dict['plot_output_name']\n\n # rbf regression dict\n svr_dict_rbf_1 = an.build_svr(kernel_id=1, gamma=0.01, file_num=1)\n svr_dict_rbf_2 = an.build_svr(kernel_id=1, gamma=1.0, file_num=2)\n\n rd = defaultdict(str)\n rd['type'] = 'rbf_regression'\n rd['plot_rbf1'] = svr_dict_rbf_1['plot_output_name']\n rd['plot_rbf2'] = svr_dict_rbf_2['plot_output_name']\n\n # composite kernel dict\n ck_dict_1 = an.build_composite_svr([0.7, 0.3, 0.], plot_output_name='plot_ck_1.png', gamma=0.01)\n ck_dict_2 = an.build_composite_svr([0.25, 0.75, 0.], plot_output_name='plot_ck_2.png', gamma=0.01)\n cd = defaultdict(str)\n cd['type'] = 'composite_kernel'\n cd['plot_ck_1'] = ck_dict_1['plot_output_name']\n cd['plot_ck_2'] = ck_dict_2['plot_output_name']\n\n gen.parse_args(**gd)\n gen.parse_args(**sd)\n gen.parse_args(**ld)\n gen.parse_args(**rd)\n gen.parse_args(**cd)\n\n gen.generate()\n #gen.print_tex()\n\n report_file = open(output + '.pdf')\n django_file = File(report_file)\n\n job = TimeSeriesJob.objects.get(job_id=self.count)\n job.reportfile = django_file\n job.in_lin_regr = linear_regression_dict['uni_content']\n job.in_svr_1 = svr_dict_rbf_1['uni_content']\n job.in_svr_2 = svr_dict_rbf_2['uni_content']\n job.in_ck_1 = ck_dict_1['uni_content']\n job.in_ck_2 = ck_dict_2['uni_content']\n job.available = True\n\n job.save()\n django_file.close()\n report_file.close()\n try:\n os.unlink(output + 'pdf') # delete the originally generated report file\n except:\n pass\n\n","sub_path":"code/website/job/time_series_handler.py","file_name":"time_series_handler.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"256389813","text":"from time import perf_counter,time,sleep\n\ndef doubles(number):\n for n in number:\n sleep(1)\n print('Double:',2*n)\n\ndef squares(number):\n for n in number:\n sleep(1)\n print('Square:',n**2)\n\nnumbers = [1,2,3,4,5,6]\n\nbegintime = perf_counter()\n\ndoubles(numbers)\nsquares(numbers)\n\nendtime = perf_counter()\n\nprint('The total time taken:',endtime-begintime)","sub_path":"Multithreading/without_multithreading.py","file_name":"without_multithreading.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"341158642","text":"#!/usr/bin/env python \n'''\nAuthor: Yushu Gao\nEmail: shuokay@gmail.com\nMSRA Paper: http://arxiv.org/pdf/1512.03385v1.pdf\n'''\n\nimport mxnet as mx\nimport logging\ndef ConvFactory(data, num_filter, kernel, stride=(1, 1), pad=(0, 0), act_type = 'relu'):\n conv = mx.symbol.Convolution(data = data, num_filter = num_filter, kernel = kernel, stride = stride, pad = pad)\n bn = mx.symbol.BatchNorm(data=conv)\n act = mx.symbol.Activation(data=bn, act_type=act_type)\n return act\n\ndef ResidualFactory(data, num_filter, diff_dim=False, stage1=False):\n if diff_dim:\n conv1 = ConvFactory( data=data, num_filter=num_filter[0], kernel=(1,1), stride=(2,2), pad=(0,0))\n conv2 = ConvFactory( data=conv1, num_filter=num_filter[1], kernel=(3,3), stride=(1,1), pad=(1,1))\n conv3 = mx.symbol.Convolution(data=conv2, num_filter=num_filter[2], kernel=(1,1), stride=(1,1), pad=(0,0))\n _data = mx.symbol.Convolution(data=data, num_filter=num_filter[2], kernel=(1,1), stride=(2,2), pad=(0,0))\n data = _data+conv3\n bn = mx.symbol.BatchNorm(data=data)\n act = mx.symbol.Activation(data=bn, act_type='relu')\n return act\n else:\n _data=data\n conv1 = ConvFactory(data=data, num_filter=num_filter[0], kernel=(1,1), stride=(1,1), pad=(0,0))\n conv2 = ConvFactory(data=conv1, num_filter=num_filter[1], kernel=(3,3), stride=(1,1), pad=(1,1))\n conv3 = ConvFactory(data=conv2, num_filter=num_filter[2], kernel=(1,1), stride=(1,1), pad=(0,0))\n data = _data+conv3\n bn = mx.symbol.BatchNorm(data=data)\n act = mx.symbol.Activation(data=bn, act_type='relu')\n return act\ndef ResidualSymbol(data):\n \"stage 1\"\n for i in xrange(3):\n if i == 0:\n _data = mx.symbol.Convolution(data=data, num_filter=256, kernel=(1,1), stride=(1,1), pad=(0,0))\n conv1 = ConvFactory( data=data, num_filter=64, kernel=(1,1), stride=(1,1), pad=(0,0))\n conv2 = ConvFactory( data=conv1, num_filter=64, kernel=(3,3), stride=(1,1), pad=(1,1))\n conv3 = mx.symbol.Convolution(data=conv2, num_filter=256, kernel=(1,1), stride=(1,1), pad=(0,0))\n data = _data+conv3\n bn = mx.symbol.BatchNorm(data=data)\n act = mx.symbol.Activation(data=bn, act_type='relu')\n data = act\n else:\n data = ResidualFactory(data, (64, 64, 256))\n \"stage 2\"\n for i in xrange(8):\n if i == 0:\n data = ResidualFactory(data, (128, 128, 512), True)\n else:\n data = ResidualFactory(data, (128, 128, 512))\n \"stage 3\"\n for i in xrange(36):\n if i == 0:\n data = ResidualFactory(data, (256, 256, 1024), True)\n else:\n data = ResidualFactory(data, (256, 256, 1024))\n \"stage 4\"\n for i in xrange(3):\n if i==0:\n data = ResidualFactory(data, (512, 512, 2048), True)\n else:\n data = ResidualFactory(data, (512, 512, 2048))\n return data\n\n\ndef get_dataiter(batch_size = 8):\n train_dataiter = mx.io.ImageRecordIter(\n path_imgrec = \"./train.rec\",\n rand_crop = True,\n rand_mirror = True,\n shuffle = True,\n data_shape = (3,224,224),\n batch_size = batch_size,\n preprocess_threads = 4,\n prefetch_buffer = 4,\n )\n test_dataiter = mx.io.ImageRecordIter(\n path_imgrec = \"./val.rec\",\n rand_crop = False,\n rand_mirror = False,\n data_shape = (3,224,224),\n batch_size = batch_size,\n preprocess_threads = 4,\n prefetch_buffer = 4,\n )\n return train_dataiter, test_dataiter\n\nif __name__=='__main__':\n logging.basicConfig(level=logging.DEBUG)\n \"before residual net\"\n data = ConvFactory(data=mx.symbol.Variable(name='data'), num_filter=64, kernel=(7,7), stride=(2,2), pad=(3,3))\n pool = mx.symbol.Pooling(data=data, kernel=(3,3), stride=(2,2), pad=(0,0), pool_type='max')\n\n \"get residual net\"\n res = ResidualSymbol(pool)\n\n \"global pooling + classify\"\n pool = mx.symbol.Pooling(data=res, kernel=(7,7), pool_type='avg')\n flatten = mx.symbol.Flatten(data=pool, name='flatten')\n \"set num_hidden=1000 when test on ImageNet competition dataset\"\n fc = mx.symbol.FullyConnected(data=flatten, num_hidden=200, name='fc1')\n softmax = mx.symbol.SoftmaxOutput(data=fc, name='softmax')\n\n \"uncomment the following two line to visualize resnet\"\n # g=mx.visualization.plot_network(softmax)\n # g.view()\n model = mx.model.FeedForward(ctx=mx.gpu(0), symbol=softmax, num_epoch=10, learning_rate=0.1, momentum=0.9, wd=0.0001,initializer=mx.init.Uniform(0.07))\n train_dataiter, test_dataiter = get_dataiter()\n model.fit(X=train_dataiter, eval_data=test_dataiter, batch_end_callback=mx.callback.Speedometer(8))\n\n","sub_path":"resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"276863133","text":"import requests\n\nurl_projects = \"https://sandbox.toloka.yandex.com/api/v1/projects\"\nurl_pools = \"https://sandbox.toloka.yandex.com/api/v1/pools\"\nurl_tasks = \"https://sandbox.toloka.yandex.com/api/v1/tasks\"\n\nOAuth_token = \"\"\nheaders = {'Authorization': f\"OAuth {OAuth_token}\", \"Content-type\": \"application/JSON\"}\n\nproject_data = {\n \"public_name\": \"Выделите все дорожные знаки на картинке (Final launch)\",\n \"public_description\": \"Посмотрите на фото и выделите все дорожные дорожные знаки.\",\n \"public_instructions\": \"Найдите на фото все дорожные знаки и выделите их в отдельные рамки.\",\n \"private_comment\": \"ismail2001\",\n \"task_spec\": {\n \"input_spec\": {\n \"image\": {\n \"type\": \"URL\",\n \"required\": True,\n \"hidden\": False\n }\n },\n \"output_spec\": {\n \"result\": {\n \"type\": \"json\",\n \"required\": True,\n \"hidden\": False\n }\n },\n \"view_spec\": {\n \"assets\": {\n \"script_urls\": [\"$TOLOKA_ASSETS/js/toloka-handlebars-templates.js\",\n \"$TOLOKA_ASSETS/js/image-annotation.js\"]\n },\n \"markup\": \"\"\"{{field type=\"image-annotation\" name=\"result\" src=image}}\"\"\",\n \"script\": \"\"\"exports.Task = extend(TolokaHandlebarsTask, function (options) {\n TolokaHandlebarsTask.call(this, options);\n}, {\n onRender: function() {\n // DOM element for task is formed (available via #getDOMElement()) \n },\n onDestroy: function() {\n // Task is completed. Global resources can be released (if used)\n }\n});\n\nfunction extend(ParentClass, constructorFunction, prototypeHash) {\n constructorFunction = constructorFunction || function () {};\n prototypeHash = prototypeHash || {};\n if (ParentClass) {\n constructorFunction.prototype = Object.create(ParentClass.prototype);\n }\n for (var i in prototypeHash) {\n constructorFunction.prototype[i] = prototypeHash[i];\n }\n return constructorFunction;\n}\"\"\",\n \"styles\": \"\"\"/* disable rectangle-editor controls */\n.image-annotation-editor__shape-rectangle {\n display: none;\n}\"\"\",\n \"settings\": {\n \"showSkip\": True,\n \"showTimer\": True,\n \"showTitle\": True,\n \"showSubmit\": True,\n \"showFullscreen\": True,\n \"showInstructions\": True,\n \"showFinish\": True,\n \"showMessage\": True,\n \"showReward\": True\n }\n }\n },\n \"assignments_issuing_type\": \"AUTOMATED\",\n \"assignments_automerge_enabled\": False,\n \"max_active_assignments_count\": 15,\n \"localization_config\": {\n \"default_language\": \"RU\"\n }\n}\n\nproject_response = requests.post(url=url_projects, headers=headers, json=project_data)\nprint(project_response.json())\nproject_id = requests.get(url=url_projects, headers=headers).json()[\"items\"][0][\"id\"]\n\npool_data = {\n \"project_id\": project_id,\n \"private_name\": \"Разметка дорожных знаков на фото попытка (this is a final launch)\",\n \"private_comment\": \"ismail2001\",\n \"public_description\": \"Посмотрите на картинку и выделите все дорожные знаки в отдельные рамки\",\n \"may_contain_adult_content\": False,\n \"will_expire\": \"2021-09-30T13:00\",\n \"reward_per_assignment\": 0.05,\n \"assignment_max_duration_seconds\": 300,\n \"auto_accept_solutions\": True,\n \"auto_accept_period_day\": 7,\n \"assignments_issuing_config\": {\n \"issue_task_suites_in_creation_order\": False\n },\n \"filter\": {\n \"and\": [{\n \"or\": [{\n \"category\": \"profile\",\n \"key\": \"country\",\n \"operator\": \"EQ\",\n \"value\": \"RU\"\n }]\n }, {\n \"or\": [{\n \"category\": \"profile\",\n \"key\": \"city\",\n \"value\": 213,\n \"operator\": \"IN\"\n }]\n }]\n },\n \"quality_control\": {\n \"configs\": [\n {\n \"collector_config\": {\n \"type\": \"ASSIGNMENT_SUBMIT_TIME\",\n \"parameters\": {\n \"history_size\": 10,\n \"fast_submit_threshold_seconds\": 3\n }\n },\n \"rules\": [\n {\n \"conditions\": [\n {\n \"key\": \"total_submitted_count\",\n \"operator\": \"EQ\",\n \"value\": 10\n },\n {\n \"key\": \"fast_submitted_count\",\n \"operator\": \"GTE\",\n \"value\": 4\n }\n ],\n \"action\": {\n \"type\": \"RESTRICTION_V2\",\n \"parameters\": {\n \"scope\": \"PROJECT\",\n \"duration_unit\": \"DAYS\",\n \"duration\": 7,\n \"private_comment\": \"4 или более быстрых ответа подряд\"\n }\n }\n }\n ]\n },\n {\n \"collector_config\": {\n \"type\": \"SKIPPED_IN_ROW_ASSIGNMENTS\"\n },\n \"rules\": [{\n \"conditions\": [{\n \"key\": \"skipped_in_row_count\",\n \"operator\": \"GTE\",\n \"value\": 10\n }],\n \"action\": {\n \"type\": \"RESTRICTION_V2\",\n \"parameters\": {\n \"scope\": \"PROJECT\",\n \"duration_unit\": \"DAYS\",\n \"duration\": 7,\n \"private_comment\": \"Пропущено 10 или более страниц подряд\"\n }\n }\n }]\n }\n ]\n },\n \"defaults\": {\n \"default_overlap_for_new_task_suites\": 1,\n \"default_overlap_for_new_tasks\": 1\n },\n \"mixer_config\": {\n \"real_tasks_count\": 1,\n \"golden_tasks_count\": 0,\n \"training_tasks_count\": 0,\n \"min_real_tasks_count\": 1,\n \"min_golden_tasks_count\": 0,\n \"min_training_tasks_count\": 0,\n \"force_last_assignment\": True,\n \"force_last_assignment_delay_seconds\": 10,\n \"mix_tasks_in_creation_order\": True,\n \"shuffle_tasks_in_task_suite\": False,\n },\n \"priority\": 10,\n}\n\npool = requests.post(url=url_pools, headers=headers, json=pool_data)\nprint(pool.json())\npool_id = requests.get(url=f\"{url_pools}?project_id={project_id}\", headers=headers).json()[\"items\"][-1][\"id\"]\ntasks = []\n\nwith open(\"//Users//ismail2001//Desktop//tasks.tsv\", \"r\", encoding=\"utf-8\") as in_file:\n files = in_file.readlines()\n files.pop()\n for image_url in files[1:]:\n tasks.append({\"input_values\": {\"image\": image_url.strip()}, \"pool_id\": pool_id, \"overlap\": 1})\n\ntask_response = requests.post(url=url_tasks, headers=headers, json=tasks)\nprint(task_response.json())\n","sub_path":"API_Toloka.py","file_name":"API_Toloka.py","file_ext":"py","file_size_in_byte":7571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"} +{"seq_id":"471192776","text":"# https://leetcode-cn.com/problems/subarray-sum-equals-k/\n\nclass Solution:\n # def subarraySum(self, nums: List[int], k: int) -> int:\n# '''n^2, 1'''\n# pass\n# '''前缀和'''\n# '''定义preSum[i]为下标为0-i的子数组的和'''\n# '''O(n^2), O(n)'''\n# preSum, _sum = [0] * (len(nums) + 1), 0\n# for i in range(1, len(nums)+1):\n# _sum += nums[i-1]\n# preSum[i] = _sum\n# res = 0\n# for i in range(1, len(nums)+1): # [j~i]\n# for j in range(0, i):\n# if preSum[i] - preSum[j] == k: res += 1\n# return res\n def subarraySum(self, nums: List[int], k: int) -> int:\n '''优化前缀和,若以i为结尾的所有子数组中,存在答案,'''\n '''则一定满足:preSum[j] == preSum[i] - k in HashTable'''\n '''注意,需要初始化hashTable[0]为1,因为当 preSum[i] - k = 0 时,nums[i]即为答案'''\n hashTable, _sum, count = {0: 1}, 0, 0\n for i in range(len(nums)):\n _sum += nums[i]\n if _sum - k in hashTable:\n count += hashTable[_sum - k]\n hashTable[_sum] = hashTable.get(_sum, 0) + 1\n return count\n ","sub_path":"Week_05/560. 和为K的子数组.py","file_name":"560. 和为K的子数组.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"59"}