diff --git "a/3824.jsonl" "b/3824.jsonl" new file mode 100644--- /dev/null +++ "b/3824.jsonl" @@ -0,0 +1,763 @@ +{"seq_id":"570889036","text":"import pylot.utils\n\n\nclass SpeedLimitSign(object):\n \"\"\" Class used to store info about speed limit signs.\n\n Attributes:\n transform: The transform of the speed limit sign.\n limit: The speed limit of the sign.\n \"\"\"\n def __init__(self, transform, limit):\n self.transform = transform\n self.limit = limit\n\n @classmethod\n def from_carla_actor(cls, actor):\n import carla\n if not isinstance(actor, carla.TrafficSign):\n raise ValueError('actor should be of type carla.TrafficSign')\n transform = pylot.utils.Transform.from_carla_transform(\n actor.get_transform())\n speed_limit = int(actor.type_id.split('.')[-1])\n return cls(transform, speed_limit)\n","sub_path":"pylot/perception/detection/speed_limit_sign.py","file_name":"speed_limit_sign.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"253502291","text":"from flask import Flask, render_template, request, redirect, jsonify, url_for, flash\nfrom RestaurantDB import RestaurantDB\nfrom database_setup import Base, Restaurant, MenuItem\nfrom sqlalchemy import asc\n\napp = Flask(__name__)\n\n# Connect to Database and create database session\ndb = RestaurantDB('sqlite:///restaurantmenu.db')\n\n# JSON APIs to view Restaurant Information\n@app.route('/restaurant//menu/JSON')\ndef restaurantMenuJSON(restaurant_id):\n items = db.filterMenuItems(restaurant_id = restaurant_id)\n return jsonify(MenuItems=[i.serialize for i in items])\n\n@app.route('/restaurant//menu//JSON')\ndef menuItemJSON(restaurant_id, menu_id):\n menuItem = db.filterMenuItems(id = menu_id)[0]\n return jsonify(Menu_Item=menuItem.serialize)\n\n@app.route('/restaurant/JSON')\ndef restaurantsJSON():\n restaurants = db.getAllRestaurants()\n return jsonify(restaurants=[r.serialize for r in restaurants])\n\n# Show all restaurants\n@app.route('/')\n@app.route('/restaurant/')\ndef showRestaurants():\n restaurants = db.orderRestaurants(asc(Restaurant.name))\n return render_template('restaurants.html', restaurants=restaurants)\n\n# Create a new restaurant\n@app.route('/restaurant/new/', methods=['GET', 'POST'])\ndef newRestaurant():\n if request.method == 'POST':\n newRestaurant = Restaurant(name=request.form['name'])\n db.addRestaurant(newRestaurant)\n flash('New Restaurant %s Successfully Created' % newRestaurant.name)\n return redirect(url_for('showRestaurants'))\n else:\n return render_template('newRestaurant.html')\n\n# Edit a restaurant\n@app.route('/restaurant//edit/', methods=['GET', 'POST'])\ndef editRestaurant(restaurant_id):\n editedRestaurant = db.filterRestaurants(id = restaurant_id)[0]\n if request.method == 'POST':\n if request.form['name']:\n editedRestaurant.name = request.form['name']\n db.addRestaurant(editedRestaurant)\n flash('Restaurant Successfully Edited %s' % editedRestaurant.name)\n return redirect(url_for('showRestaurants'))\n else:\n return render_template('editRestaurant.html', restaurant=editedRestaurant)\n\n# Delete a restaurant\n@app.route('/restaurant//delete/', methods=['GET', 'POST'])\ndef deleteRestaurant(restaurant_id):\n restaurantToDelete = db.filterRestaurants(id = restaurant_id)[0]\n if request.method == 'POST':\n db.removeRestaurant(restaurantToDelete)\n flash('%s Successfully Deleted' % restaurantToDelete.name)\n return redirect(url_for('showRestaurants', restaurant_id=restaurant_id))\n else:\n return render_template('deleteRestaurant.html', restaurant=restaurantToDelete)\n\n# Show a restaurant menu\n@app.route('/restaurant//')\n@app.route('/restaurant//menu/')\ndef showMenu(restaurant_id):\n restaurant = db.filterRestaurants(id = restaurant_id)[0]\n items = db.filterMenuItems(restaurant_id = restaurant_id)\n return render_template('menu.html', items=items, restaurant=restaurant)\n\n# Create a new menu item\n@app.route('/restaurant//menu/new/', methods=['GET', 'POST'])\ndef newMenuItem(restaurant_id):\n if request.method == 'POST':\n newItem = MenuItem(name=request.form['name'], description=request.form['description'],\n price=request.form['price'], course=request.form['course'], restaurant_id=restaurant_id)\n db.addMenuItem(newItem)\n flash('New Menu %s Item Successfully Created' % (newItem.name))\n return redirect(url_for('showMenu', restaurant_id=restaurant_id))\n else:\n return render_template('newmenuitem.html', restaurant_id=restaurant_id)\n\n# Edit a menu item\n@app.route('/restaurant//menu//edit', methods=['GET', 'POST'])\ndef editMenuItem(restaurant_id, menu_id):\n editedItem = db.filterMenuItems(id = menu_id)[0]\n if request.method == 'POST':\n if request.form['name']:\n editedItem.name = request.form['name']\n if request.form['description']:\n editedItem.description = request.form['description']\n if request.form['price']:\n editedItem.price = request.form['price']\n if request.form['course']:\n editedItem.course = request.form['course']\n db.addMenuItem(editedItem)\n flash('Menu Item Successfully Edited')\n return redirect(url_for('showMenu', restaurant_id=restaurant_id))\n else:\n return render_template('editmenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id, item=editedItem)\n\n# Delete a menu item\n@app.route('/restaurant//menu//delete', methods=['GET', 'POST'])\ndef deleteMenuItem(restaurant_id, menu_id):\n itemToDelete = db.filterMenuItems(id = menu_id)[0]\n if request.method == 'POST':\n db.removeMenuItem(itemToDelete)\n flash('Menu Item Successfully Deleted')\n return redirect(url_for('showMenu', restaurant_id=restaurant_id))\n else:\n return render_template('deleteMenuItem.html', item=itemToDelete)\n\nif __name__ == '__main__':\n app.secret_key = 'super_secret_key'\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"426395986","text":"from ase_nrlmol_calculator import NRLMOL\nfrom flosic_os import xyz_to_nuclei_fod\nfrom ase.io import read \n\ndef pyflosic2nrlmol(ase_atoms):\n #\n # extract all information from a nuclei+fod xyz file \n #\n # ase_atoms ... contains both nuclei and fod information \n ase_atoms = read(ase_atoms)\n [geo,nuclei,fod1,fod2,included] = xyz_to_nuclei_fod(ase_atoms)\n e_up = len(fod1)\n e_dn = -1*len(fod2)\n atoms = nuclei \n fods = fod1.extend(fod2)\n return [atoms,fods,e_up,e_dn] \n\n# Read Nuclei+FOD xyz file. \nase_atoms = 'CH4.xyz'\n[atoms,fods,e_up,e_dn] = pyflosic2nrlmol(ase_atoms)\n# The NRLOMOL calculator. \nnrl = NRLMOL(atoms=atoms,fods=fods,basis='DFO',e_up=e_up,e_dn=e_dn,extra=0,FRMORB='FRMORB')\n# Write only NRLMOL input files. \nnrl.write_input(atoms=atoms)\n# The calculator can be used the perform the nrlmol calculation as well. \n# See 02_py2nrl folder for more details \n# nrl.calculate(atoms)\n\n","sub_path":"examples/nrlmol_io/02_py2nrl.py","file_name":"02_py2nrl.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"515947454","text":"import kubernetes\nimport os\nimport yaml\nimport json\nimport logging\nfrom kubernetes.client import V1EnvVar, V1ResourceRequirements, V1ConfigMap, V1ObjectMeta, V1SecurityContext, V1Capabilities, V1SELinuxOptions\nfrom kubernetes.client.rest import ApiException\nfrom openshift.dynamic import DynamicClient\nfrom .service import Service\nfrom .utils import escape, parse_resources\nfrom .sizes import Sizes\nfrom .images import Images\n\n_LOGGER = logging.getLogger(__name__)\n\n_JUPYTERHUB_USER_NAME_ENV = \"JUPYTERHUB_USER_NAME\"\n_USER_CONFIG_MAP_TEMPLATE = \"jupyterhub-singleuser-profile-%s\"\n_USER_CONFIG_PROFILE_NAME = \"@singleuser@\"\n_GPU_KEY = \"nvidia.com/gpu\"\n\nclass SingleuserProfiles(object):\n GPU_MODE_SELINUX = \"selinux\"\n GPU_MODE_PRIVILEGED = \"privileged\"\n def __init__(self, namespace=None, verify_ssl=True, gpu_mode=None, service_account_path='/var/run/secrets/kubernetes.io/serviceaccount'):\n self.profiles = []\n self.api_client = None\n self.namespace = namespace #TODO why do I need to pass namespace?\n self.gpu_mode = gpu_mode\n self.oapi_client = None\n\n if not self.namespace:\n with open(os.path.join(service_account_path, 'namespace')) as fp:\n self.namespace = fp.read().strip()\n kubernetes.config.load_incluster_config()\n self.api_client = kubernetes.client.CoreV1Api()\n\n configuration = kubernetes.client.Configuration()\n configuration.verify_ssl = verify_ssl\n self.oapi_client = DynamicClient(\n kubernetes.client.ApiClient(configuration=configuration)\n )\n\n self.service = Service(self.namespace, verify_ssl)\n\n @property\n def gpu_mode(self):\n return self._gpu_mode\n\n @gpu_mode.setter\n def gpu_mode(self, value):\n if value == self.GPU_MODE_PRIVILEGED:\n self._gpu_mode = self.GPU_MODE_PRIVILEGED\n elif value == self.GPU_MODE_SELINUX:\n self._gpu_mode = self.GPU_MODE_SELINUX\n else:\n self._gpu_mode = None\n\n def get_config_maps_matching_label(self, target_label='jupyterhub=singleuser-profiles'):\n config_maps_list = []\n try:\n config_maps = self.api_client.list_namespaced_config_map(self.namespace, label_selector=target_label)\n except ApiException as e:\n if e.status != 404:\n _LOGGER.error(e)\n return config_maps_list\n for cm in config_maps.items:\n config_maps_list.append(cm.metadata.name)\n\n _LOGGER.info(\"Found these additional Config Maps: %s\" % config_maps_list)\n return config_maps_list\n\n def read_config_map(self, config_map_name, key_name=\"profiles\"):\n try:\n config_map = self.api_client.read_namespaced_config_map(config_map_name, self.namespace)\n except ApiException as e:\n if e.status != 404:\n _LOGGER.error(e)\n return {}\n \n config_map_yaml = yaml.load(config_map.data[key_name])\n return config_map_yaml\n\n def write_config_map(self, config_map_name, key_name, data):\n cm = V1ConfigMap()\n cm.metadata = V1ObjectMeta(name=config_map_name, labels={'app': 'jupyterhub'})\n cm.data = {key_name: yaml.dump(data, default_flow_style=False)}\n try: \n api_response = self.api_client.replace_namespaced_config_map(config_map_name, self.namespace, cm)\n except ApiException as e:\n if e.status == 404:\n try: \n api_response = self.api_client.create_namespaced_config_map(self.namespace, cm)\n except ApiException as e:\n _LOGGER.error(\"Exception when calling CoreV1Api->create_namespaced_config_map: %s\\n\" % e)\n else:\n raise\n\n def update_user_profile_cm(self, username, data={}, key=None, value=None):\n cm_name = _USER_CONFIG_MAP_TEMPLATE % escape(username)\n cm_key_name = \"profile\"\n cm_data = data\n if len(data) > 0 and 'env' not in data:\n cm_data = {'env': data}\n if key and value:\n cm_data[key] = value\n self.write_config_map(cm_name, cm_key_name, cm_data)\n\n def get_user_profile_cm(self, username):\n return self.read_config_map(_USER_CONFIG_MAP_TEMPLATE % escape(username), \"profile\")\n \n def load_profiles(self, secret_name=\"jupyter-singleuser-profiles\", filename=None, key_name=\"jupyterhub-singleuser-profiles.yaml\", username=None):\n self.profiles = []\n self.sizes = []\n if self.api_client:\n profiles_config_maps = [secret_name]\n profiles_config_maps.extend(sorted(self.get_config_maps_matching_label()))\n for cm_name in profiles_config_maps:\n config_map_yaml = self.read_config_map(cm_name, key_name)\n if config_map_yaml:\n self.sizes.extend(config_map_yaml.get(\"sizes\", [self.empty_profile()]))\n self.profiles.extend(config_map_yaml.get(\"profiles\", [self.empty_profile()]))\n else:\n _LOGGER.error(\"Could not find config map %s\" % config_map_name)\n if len(self.profiles) == 0:\n self.profiles.append(self.empty_profile())\n if username:\n config_map_yaml = self.read_config_map(_USER_CONFIG_MAP_TEMPLATE % escape(username), \"profile\")\n if config_map_yaml:\n if not config_map_yaml.get('name'):\n config_map_yaml['name'] = _USER_CONFIG_PROFILE_NAME\n self.profiles.append(config_map_yaml)\n else:\n with open(filename) as fp:\n data = yaml.load(fp)\n if len(data[\"data\"][key_name]) > 0:\n self.profiles.extend(yaml.load(data[\"data\"][key_name]).get(\"profiles\", [self.empty_profile()]))\n else:\n self.profiles.append(self.empty_profile())\n\n def filter_by_username(self, profile, user):\n if not user or not profile.get(\"users\") or \"*\" in profile.get(\"users\", []):\n return profile\n if user in profile.get(\"users\", []):\n _LOGGER.info(\"Found profile '%s' for user %s\" % (profile.get(\"name\"), user))\n return profile\n return {}\n\n def get_profile_by_image(self, image, user=None):\n for profile in self.profiles:\n if profile.get(\"images\") and len(profile.get(\"images\")) > 0:\n if image in profile.get(\"images\"):\n _LOGGER.info(\"Found profile for image %s\" % image)\n yield self.filter_by_username(profile, user)\n else:\n yield self.filter_by_username(profile, user)\n\n return iter(())\n\n def get_merged_profile(self, image, user=None, size=None):\n profile = self.get_profile_by_image(image, user)\n res = self.empty_profile()\n for p in profile:\n res = self.merge_profiles(res, p)\n\n if size:\n s = Sizes(self.sizes)\n loaded_size = s.get_size(size)\n if loaded_size:\n res = self.merge_profiles(res, loaded_size)\n\n return res\n\n def get_profile_by_name(self, name):\n for profile in self.profiles:\n if profile.get(\"name\") == name:\n return profile\n\n return {}\n\n def setup_services(self, spawner, image, user):\n profile = self.get_merged_profile(image, user)\n if profile.get(\"services\"):\n deployed_services, env_groups = self.service.deploy_services(profile.get(\"services\"), user)\n for envs in env_groups:\n if not envs:\n continue\n spawner.environment = {**spawner.environment, **envs}\n for deployed_service in deployed_services:\n spawner.single_user_services.append(deployed_service.get(\"metadata\", {}).get(\"name\"))\n\n\n def clean_services(self, spawner, user):\n self.service.delete_reference_cm(user)\n\n def get_sizes_form(self, username=None):\n if not self.profiles:\n self.load_profiles(username=username)\n s = Sizes(self.sizes)\n return s.get_form(self.get_profile_by_name(_USER_CONFIG_PROFILE_NAME).get('last_selected_size'))\n\n def get_image_list_form(self, username=None):\n\n if not self.profiles:\n self.load_profiles(username=username)\n\n i = Images(self.oapi_client, self.namespace)\n return i.get_form(self.get_profile_by_name(_USER_CONFIG_PROFILE_NAME).get('last_selected_image'))\n\n @classmethod\n def empty_profile(self):\n return {\n \"name\": \"\",\n \"users\": [],\n \"images\": [],\n \"env\": {},\n \"node_tolerations\": [],\n \"node_affinity\": {},\n \"resources\": {\n \"requests\": {\n \"memory\": None,\n \"cpu\": None\n },\n \"limits\": {\n \"memory\": None,\n \"cpu\": None\n },\n \"mem_limit\": None,\n \"cpu_limit\": None\n },\n \"services\": {}\n }\n\n @classmethod\n def env_dict_to_list(self, env_data):\n result = []\n \n for k, v in env_data.items():\n result.append({\"name\": k, \"value\": v})\n\n return result\n\n @classmethod\n def merge_profiles(self, profile1, profile2):\n\n if isinstance(profile1.get('env'), dict):\n profile1['env'] = self.env_dict_to_list(profile1['env'])\n if isinstance(profile2.get('env'), dict):\n profile2['env'] = self.env_dict_to_list(profile2['env'])\n\n profile1[\"name\"] = \", \".join(filter(None, [profile1.get(\"name\", \"\"), profile2.get(\"name\", \"\")]))\n profile1[\"images\"] = list(set(profile1.get(\"images\", []) + profile2.get(\"images\", [])))\n profile1[\"users\"] = list(set(profile1.get(\"users\", []) + profile2.get(\"users\", [])))\n profile1[\"env\"] = profile1.get('env', []) + profile2.get('env', [])\n profile1[\"resources\"] = {**profile1.get('resources', {}), **profile2.get('resources', {})}\n profile1[\"services\"] = {**profile1.get('services', {}), **profile2.get('services', {})}\n profile1[\"node_tolerations\"] = profile1.get(\"node_tolerations\", []) + profile2.get(\"node_tolerations\", [])\n profile1[\"node_affinity\"] = {**profile1.get('node_affinity', {}), **profile2.get('node_affinity', {})}\n\n profile1['resources'] = parse_resources(profile1['resources'])\n\n return profile1\n\n @classmethod\n def apply_gpu_config(self, gpu_mode, gpu_count, pod):\n if int(gpu_count) > 0:\n pod.spec.containers[0].resources.limits[_GPU_KEY] = str(gpu_count)\n pod.spec.containers[0].resources.requests[_GPU_KEY] = str(gpu_count)\n\n if gpu_mode:\n if gpu_mode == self.GPU_MODE_SELINUX:\n pod.spec.security_context.capabilities = V1Capabilities(drop=['ALL'])\n pod.spec.security_context.se_linux_options = V1SELinuxOptions(type='nvidia_container_t')\n\n if gpu_mode == self.GPU_MODE_PRIVILEGED:\n pod.spec.security_context.privileged = True\n\n return pod\n\n @classmethod\n def apply_pod_profile(self, spawner, pod, profile):\n api_client = kubernetes.client.ApiClient()\n\n pod.metadata.labels['jupyterhub.opendatahub.io/user'] = escape(spawner.user.name)\n\n profile_environment = profile.get('env')\n\n if profile_environment:\n\n # Kept for backwards compatibility with simplified env var definitions\n if isinstance(profile_environment, dict):\n for k, v in profile['env'].items():\n update = False\n for e in pod.spec.containers[0].env:\n if e.name == k:\n e.value = v\n update = True\n break\n if not update:\n pod.spec.containers[0].env.append(V1EnvVar(k, v))\n \n elif isinstance(profile_environment, list):\n for i in profile_environment:\n r = type(\"Response\", (), {})\n r.data = json.dumps(i)\n env_var = api_client.deserialize(r, V1EnvVar)\n pod.spec.containers[0].env.append(env_var)\n \n resource_var = None\n resource_json = type(\"Response\", (), {})\n resource_json.data = json.dumps(profile.get('resources'))\n resource_var = api_client.deserialize(resource_json, V1ResourceRequirements)\n\n if resource_var:\n pod.spec.containers[0].resources = resource_var\n \n if profile.get('node_tolerations'):\n pod.spec.tolerations = profile.get('node_tolerations')\n\n if profile.get('node_affinity'):\n if not pod.spec.affinity:\n pod.spec.affinity = {}\n pod.spec.affinity['nodeAffinity'] = profile.get('node_affinity')\n\n for c in pod.spec.containers:\n update = False\n if type(c) is dict:\n env = c['env']\n else:\n env = c.env\n for e in env:\n if type(e) is dict:\n if e['name'] == _JUPYTERHUB_USER_NAME_ENV:\n e['value'] = spawner.user.name\n update = True\n break\n else:\n if e.name == _JUPYTERHUB_USER_NAME_ENV:\n e.value = spawner.user.name\n update = True\n break\n\n if not update:\n env.append(V1EnvVar(_JUPYTERHUB_USER_NAME_ENV, spawner.user.name))\n\n self.apply_gpu_config(spawner.gpu_mode, spawner.gpu_count, pod)\n\n return pod \n","sub_path":"jupyterhub_singleuser_profiles/profiles.py","file_name":"profiles.py","file_ext":"py","file_size_in_byte":12336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"413034722","text":"# coding=utf-8\nMAINPATH = '/opt/data/region'\nHOME = ['AiData', 'meetingData', 'mtLog', 'platformData', 'platformLog']\nFILE = 0\nPATH = 1\nFAIL = '0'\nSUCCESS = '1'\nLOGIN_SUCCESS = u'登录成功!'\nFUNCTION_NOT_FINISHED = u'功能尚未实现...'\nSEARCH_DISK_LIST_FAIL =u'查找磁盘列表失败!'\nDISK_IS_NOT_EXIST = u'服务器上没有该磁盘,请重新输入正确的磁盘!'\nSEARCH_SUCCESS = u'查询成功!'\nSEARCH_HAVE_NO_RESULT = u'查询结果为空'\nPAREM_ERROR = u'参数错误,请检查!'\nFILE_EXIST = u'文件或目录已存在!'\nFILE_NOT_EXIST = u'文件或目录不存在!'\nFILE_REMOVE_ERROR = u'文件或目录删除失败!'\nDIRECTORY_NEW_SUCCESS = u'文件夹创建成功!'\nDIRECTORY_NEW_ERROR = u'文件夹创建失败!'\nUPLOAD_FILE_NOT_EXIST = u'上传的文件不存在!'\nUPLOAD_FILE_SUCCESS = u'文件上传成功!'\nUPLOAD_FILE_FAIL = u'文件上传失败!'\nDOWNLOAD_FILE_SUCCESS = u'文件下载成功!'\nDOWNLOAD_FILE_FAIL = u'文件下载失败!'\nCOPY_FILE_SUCCESS = u'文件复制成功!'\nCOPY_FILE_FAIL = u'文件复制失败!'\nCOPY_DIRECTORY_SUCCESS = u'文件复制成功!'\nCOPY_DIRECTORY_FAIL = u'文件复制失败!'\n\n\nclass WebMsg:\n def __init__(self, success=\"\", code=\"\", desp=\"\"):\n self.success = success\n self.errcode = code\n self.details = desp\n\n def to_dict(self):\n return {'success':self.success, 'errcode': self.errcode, 'details':self.details}\n\n\n","sub_path":"common/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"162867912","text":"# /usr/bin/evn python\n# -*- coding: utf8 -*-\n__author__ = 'su21'\n15 / 6 / 22\n\nimport struct\n\nimport protocol\n\n\nclass Protocol(protocol.BaseProtocol):\n _head_size = 8\n\n def head_size(self):\n return self._head_size\n\n @staticmethod\n def handle_head(session, head):\n head_size, receive_bytes = struct.unpack(\" thresh_min and < thresh_max\n # 6) Return this mask as your binary_output image\n\n gray = img if len(img.shape) == 2 else cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n if orient == 'x':\n sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n else:\n sobel = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n\n sobel = np.absolute(sobel)\n sobel = (255 * sobel / np.max(sobel)).astype(np.uint8)\n binary_output = np.zeros_like(sobel)\n binary_output[(sobel > thresh[0]) & (sobel < thresh[1])] = 1\n return binary_output\n\n\ndef mag_thresh(img, sobel_kernel=3, thresh=(0, 255)):\n # Apply the following steps to img\n # 1) Convert to grayscale\n # 2) Take the gradient in x and y separately\n # 3) Calculate the magnitude \n # 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8\n # 5) Create a binary mask where mag thresholds are met\n # 6) Return this mask as your binary_output image\n gray = img if len(img.shape) == 2 else cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n sobelx = np.abs(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))\n sobely = np.abs(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))\n magnitude = np.sqrt(sobelx ** 2 + sobely ** 2)\n magnitude = (255. * magnitude / np.max(magnitude)).astype(np.uint8)\n binary_output = np.zeros_like(magnitude)\n binary_output[(magnitude >= thresh[0]) & (magnitude <= thresh[1])] = 1\n return binary_output\n\n\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi / 2)):\n # Apply the following steps to img\n # 1) Convert to grayscale\n # 2) Take the gradient in x and y separately\n # 3) Take the absolute value of the x and y gradients\n # 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient \n # 5) Create a binary mask where direction thresholds are met\n # 6) Return this mask as your binary_output image\n gray = img if len(img.shape) == 2 else cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n sobelx = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))\n sobely = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))\n direction = np.arctan2(sobely, sobelx)\n binary_output = np.zeros_like(gray)\n binary_output[(direction >= thresh[0]) & (direction <= thresh[1])] = 1\n return binary_output\n\n\ndef threshold_image(test_image, ksize=3, gradx_thresh=(20, 100), grady_thresh=(20, 100), magnitude_thresh=(30, 150),\n dir_thresh=(0.9, 1.1)):\n # Apply each of the thresholding functions\n gradx = abs_sobel_thresh(test_image, orient='x', sobel_kernel=ksize, thresh=gradx_thresh)\n # grady = abs_sobel_thresh(test_image, orient='y', sobel_kernel=ksize, thresh=grady_thresh)\n mag_binary = mag_thresh(test_image, sobel_kernel=ksize, thresh=magnitude_thresh)\n dir_binary = dir_threshold(test_image, sobel_kernel=ksize, thresh=dir_thresh)\n\n combined = np.zeros_like(dir_binary)\n # combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1\n combined[((gradx == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1\n\n return combined\n\n\ndef threshold_color(image, thresh=(170, 255)):\n image_hsl = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n s_channel = image_hsl[:, :, 2]\n l_channel = image_hsl[:, :, 1]\n\n s_min = thresh[0]\n s_max = thresh[1]\n s_binary = np.zeros_like(s_channel)\n s_binary[((s_channel >= s_min) & (s_channel <= s_max)) & (l_channel > 120 & l_channel < 255)] = 1\n return s_binary\n\n\ndef create_binary_image(image, ksize=3):\n gradient_threshold = threshold_image(image, ksize)\n color_threshold = threshold_color(image)\n\n binary = np.zeros_like(gradient_threshold)\n binary[(color_threshold == 1) | (gradient_threshold == 1)] = 1\n return binary\n\n\ndef show_image_gray(image):\n plt.imshow(image, cmap='gray', )\n\n\ndef undistort_image(img, mtx, dist):\n dst = cv2.undistort(img, mtx, dist, None, mtx)\n return dst\n\n\ndef warp_image(img, M):\n return cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)\n\n\ndef create_binary_image(image):\n \"\"\"\n Return the colour thresholds binary for L, S and R channels in an image\n img: RGB image\n \"\"\"\n\n def bin_it(image, threshold):\n output_bin = np.zeros_like(image)\n output_bin[(image >= threshold[0]) & (image <= threshold[1])] = 1\n return output_bin\n\n # convert image to hls colour space\n hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS).astype(np.float)\n\n # binary threshold values\n bin_thresh = [20, 255]\n\n # rgb thresholding for yellow\n lower = np.array([225, 180, 0], dtype=\"uint8\")\n upper = np.array([255, 255, 170], dtype=\"uint8\")\n mask = cv2.inRange(image, lower, upper)\n rgb_y = cv2.bitwise_and(image, image, mask=mask).astype(np.uint8)\n rgb_y = cv2.cvtColor(rgb_y, cv2.COLOR_RGB2GRAY)\n rgb_y = bin_it(rgb_y, bin_thresh)\n\n # rgb thresholding for white (best)\n lower = np.array([100, 100, 200], dtype=\"uint8\")\n upper = np.array([255, 255, 255], dtype=\"uint8\")\n mask = cv2.inRange(image, lower, upper)\n rgb_w = cv2.bitwise_and(image, image, mask=mask).astype(np.uint8)\n rgb_w = cv2.cvtColor(rgb_w, cv2.COLOR_RGB2GRAY)\n rgb_w = bin_it(rgb_w, bin_thresh)\n\n # hls thresholding for yellow\n lower = np.array([20, 120, 80], dtype=\"uint8\")\n upper = np.array([45, 200, 255], dtype=\"uint8\")\n mask = cv2.inRange(hls, lower, upper)\n hls_y = cv2.bitwise_and(image, image, mask=mask).astype(np.uint8)\n hls_y = cv2.cvtColor(hls_y, cv2.COLOR_HLS2RGB)\n hls_y = cv2.cvtColor(hls_y, cv2.COLOR_RGB2GRAY)\n hls_y = bin_it(hls_y, bin_thresh)\n\n im_bin = np.zeros_like(hls_y)\n im_bin[(hls_y == 1) | (rgb_y == 1) | (rgb_w == 1)] = 1\n\n return im_bin\n\n\nclass Map(dict):\n \"\"\"\n Example:\n m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(Map, self).__init__(*args, **kwargs)\n for arg in args:\n if isinstance(arg, dict):\n for k, v in arg.items():\n self[k] = v\n\n if kwargs:\n for k, v in kwargs.items():\n self[k] = v\n\n def __getattr__(self, attr):\n return self.get(attr)\n\n def __setattr__(self, key, value):\n self.__setitem__(key, value)\n\n def __setitem__(self, key, value):\n super(Map, self).__setitem__(key, value)\n self.__dict__.update({key: value})\n\n def __delattr__(self, item):\n self.__delitem__(item)\n\n def __delitem__(self, key):\n super(Map, self).__delitem__(key)\n del self.__dict__[key]\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"638634576","text":"import sys\nENCODING=\"utf-8\"\n\ndef fixMultiWordsWithInflection(lexform):\n\tpartsplus=lexform.split(u\"+\")\n\tfinalpp=[]\n\tfor partp in partsplus:\n\t\tif u\"#\" in partp:\n\t\t\tpartsmark=partp.split(u\"#\")\n\t\t\tif len(partsmark) == 2:\n\t\t\t\tstartTagsI=partsmark[0].find(u\"<\")\n\t\t\t\tfinalpp.append(partsmark[0][:startTagsI]+u\"#\"+partsmark[1]+partsmark[0][startTagsI:] )\n\t\t\telse:\n\t\t\t\tfinalpp.append(partp)\n\t\telse:\n\t\t\tfinalpp.append(partp)\n\n\treturn u\"+\".join(finalpp)\n\n#returns a list of tuples [ (surface1,[lex11,lex12,etc]) , (surface2,[..]) ]\ndef parseLexicalForms(line):\n\treturnlist=[]\n\tpartsbystartingsymbol=line.split(u\"^\")\n\tfor partst in partsbystartingsymbol:\n\t\tif len(partst.strip()) > 0:\n\t\t\tpartsbyending=partst.split(u\"$\")\n\t\t\tif len(partsbyending) == 2:\n\t\t\t\tpartsoflexform=partsbyending[0].split(u\"/\")\n\t\t\t\t#if not u\"<\" in partsoflexform[1]:\n\t\t\t\t#\treturn []\n\t\t\t\treturnlist.append( (partsoflexform[0],[ fixMultiWordsWithInflection(lf) for lf in partsoflexform[1:] ] ) )\n\treturn returnlist\n\ndef parseAllowedAnalysisSL(line):\n\treturnset=set()\n\tpartsbystartingsymbol=line.split(u\"^\")\n\tfor partst in partsbystartingsymbol:\n\t\tif len(partst.strip()) > 0:\n\t\t\tpartsbyending=partst.split(u\"$\")\n\t\t\tif len(partsbyending) == 2:\n\t\t\t\tpartsoflexform=partsbyending[0].split(u\"/\")\n\t\t\t\tfor p in partsoflexform:\n\t\t\t\t\treturnset.add(p.lower())\n\treturn returnset\n\ndef extractLemmaAndPos(p):\n\treturn p.split(u\">\")[0]+u\">\".lower()\n\ndef parseAllowedAnalysisTL(line):\n\treturnset=dict()\n\treturnsetLemmaAndPos=dict()\n\tcurPos=0\n\tpartsbydebug=line.split(\"[debug-transfer\")\n\tif len(partsbydebug) > 1:\n\t\tusefulpart=partsbydebug[0]\n\t\t#now identofy chunks\n\t\tpartsbychunkstart=usefulpart.split(u\"{\")\n\t\tchunkMode=True\n\t\tif len(partsbychunkstart) == 1:\n\t\t\tchunkMode=False\n\t\tif chunkMode:\n\t\t\tpartsbychunkstart=partsbychunkstart[1:]\n\t\tfor partcs in partsbychunkstart:\n\t\t\tpartsbychunkend = partcs.split(\"}\")\n\t\t\tif len(partsbychunkend) == 2 or ( len(partsbychunkend)==1 and not chunkMode ):\n\t\t\t\tinsidechunk=partsbychunkend[0]\n\t\t\t\t#identify lexical forms inside chunk\n\t\t\t\tpartsbystartingsymbol=insidechunk.split(u\"^\")\n\t\t\t\tfor partst in partsbystartingsymbol:\n\t\t\t\t\tpartsbyending=partst.split(u\"$\")\n\t\t\t\t\tif len(partsbyending) == 2:\n\t\t\t\t\t\tcurPos+=1\n\t\t\t\t\t\tpartsoflexform=partsbyending[0].split(u\"/\")\n\t\t\t\t\t\tfor p in partsoflexform:\n\t\t\t\t\t\t\tif not p.lower() in returnset:\n\t\t\t\t\t\t\t\treturnset[p.lower()]=[]\n\t\t\t\t\t\t\treturnset[p.lower()].append(curPos)\n\t\t\t\t\t\t\tponlylemmaandpos=extractLemmaAndPos(p)\n\t\t\t\t\t\t\tif not ponlylemmaandpos in returnsetLemmaAndPos:\n\t\t\t\t\t\t\t\treturnsetLemmaAndPos[ponlylemmaandpos]=[]\n\t\t\t\t\t\t\treturnsetLemmaAndPos[ponlylemmaandpos].append(curPos)\n\treturn returnset,returnsetLemmaAndPos\n\nfor line in sys.stdin:\n\tline=line.rstrip(\"\\n\").decode(ENCODING)\n\tparts=line.split(\"\\t\")\n\t#first part is result of analysing input with Apertium\n\t#second part is output of debug transfer\n\t\n\t#we have to print disambiguated first part, ||| plus alignments between output of transfer and what we have analysed\n\tanLexForms_l=parseLexicalForms(parts[0])\n\tlexFormsToPosition,lexFormsSimpleToPosition = parseAllowedAnalysisTL(line)\n\t\n\t\n\tusedInputAlignments=set()\n\n\t#do alignment!!!!\n\toutputAlignments=[]\n\tcurIndex=0\n\tfor sf,lflist in anLexForms_l:\n\t\tcurIndex+=1\n\t\t#try exact macth\n\t\texactMatches=[ lexFormsToPosition[lf.lower()] for lf in lflist if lf.lower() in lexFormsToPosition]\n\t\tif len(exactMatches) > 0:\n\t\t\tif len(exactMatches) == 1:\n\t\t\t\t#onlt one exact match: perfect. choose the first input token that has not been used yet\n\t\t\t\tnotusedinput=[ i for i in exactMatches[0] if i not in usedInputAlignments ]\n\t\t\t\tif len(notusedinput) > 0:\n\t\t\t\t\toutputAlignments.append((notusedinput[0],curIndex))\n\t\t\t\t\tusedInputAlignments.add(notusedinput[0])\n\t\t\t\telse:\n\t\t\t\t\t#just use the first input point\n\t\t\t\t\toutputAlignments.append((exactMatches[0][0],curIndex))\n\t\t\telse:\n\t\t\t\t#we have more than one exact match: keeo only the not used inputs\n\t\t\t\tnotusedinputS=set()\n\t\t\t\tfor match in exactMatches:\n\t\t\t\t\tnotusedinputS|=set([ i for i in match if i not in usedInputAlignments ])\n\t\t\t\tif len(notusedinputS) > 0:\n\t\t\t\t\tinputp=min(notusedinputS)\n\t\t\t\t\toutputAlignments.append((inputp,curIndex))\n\t\t\t\t\tusedInputAlignments.add(inputp)\n\t\t\t\telse:\n\t\t\t\t\toutputAlignments.append((exactMatches[0][0],curIndex))\n\t\telse:\n\t\t\t#use approx matches\n\t\t\tapproxMatches=[ lexFormsSimpleToPosition[extractLemmaAndPos(lf)] for lf in lflist if extractLemmaAndPos(lf) in lexFormsSimpleToPosition ]\n\t\t\tnotusedinputS=set()\n\t\t\tfor match in approxMatches:\n\t\t\t\tnotusedinputS|=set([ i for i in match if i not in usedInputAlignments ])\n\t\t\t\tif len(notusedinputS) > 0:\n\t\t\t\t\tinputp=min(notusedinputS)\n\t\t\t\t\toutputAlignments.append((inputp,curIndex))\n\t\t\t\t\tusedInputAlignments.add(inputp)\n\t\t\t\telse:\n\t\t\t\t\toutputAlignments.append((exactMatches[0][0],curIndex))\n\n\t#print output: we are not interested in disambiguating\t\n\tprint (u\" \".join(u\"^\"+sf+u\"/\"+lfs[0]+u\"$\" for sf,lfs in anLexForms_l)+u\" ||| \"+u\" \".join(unicode(a)+u\"-\"+unicode(b) for a,b in outputAlignments )).encode(ENCODING)\n\t\n\n\t\n","sub_path":"apertium-scripts/tokenizeWithApertiumAlignmentsSource.py","file_name":"tokenizeWithApertiumAlignmentsSource.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"5068162","text":"\"\"\"\nUnits tests for evaluator.datasets\n\"\"\"\nimport json\n\nimport pytest\n\nfrom evaluator import unit\nfrom evaluator.datasets import CalculationSource, PhysicalPropertyDataSet, PropertyPhase\nfrom evaluator.properties import (\n Density,\n DielectricConstant,\n EnthalpyOfMixing,\n ExcessMolarVolume,\n)\nfrom evaluator.substances import Component, MoleFraction, Substance\nfrom evaluator.tests.utils import create_dummy_property, create_filterable_data_set\nfrom evaluator.thermodynamics import ThermodynamicState\nfrom evaluator.utils.serialization import TypedJSONEncoder\n\n\ndef test_physical_property_state_methods():\n\n dummy_property = create_dummy_property(Density)\n property_state = dummy_property.__getstate__()\n\n recreated_property = Density()\n recreated_property.__setstate__(property_state)\n\n recreated_state = recreated_property.__getstate__()\n\n original_json = json.dumps(property_state, cls=TypedJSONEncoder)\n recreated_json = json.dumps(recreated_state, cls=TypedJSONEncoder)\n\n assert original_json == recreated_json\n\n\ndef test_physical_property_id_generation():\n\n dummy_property_1 = create_dummy_property(Density)\n dummy_property_2 = create_dummy_property(Density)\n\n assert dummy_property_1.id != dummy_property_2.id\n\n\ndef test_serialization():\n \"\"\"A test to ensure that data sets are JSON serializable.\"\"\"\n\n data_set = PhysicalPropertyDataSet()\n data_set.add_properties(create_dummy_property(Density))\n\n data_set_json = data_set.json()\n\n parsed_data_set = PhysicalPropertyDataSet.parse_json(data_set_json)\n assert len(data_set) == len(parsed_data_set)\n\n parsed_data_set_json = parsed_data_set.json()\n assert parsed_data_set_json == data_set_json\n\n\ndef test_to_pandas():\n \"\"\"A test to ensure that data sets are convertable to pandas objects.\"\"\"\n\n source = CalculationSource(\"Dummy\", {})\n\n pure_substance = Substance.from_components(\"C\")\n binary_substance = Substance.from_components(\"C\", \"O\")\n\n data_set = PhysicalPropertyDataSet()\n\n for temperature in [298 * unit.kelvin, 300 * unit.kelvin, 302 * unit.kelvin]:\n\n thermodynamic_state = ThermodynamicState(\n temperature=temperature, pressure=1.0 * unit.atmosphere\n )\n\n density_property = Density(\n thermodynamic_state=thermodynamic_state,\n phase=PropertyPhase.Liquid,\n substance=pure_substance,\n value=1 * unit.gram / unit.milliliter,\n uncertainty=0.11 * unit.gram / unit.milliliter,\n source=source,\n )\n\n dielectric_property = DielectricConstant(\n thermodynamic_state=thermodynamic_state,\n phase=PropertyPhase.Liquid,\n substance=pure_substance,\n value=1 * unit.dimensionless,\n uncertainty=0.11 * unit.dimensionless,\n source=source,\n )\n\n data_set.add_properties(density_property)\n data_set.add_properties(dielectric_property)\n\n for temperature in [298 * unit.kelvin, 300 * unit.kelvin, 302 * unit.kelvin]:\n\n thermodynamic_state = ThermodynamicState(\n temperature=temperature, pressure=1.0 * unit.atmosphere\n )\n\n enthalpy_property = EnthalpyOfMixing(\n thermodynamic_state=thermodynamic_state,\n phase=PropertyPhase.Liquid,\n substance=binary_substance,\n value=1 * unit.kilojoules / unit.mole,\n uncertainty=0.11 * unit.kilojoules / unit.mole,\n source=source,\n )\n\n excess_property = ExcessMolarVolume(\n thermodynamic_state=thermodynamic_state,\n phase=PropertyPhase.Liquid,\n substance=binary_substance,\n value=1 * unit.meter ** 3 / unit.mole,\n uncertainty=0.11 * unit.meter ** 3 / unit.mole,\n source=source,\n )\n\n data_set.add_properties(enthalpy_property)\n data_set.add_properties(excess_property)\n\n data_set_pandas = data_set.to_pandas()\n\n required_columns = [\n \"Temperature (K)\",\n \"Pressure (kPa)\",\n \"Phase\",\n \"N Components\",\n \"Source\",\n \"Component 1\",\n \"Role 1\",\n \"Mole Fraction 1\",\n \"Exact Amount 1\",\n \"Component 2\",\n \"Role 2\",\n \"Mole Fraction 2\",\n \"Exact Amount 2\",\n ]\n\n assert all(x in data_set_pandas for x in required_columns)\n\n assert data_set_pandas is not None\n assert data_set_pandas.shape == (12, 21)\n\n data_set_without_na = data_set_pandas.dropna(axis=1, how=\"all\")\n assert data_set_without_na.shape == (12, 19)\n\n\ndef test_sources_substances():\n\n physical_property = create_dummy_property(Density)\n\n data_set = PhysicalPropertyDataSet()\n data_set.add_properties(physical_property)\n\n assert next(iter(data_set.sources)) == physical_property.source\n assert next(iter(data_set.substances)) == physical_property.substance\n\n\ndef test_properties_by_type():\n\n density = create_dummy_property(Density)\n dielectric = create_dummy_property(DielectricConstant)\n\n data_set = PhysicalPropertyDataSet()\n data_set.add_properties(density, dielectric)\n\n densities = [x for x in data_set.properties_by_type(\"Density\")]\n assert len(densities) == 1\n assert densities[0] == density\n\n dielectrics = [x for x in data_set.properties_by_type(\"DielectricConstant\")]\n assert len(dielectrics) == 1\n assert dielectrics[0] == dielectric\n\n\ndef test_filter_by_property_types():\n \"\"\"A test to ensure that data sets may be filtered by property type.\"\"\"\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_property_types(\"Density\")\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_property_types(\"Density\", \"DielectricConstant\")\n\n assert len(dummy_data_set) == 2\n\n\ndef test_filter_by_phases():\n \"\"\"A test to ensure that data sets may be filtered by phases.\"\"\"\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_phases(phases=PropertyPhase.Liquid)\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_phases(\n phases=PropertyPhase(PropertyPhase.Liquid | PropertyPhase.Solid)\n )\n\n assert len(dummy_data_set) == 2\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_phases(\n phases=PropertyPhase(\n PropertyPhase.Liquid | PropertyPhase.Solid | PropertyPhase.Gas\n )\n )\n\n assert len(dummy_data_set) == 3\n\n\ndef test_filter_by_temperature():\n \"\"\"A test to ensure that data sets may be filtered by temperature.\"\"\"\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_temperature(\n min_temperature=287 * unit.kelvin, max_temperature=289 * unit.kelvin\n )\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_temperature(\n min_temperature=287 * unit.kelvin, max_temperature=299 * unit.kelvin\n )\n\n assert len(dummy_data_set) == 2\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_temperature(\n min_temperature=287 * unit.kelvin, max_temperature=309 * unit.kelvin\n )\n\n assert len(dummy_data_set) == 3\n\n\ndef test_filter_by_pressure():\n \"\"\"A test to ensure that data sets may be filtered by pressure.\"\"\"\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_pressure(\n min_pressure=0.4 * unit.atmosphere, max_pressure=0.6 * unit.atmosphere\n )\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_pressure(\n min_pressure=0.4 * unit.atmosphere, max_pressure=1.1 * unit.atmosphere\n )\n\n assert len(dummy_data_set) == 2\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_pressure(\n min_pressure=0.4 * unit.atmosphere, max_pressure=1.6 * unit.atmosphere\n )\n\n assert len(dummy_data_set) == 3\n\n\ndef test_filter_by_components():\n \"\"\"A test to ensure that data sets may be filtered by the number of components.\"\"\"\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_components(number_of_components=1)\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_components(number_of_components=2)\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_components(number_of_components=3)\n\n assert len(dummy_data_set) == 1\n\n\ndef test_filter_by_elements():\n \"\"\"A test to ensure that data sets may be filtered by which elements their\n measured properties contain.\"\"\"\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_elements(\"H\", \"C\")\n\n assert len(dummy_data_set) == 1\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_elements(\"H\", \"C\", \"N\")\n\n assert len(dummy_data_set) == 2\n\n dummy_data_set = create_filterable_data_set()\n dummy_data_set.filter_by_elements(\"H\", \"C\", \"N\", \"O\")\n\n assert len(dummy_data_set) == 3\n\n\ndef test_filter_by_smiles():\n \"\"\"A test to ensure that data sets may be filtered by which smiles their\n measured properties contain.\"\"\"\n\n methanol_substance = Substance()\n methanol_substance.add_component(Component(\"CO\"), MoleFraction(1.0))\n\n ethanol_substance = Substance()\n ethanol_substance.add_component(Component(\"CCO\"), MoleFraction(1.0))\n\n property_a = create_dummy_property(Density)\n property_a.substance = methanol_substance\n\n property_b = create_dummy_property(Density)\n property_b.substance = ethanol_substance\n\n data_set = PhysicalPropertyDataSet()\n data_set.add_properties(property_a, property_b)\n\n data_set.filter_by_smiles(\"CO\")\n\n assert len(data_set) == 1\n assert methanol_substance in data_set.substances\n assert ethanol_substance not in data_set.substances\n\n\ndef test_phase_from_string():\n\n assert PropertyPhase.from_string(\"\") == PropertyPhase.Undefined\n\n phase_enums = [\n PropertyPhase.Undefined,\n PropertyPhase.Solid,\n PropertyPhase.Liquid,\n PropertyPhase.Gas,\n PropertyPhase.Solid | PropertyPhase.Liquid,\n PropertyPhase.Solid | PropertyPhase.Gas,\n PropertyPhase.Liquid | PropertyPhase.Gas,\n PropertyPhase.Solid | PropertyPhase.Liquid | PropertyPhase.Gas,\n ]\n\n assert all(x == PropertyPhase.from_string(str(x)) for x in phase_enums)\n\n\ndef test_validate_data_set():\n\n valid_property = Density(\n ThermodynamicState(298 * unit.kelvin, 1 * unit.atmosphere),\n PropertyPhase.Liquid,\n Substance.from_components(\"O\"),\n 0.0 * unit.gram / unit.milliliter,\n 0.0 * unit.gram / unit.milliliter,\n )\n\n data_set = PhysicalPropertyDataSet()\n data_set.add_properties(valid_property)\n\n data_set.validate()\n\n invalid_property = Density(\n ThermodynamicState(-1 * unit.kelvin, 1 * unit.atmosphere),\n PropertyPhase.Liquid,\n Substance.from_components(\"O\"),\n 0.0 * unit.gram / unit.milliliter,\n 0.0 * unit.gram / unit.milliliter,\n )\n\n with pytest.raises(AssertionError):\n data_set.add_properties(invalid_property)\n\n data_set.add_properties(invalid_property, validate=False)\n\n with pytest.raises(AssertionError):\n data_set.validate()\n","sub_path":"evaluator/tests/test_datasets/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":11437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"241157921","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 27 13:18:21 2019\n\n@author: rchiechi\n\"\"\"\nimport os\n#import sys\nimport logging\nimport platform\nimport threading\nimport numpy as np\nimport queue\nimport time\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import font\nfrom tkinter import filedialog\n#import matplotlib as mpl\n#mpl.use('TkAgg')\n#import matplotlib.pyplot as plt\n#import matplotlib.backends.tkagg as tkagg\n#from matplotlib.backends.backend_agg import FigureCanvasAgg\nimport gui.colors as cl\n#import gui.tooltip as tip\nfrom util.Cache import Cache\nfrom util.logger import GUIHandler\nfrom parse.read import ReadIVS\nfrom plot.canvasplotter import XYplot, XYZplot, Histplot\nfrom parse.GHistogram import GHistogram\nfrom parse.write import Ghistwriter\n#from parse.Guess import CountPlateaux\nfrom parse.Guess import CountThread\n#from gui.BusyWidget import BusyWidget\n#import matplotlib.pyplot as plt\n#import matplotlib.backends.tkagg as tkagg\n\n\n\nMASTER_LOCK = threading.RLock()\n\nclass BJParserFrame(tk.Frame):\n\n indir=str()\n outdir=str()\n# Keep_selected_files = []\n# Toss_selected_files = []\n style = ttk.Style()\n child_threads = []\n all_files_parsed = False\n\n\n boolmap = {1:True, 0:False}\n \n def __init__(self, opts, master=None):\n tk.Frame.__init__(self, master)\n self.opts = opts\n self.alive = threading.Event()\n self.alive.set()\n self.master.tk_setPalette(background=cl.GREY,\n activeBackground=cl.GREY)\n self.master.title(\"RCCLab STMBJ Data Parser\")\n self.master.geometry('900x850+250-250')\n self.pack(fill=tk.BOTH, expand=True)\n self.update_idletasks()\n self.__createWidgets()\n self.cache = Cache(self.logger)\n self.ivs_files = ReadIVS(self.logger, MASTER_LOCK, self.opts)\n self.checkOptions()\n self.ToFront() \n self.after('1000', self.WaitForThreads)\n self.mainloop()\n\n\n def __createWidgets(self):\n self.update()\n \n self.ButtonFrame = ttk.Frame(self)\n self.LoggingFrame = ttk.Frame(self)\n self.FileListBoxFrame = ttk.Frame(self)\n self.CanvasFrame = ttk.Frame(self)\n\n yScroll = ttk.Scrollbar(self.LoggingFrame, orient=tk.VERTICAL)\n self.Logging = tk.Text(self.LoggingFrame, height=10, width=0, \n bg=cl.BLACK, fg=cl.WHITE, yscrollcommand=yScroll.set)\n yScroll['command'] = self.Logging.yview\n self.Logging.pack(side=tk.BOTTOM,fill=tk.BOTH,expand=True)\n yScroll.pack(side=tk.RIGHT,fill=tk.Y)\n\n self.__createButtons()\n self.__createFileListBox()\n self.__createCanvas()\n\n self.CanvasFrame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\n self.FileListBoxFrame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\n self.ButtonFrame.pack(side=tk.BOTTOM,fill=None)\n self.LoggingFrame.pack(side=tk.BOTTOM, fill=tk.BOTH)\n self.logger = logging.getLogger('parser.gui')\n self.handler = GUIHandler(self.Logging)\n self.logger.addHandler(self.handler)\n self.logger.setLevel(getattr(logging,self.opts.loglevel.upper()))\n self.logger.info(\"Logging...\")\n self.handler.flush()\n\n \n\n def __createButtons(self):\n \n buttons = [\n {'name':'Quit','text':'QUIT','command':'Quit','side':tk.BOTTOM},\n {'name':'Reset','text':'Reset','command':'Reset','side':tk.BOTTOM},\n {'name':'SpawnInputDialog','text':'Input Directory','side':tk.LEFT},\n {'name':'TossFile','text':'Toss','side':tk.LEFT},\n {'name':'KeepFile','text':'Keep','side':tk.LEFT},\n {'name':'ArchiveTossed','text':'Archive Tossed','side':tk.LEFT},\n {'name':'SpawnOutputDialog','text':'Output Directory','side':tk.LEFT},\n {'name':'Guess','text':'Guess Which Plots to Toss', 'side':tk.LEFT},\n {'name':'Parse','text':'Parse!','side':tk.LEFT}\n ]\n\n for b in buttons:\n button = ttk.Button(self.ButtonFrame)\n button.config(text=b['text'],command=getattr(self,b['name']+'Click'))\n button.pack(side=b['side'])\n setattr(self,'Button'+b['name'],button)\n \n self.master.bind('', self.KeepFileClick)\n self.master.bind('', self.TossFileClick)\n \n def __createFileListBox(self):\n _h = int(self.winfo_height())\n _w = int(self.winfo_width())\n \n self.FileListBoxFrameLabelVar = tk.StringVar()\n self.FileListBoxFrameLabel = tk.Label(self,\n textvariable=self.FileListBoxFrameLabelVar,\n font=font.Font(size=10,weight=\"bold\"))\n self.FileListBoxFrameLabel.pack(side=tk.TOP,fill=tk.X)\n \n scrolls = {}\n styles = {'Keep': (tk.LEFT, cl.LIGHTGREEN),\n 'Toss': (tk.RIGHT, cl.LIGHTRED)}\n for _prefix in ('Keep', 'Toss'):\n setattr(self, _prefix+'FileListBoxFrame', ttk.Frame(self.FileListBoxFrame, height = _h/3, width = _w/2)) \n getattr(self, _prefix+'FileListBoxFrame').pack(side=tk.LEFT, fill=tk.BOTH, expand=True)\n scrolls[_prefix+'yScroll']=ttk.Scrollbar(getattr(self, _prefix+'FileListBoxFrame'), orient=tk.VERTICAL)\n scrolls[_prefix+'yScroll'].pack(side=styles[_prefix][0], fill=tk.Y)\n scrolls[_prefix+'xScroll']=ttk.Scrollbar(getattr(self, _prefix+'FileListBoxFrame'), orient=tk.HORIZONTAL)\n scrolls[_prefix+'xScroll'].pack(side=tk.BOTTOM, fill=tk.X)\n setattr(self, _prefix+'filelist', tk.StringVar())\n \n setattr(self, _prefix+'FileListBox', tk.Listbox(getattr(self, _prefix+'FileListBoxFrame'),\n listvariable=getattr(self, _prefix+'filelist'), \n selectmode=tk.EXTENDED, \n height = 20, width = 45, relief=tk.RAISED, bd=1,\n bg=styles[_prefix][1], \n #font=Font(size=10),\n xscrollcommand=scrolls[_prefix+'xScroll'].set, \n yscrollcommand=scrolls[_prefix+'yScroll'].set))\n \n getattr(self, _prefix+'FileListBox').bind('<>', getattr(self, _prefix+'ListBoxClick'))\n scrolls[_prefix+'xScroll']['command'] = getattr(self, _prefix+'FileListBox').xview\n scrolls[_prefix+'yScroll']['command'] = getattr(self, _prefix+'FileListBox').yview\n getattr(self, _prefix+'FileListBox').pack(side=tk.LEFT, fill=tk.BOTH, expand=True)\n \n \n def __createCanvas(self):\n _h = int(self.winfo_height())\n _w = int(self.winfo_width())\n self.KeepPlotCanvas = tk.Canvas(self.CanvasFrame, bg='white',\n height = _h/3, width = _w/2)\n self.KeepPlotCanvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)\n self.TossPlotCanvas = tk.Canvas(self.CanvasFrame, bg='white',\n height = _h/3, width = _w/2)\n self.TossPlotCanvas.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)\n\n \n def ToFront(self):\n if platform.system() == \"Darwin\":\n os.system('''/usr/bin/osascript -e 'tell app \"Finder\" to set frontmost of process \"Python\" to true' ''')\n else:\n self.master.attributes('-topmost', 1)\n self.master.attributes('-topmost', 0) \n\n def QuitClick(self):\n self.alive.clear()\n print(\"Quitting...\")\n self.Quit()\n\n def KeepListBoxClick(self, event):\n self.__ListBoxClick('Keep')\n\n def TossListBoxClick(self, event):\n self.__ListBoxClick('Toss')\n\n def __ListBoxClick(self, _prefix):\n selected = [getattr(self, _prefix+'FileListBox').get(x).replace(\"_\",\" \") \n for x in getattr(self, _prefix+'FileListBox').curselection()]\n# if selected == getattr(self, _prefix+'_selected_files'):\n# self.logger.debug(\"%s file selection unchanged.\", _prefix)\n# self.handler.flush()\n# return\n\n# setattr(self, _prefix+'_selected_files', selected)\n if len(selected) == 1:\n self.DisplayDataFigure(_prefix, \n getattr(self, _prefix+'PlotCanvas'), selected[-1])\n elif len(selected) > 1:\n self.DisplayDataFigures(_prefix, \n getattr(self, _prefix+'PlotCanvas'), selected)\n \n def GuessClick(self):\n if not hasattr(self, 'selection_cache'):\n self.logger.error(\"No files loaded\")\n self.handler.flush()\n return\n if not self.all_files_parsed:\n self.logger.error(\"Wait for parser to complete\")\n return\n self.child_threads.append({'thread':threading.Thread(target=self.doGuess),\n 'widgets':[self.ButtonGuess,\n self.ButtonParse,\n self.KeepFileListBox, \n self.TossFileListBox]})\n self.child_threads[-1]['thread'].name = 'Plateaux Guesser'\n self.child_threads[-1]['thread'].start()\n \n def doGuess(self):\n self.logger.info(\"Starting search for plateaux...\")\n guessQ = queue.Queue()\n for fn in self.selection_cache['Keep_files']:\n _fn = os.path.join(self.indir, fn)\n guessQ.put((fn, self.ivs_files[_fn]['d'], self.ivs_files[_fn]['I']))\n \n children = []\n for i in range(0,8):\n children.append(CountThread(self.alive, guessQ))\n children[-1].start()\n \n while not guessQ.empty():\n kept = 0\n last_kept = kept\n for c in children:\n kept += len(c.keep)\n if kept != last_kept:\n self.logger.info(\"Keeping %s traces\", kept)\n _keep = []\n _toss = []\n for c in children:\n _keep += c.keep\n _toss += c.toss\n _keep.sort()\n _toss.sort()\n self.logger.info(\"Search for plateaux done.\")\n self.selection_cache['Keep_files'] = _keep\n self.selection_cache['Toss_files'] = _toss \n self.__updateFileListBox('Toss')\n self.__updateFileListBox('Keep')\n self.__ListBoxClick('Keep')\n \n kept = len(self.selection_cache['Keep_files']) \n tossed = len(self.selection_cache['Toss_files'])\n self.logger.info(\"Kept %0.1f%% of traces.\", (kept/(kept+tossed))*100)\n \n def ParseClick(self):\n if not hasattr(self, 'selection_cache'):\n self.logger.error(\"No files selected.\")\n self.handler.flush()\n return\n self.checkOptions()\n self.child_threads.append({'thread':threading.Thread(target=self.Parse),\n 'widgets':[self.ButtonParse, \n self.KeepFileListBox, \n self.TossFileListBox]})\n self.child_threads[-1]['thread'].name = 'G-histogram parser'\n self.child_threads[-1]['thread'].start()\n #self.Parse()\n \n def ResetClick(self):\n self.logger.info(\"Killing background tasks\")\n self.alive.clear()\n self.handler.flush()\n time.sleep(3)\n self.alive.set() \n self.SpawnInputDialogClick(True)\n \n def SpawnInputDialogClick(self, reset=False):\n\n self.checkOptions()\n self.indir = filedialog.askdirectory(title=\"Files to parse\", \\\n initialdir=self.cache['last_input_path'])\n if os.path.exists(self.indir):\n self.cache['last_input_path'] = self.indir\n else:\n return\n if reset:\n try:\n os.unlink(os.path.join(\n self.indir, 'STMBJParse.cache'))\n except IOError:\n pass\n self.selection_cache = Cache(self.logger, os.path.join(\n self.indir, 'STMBJParse.cache'))\n if not self.selection_cache['Keep_files']:\n self.selection_cache['Keep_files'] = [] \n if not self.selection_cache['Toss_files']:\n self.selection_cache['Toss_files'] = []\n fns = os.listdir(self.indir)\n fns.sort()\n if not self.selection_cache['Keep_files']:\n for _f in fns:\n if _f[-3:].lower() == self.opts.extension:\n if os.path.isfile(os.path.join(self.indir,_f)):\n self.selection_cache['Keep_files'].append(_f)\n else:\n self.logger.debug(\"Skipping %s\", _f)\n if len(self.selection_cache['Keep_files']): \n self.updateKeepFileListBox()\n self.updateTossFileListBox()\n self.logger.debug(\"Input directory is %s\", self.indir)\n if not self.outdir:\n self.outdir = os.path.join(self.indir, 'parsed')\n self.checkOptions()\n self.child_threads.append({'thread':threading.Thread(target=self.BackgroundParseFiles),\n 'widgets':[self.ButtonGuess,\n self.ButtonReset,\n self.ButtonArchiveTossed]})\n self.child_threads[-1]['thread'].name = 'IVS File parser'\n self.child_threads[-1]['thread'].start()\n \n def BackgroundParseFiles(self): \n self.logger.info(\"Background IVS file parsing started.\")\n for _fn in self.selection_cache['Keep_files']:\n if not self.alive.is_set():\n return\n fn = os.path.join(self.indir, _fn)\n self.ivs_files.AddFile(fn)\n self.all_files_parsed = True\n self.logger.info(\"Background IVS file parsing complete.\") \n \n def WaitForThreads(self):\n if len(self.child_threads):\n# print(\"THREAD RUNNING\")\n c = self.child_threads.pop()\n if c['thread'].is_alive():\n if 'widgets' in c:\n for w in c['widgets']:\n w['state'] = tk.DISABLED\n self.child_threads.append(c)\n else:\n if 'widgets' in c:\n for w in c['widgets']:\n w['state'] = tk.NORMAL\n if 'after' in c:\n tk.messagebox.showinfo(\"Complete\", \"%s completed.\" % c['thread'].name)\n c['after'][0](*c['after'][1]) \n self.after('1000', self.WaitForThreads)\n \n def ArchiveTossedClick(self):\n if not hasattr(self, 'selection_cache'):\n return\n if not len(self.selection_cache['Toss_files']):\n self.logger.info(\"No files to toss.\")\n return\n archive_dir = os.path.join(self.indir, 'TossedArchive')\n if not os.path.exists(archive_dir):\n os.mkdir(archive_dir)\n while len(self.selection_cache['Toss_files']):\n fn = self.selection_cache['Toss_files'].pop()\n os.rename(os.path.join(self.indir, fn),\n os.path.join(archive_dir, fn))\n self.logger.info(\"Archived %s\", fn)\n self.handler.flush()\n self.__updateFileListBox('Toss')\n \n \n def updateKeepFileListBox(self):\n self.__updateFileListBox('Keep')\n\n def updateTossFileListBox(self):\n self.__updateFileListBox('Toss')\n\n def __updateFileListBox(self, _prefix):\n getattr(self, _prefix+'filelist').set(\" \".join([x.replace(\" \",\"_\") \n for x in self.selection_cache[_prefix+'_files']]))\n# getattr(self, _prefix+'filelist').set(\" \".join([x.replace(\" \",\"_\") \n# for x in self.selection_cache[_prefix+'_files']]))\n if len(self.selection_cache[_prefix+'_files']) == 0:\n setattr(self, _prefix+'fig_photo', None)\n\n def KeepFileClick(self, event=None):\n self.__FileClick('Toss', 'Keep')\n \n def TossFileClick(self, event=None):\n self.__FileClick('Keep', 'Toss')\n \n def __FileClick(self, _from, _to): \n self.checkOptions()\n selected = [getattr(self, _from+'FileListBox').get(x).replace(\"_\",\" \") \n for x in getattr(self, _from+'FileListBox').curselection()]\n if selected:\n idx = getattr(self, _from+'FileListBox').curselection()[0]\n else:\n idx = -1\n tomove = []\n filelist = []\n for i in range(0, len(self.selection_cache[_from+'_files'])):\n for s in selected:\n if self.selection_cache[_from+'_files'][i] == s:\n tomove.append(i)\n \n for i in range(0, len(self.selection_cache[_from+'_files'])):\n if i not in tomove:\n filelist.append(self.selection_cache[_from+'_files'][i])\n else:\n self.selection_cache[_to+'_files'].append(self.selection_cache[_from+'_files'][i])\n self.selection_cache[_from+'_files'] = filelist\n getattr(self, _from+'FileListBox').selection_clear(0,tk.END)\n if idx > -1:\n getattr(self, _from+'FileListBox').activate(idx)\n getattr(self, _from+'FileListBox').selection_set(idx)\n self.__updateFileListBox(_to)\n self.__updateFileListBox(_from)\n self.__ListBoxClick(_from)\n \n \n def SpawnOutputDialogClick(self):\n if not self.outdir and self.indir:\n self.outdir = self.indir\n outdir = tk.filedialog.askdirectory(title=\"Select Output Directory\", \n initialdir=self.outdir)\n if os.path.exists(outdir):\n self.outdir = outdir\n self.checkOptions()\n \n def Quit(self):\n for c in self.child_threads:\n try:\n c['thread'].join(timeout=10)\n except RuntimeError:\n print(\"Thread %s not started yet\" % c['thread'].name)\n self.master.destroy()\n\n def checkOptions(self): \n if not self.cache['last_input_path']:\n self.cache['last_input_path'] = os.getcwd()\n if not os.path.exists(self.cache['last_input_path']):\n self.last_input_path = os.path.expanduser('~')\n# if not self.outdir:\n# self.outdir = os.path.join(self.indir, 'parsed')\n# self.logger.debug(\"Set outdir to %s\", self.outdir)\n self.handler.flush()\n self.FileListBoxFrameLabelVar.set(\"Output to: %s\"% (self.outdir) )\n\n\n\n def Parse(self):\n self.logger.info(\"Reading file selection...\")\n self.handler.flush()\n X = np.array([])\n for _fn in self.selection_cache['Keep_files']:\n if not self.alive.is_set():\n break\n fn = os.path.join(self.indir, _fn)\n self.ivs_files.AddFile(fn) \n X = np.append(X, self.ivs_files[fn]['I'])\n self.logger.info(\"Done!\")\n self.handler.flush()\n Ghist = GHistogram(self.logger, X)\n self.DisplayHistogramData('Keep', self.KeepPlotCanvas, Ghist)\n Ghistwriter(self.logger, self.outdir, Ghist)\n\n\n def DisplayHistogramData(self, label, master, hist):\n \n labels={'title':'G Histogram',\n 'X': 'G/G0',\n 'Y': 'Frequency'}\n plotter = Histplot(hist.fits['bins'], \n hist.fits['freq'],\n hist.fits['fit'],\n labels)\n\n plotter.Draw(tk.PhotoImage(master=master,\n width=plotter.figure_w,\n height=plotter.figure_h))\n getattr(self, label+'PlotCanvas').create_image(plotter.figure_w/2, \n plotter.figure_h/2, image=plotter.fig_photo)\n setattr(self, label+'fig_photo', plotter)\n\n \n def DisplayDataFigure(self, label, master, _fn):\n #https://matplotlib.org/gallery/user_interfaces/embedding_in_tk_canvas_sgskip.html\n fn = os.path.join(self.indir, _fn)\n self.ivs_files.AddFile(fn)\n self.handler.flush() \n labels={'title':os.path.basename(fn),\n 'X': 'distance',\n 'Y': 'current'}\n plotter = XYplot(self.ivs_files[fn]['d'], \n self.ivs_files[fn]['I'],\n labels)\n plotter.Draw(tk.PhotoImage(master=master,\n width=plotter.figure_w,\n height=plotter.figure_h))\n #plotter.Draw(fig_photo)\n getattr(self, label+'PlotCanvas').create_image(plotter.figure_w/2, \n plotter.figure_h/2, image=plotter.fig_photo)\n setattr(self, label+'fig_photo', plotter)\n\n def DisplayDataFigures(self, label, master, fns):\n #https://matplotlib.org/gallery/user_interfaces/embedding_in_tk_canvas_sgskip.html\n _title = ''\n \n X, Y, Z = [], [], []\n for _fn in fns:\n fn = os.path.join(self.indir, _fn)\n self.ivs_files.AddFile(fn)\n self.handler.flush()\n _title += os.path.basename(fn)+' '\n X.append([])\n Y.append([])\n Z.append([])\n for i in range(0, len(self.ivs_files[fn]['I'])):\n X[-1].append(self.ivs_files[fn]['d'][i])\n Y[-1].append(self.ivs_files[fn]['I'][i])\n\n \n labels={'title':_title,\n 'X': 'distance',\n 'Y': 'trace',\n 'Z': 'current'}\n plotter = XYZplot(X, Y, labels)\n \n plotter.Draw(tk.PhotoImage(master=master,\n width=plotter.figure_w,\n height=plotter.figure_h))\n #plotter.Draw(fig_photo)\n getattr(self, label+'PlotCanvas').create_image(plotter.figure_w/2, \n plotter.figure_h/2, image=plotter.fig_photo)\n setattr(self, label+'fig_photo', plotter)\n","sub_path":"gui/BJParserFrame.py","file_name":"BJParserFrame.py","file_ext":"py","file_size_in_byte":22264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"236295809","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\nfrom tensorflow.keras import models\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport pandas as pd\nfrom numpy import asarray\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport math\nfrom pathlib import Path\nimport os\nimport glob\nfrom keras_video import VideoFrameGenerator\n\n\n\ndef float2bin(value, bits):\n bina = np.binary_repr(value, width= bits)\n return bina\n\ndef check_bit(bina, bit):\n setting = bina[bit]=='1'\n return setting\n\ndef SOA(path, trainpath):\n listeSOA=[]\n imp_csv = pd.read_csv(path, sep=';', encoding= 'utf8',\n usecols=['TcFrameID',\n 'm_cuttingState.m_controlFeedVelocity.m_cuttingState'], \n dtype={'TcFrameID':float, 'm_cuttingState.m_controlFeedVelocity.m_cuttingState':np.int64}, \n skiprows=[1,2],\n decimal=',')\n for i in range(len(imp_csv)):\n cs= imp_csv.iat[i,1]\n bcs= float2bin(cs, 64)\n ss= check_bit(bcs, 35)\n searchfor= '*'+str(math.trunc(imp_csv.iat[i,0]))+'*'\n for path in Path(trainpath).rglob(searchfor):\n if ss == True:\n listeSOA.append(0)\n elif ss == False:\n listeSOA.append(1)\n return listeSOA\n#Testbilder\ndef error(BS, globname, model):\n classes = [i.split(os.path.sep)[1] for i in glob.glob('normal/*')]\n classes.sort()\n # some global params\n SIZE = (150, 150)\n CHANNELS = 3\n NBFRAME = 5\n # pattern to get videos and classes\n glob_pattern=globname\n # Create video frame generator\n train = VideoFrameGenerator(\n classes=classes, \n glob_pattern=glob_pattern,\n nb_frames=NBFRAME,\n #split=0.5, \n shuffle=False,\n batch_size=BS,\n target_shape=SIZE,\n nb_channel=CHANNELS\n #transformation=none\n #use_frame_cache=True\n )\n sample_test_images, labels = next(train)\n prediction = model.predict(sample_test_images)\n class_names = ['CI', 'PO']\n #print(prediction)\n pred=[]\n pred.append(1)\n pred.append(1)\n pred.append(1)\n pred.append(1)\n pred.append(1)\n for ix in range(0,BS): \n #for higher confidence\n '''\n if prediction[ix,1] > 0.8:\n pred.append(1)\n else:\n pred.append(0) \n '''\n P = np.argmax(prediction[ix])\n pred.append(P)\n \n return pred\n### Generate error image\ndef eim(prediction, name, posCI, listeSOA):\n b3=2300\n b4=3300\n a3=1100\n a4=2200\n w= int(len(prediction)*300)\n o1=0\n o2=1000\n array = np.zeros([b4, w, 3], dtype=np.uint8)\n # Real Line\n array[0:o2,0:(posCI*300)] = [127, 255, 0] #PO grun1\n array[0:o2,(posCI*300):w] = [69, 139, 0] #CI grun2\n # SOA Line\n a2=0\n for i in range(len(listeSOA)):\n a1=a2\n a2= int(a1 + 300)\n \n if listeSOA[i] == 1:\n array[a3:a4,a1:a2] = [127, 255, 0] #PO grun1\n elif listeSOA[i] == 0:\n array[a3:a4,a1:a2] = [69, 139, 0] #CI grun2\n\n # Prediction Line\n b2=0\n for i in range(0,len(prediction)):\n b1= b2\n b2= int(b1 + 300)\n \n if prediction[i] == 1:\n array[b3:b4,b1:b2] = [127, 255, 0] #PO grun1\n elif prediction[i] == 0:\n array[b3:b4,b1:b2] = [69, 139, 0] #CI grun2\n \n img = Image.fromarray(array, 'RGB')\n img.save(name)\n\n\nmodel= load_model('RCNNmodel.h5')\n\nPOdir='F:/DataRCNN/Test/confusion/10/normal/PO'\nCIdir='F:/DataRCNN/Test/time/10/normal/CI'\nBS=len(os.listdir(CIdir)) + len(os.listdir(POdir))-5\nposCI=len(os.listdir(POdir))\nsoatest_dir = 'F:/DataCNN/Test/confusion/10/normal'\ndatadir= 'F:/Test_Sequenzen/ST100-N2H0/0_ST100N2H0_Rampe100-130_Standard/data.csv'\npred = error(BS, 'normal/{classname}/*.avi', model)\nlisteSOA= SOA(datadir, soatest_dir)\neim(pred,'PO0.810normal.png',posCI, listeSOA)\n\nPOdir='F:/DataRCNN/Test/confusion/10/ESM/PO'\nCIdir='F:/DataRCNN/Test/time/10/ESM/CI'\nBS=len(os.listdir(CIdir)) + len(os.listdir(POdir))-5\nposCI=len(os.listdir(POdir))\nsoatest_dir = 'F:/DataCNN/Test/confusion/10/ESM'\ndatadir= 'F:/Test_Sequenzen/ST100-N2H0/1_ST100N2H0_Rampe100-130_ESM+0.5/data.csv'\npred = error(BS, 'ESM/{classname}/*.avi', model)\nlisteSOA= SOA(datadir, soatest_dir)\neim(pred,'PO0.810ESM.png',posCI, listeSOA)\n\nPOdir='F:/DataRCNN/Test/confusion/10/140/PO'\nCIdir='F:/DataRCNN/Test/time/10/140/CI'\nBS=len(os.listdir(CIdir)) + len(os.listdir(POdir))-5\nposCI=len(os.listdir(POdir))\nsoatest_dir = 'F:/DataCNN/Test/confusion/10/140'\ndatadir= 'F:/Test_Sequenzen/ST100-N2H0/3_ST100N2H0_Rampe100-130_Pq140/data.csv'\npred = error(BS, '140/{classname}/*.avi', model)\nlisteSOA= SOA(datadir, soatest_dir)\neim(pred,'PO0.810140.png',posCI, listeSOA)\n\nPOdir='F:/DataRCNN/Test/confusion/10/strahl/PO'\nCIdir='F:/DataRCNN/Test/time/10/strahl/CI'\nBS=len(os.listdir(CIdir)) + len(os.listdir(POdir))-5\nposCI=len(os.listdir(POdir))\nsoatest_dir = 'F:/DataCNN/Test/confusion/10/strahl'\ndatadir= 'F:/Test_Sequenzen/ST100-N2H0/4_ST100N2H0_Rampe100-130_Strahlaußermittigkeit/data.csv'\npred = error(BS, 'strahl/{classname}/*.avi', model)\nlisteSOA= SOA(datadir, soatest_dir)\neim(pred,'PO0.810strahl.png',posCI, listeSOA)\n\nPOdir='F:/DataRCNN/Test/confusion/10/70/PO'\nCIdir='F:/DataRCNN/Test/time/10/70/CI'\nBS=len(os.listdir(CIdir)) + len(os.listdir(POdir))-5\nposCI=len(os.listdir(POdir))\nsoatest_dir = 'F:/DataCNN/Test/confusion/10/70'\ndatadir= 'F:/Test_Sequenzen/ST100-N2H0/2_ST100N2H0_Rampe100-130_Pq70/data.csv'\npred = error(BS, '70/{classname}/*.avi', model)\nlisteSOA= SOA(datadir, soatest_dir)\neim(pred,'PO0.81070.png',posCI, listeSOA)\n","sub_path":"RCNN/Test/10soaanalysiserror.py","file_name":"10soaanalysiserror.py","file_ext":"py","file_size_in_byte":5785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"324227873","text":"import os\n\n\nclass Page:\n def __init__(self, page_id):\n self.page_id = page_id\n self.from_num = 0\n self.from_list = []\n\n self.cnct_num = 0\n\n def new_from(self, from_id):\n self.from_num += 1\n self.from_list.append(from_id)\n\n def write_to_file(self, file):\n \"\"\"\n page_id cnct_num from_num from_list\n \"\"\"\n file.write(\"{} \".format(self.page_id))\n file.write(\"{} \".format(self.cnct_num))\n file.write(\"{} \".format(len(self.from_list)))\n for from_id in self.from_list:\n file.write(\"{} \".format(from_id))\n file.write(\"\\n\")\n\npage_num = 1000000\npage_list = [Page(page_id) for page_id in range(page_num)]\n\noutput_path = r\"data/page_info/reverse_info.txt\"\noutput_file = open(output_path, \"w\", encoding=\"utf-8\")\n\ndata_path = r\"data/page_info/proc_info.txt\"\ndata_file = open(data_path, \"r\", encoding=\"utf-8\")\n\nfor line in data_file:\n page_data = line.split(\" \")[:-1]\n from_id = int(page_data[0])\n cnct_num = int(page_data[1])\n\n if from_id % 10000 == 0:\n os.system(\"cls\")\n if from_id % 1000 == 0:\n print(\"Finish {} ...\".format(from_id))\n\n page_list[from_id].cnct_num = cnct_num\n\n for cnct in range(2, len(page_data)):\n cnct_id = int(page_data[cnct])\n page_list[cnct_id].new_from(from_id)\n\nfor page in page_list:\n page.write_to_file(file=output_file)\n","sub_path":"proc_reverse.py","file_name":"proc_reverse.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"112704598","text":"# Echo server program\nfrom flower import tasklet, run\nfrom flower.net import Listen\n\n\n# handle the connection. It return data to the sender.\ndef handle_connection(conn):\n while True:\n data = conn.read()\n if not data:\n break\n\n conn.write(data)\n\n\n# Listen on tcp port 8000 on localhost using the python socket module.\nl = Listen(('127.0.0.1', 8000), \"socktcp\")\ntry:\n while True:\n try:\n\n # wait for new connections (it doesn't block other tasks)\n conn, err = l.accept()\n\n # Handle the connection in a new task.\n # The loop then returns to accepting, so that\n # multiple connections may be served concurrently.\n\n t = tasklet(handle_connection)(conn)\n except KeyboardInterrupt:\n break\nfinally:\n l.close()\n\nrun()\n","sub_path":"examples/echo_sockserver.py","file_name":"echo_sockserver.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"452670315","text":"# Created by Gnacik\r\n# 2010-02-17 based on official Franz server\r\n\r\nimport sys\r\nfrom com.l2jfree.gameserver.model.quest\t\t\t\timport State\r\nfrom com.l2jfree.gameserver.model.quest\t\t\t\timport QuestState\r\nfrom com.l2jfree.gameserver.model.quest.jython\t\timport QuestJython as JQuest\r\n\r\nqn = \"376_GiantsExploration1\"\r\n\r\n# NPC\r\nSOBLING = 31147\r\n\r\n# Items\r\nANCIENT_PARCHMENT = 14841\r\nBOOK1,BOOK2,BOOK3,BOOK4,BOOK5 = [14836,14837,14838,14839,14840]\r\n\r\n# Drop Chance\r\nDROP_CHANCE = 20\r\n\r\n# Mobs\r\nMOBS = [22670,22671,22672,22673,22674,22675,22676,22677]\r\n\r\n\r\nclass Quest (JQuest) :\r\n\r\n\tdef __init__(self,id,name,descr):\r\n\t\tJQuest.__init__(self,id,name,descr)\r\n\t\tself.questItemIds = [ANCIENT_PARCHMENT]\r\n\r\n\tdef onExchangeRequest(self,event,st,qty,rem) :\r\n\t\tif st.getQuestItemsCount(BOOK1) >= rem and st.getQuestItemsCount(BOOK2) >= rem and st.getQuestItemsCount(BOOK3) >= rem and st.getQuestItemsCount(BOOK4) >= rem and st.getQuestItemsCount(BOOK5) >= rem :\r\n\t\t\tst.takeItems(BOOK1,rem)\r\n\t\t\tst.takeItems(BOOK2,rem)\r\n\t\t\tst.takeItems(BOOK3,rem)\r\n\t\t\tst.takeItems(BOOK4,rem)\r\n\t\t\tst.takeItems(BOOK5,rem)\r\n\t\t\tst.giveItems(int(event),qty)\r\n\t\t\tst.playSound(\"ItemSound.quest_finish\")\r\n\t\t\treturn \"31147-ok.htm\"\r\n\t\telse:\r\n\t\t\treturn \"31147-no.htm\"\r\n\r\n\tdef onAdvEvent (self,event,npc,player) :\r\n\t\thtmltext = event\r\n\t\tst = player.getQuestState(qn)\r\n\t\tif not st : return\r\n\t\tif event == \"31147-02.htm\" :\r\n\t\t\tst.set(\"cond\",\"1\")\r\n\t\t\tst.setState(State.STARTED)\r\n\t\t\tst.playSound(\"ItemSound.quest_accept\")\r\n\t\telif event == \"31147-quit.htm\" :\r\n\t\t\tst.unset(\"cond\")\r\n\t\t\tst.exitQuest(1)\r\n\t\t\tst.playSound(\"ItemSound.quest_finish\")\r\n\t\telif event.isdigit() :\r\n\t\t\tif int(event) == 9967 :\t\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Sword (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9968 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Blade (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9969 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Phantom (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9970 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Bow (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9971 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Knife (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9972 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Halberd (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9973 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Cudgel (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9974 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Mace (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9975 :\t\t\t\t\t\t\t\t\t\t# Recipe - Dynasty Bagh-Nakh (60%)\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,1,10)\r\n\t\t\telif int(event) == 9628 :\t\t\t\t\t\t\t\t\t\t# Leonard\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,6,1)\r\n\t\t\telif int(event) == 9629 :\t\t\t\t\t\t\t\t\t\t# Adamantine\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,3,1)\r\n\t\t\telif int(event) == 9630 :\t\t\t\t\t\t\t\t\t\t# Orichalcum\r\n\t\t\t\thtmltext = self.onExchangeRequest(event,st,4,1)\r\n\r\n\t\treturn htmltext\r\n\r\n\tdef onTalk (self,npc,player) :\r\n\t\thtmltext = \"You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.\"\r\n\t\tst = player.getQuestState(qn)\r\n\t\tif not st : return htmltext\r\n\r\n\t\tnpcId = npc.getNpcId()\r\n\t\tcond = st.getInt(\"cond\")\r\n\r\n\t\tif npcId == SOBLING:\r\n\t\t\tif st.getState() == State.STARTED :\r\n\t\t\t\tif st.getQuestItemsCount(BOOK1) > 0 and st.getQuestItemsCount(BOOK2) > 0 and st.getQuestItemsCount(BOOK3) > 0 and st.getQuestItemsCount(BOOK4) > 0 and st.getQuestItemsCount(BOOK5) > 0 :\r\n\t\t\t\t\t# To do\r\n\t\t\t\t\thtmltext = \"31147-03.htm\"\r\n\t\t\t\telse:\r\n\t\t\t\t\thtmltext = \"31147-02a.htm\"\r\n\t\t\telse:\r\n\t\t\t\tif player.getLevel() >= 79 :\r\n\t\t\t\t\thtmltext = \"31147-01.htm\"\r\n\t\t\t\telse :\r\n\t\t\t\t\thtmltext = \"31147-00.htm\"\r\n\t\treturn htmltext\r\n\r\n\tdef onKill(self,npc,player,isPet) :\r\n\t\tst = player.getQuestState(qn)\r\n\t\tif not st : return\r\n\t\tif st.getState() != State.STARTED : return\r\n\r\n\t\tnpcId = npc.getNpcId()\r\n\t\tcond = st.getInt(\"cond\")\r\n\t\tif cond == 1 and npcId in MOBS :\r\n\t\t\tif st.getRandom(100) < DROP_CHANCE :\r\n\t\t\t\tst.giveItems(ANCIENT_PARCHMENT,1)\r\n\t\t\t\tst.playSound(\"ItemSound.quest_itemget\")\r\n\t\treturn\r\n\r\nQUEST\t\t= Quest(376,qn,\"Exploration of the Giants Cave, Part I\")\r\n\r\nQUEST.addStartNpc(SOBLING)\r\nQUEST.addTalkId(SOBLING)\r\n\r\nfor i in MOBS :\r\n\tQUEST.addKillId(i)\r\n","sub_path":"trunk/l2jfree-datapack/data/scripts/quests/376_GiantsExploration1/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"93463890","text":"import codecs\nfrom causality.tools import project_source_path\nimport os\nfrom tqdm import tqdm\n\n\nif __name__ == '__main__':\n path = os.path.join(project_source_path, 'cross/pmi.txt')\n print(path)\n pmi = {}\n lines = codecs.open(path, 'r', 'utf-8').readlines()\n print(len(lines))\n for line in tqdm(lines):\n res = line.strip().split(' ')\n pmi[res[0]] = float(res[1])\n\n labeledLeft, labeledRight, labeledPair = [], [], []\n lines = codecs.open(os.path.join(project_source_path, 'cross/sg_eva.txt'), 'r', 'utf-8').readlines()\n for line in lines:\n res = line.strip().split('##')\n\n if '_'.join(res[1].split(' ')) in pmi:\n labeledPair.append(res[1].split(' '))\n res = res[0].split('----')\n labeledLeft.append(res[1].split(' '))\n labeledRight.append(res[2].split(' '))\n\n count = 0\n values = []\n totalValid = len(labeledPair)\n print(totalValid)\n for i in range(totalValid):\n d = {}\n for l in labeledLeft[i]:\n for r in labeledRight[i]:\n key = '_'.join([l, r])\n if key in pmi:\n d[key] = pmi[key]\n res = sorted(d.items(), key=lambda x: x[1], reverse=True)\n if res[0][0] == '_'.join(labeledPair[i]):\n count += 1\n for j in range(len(res)):\n if res[j][0] == '_'.join(labeledPair[i]):\n values.append(1.0/float(1+j))\n print(float(count)/totalValid)\n print(sum(values)/totalValid)","sub_path":"causalvec/eval/baselines/pmi.py","file_name":"pmi.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"244596500","text":"class Solution(object):\n def leastInterval(self, tasks, n):\n length = len(tasks)\n task_map = {}\n for task in tasks:\n task_map[task] = tasks.get(task,0) + 1\n task_sort = sorted(task_map.items(), key=lambda x:x[1], reverse=True)\n max_task_count = task_sort[0][1]\n res = (max_task_count - 1) * (n + 1)\n for sort in task_sort:\n if sort[1] == max_task_count:\n res += 1\n return res if res < length else length\n","sub_path":"Week_05/G20190343020006/Leecode_621_006.py","file_name":"Leecode_621_006.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"651187782","text":"import sys\nimport os, os.path\nimport copy\nimport numpy\nfrom scipy import optimize, special\nfrom galpy.util import bovy_plot, bovy_coords, bovy_conversion\nfrom galpy import potential\nfrom galpy.orbit import Orbit\nfrom galpy.actionAngle_src.actionAngleIsochroneApprox\\\n import actionAngleIsochroneApprox\nfrom galpy.df_src.streamdf import streamdf\nfrom matplotlib import pyplot\nfrom matplotlib.ticker import NullFormatter\n_STREAMSNAPDIR= '../sim/snaps-hisigv'\n_STREAMSNAPAADIR= '../sim/snaps_aai'\n_NTRACKCHUNKS= 64\n_SIGV=0.365*10. #x 10 because stream is 10x hotter\ndef plot_stream_xz(plotfilename):\n #Read stream\n data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1-hisigv_evol_00041.dat'),\n delimiter=',')\n includeorbit= True\n if includeorbit:\n npts= 201\n pot= potential.LogarithmicHaloPotential(normalize=1.,q=0.9)\n pts= numpy.linspace(0.,17.,npts)\n #Calculate progenitor orbit around this point\n pox= numpy.median(data[:,1])\n poy= numpy.median(data[:,3])\n poz= numpy.median(data[:,2])\n povx= numpy.median(data[:,4])\n povy= numpy.median(data[:,6])\n povz= numpy.median(data[:,5])\n pR,pphi,pZ= bovy_coords.rect_to_cyl(pox,poy,poz)\n pvR,pvT,pvZ= bovy_coords.rect_to_cyl_vec(povx,povy,povz,pR,\n pphi,pZ,cyl=True)\n ppo= Orbit([pR/8.,pvR/220.,pvT/220.,pZ/8.,pvZ/220.,pphi])\n pno= Orbit([pR/8.,-pvR/220.,-pvT/220.,pZ/8.,-pvZ/220.,pphi])\n ppo.integrate(pts,pot)\n pno.integrate(pts,pot)\n pvec= numpy.zeros((3,npts*2-1))\n pvec[0,:npts-1]= pno.x(pts)[::-1][:-1]\n pvec[1,:npts-1]= pno.z(pts)[::-1][:-1]\n pvec[2,:npts-1]= pno.y(pts)[::-1][:-1]\n pvec[0,npts-1:]= ppo.x(pts)\n pvec[1,npts-1:]= ppo.z(pts)\n pvec[2,npts-1:]= ppo.y(pts)\n pvec*= 8.\n includetrack= True\n if includetrack:\n #Setup stream model\n lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)\n aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)\n obs= numpy.array([1.56148083,0.35081535,-1.15481504,\n 0.88719443,-0.47713334,0.12019596])\n sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,\n leading=True,nTrackChunks=_NTRACKCHUNKS,\n tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),\n deltaAngleTrack=13.5,multi=_NTRACKCHUNKS)\n sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,\n leading=False,nTrackChunks=_NTRACKCHUNKS,\n tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),\n deltaAngleTrack=13.5,multi=_NTRACKCHUNKS)\n #Plot\n bovy_plot.bovy_print()\n bovy_plot.bovy_plot(data[:,1],data[:,2],'k,',\n xlabel=r'$X\\,(\\mathrm{kpc})$',\n ylabel=r'$Z\\,(\\mathrm{kpc})$',\n xrange=[-30.,30.],\n yrange=[-20.,20])\n if includeorbit:\n bovy_plot.bovy_plot(pox,poz,'o',color='0.5',mec='none',overplot=True,ms=8)\n bovy_plot.bovy_plot(pvec[0,:],pvec[1,:],'k--',overplot=True,lw=1.)\n if includetrack:\n d1= 'x'\n d2= 'z'\n sdf.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,\n overplot=True,lw=1.,scaleToPhysical=True)\n sdft.plotTrack(d1=d1,d2=d2,interp=True,color='k',spread=0,\n overplot=True,lw=1.,scaleToPhysical=True)\n bovy_plot.bovy_text(r'$M^p = 2\\times 10^7\\,M_\\odot$'+'\\n'+\n r'$\\sigma_v^p = 14\\,\\mathrm{km\\,s}^{-1}$',\n top_left=True,size=16.)\n bovy_plot.bovy_end_print(plotfilename)\n\nif __name__ == '__main__':\n if 'xz' in sys.argv[1]:\n plot_stream_xz(sys.argv[1])\n","sub_path":"py/plot_stream_hisigv.py","file_name":"plot_stream_hisigv.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"569787752","text":"import random\nimport sys\nimport time\nfrom random import randint\nfrom threading import Thread\nimport deploy\n\nfrom pygame.locals import *\nfrom sys import exit\n\n\nimport pygame\nimport socket # 导入 socket 模块\n\nfrom base import Protocol\n\n\n\n\n# 设置背景颜色和线条颜色\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\n\n# 设置直线的坐标\npoints = [(200, 75), (300, 25), (400, 75)]\n\ndef wait_room():\n # pygame.init()\n window_size = (800, 600)\n # screen = pygame.display.set_mode(window_size, 0, 32)\n deploy.screen = pygame.display.set_mode(window_size)\n clock = pygame.time.Clock()\n pygame.display.set_caption('房间001')\n\n xx = 0\n while True:\n for event in pygame.event.get():\n # 查找关闭窗口事件\n if event.type == QUIT:\n sys.exit()\n\n # 填充背景色\n deploy.screen.fill((255, 255, 255))\n\n # 画不抗锯齿的一条直线\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 40), (560, 40), 3)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 80), (460, 80), 1)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 140), (560, 140), 3)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 180), (460, 180), 1)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 240), (560, 240), 3)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 280), (460, 280), 1)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 340), (560, 340), 3)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 380), (460, 380), 1)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 440), (560, 440), 3)\n pygame.draw.line(deploy.screen, (0, 0, 0), (0, 600), (800, 600), 3)\n pygame.draw.line(deploy.screen, (0, 0, 0), (160, 40), (160, 440), 1)\n pygame.draw.line(deploy.screen, (0, 0, 0), (460, 40), (460, 440), 1)\n pygame.draw.line(deploy.screen, (0, 0, 0), (560, 0), (560, 600), 3)\n\n pygame.font.Font('bb2117/HWKT.ttf', 26)\n x = 45\n for i in range(1,5):\n WJ = deploy.g_font.render('玩家%s' % i, True, (0, 0, 0))\n WJ1 = WJ.get_rect()\n WJ1.midtop = (70, x + ((i - 1) * 100))\n deploy.screen.blit(WJ, WJ1)\n\n ZZ = deploy.g_font.render('种族', True, (0, 0, 0))\n ZZ1 = ZZ.get_rect()\n ZZ1.midtop = (290, x + ((i - 1) * 100))\n deploy.screen.blit(ZZ, ZZ1)\n\n if xx == 0:\n xx += 1\n for i in deploy.g_other_player:\n print('x : %s ' % i.x)\n print('y : %s ' % i.y)\n print('name : %s ' % i.name)\n print('number : %s ' % i.number)\n print('my : %s ' % i.my)\n print('reca : %s ' % i.reca)\n print('troops : %s ' % i.troops)\n\n for i in deploy.g_other_player:\n WJMZ = deploy.g_font.render('%s' % i.name, True, (0, 0, 0))\n WJMZ1 = WJMZ.get_rect()\n WJMZ1.midtop = (20, x + 50 + ((int(i.number) - 1) * 100))\n deploy.screen.blit(WJMZ, WJMZ1)\n\n WJZZ = deploy.g_font.render('%s' % i.reca, True, (0, 0, 0))\n WJZZ1 = WJZZ.get_rect()\n WJZZ1.midtop = (290, x + 50 + ((int(i.number) - 1) * 100))\n deploy.screen.blit(WJZZ, WJZZ1)\n\n\n\n # 刷新图s\n pygame.display.flip()\n\n clock.tick(60)","sub_path":"client/Script/wait_room_old.py","file_name":"wait_room_old.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"43393074","text":"#!/usr/bin/env python\nimport sys\nimport numpy as np\nfrom scipy.integrate import romb\nimport matplotlib.pyplot as pl\n# use pyreport -l file.py\nfrom pylab import show\nimport pyreport\n\n#$ Jaime Hopkins HW2 prob 2\n#$ % Python code for Kramers-Kronig transform of\n#$ \\varepsilon\\prime\\prime(i\\omega)\n\n#$ \\begin{equation}\n#$ p(\\cos\\theta | b/a) = N ( 1 + (b/a) \\cos^2 \\theta )\n#$ \\end{equation}\n#$ %\n#$ \\subsection{First, find N such that p = 1:}\n#$ \\begin{equation}\n#$ p = &&\\int \\limits_{-1}^{1} N ( 1 + (b/a) \\cos^2 \\theta ) d (\\cos \\theta) = 1 \n#$ \\end{equation}\n#$ %\n#$ \\begin{eqnarray}\n#$ p = &&\\int \\limits_{-1}^{1} N ( 1 + (b/a) \\cos^2 \\theta ) d (\\cos \\theta) = 1 \n#$ 1/N = &&\\int \\limits_{-1}^{1} ( 1 + (b/a) \\cos^2 \\theta ) d (\\cos \\theta)\n#$ = &&\\int \\limits_{-1}^{1} ( 1 + (b/a) \\x^2 ) dx = 2(1 + (b/a)/3)\n#$ %\n#$ N = \\frac{3}{2(3+b/a)}\n#$ \\end{eqnarray}\n#$ %\n#$ \\subsection{2 (a) using the method of moments} \n#$ \\[\\begin{eqnarray}\n#$ \\left<\\cos^2\\theta\\right> &= N \\int \\limits_{-1}^{1} \\mathrm{d}\\cos\\theta\\left(\\cos^2 \\theta + (b/a) \\cos^4 \\theta\\right)\\\\\n#$ &= N \\left.\\left(\\frac{1}{3}x^3 + \\frac{(b/a)}{5}x^5\\right)\\right|_{-1}^{1}\\\\\n#$ &= \\frac{1}{5}\\cdot\\frac{5 + 3(b/a)}{3 +(b/a)}\n#$ \\end{array}\n#$ %\n\n#$ First, input \\varepsilon\\prime\\prime(i\\omega) files from Dan:\n\neV_x,eps2_x = np.loadtxt('data/CNT6_5_xe2_solid_30.txt',unpack=True, usecols = [0,1])\neV_z,eps2_z = np.loadtxt('data/CNT6_5_ze2_solid_30.txt',unpack=True, usecols = [0,1])\n\n#eV_x,eps2_x = np.loadtxt('data/CNT9_0_xe2_solid_30.txt',unpack=True, usecols = [0,1])\n#eV_z,eps2_z = np.loadtxt('data/CNT9_0_ze2_solid_30.txt',unpack=True, usecols = [0,1])\n#eps2_z[:57] = 0.0 # removes first divergent peak in eps2_z, saves file with npk\n\n#eV_x,eps2_x = np.loadtxt('data/CNT9_1_xe2_solid_30.txt',unpack=True, usecols = [0,1])\n#eV_z,eps2_z = np.loadtxt('data/CNT9_1_ze2_solid_30.txt',unpack=True, usecols = [0,1])\n#\n#eV_x,eps2_x = np.loadtxt('data/CNT9_3_xe2_solid_30.txt',unpack=True, usecols = [0,1])\n#eV_z,eps2_z = np.loadtxt('data/CNT9_3_ze2_solid_30.txt',unpack=True, usecols = [0,1])\n#\n#eV_x,eps2_x = np.loadtxt('data/CNT29_0_xe2_solid_30.txt',unpack=True, usecols = [0,1])\n#eV_z,eps2_z = np.loadtxt('data/CNT29_0_ze2_solid_30.txt',unpack=True, usecols = [0,1])\n\neV_w,eps2_w = np.loadtxt('data/water-L.txt',unpack=True, usecols = [0,1])\n\n#$ Make a list of Matsubara energies as integer multiples of N\n#$ \\xi_{N}^(RT) = (2 \\pi k_{B} T / hbar)N = coeff*N\ncoeff = 0.159 # [eV] \nT = 300.0 # Room temp\nn = np.arange(0,500) \nz = n * coeff # energies \n\ndef Aiz(perp, par,med):\n\treturn (2.0*(perp-med)*med)/((perp+med)*(par-med))\n\n#$ Make empty lists for \\varepsilon(i\\xi) and integrand\neiz_x = np.empty(len(z))\neiz_z = np.empty(len(z))\neiz_w = np.empty(len(z))\n\nintegrand_x=np.empty(len(eV_x))\nintegrand_z=np.empty(len(eV_z))\nintegrand_w=np.empty(len(eV_w))\n\n#$ Compute \\varepsilon(i\\xi) for each \\xi_N\nfor j in range(len(z)):\n for k in range(len(eV_x)):\n integrand_x[k]=eV_x[k]*eps2_x[k] / (eV_x[k]**2 + z[j]**2)\n eiz_x[j] = 1 + (2./np.pi) * np.trapz(integrand_x,eV_x)\n\n for m in range(len(eV_z)):\n integrand_z[m]=eV_z[m]*eps2_z[m] / (eV_z[m]**2 + z[j]**2)\n eiz_z[j] = 1 + (2./np.pi) * np.trapz(integrand_z,eV_z) \n\n for p in range(len(eV_w)):\n integrand_w[p]=eV_w[p]*eps2_w[p] / (eV_w[p]**2 + z[j]**2)\n eiz_w[j] = 1 + (2./np.pi) * np.trapz(integrand_w,eV_w) \n\n#np.savetxt( \"data/energies.txt\", z )\nnp.savetxt( \"data/eiz_x_65.txt\", eiz_x)\n#np.savetxt( \"data/eiz_z_npk_90.txt\", eiz_z)\nnp.savetxt( \"data/eiz_z_65.txt\", eiz_z)\nnp.savetxt( \"data/eiz_w.txt\" , eiz_w)\n#\na = Aiz(eiz_x,eiz_z,eiz_w)\n#\nfig = pl.figure()\nax = fig.add_axes([0.1,0.1,0.8,0.8])\nax.plot(n,eiz_x, color = 'b', label = r'$\\varepsilon_{\\hat{x}}(i\\zeta_{N})$')\nax.plot(n,eiz_z, color = 'r', label = r'$\\varepsilon_{\\hat{z}}(i\\zeta_{n})$')\nax.plot(n,eiz_z, color = 'r', label = r'$max\\,%6.2f$'%max(eiz_z))\nax.plot(n,eiz_w, color = 'c', label = r'$\\varepsilon_{\\hat{w}}(i\\zeta_{n})$')\npl.axis([0,500,0,10])\npl.xlabel(r'$N$', size = 24)\npl.ylabel(r'$\\varepsilon(i\\zeta)$', size = 24)\n#pl.legend()\n#pl.title(r'$\\rm{\\varepsilon(i\\xi)\\, for\\, [9,0]\\, and\\, water}$')\n#pl.title(r'[9,0] eiz (no first peak in eps2_z) and water eiz')\n\nax_inset = fig.add_axes([0.53,0.50,0.36,0.36])\nax_inset.plot(n, a,'k-.', linewidth = 2)#,label=r'$a(i\\xi_{N})$')\npl.tick_params(labelsize = 'small')\npl.xlabel(r'$N$', size = 14)\npl.ylabel(r'$a(i\\xi)$', size = 14)\n#pl.savefig('plots/90w90_eiz.png')\n#pl.savefig('plots/90w90_eiz_npk.eps')\npl.show()\n\n\npl.figure()\npl.plot(eV_x,eps2_x, color = 'b', label = r'$\\varepsilon^{\\prime\\prime}_\\hat{x}(\\omega)$')\npl.plot(eV_z,eps2_z, color = 'r', label = r'$\\varepsilon^{\\prime\\prime}_\\hat{z}(\\omega)$')\npl.plot(eV_z,eps2_z, color = 'r', label = r'$max\\,%.8s$'%max(eps2_z))\npl.plot(eV_w,eps2_w, color = 'c', label = r'$\\varepsilon^{\\prime\\prime}_{H_{2}O}(\\omega)$')\npl.xlabel(r'$\\hbar\\omega\\,\\,\\,[eV]$', size = 24)\npl.ylabel(r'$\\varepsilon^{\\prime\\prime}(\\omega)$', size = 24)\npl.axis([0,40,0,30])\npl.legend()\n#pl.title(r'[9,0] eps2 and water eps2')\n#pl.title(r'[9,0] eps2 (no first peak) and water eps2')\n#pl.savefig('plots/90w90_eps2.png')\n#pl.savefig('plots/90w90_npk_eps2.eps')\nshow()\n\n","sub_path":"140412_eiz.py","file_name":"140412_eiz.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"578493283","text":"import torch\n\n\ndef batchify(data, bsz, cuda=True):\n # Work out how cleanly we can divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n if cuda:\n data = data.cuda()\n return data\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef repackage_hidden(h):\n \"\"\"Wraps hidden states in new Tensors,\n to detach them from their history.\"\"\"\n if isinstance(h, torch.Tensor):\n return h.detach()\n else:\n return tuple(repackage_hidden(v) for v in h)\n\n \ndef get_batch(source, i, seq_len, evaluation=False):\n \"\"\"`source` has dimension (L, N)\"\"\"\n seq_len = min(seq_len, source.size(0) - 1 - i)\n data = source[i:i + seq_len]\n if (evaluation):\n data.set_grad_enabled(False)\n target = source[i + 1:i + 1 + seq_len] # CAUTION: This is un-flattened!\n return data, target\n","sub_path":"TrellisNet/word_WT103/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"364811223","text":"#!/usr/bin/env python\n\nclass BLASTReader(object):\n def __init__(self, file):\n self.file = file\n self.last_ident = None\n \n def next (self): \n if self.last_ident is None: \n line = self.file.readline()\n assert line.startswith(\">\"), \"Not valid dasta\"\n ident = line[1:].rstrip(\"\\r\\n\")\n\n #^^^^^^ strip any new line character from the end of the line, remove and return a new line\n else:\n ident = self.last_ident\n \n sequences = []\n while True:\n line = self.file.readline()\n if not line:\n break\n if line.startswith(\">\"):\n self.last_ident = line[1:].rstrip(\"\\r\\n\")\n break\n else:\n sequences.append(line.strip()) #remove white space from front and back of the sequence. strip only does left and right \\r and \\l \n if len(sequences) == 0:\n raise StopIteration\n \n \n sequences = \"\".join(sequences) #takes a list of strings and adds them using whatever is before (in this case \"\")as separaters\n return ident, sequences\n \n# all we need to make this iterater is a code that says I'm an iterable and I meet your requirement - there must be an obeject, that returns another object that you call next.\n def __iter__( self ):\n return self","sub_path":"day5/Day5Lunch/blasta.py","file_name":"blasta.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"179194361","text":"import tkinter as tk\nfrom tkinter.filedialog import askdirectory\nfrom tkinter import ttk\nfrom tkinter.messagebox import askyesno,showinfo\nimport re\nfrom subprocess import Popen\nfrom concurrent.futures import ThreadPoolExecutor\n\nclass Trip():\n def __init__(self,root=None,vtype_inputs={},trip_inputs={},commands={}):\n\n\n self.header=[\n \"\",\n '',\n ]\n\n self.body=[]\n\n self.ender=['']\n\n self.commands=commands\n\n if root==None:\n self.root=tk.Tk()\n else:\n self.root=root\n\n #消除窗体\n # self.root.overrideredirect(True)\n #透明度\n self.root.attributes('-alpha',1)\n #置顶属性\n self.root.attributes('-topmost',True)\n # self.root.attributes('-transparentcolor','black')\n max_x, max_y = self.root.maxsize()\n self.root.state('zoomed')\n self.root.geometry(\"%sx%s+%s+%s\" % (int(max_x * 0.7), int(max_y * 0.7), int(max_x * 0.2), int(max_y * 0.2)))\n # self.root.resizable(False,False)\n self.root.title(\"TRIP XML\")\n self.font_type=('楷体',20)\n self.output_font_type=('楷体',15)\n\n self.input_area=tk.Frame(self.root)\n self.input_area.pack(side=tk.TOP, expand=tk.NO, fill=tk.BOTH)\n\n self.trip_area=tk.LabelFrame(self.input_area,text='TRIP')\n self.trip_area.pack(side=tk.LEFT,fill=tk.BOTH, expand=tk.YES)\n\n self.vtype_area=tk.LabelFrame(self.input_area,text='vType')\n self.vtype_area.pack(side=tk.LEFT,fill=tk.BOTH, expand=tk.YES)\n\n self.trip_label_area=tk.Label(self.trip_area)\n self.trip_label_area.pack(side=tk.LEFT,fill=tk.BOTH, expand=tk.YES)\n\n self.trip_input_area = tk.Label(self.trip_area)\n self.trip_input_area.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES)\n\n self.vtype_label_area = tk.Label(self.vtype_area)\n self.vtype_label_area.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)\n\n self.vtype_input_area = tk.Label(self.vtype_area)\n self.vtype_input_area.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES)\n\n if vtype_inputs=={}:\n self.vtype_inputs={\n 'id':'',\n 'test1':'',\n 'test2': '',\n 'test3': '',\n 'test4': '',\n }\n else:\n self.vtype_inputs=vtype_inputs\n\n if trip_inputs=={}:\n self.trip_inputs={\n 'id':'',\n 'depart':'',\n 'from':'',\n 'to':'',\n 'via':'',\n 'departLane':'',\n 'departPos':'',\n 'departSpeed':'',\n 'type':'',\n }\n else:\n self.trip_inputs=trip_inputs\n\n for name in self.vtype_inputs.keys():\n\n label=tk.Label(self.vtype_label_area, bd=1,relief=\"raised\",highlightthickness=0,text=name+':',\n font=(self.font_type))\n input = ttk.Combobox(self.vtype_input_area, font=(self.font_type))\n\n label.pack(expand=True,fill=tk.BOTH)\n input.pack(expand=True,fill=tk.BOTH)\n self.vtype_inputs[name]=input\n\n\n\n\n for name in self.trip_inputs.keys():\n label=tk.Label(self.trip_label_area, bd=1,relief=\"raised\",highlightthickness=0,text=name+':',\n font=(self.font_type))#,\n input = ttk.Combobox(self.trip_input_area, font=(self.font_type))\n label.pack(expand=True,fill=tk.BOTH)\n input.pack(expand=True,fill=tk.BOTH)\n self.trip_inputs[name]=input\n\n\n self.up_area=tk.Frame(self.root)\n self.up_area.pack(side=tk.TOP, fill=tk.BOTH)\n\n self.add_trip_button = tk.Button(self.up_area,relief=tk.GROOVE, command=self.on_add_trip_button_click,text='增加trip', font=(self.font_type),bd=5)\n self.add_trip_button.pack(side=tk.LEFT, expand=True,fill=tk.BOTH)\n\n self.add_vtype_button = tk.Button(self.up_area,relief=tk.GROOVE, command=self.on_add_vtype_button_click,text='增加vType', font=(self.font_type),bd=5)\n self.add_vtype_button.pack(side=tk.LEFT, expand=True,fill=tk.BOTH)\n\n\n self.del_button = tk.Button(self.up_area,relief=tk.GROOVE, command=self.on_del_button_click,text='删除', font=(self.font_type),bd=5)\n self.del_button.pack(side=tk.RIGHT, expand=True,fill=tk.BOTH)\n\n #self.output = tk.Text(self.root,font=('楷体',15),bd=5,wrap=tk.NONE) #设置wrap可以实现自动换行和不自动换行\n self.output = tk.Listbox(self.root,font=self.output_font_type,bd=5) #设置wrap可以实现自动换行和不自动换行\n self.output.pack(side=tk.TOP, expand=tk.YES, fill=tk.BOTH)\n\n output_xscrollbar = tk.Scrollbar(self.output, orient=tk.HORIZONTAL)\n output_xscrollbar.pack(side=tk.BOTTOM, fill=tk.X)\n output_xscrollbar.config(command=self.output.xview)\n self.output.config(xscrollcommand=output_xscrollbar.set)\n\n output_yscrollbar = tk.Scrollbar(self.output,orient=tk.VERTICAL)\n output_yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n output_yscrollbar.config(command=self.output.yview)\n self.output.config(yscrollcommand=output_yscrollbar.set)\n\n self.bottom_area=tk.Frame(self.root,relief=tk.FLAT)\n self.bottom_area.pack(side=tk.TOP,anchor=tk.S,expand=tk.NO,fill=tk.X)\n\n self.change=tk.Button(self.bottom_area,text='切换为FLOW模式',relief=tk.GROOVE,bd=5,font=self.font_type,command=self.on_change_button_click)\n self.change.pack(side=tk.LEFT,fill=tk.BOTH,expand=True)\n\n self.save_button=tk.Button(self.bottom_area,text='保存TRIP XML',relief=tk.GROOVE,bd=5,font=self.font_type,command=self.on_save_button_click)\n self.save_button.pack(side=tk.LEFT,fill=tk.BOTH,expand=True)\n\n\n for name,command in self.commands.items():\n temp=tk.Button(self.bottom_area,text=f'运行{name}',relief=tk.GROOVE,bd=5,font=self.font_type)\n temp.pack(side=tk.LEFT,fill=tk.BOTH,expand=True)\n temp.bind(\"\", self.on_run_button_click)\n\n self.scale = tk.Scale(self.root, from_=50, to=100, orient=tk.HORIZONTAL,\n repeatinterval=300, repeatdelay=300, sliderlength=10,\n )#label='阈值',showvalue=1,borderwidth=0.01,resolution=1 , tickinterval=10,\n self.scale.set(90)\n self.scale.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)\n self.scale.bind(\"\", self.on_scale_click)\n self.scale.bind(\"\", self.on_scale_click)\n self.scale.bind(' ', self.on_scale_click)\n self.scale.bind(\"\", self.on_scale_click)\n\n\n def get_record_index(self):\n s=self.output.curselection()\n if s:\n index = self.output.index(s)\n print(index)\n return index\n else:\n print(s)\n return None\n\n def on_del_button_click(self):\n index=self.get_record_index()\n if index==None or index in [0,1,len(self.header+self.body+self.ender)]:\n return False\n else:\n self.body.pop(index-2)\n self.refresh_output()\n self.output.selection_set(index)\n return True\n\n\n def on_scale_click(self,event):\n self.root.attributes(\"-alpha\", self.scale.get() / 100)\n\n\n def refresh_output(self):\n\n if self.body==[]:\n xml=[]\n else:\n xml=self.header+self.body+self.ender\n\n self.output.delete(0,'end')\n\n for row in xml:\n\n self.output.insert('end', row.replace('\\t',' '))\n\n def on_add_vtype_button_click(self):\n\n if self.vtype_inputs['id'].get()=='':\n\n showinfo('注意','必须输入vtype id')\n\n return False\n\n items={}\n for name in self.vtype_inputs.keys():\n value=self.vtype_inputs[name].get()\n if value!='':\n items[name]=value\n line=self.create_line('vType',items)\n\n if line!=False:\n print(line)\n self.body.append(line)\n\n self.refresh_output()\n\n def create_line(self,type,items):\n print(items)\n if items!={}:\n\n header=[f'\\t<{type}']\n\n ender=[f'/>']\n\n body=[]\n\n for name in items.keys():\n body.append(f'{name} = \"{items[name]}\"')\n\n line=header+body+ender\n\n line=' '.join(line)\n\n line=line.replace(' />','/>')\n\n print(line)\n return line\n\n else:\n return False\n\n def set_input_values(self,types,name,values,default=0):\n types=str.lower(types)\n if types not in ['trip','vtype']:\n print('types must be trip or vtype' )\n return False\n\n if not isinstance(values,(list)):\n print('values must be list')\n return False\n\n if types =='trip':\n if name in self.trip_inputs.keys():\n if isinstance(default,(int)):\n self.trip_inputs[name]['values'] = values\n self.trip_inputs[name].current(default)\n return True\n else:\n self.trip_inputs[name]['values'] = values\n return True\n else:\n print(f'trip {name} 不存在')\n return False\n\n\n if types =='vtype':\n if name in self.vtype_inputs.keys():\n if isinstance(default, (int)):\n self.vtype_inputs[name]['values']=values\n self.vtype_inputs[name].current(default)\n return True\n else:\n self.vtype_inputs[name]['values'] = values\n return True\n\n else:\n print(f'vtype {name} 不存在')\n return False\n\n def on_add_trip_button_click(self):\n\n items = {}\n for name in self.trip_inputs.keys():\n value = self.trip_inputs[name].get()\n if value != '':\n items[name] = value\n line = self.create_line('trip', items)\n\n if line != False:\n print(line)\n self.body.append(line)\n\n self.refresh_output()\n\n def remove_special_char(self,s):\n return re.sub('[?/*<>|]','',s)\n\n def init(self):\n self.body=[]\n self.refresh_output()\n\n def on_save_button_click(self):\n if self.body==[]:\n self.refresh_output()\n return False\n\n xml=self.header+self.body+self.ender\n self.refresh_output()\n output_filename=self.remove_special_char(self.vtype_inputs['id'].get())+'.trip.xml'\n txt='\\n'.join(xml)\n with open(output_filename,'w',encoding='utf-8') as f:\n f.write(txt)\n showinfo('成功','保存成功')\n self.init()\n\n def on_change_button_click(self):\n if askyesno('注意','是否切换到FLOW模式,为保存的数据将丢失'):\n return True\n\n def on_run_button_click(self,event):\n name=event.widget['text'].replace('运行','')\n command=self.commands[name]\n def do():\n if command:\n Popen(command,creationflags=16)\n\n if askyesno('注意',f'是否运行命令 {command}'):\n ThreadPoolExecutor(max_workers=1).submit(do)\n\n\nif __name__ == '__main__':\n\n app=Trip()\n app.root.mainloop()\n\n","sub_path":"图形界面处理/Ferryman_第三版-图形界面程序-类方式增加命令运行按钮-tk/trip.py","file_name":"trip.py","file_ext":"py","file_size_in_byte":11682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"408646752","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('properties', '0002_auto_20151122_1125'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='property',\n old_name='price_with_food',\n new_name='price_accomodaton',\n ),\n migrations.RenameField(\n model_name='property',\n old_name='price_without_food',\n new_name='price_food',\n ),\n migrations.AlterField(\n model_name='address',\n name='pin',\n field=models.PositiveIntegerField(verbose_name=b'PIN Code'),\n ),\n ]\n","sub_path":"properties/migrations/0003_auto_20151122_2207.py","file_name":"0003_auto_20151122_2207.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"615034075","text":"import Util\nimport socket\nimport struct\nimport threading\nimport msgpack\nfrom io import BytesIO\nfrom OpenSSL import crypto, SSL\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.Hash import SHA\nfrom Crypto.Cipher import AES\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto import Random\nimport os\n\n\nclass Server:\n\n def __init__(self, ID, sock=None):\n if sock is None:\n self.sock = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n else:\n self.sock = sock\n\n self.ID = ID\n\n def bind(self, host, port):\n self.sock.bind((host, port))\n\n def data_send_receive(self,socket,aes_encryptor):\n data = str.encode('result = aes_encryptor.decrypt(message.payload.data)')\n length = 16 - (len(data) % 16)\n while True:\n message = Util.receive(socket)\n result = aes_encryptor.decrypt(message.payload.data)\n result = result[:-result[-1]]\n if(message.payload.type == int(Util.MESSAGE_TYPE['shutdown'])):\n #print('server shutdown')\n break\n Util.send(socket, aes_encryptor.encrypt(data+bytes([length])*length),int(Util.ENCODING),int(Util.COMPRESSION),1,int(Util.MESSAGE_TYPE['data']),1) \n \n\n def establishSecureConn(self, socket, cert_data, encoding, compression):\n #print('server est secure conn')\n cert = Util.read_cert('','',cert_data)\n pub_key = cert.get_pubkey()\n shared_key = Util.random_string(10)\n shared_key = \"{: <32}\".format(shared_key).encode(\"utf-8\")\n aes_encryptor = AES.new(shared_key,AES.MODE_CBC,'This is an IV456')\n pkcs1CipherTmp = PKCS1_OAEP.new(RSA.importKey(crypto.dump_publickey(crypto.FILETYPE_PEM,pub_key)))\n encryptedKey = pkcs1CipherTmp.encrypt(shared_key)\n #print(\"\\nresource server: sent back a key encrypted via client public key\")\n Util.send(socket,encryptedKey,int(encoding), int(compression),1,int(Util.MESSAGE_TYPE['secure']),1)\n #signature = aes_encryptor.decrypt(message.payload.data)\n message = Util.receive(socket)\n #print(\"\\nresource server: permissions received\")\n permission = aes_encryptor.decrypt(message.payload.data)\n permission = permission[:-permission[-1]]\n hash = SHA.new(permission)\n message = Util.receive(socket)\n signature = aes_encryptor.decrypt(message.payload.data)\n signature = signature[:-signature[-1]]\n MASTER_CERT_PATH = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n auth_public_key = Util.read_cert(MASTER_CERT_PATH,'\\\\cert').get_pubkey()\n public_key = RSA.importKey(crypto.dump_publickey(crypto.FILETYPE_PEM,auth_public_key))\n verifier = PKCS1_v1_5.new(public_key)\n if verifier.verify(hash, signature):\n #print(\"The signature is authentic.\")\n permission_card = Util.jsonDeserialization(str(permission, 'utf-8'))\n resources = permission_card['resources']\n permissions = permission_card['permissions']\n for i in range(0,len(resources)):\n if(resources[i] == self.ID):\n '''if(permissions[i] == 'r'):\n print('read permission granted on ' + self.ID)\n elif(permissions[i] == 'w'):\n print('write permission granted on ' + self.ID)\n elif(permissions[i] == 'x'):\n print('read write permission granted on ' + self.ID)\n elif(permissions[i] == 'n'):\n print('permission denied on ' + self.ID)'''\n break\n data = str.encode('whatever')\n length = 16 - (len(data) % 16)\n Util.send(socket, aes_encryptor.encrypt(data+bytes([length])*length),int(Util.ENCODING),int(Util.COMPRESSION),1,int(Util.MESSAGE_TYPE['secure_ack']),1)\n self.data_send_receive(socket,aes_encryptor)\n else:\n print (\"The signature is not authentic.\")\n \n\n def receiveMsg(self):\n while True:\n self.sock.listen(1)\n socket, sender = self.sock.accept()\n encoding = int.from_bytes(struct.unpack(\"s\",socket.recv(1))[0],byteorder='big') \n compression = int.from_bytes(struct.unpack(\"s\",socket.recv(1))[0],byteorder='big') \n size = bytes([struct.unpack(\"B\",socket.recv(1))[0],struct.unpack(\"B\",socket.recv(1))[0],struct.unpack(\"B\",socket.recv(1))[0]])\n sz = int.from_bytes(size,byteorder='big')\n payload = socket.recv(int.from_bytes(size,byteorder='big'))\n message = Util.Message(encoding,compression,Util.decompress(payload,compression))\n bytesio = BytesIO(message.payload) \n unpacker = msgpack.Unpacker(bytesio)\n if message.encoding == Util.Message.Encoding.JSON: \n message.payload = message.jsonDeserialization(''.join(message.payload))\n elif message.encoding == Util.Message.Encoding.PICKLE: \n message.payload = message.pickleDeserialaization(''.join(message.payload))\n elif message.encoding == Util.Message.Encoding.MSGPACK: \n payload = Util.Payload(unpacker.unpack(),unpacker.unpack(),unpacker.unpack(),unpacker.unpack()) \n message.payload = payload \n \n if message.payload.type == int(Util.MESSAGE_TYPE['secure']):\n #print(\"\\nresource server: a request to setup a secure connection received\")\n receiverThread = threading.Thread(target=self.establishSecureConn(socket,message.payload.data,encoding,compression))\n receiverThread.start()\n\n def receiver(self):\n receiverThread = threading.Thread(target=self.receiveMsg)\n receiverThread.start()","sub_path":"ProtocolClient/ProtocolServer.py","file_name":"ProtocolServer.py","file_ext":"py","file_size_in_byte":5934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"46907222","text":"from modules import config\r\nfrom modules.feature_engineering import heuristic_features\r\n\r\nfrom pathlib import Path\r\nimport pandas as pd\r\n\r\n\r\ndef load_data(path_enhanced, path_normal):\r\n if Path(path_enhanced).is_file():\r\n data = pd.read_csv(path_enhanced, names=config.ALL_LIST_ENHANCED_V1)\r\n else:\r\n data = pd.read_csv(path_normal, names=config.ALL_LIST)\r\n data = heuristic_features.sequence_end_feat(data)\r\n data = heuristic_features.max_same_colour_count_feat(data)\r\n data = heuristic_features.max_values_count_feat(data)\r\n data.to_csv(path_enhanced, header=False)\r\n return data\r\n","sub_path":"modules/loaders/loader_v1.py","file_name":"loader_v1.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"439375103","text":"# Copyright (c): Wenyi Tang 2017-2019.\n# Author: Wenyi Tang\n# Email: wenyi.tang@intel.com\n# Update Date: 2019/4/3 下午5:03\n\nimport numpy as np\n\nfrom . import _logger\nfrom ..VirtualFile import ImageFile\n\n\nclass Parser(object):\n def __init__(self, dataset, config):\n urls = sorted(dataset.get(config.method, []))\n flow = sorted(dataset.flow)\n self.files = [ImageFile(fp).attach_flow(f) for fp, f in zip(urls, flow)]\n self.depth = config.depth\n self.method = config.method\n if config.convert_to.lower() in ('gray', 'l'):\n self.color_format = 'L'\n elif config.convert_to.lower() in ('yuv', 'ycbcr'):\n self.color_format = 'YCbCr'\n elif config.convert_to.lower() in ('rgb',):\n self.color_format = 'RGB'\n else:\n _logger.warning('Use grayscale by default. '\n 'Unknown format {}'.format(config.convert_to))\n self.color_format = 'L'\n\n def __getitem__(self, index):\n if isinstance(index, slice):\n ret = []\n for vf in self.files[index]:\n ret += self.gen_frames(vf)\n return ret\n else:\n vf = self.files[index]\n return self.gen_frames(vf)\n\n def __len__(self):\n return len(self.files)\n\n def gen_frames(self, vf):\n assert isinstance(vf, ImageFile)\n\n _logger.debug('Prefetching ' + vf.name)\n vf.reopen()\n img = [x for x in vf.read_frame(2)]\n img = [x.convert(self.color_format) for x in img]\n frames = [(img, [vf.flow], (vf.name, 0, vf.frames))]\n return frames\n\n @property\n def capacity(self):\n bpp = 14 # bytes per pixel\n # NOTE use uint64 to prevent sum overflow\n return np.sum([np.prod((*vf.shape, vf.frames, bpp), dtype=np.uint64)\n for vf in self.files])\n","sub_path":"VSR/DataLoader/Parser/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"158245635","text":"import csv \n\nfilename = \"freemansbridgecrests.txt\"\n\nf = open(filename)\n# read away the header\nheight = []\ndate = []\nf.readline()\nfor line in f:\n\tdata = line.split()\n\theight += [data[1]]\n\tdate += [data[4]]\n\t\ncsv_file = open(\"crests.csv\", \"w\")\ntry:\n\twriter = csv.writer(csv_file)\n\twriter.writerow((\"Gage Height (ft)\", \"Date\"))\n\tfor h, d in zip(height, date):\n\t\twriter.writerow((h,d))\nfinally:\n\tf.close()\n\tcsv_file.close()\n\t\n","sub_path":"data/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"353151645","text":"from tkinter import *\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\nimport tkinter.messagebox as messagebox\nimport usb.core\nimport usb.util\nROMsize = 0\nRAMsize = 0\nROMbuffer = ''\nRAMbuffer = ''\nUSBbuffer = ''\nFlashBlockSize = 0\nfor usbfill in range(64):\n USBbuffer = USBbuffer + '\\x00'\n\nCommand_Get_Version = [\n 0]\nCommand_Get_ROM = [16]\nCommand_Set_Bank = [8]\nCommand_Flash_ROM = [32]\n\nclass Window(Frame):\n\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n self.init_window()\n\n def init_window(self):\n self.master.title('Joey Joebags by BennVenn - V3.15')\n self.pack(fill=BOTH, expand=1)\n self.lowerLeftLabel = StringVar()\n cartSelectionLabel = Label(root, textvariable=self.lowerLeftLabel)\n cartSelectionLabel.place(x=0, y=280)\n self.lowerRightLabel = StringVar()\n hardwareStatusLabel = Label(root, textvariable=self.lowerRightLabel)\n hardwareStatusLabel.place(x=270, y=280)\n self.ROMtitleLabel = StringVar()\n ROMtitleLabel = Label(root, textvariable=self.ROMtitleLabel)\n ROMtitleLabel.place(x=0, y=0)\n self.ROMsizeLabel = StringVar()\n ROMsizeLabel = Label(root, textvariable=self.ROMsizeLabel)\n ROMsizeLabel.place(x=0, y=20)\n self.RAMsizeLabel = StringVar()\n RAMsizeLabel = Label(root, textvariable=self.RAMsizeLabel)\n RAMsizeLabel.place(x=0, y=40)\n self.MAPPERtypeLabel = StringVar()\n MAPPERtypeLabel = Label(root, textvariable=self.MAPPERtypeLabel)\n MAPPERtypeLabel.place(x=0, y=60)\n menu = Menu(root)\n root.config(menu=menu)\n filemenu = Menu(menu)\n menu.add_cascade(label='File', menu=filemenu)\n filemenu.add_command(label='Exit', command=main_Exit)\n cartTypeMenu = Menu(menu)\n menu.add_cascade(label='Cart Type', menu=cartTypeMenu)\n MBCmenu = Menu(menu)\n cartTypeMenu.add_cascade(label='GB(C) Generic', menu=MBCmenu)\n MBCmenu.add_command(label='Get Save RAM', command=main_MBC_Dump_RAM)\n MBCmenu.add_command(label='Write Save RAM', command=main_MBC_Burn_RAM)\n MBCmenu.add_command(label='Dump ROM', command=main_MBC_Dump_ROM)\n MBC2menu = Menu(menu)\n cartTypeMenu.add_cascade(label='GB MBC2', menu=MBC2menu)\n MBC2menu.add_command(label='Get Save RAM', command=main_MBC2_Dump_RAM)\n MBC2menu.add_command(label='Write Save RAM', command=main_MBC2_Burn_RAM)\n MBC2menu.add_command(label='Dump ROM', command=main_MBC_Dump_ROM)\n GBCammenu = Menu(menu)\n cartTypeMenu.add_cascade(label='GB Camera', menu=GBCammenu)\n GBCammenu.add_command(label='Get Save RAM', command=main_Cam_Dump_RAM)\n GBCammenu.add_command(label='Write Save RAM', command=main_Cam_Burn_RAM)\n EMS32menu = Menu(menu)\n cartTypeMenu.add_cascade(label='EMS32', menu=EMS32menu)\n EMS32menu.add_command(label='Get Save RAM')\n EMS32menu.add_command(label='Write Save RAM')\n EMS32menu.add_command(label='Dump ROM')\n EMS32menu.add_command(label='Flash ROM')\n EMS64menu = Menu(menu)\n cartTypeMenu.add_cascade(label='EMS64', menu=EMS64menu)\n EMS64menu.add_command(label='Get Save RAM', command=main_MBC_Dump_256RAM)\n EMS64menu.add_command(label='Write Save RAM', command=main_MBC_Burn_RAM)\n EMS64menu.add_command(label='Dump ROM', command=main_MBC_Dump_ROM)\n EMS64menu.add_command(label='Flash ROM', command=main_EMS64_Burn_ROM)\n EMS64menu.add_command(label='Set page 2', command=main_EMS64_PageSwap)\n BV64menu = Menu(menu)\n BV64GSR = Menu(menu)\n BV64WSR = Menu(menu)\n cartTypeMenu.add_cascade(label='BennVenn 64M', menu=BV64menu)\n BV64menu.add_cascade(label='Get Save RAM', menu=BV64GSR)\n BV64GSR.add_command(label='128K', command=main_BV64_Dump_128K0)\n BV64GSR.add_command(label='32K (1)', command=main_BV64_Dump_32K1)\n BV64GSR.add_command(label='32K (2)', command=main_BV64_Dump_32K2)\n BV64GSR.add_command(label='32K (3)', command=main_BV64_Dump_32K3)\n BV64GSR.add_command(label='32K (4)', command=main_BV64_Dump_32K4)\n BV64menu.add_cascade(label='Write Save RAM', menu=BV64WSR)\n BV64WSR.add_command(label='128K', command=main_BV_Burn_128k0)\n BV64WSR.add_command(label='32K (1)', command=main_BV_Burn_32K0)\n BV64WSR.add_command(label='32K (2)', command=main_BV_Burn_32K1)\n BV64WSR.add_command(label='32K (3)', command=main_BV_Burn_32K2)\n BV64WSR.add_command(label='32K (4)', command=main_BV_Burn_32K3)\n BV64menu.add_command(label='Dump ROM', command=main_BV64_Dump_ROM0)\n BV64menu.add_command(label='Flash ROM', command=main_BV64_Flash_ROM0)\n BV256menu = Menu(menu)\n BV256B1 = Menu(menu)\n BV256B2 = Menu(menu)\n BV256B3 = Menu(menu)\n BV256B4 = Menu(menu)\n BV1256GSR = Menu(menu)\n BV1256WSR = Menu(menu)\n BV2256GSR = Menu(menu)\n BV2256WSR = Menu(menu)\n BV3256GSR = Menu(menu)\n BV3256WSR = Menu(menu)\n BV4256GSR = Menu(menu)\n BV4256WSR = Menu(menu)\n cartTypeMenu.add_cascade(label='BennVenn 256M', menu=BV256menu)\n BV256menu.add_cascade(label='Block1', menu=BV256B1)\n BV256menu.add_cascade(label='Block2', menu=BV256B2)\n BV256menu.add_cascade(label='Block3', menu=BV256B3)\n BV256menu.add_cascade(label='Block4', menu=BV256B4)\n BV256B1.add_cascade(label='Get Save RAM', menu=BV1256GSR)\n BV1256GSR.add_command(label='128K', command=main_BV64_Dump_128K0)\n BV1256GSR.add_command(label='32K (1)', command=main_BV64_Dump_32K1)\n BV1256GSR.add_command(label='32K (2)', command=main_BV64_Dump_32K1)\n BV1256GSR.add_command(label='32K (3)', command=main_BV64_Dump_32K1)\n BV1256GSR.add_command(label='32K (4)', command=main_BV64_Dump_32K1)\n BV256B1.add_cascade(label='Write Save RAM', menu=BV1256WSR)\n BV1256WSR.add_command(label='128K', command=main_BV_Burn_128k0)\n BV1256WSR.add_command(label='32K (1)', command=main_BV_Burn_32K0)\n BV1256WSR.add_command(label='32K (2)', command=main_BV_Burn_32K1)\n BV1256WSR.add_command(label='32K (3)', command=main_BV_Burn_32K2)\n BV1256WSR.add_command(label='32K (4)', command=main_BV_Burn_32K3)\n BV256B1.add_command(label='Dump ROM', command=main_BV64_Dump_ROM0)\n BV256B1.add_command(label='Flash ROM', command=main_BV64_Flash_ROM0)\n BV256B2.add_cascade(label='Get Save RAM', menu=BV2256GSR)\n BV2256GSR.add_command(label='128K', command=main_BV64_Dump_128K1)\n BV2256GSR.add_command(label='32K (1)', command=main_BV64_Dump_32K21)\n BV2256GSR.add_command(label='32K (2)', command=main_BV64_Dump_32K21)\n BV2256GSR.add_command(label='32K (3)', command=main_BV64_Dump_32K21)\n BV2256GSR.add_command(label='32K (4)', command=main_BV64_Dump_32K21)\n BV256B2.add_cascade(label='Write Save RAM', menu=BV2256WSR)\n BV2256WSR.add_command(label='128K', command=main_BV_Burn_128k1)\n BV2256WSR.add_command(label='32K (1)', command=main_BV_Burn_32K10)\n BV2256WSR.add_command(label='32K (2)', command=main_BV_Burn_32K11)\n BV2256WSR.add_command(label='32K (3)', command=main_BV_Burn_32K12)\n BV2256WSR.add_command(label='32K (4)', command=main_BV_Burn_32K13)\n BV256B2.add_command(label='Dump ROM', command=main_BV64_Dump_ROM1)\n BV256B2.add_command(label='Flash ROM', command=main_BV64_Flash_ROM1)\n BV256B3.add_cascade(label='Get Save RAM', menu=BV3256GSR)\n BV3256GSR.add_command(label='128K', command=main_BV64_Dump_128K2)\n BV3256GSR.add_command(label='32K (1)', command=main_BV64_Dump_32K31)\n BV3256GSR.add_command(label='32K (2)', command=main_BV64_Dump_32K31)\n BV3256GSR.add_command(label='32K (3)', command=main_BV64_Dump_32K31)\n BV3256GSR.add_command(label='32K (4)', command=main_BV64_Dump_32K31)\n BV256B3.add_cascade(label='Write Save RAM', menu=BV3256WSR)\n BV3256WSR.add_command(label='128K', command=main_BV_Burn_128k2)\n BV3256WSR.add_command(label='32K (1)', command=main_BV_Burn_32K20)\n BV3256WSR.add_command(label='32K (2)', command=main_BV_Burn_32K21)\n BV3256WSR.add_command(label='32K (3)', command=main_BV_Burn_32K22)\n BV3256WSR.add_command(label='32K (4)', command=main_BV_Burn_32K23)\n BV256B3.add_command(label='Dump ROM', command=main_BV64_Dump_ROM2)\n BV256B3.add_command(label='Flash ROM', command=main_BV64_Flash_ROM2)\n BV256B4.add_cascade(label='Get Save RAM', menu=BV4256GSR)\n BV4256GSR.add_command(label='128K', command=main_BV64_Dump_128K3)\n BV4256GSR.add_command(label='32K (1)', command=main_BV64_Dump_32K41)\n BV4256GSR.add_command(label='32K (2)', command=main_BV64_Dump_32K41)\n BV4256GSR.add_command(label='32K (3)', command=main_BV64_Dump_32K41)\n BV4256GSR.add_command(label='32K (4)', command=main_BV64_Dump_32K41)\n BV256B4.add_cascade(label='Write Save RAM', menu=BV4256WSR)\n BV4256WSR.add_command(label='128K', command=main_BV_Burn_128k3)\n BV4256WSR.add_command(label='32K (1)', command=main_BV_Burn_32K30)\n BV4256WSR.add_command(label='32K (2)', command=main_BV_Burn_32K31)\n BV4256WSR.add_command(label='32K (3)', command=main_BV_Burn_32K32)\n BV4256WSR.add_command(label='32K (4)', command=main_BV_Burn_32K33)\n BV256B4.add_command(label='Dump ROM', command=main_BV64_Dump_ROM3)\n BV256B4.add_command(label='Flash ROM', command=main_BV64_Flash_ROM3)\n Bung32menu = Menu(menu)\n cartTypeMenu.add_cascade(label='Bung 32M', menu=Bung32menu, state=DISABLED)\n Bung32menu.add_command(label='Get Save RAM')\n Bung32menu.add_command(label='Write Save RAM')\n Bung32menu.add_command(label='Dump ROM')\n Bung32menu.add_command(label='Flash ROM')\n Bung64menu = Menu(menu)\n cartTypeMenu.add_cascade(label='Bung 64M', menu=Bung64menu, state=DISABLED)\n Bung64menu.add_command(label='Get Save RAM')\n Bung64menu.add_command(label='Write Save RAM')\n Bung64menu.add_command(label='Dump ROM')\n Bung64menu.add_command(label='Flash ROM')\n JPNmenu = Menu(menu)\n cartTypeMenu.add_cascade(label='DMG-MMSA-JPN', menu=JPNmenu)\n JPNmenu.add_command(label='Get Save RAM', command=main_MBC_Dump_RAM)\n JPNmenu.add_command(label='Write Save RAM', command=main_MBC_Burn_RAM)\n JPNmenu.add_command(label='Dump ROM', command=main_MBC_Dump_ROM)\n JPNmenu.add_command(label='Flash ROM', command=main_JPN_Burn_ROM)\n JPNmenu.add_command(label='Unlock Sector 0', command=main_JPN_Unlock_ROM)\n MXmenu = Menu(menu)\n cartTypeMenu.add_cascade(label='Shark MX', menu=MXmenu, state=DISABLED)\n MXmenu.add_command(label='Get Save RAM', command=main_MBC_Dump_RAM)\n MXmenu.add_command(label='Write Save RAM', command=main_MBC_Burn_RAM)\n MXmenu.add_command(label='Dump ROM', command=main_MX_Dump_ROM)\n MXmenu.add_command(label='Flash ROM', command=main_MX_Burn_ROM)\n ELmenu = Menu(menu)\n cartTypeMenu.add_cascade(label='El-Cheapo', menu=ELmenu)\n ELmenu.add_command(label='Erase', command=main_ELCheapo_Erase)\n ELmenu.add_command(label='Flash ROM', command=main_ELCheapo_Write)\n cartTypeMenu.add_separator()\n GBA_GenericMenu = Menu(menu)\n GBA_ROM_Size = Menu(menu)\n GBA_ROM_Burn = Menu(menu)\n cartTypeMenu.add_cascade(label='GBA Generic', menu=GBA_GenericMenu)\n GBA_GenericMenu.add_command(label='Read Header', command=main_GBA_ReadHeader)\n GBA_GenericMenu.add_separator()\n GBA_GenericMenu.add_command(label='Dump 4kbit EEPROM', command=main_GBA_EEPROM_4k)\n GBA_GenericMenu.add_command(label='Dump 64kbit EEPROM', command=main_GBA_EEPROM_64k)\n GBA_GenericMenu.add_command(label='Write 4kbit EEPROM', command=main_GBA_Write4kEEPROM)\n GBA_GenericMenu.add_command(label='Write 64kbit EEPROM', command=main_GBA_Write64kEEPROM)\n GBA_GenericMenu.add_separator()\n GBA_GenericMenu.add_command(label='Dump 64kbytes SRAM', command=main_GBA_Dump64kSRAM)\n GBA_GenericMenu.add_command(label='Write 64k to SRAM', command=main_GBA_Write64kSRAM)\n GBA_GenericMenu.add_separator()\n GBA_GenericMenu.add_command(label='Dump 64kbytes FLASH', command=main_GBA_Dump64kFLASH)\n GBA_GenericMenu.add_command(label='Dump 128kbytes FLASH', command=main_GBA_Dump128kFLASH)\n GBA_GenericMenu.add_command(label='Write 64k to FLASH', command=main_GBA_Write64kFLASHRAM)\n GBA_GenericMenu.add_command(label='Write 128k to FLASH', command=main_GBA_Write128kFLASHRAM)\n GBA_GenericMenu.add_separator()\n GBA_GenericMenu.add_cascade(label='Dump ROM', menu=GBA_ROM_Size)\n GBA_ROM_Size.add_command(label='8mbit', command=main_GBA_Dump_8)\n GBA_ROM_Size.add_command(label='16mbit', command=main_GBA_Dump_16)\n GBA_ROM_Size.add_command(label='32mbit', command=main_GBA_Dump_32)\n GBA_ROM_Size.add_command(label='64mbit', command=main_GBA_Dump_64)\n GBA_ROM_Size.add_command(label='128mbit', command=main_GBA_Dump_128)\n GBA_BV = Menu(menu)\n cartTypeMenu.add_cascade(label='GBA BennVenn128M', menu=GBA_BV)\n GBA_BV.add_command(label='Flash ROM', command=main_GBA_Flash_ROM)\n functionMenu = Menu(menu)\n menu.add_cascade(label='Function', menu=functionMenu)\n functionMenu.add_command(label='Read Cart Header', command=main_readCartHeader)\n functionMenu.add_separator()\n joeyMenu = Menu(menu)\n menu.add_cascade(label='Joey', menu=joeyMenu)\n joeyMenu.add_command(label='Update Firmware', command=main_updateFirmware)\n joeyMenu.add_separator()\n self.lowerRightLabel.set('Hardware Not Detected')\n self.ROMtitleLabel.set('ROM Title: Unknown')\n self.ROMsizeLabel.set('ROM Size: Unknown')\n self.RAMsizeLabel.set('RAM Size: Unknown')\n self.MAPPERtypeLabel.set('Mapper: Unknown')\n\n\ndef main_readCartHeader():\n global ROMsize\n global RAMsize\n main_BV_SetBank(0, 0)\n main_ROMBankSwitch(1)\n RAMtypes = [0, 2048, 8192, 32768, 131072, 65536]\n Header = ''\n dev.write(1, [16, 0, 0, 1, 0])\n dat = dev.read(129, 64)\n Header = dat\n msg = [16, 0, 0, 1, 64]\n dev.write(1, msg)\n dat = dev.read(129, 64)\n Header += dat\n msg = [16, 0, 0, 1, 128]\n dev.write(1, msg)\n dat = dev.read(129, 64)\n Header += dat\n ROMsize = 32768 * 2 ** Header[72]\n app.ROMtitleLabel.set('ROM Title: ' + str(Header[52:67], 'utf-8'))\n app.ROMsizeLabel.set('ROM Size: ' + str(32768 * 2 ** Header[72]))\n RAMsize = RAMtypes[Header[73]]\n app.RAMsizeLabel.set('RAM Size:' + str(RAMsize))\n\n\ndef main_Exit():\n exit()\n\n\ndef main_LoadROM():\n global ROMbuffer\n global ROMsize\n ROMfileName = askopenfilename(filetypes=(('GB ROM File', '*.GB'), ('GBC ROM File', '*.GBC'),\n ('GBA ROM File', '*.GBA'), ('All Files', '*.*')))\n if ROMfileName:\n ROMfile = open(ROMfileName, 'rb')\n ROMbuffer = ROMfile.read()\n ROMsize = len(ROMbuffer)\n ROMfile.close()\n return 1\n return 0\n\n\ndef main_SaveROM():\n ROMfileName = asksaveasfilename(defaultextension='.GB', filetypes=(('GB ROM File', '*.GB'),\n ('GBC ROM File', '*.GBC'),\n ('GBA ROM File', '*.GBA'),\n ('All Files', '*.*')))\n if ROMfileName:\n ROMfile = open(ROMfileName, 'wb')\n ROMfile.write(ROMbuffer)\n ROMfile.close()\n\n\ndef main_LoadRAM():\n global RAMbuffer\n global RAMsize\n RAMfileName = askopenfilename(filetypes=(('GB/C/A SRAM File', '*.SAV'), ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'rb')\n RAMbuffer = RAMfile.read()\n RAMsize = len(RAMbuffer)\n RAMfile.close()\n return 1\n return 0\n\n\ndef main_SaveRAM():\n print(len(RAMbuffer))\n RAMfileName = asksaveasfilename(defaultextension='.SAV', filetypes=(('GB/C/A SRAM File', '*.SAV'),\n ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'wb')\n RAMfile.write(RAMbuffer)\n RAMfile.close()\n\n\ndef main_updateFirmware():\n FWfileName = askopenfilename(filetypes=(('BennVenn Firmware File', '*.BEN'), ('All Files', '*.*')))\n if FWfileName:\n FWfile = open(FWfileName, 'rb')\n FWbuffer = FWfile.read()\n FWsize = len(FWbuffer)\n if FWsize == 33280:\n dev.write(1, [3])\n USBbuffer = dev.read(129, 64)\n app.lowerRightLabel.set('File Size Correct')\n for FWpos in range(512, 33279, 64):\n dev.write(1, FWbuffer[FWpos:FWpos + 64])\n\n else:\n app.lowerRightLabel.set('File Invalid')\n FWfile.close()\n exit()\n\n\ndef main_CheckVersion():\n dev.write(1, Command_Get_Version)\n dat = dev.read(129, 64)\n sdat = ''\n for x in range(5):\n sdat = sdat + chr(dat[x])\n\n app.lowerRightLabel.set('Firmware ' + sdat)\n\n\ndef main_MBC_Dump_ROM():\n global BankSize\n BankSize = 16384\n main_readCartHeader()\n main_dumpROM()\n\n\ndef main_MX_Dump_ROM():\n global BankSize\n BankSize = 16384\n main_readCartHeader()\n main_dumpMXROM()\n\n\ndef main_MBC_Dump_RAM():\n global BankSize\n BankSize = 16384\n main_readCartHeader()\n main_dumpRAM()\n main_SaveRAM()\n\n\ndef main_MBC_Dump_256RAM():\n global BankSize\n global RAMsize\n BankSize = 16384\n main_readCartHeader()\n RAMsize = 131072\n main_dumpRAM()\n main_SaveRAM()\n\n\ndef main_MBC2_Dump_RAM():\n global BankSize\n global RAMsize\n RAMsize = 512\n BankSize = 512\n main_dumpRAM2()\n main_SaveRAM()\n\n\ndef main_MBC_Burn_RAM():\n global BankSize\n BankSize = 16384\n main_readCartHeader()\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_MBC2_Burn_RAM():\n global BankSize\n global RAMsize\n RAMsize = 512\n BankSize = 512\n if main_LoadRAM() == 1:\n main_BurnRAM2()\n\n\ndef main_BV64_Dump_ROM(ROMBlk):\n global BankSize\n global ROMsize\n BankSize = 16384\n ROMsize = 8388608\n main_BV_SetBank(ROMBlk, 0)\n main_dumpROM()\n\n\ndef main_BV64_Flash_ROM():\n global BankSize\n global FlashBlockSize\n FlashBlockSize = 131072\n BankSize = 16384\n if main_LoadROM() == 1:\n main_BV_lockBank(1)\n main_BV_FlashROM()\n\n\ndef main_BV64_Flash_ROM0():\n main_BV_Flash_ROM(0)\n\n\ndef main_BV64_Flash_ROM1():\n main_BV_Flash_ROM(1)\n\n\ndef main_BV64_Flash_ROM2():\n main_BV_Flash_ROM(2)\n\n\ndef main_BV64_Flash_ROM3():\n main_BV_Flash_ROM(3)\n\n\ndef main_BV64_Dump_ROM0():\n main_BV64_Dump_ROM(0)\n\n\ndef main_BV64_Dump_ROM1():\n main_BV64_Dump_ROM(1)\n\n\ndef main_BV64_Dump_ROM2():\n main_BV64_Dump_ROM(2)\n\n\ndef main_BV64_Dump_ROM3():\n main_BV64_Dump_ROM(3)\n\n\ndef main_BV64_Dump_32K1():\n main_BV64_Dump_32K(0, 0)\n\n\ndef main_BV64_Dump_32K2():\n main_BV64_Dump_32K(0, 1)\n\n\ndef main_BV64_Dump_32K3():\n main_BV64_Dump_32K(0, 2)\n\n\ndef main_BV64_Dump_32K4():\n main_BV64_Dump_32K(0, 3)\n\n\ndef main_BV64_Dump_32K21():\n main_BV64_Dump_32K(1, 0)\n\n\ndef main_BV64_Dump_32K22():\n main_BV64_Dump_32K(1, 1)\n\n\ndef main_BV64_Dump_32K23():\n main_BV64_Dump_32K(1, 2)\n\n\ndef main_BV64_Dump_32K24():\n main_BV64_Dump_32K(1, 3)\n\n\ndef main_BV64_Dump_32K31():\n main_BV64_Dump_32K(2, 0)\n\n\ndef main_BV64_Dump_32K32():\n main_BV64_Dump_32K(2, 1)\n\n\ndef main_BV64_Dump_32K33():\n main_BV64_Dump_32K(2, 2)\n\n\ndef main_BV64_Dump_32K34():\n main_BV64_Dump_32K(2, 3)\n\n\ndef main_BV64_Dump_32K41():\n main_BV64_Dump_32K(3, 0)\n\n\ndef main_BV64_Dump_32K42():\n main_BV64_Dump_32K(3, 1)\n\n\ndef main_BV64_Dump_32K43():\n main_BV64_Dump_32K(3, 2)\n\n\ndef main_BV64_Dump_32K44():\n main_BV64_Dump_32K(3, 3)\n\n\ndef main_BV64_Dump_128K0():\n main_BV64_Dump_128K(0)\n\n\ndef main_BV64_Dump_128K1():\n main_BV64_Dump_128K(1)\n\n\ndef main_BV64_Dump_128K2():\n main_BV64_Dump_128K(2)\n\n\ndef main_BV64_Dump_128K3():\n main_BV64_Dump_128K(3)\n\n\ndef main_Cam_Dump_RAM():\n global BankSize\n global RAMsize\n BankSize = 16384\n RAMsize = 131072\n main_dumpRAM()\n main_SaveRAM()\n\n\ndef main_Cam_Burn_RAM():\n global RAMsize\n if main_LoadRAM() == 1:\n RAMsize = 131072\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K0():\n main_BV_SetBank(0, 0)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K1():\n main_BV_SetBank(0, 1)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K2():\n main_BV_SetBank(0, 2)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K3():\n main_BV_SetBank(0, 3)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K10():\n main_BV_SetBank(1, 0)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K11():\n main_BV_SetBank(1, 1)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K12():\n main_BV_SetBank(1, 2)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K13():\n main_BV_SetBank(1, 3)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K20():\n main_BV_SetBank(2, 0)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K21():\n main_BV_SetBank(2, 1)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K22():\n main_BV_SetBank(2, 2)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K23():\n main_BV_SetBank(2, 3)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K30():\n main_BV_SetBank(3, 0)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K31():\n main_BV_SetBank(3, 1)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K32():\n main_BV_SetBank(3, 2)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_32K33():\n main_BV_SetBank(3, 3)\n if main_LoadRAM() == 1:\n main_BurnRAM()\n\n\ndef main_BV_Burn_128k0():\n main_BV_Burn_128k(0)\n\n\ndef main_BV_Burn_128k1():\n main_BV_Burn_128k(1)\n\n\ndef main_BV_Burn_128k2():\n main_BV_Burn_128k(2)\n\n\ndef main_BV_Burn_128k3():\n main_BV_Burn_128k(3)\n\n\ndef main_BV_Burn_128k(bnum):\n global RAMbuffer\n global RAMsize\n if main_LoadRAM() == 1:\n RAMsize = 32768\n tempRAMbuffer = RAMbuffer\n RAMbuffer = tempRAMbuffer[0:32768]\n main_BV_SetBank(bnum, 0)\n main_BurnRAM()\n RAMbuffer = tempRAMbuffer[32768:65536]\n main_BV_SetBank(bnum, 1)\n main_BurnRAM()\n RAMbuffer = tempRAMbuffer[65536:98304]\n main_BV_SetBank(bnum, 2)\n main_BurnRAM()\n RAMbuffer = tempRAMbuffer[98304:131072]\n main_BV_SetBank(bnum, 3)\n main_BurnRAM()\n\n\ndef main_BV64_Dump_128K(blk):\n global BankSize\n global RAMbuffer\n global RAMsize\n TempRAMbuffer = b''\n BankSize = 16384\n RAMsize = 32768\n main_BV_SetBank(blk, 0)\n main_dumpRAM()\n TempRAMbuffer = RAMbuffer\n main_BV_SetBank(blk, 1)\n main_dumpRAM()\n TempRAMbuffer = TempRAMbuffer + RAMbuffer\n main_BV_SetBank(blk, 2)\n main_dumpRAM()\n TempRAMbuffer = TempRAMbuffer + RAMbuffer\n main_BV_SetBank(blk, 3)\n main_dumpRAM()\n RAMbuffer = TempRAMbuffer + RAMbuffer\n RAMsize = 131072\n main_SaveRAM()\n\n\ndef main_BV64_Dump_32K(blk, sublk):\n global BankSize\n global RAMsize\n BankSize = 16384\n RAMsize = 32768\n main_BV_SetBank(blk, sublk)\n main_dumpRAM()\n main_SaveRAM()\n\n\ndef main_BV_lockBank(bnum):\n bnum = bnum + 144\n print('Flash locked to ', hex(bnum))\n dev.write(1, [10, 0, 3, 112, 0, 0, 112, 1, 0, 112, 2, bnum])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_BV_SetBank(blk, sublk):\n sublk = sublk * 64\n print(hex(blk), hex(sublk))\n dev.write(1, [10, 0, 3, 112, 0, sublk, 112, 1, 224, 112, 2, blk])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_BV_Flash_ROM(block):\n FFtest = ''\n for usbfill in range(32):\n FFtest = FFtest + 'ÿ'\n\n main_LoadROM()\n FlashBlockSize = 131072\n messagebox.showinfo('Block Change Required', 'Please remove and insert Flash cart, then click OK')\n main_BV_lockBank(block)\n print('from flashrom() ', ROMsize, FlashBlockSize)\n NumOfBlks = int(ROMsize / FlashBlockSize)\n if NumOfBlks == 0:\n NumOfBlks = 1\n print('erasing ', NumOfBlks)\n print('Erasing ROM Area required for flash')\n for blknum in range(0, NumOfBlks):\n main_BV_EraseFlashBlock(blknum)\n\n print('Writing ROM Data')\n ROMpos = 0\n waitcount = 0\n for BankNumber in range(0, int(ROMsize / 16384)):\n main_ROMBankSwitch(BankNumber)\n print(BankNumber * 16384, ' of ', ROMsize)\n for ROMAddress in range(16384, 32768, 32):\n if BankNumber == 0:\n ROMAddress = ROMAddress - 16384\n AddHi = ROMAddress >> 8\n AddLo = ROMAddress & 255\n Data32Bytes = ROMbuffer[ROMpos:ROMpos + 32]\n if Data32Bytes == FFtest:\n pass\n else:\n AddHi = AddHi.to_bytes(1, 'little')\n AddLo = AddLo.to_bytes(1, 'little')\n FlashWriteCommand = b' \\x00\\x04*\\n\\xaa\\xa9\\x05UV' + AddHi + AddLo + b'&' + AddHi + AddLo + b'\\x1f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n while main_IsFlashBusy() == 1:\n waitcount += 1\n if waitcount == 10:\n print('Error: ', USBoutputPacket, BankNumber, AddHi, AddLo, ROMpos)\n continue\n\n waitcount = 0\n ROMpos += 32\n\n app.lowerLeftLabel.set(str(ROMsize) + ' Bytes Written')\n messagebox.showinfo('Block Unlock Required', 'Writing Complete. Please remove and insert Flash cart, then click OK')\n\n\ndef main_MX_Burn_ROM():\n dev.write(1, [10, 0, 7, 63, 0, 65, 85, 85, 170, 42, 170, 85, 85, 85, 128, 85, 85, 170, 42, 170, 85, 85, 85, 16])\n print('Erasing Flash')\n while main_JPN_Read(0) != 255:\n pass\n\n print('Chip erase complete')\n tmp = main_JPN_Read(336)\n main_LoadROM()\n addold = 0\n print('Writing ROM Data')\n for address in range(0, ROMsize, 32):\n AddHi = address >> 16 & 255\n AddMe = address >> 8 & 255\n AddLo = address & 255\n Data32Bytes = ROMbuffer[address:address + 32]\n AddHi = AddHi.to_bytes(1, 'little')\n AddMe = AddMe.to_bytes(1, 'little')\n AddLo = AddLo.to_bytes(1, 'little')\n FlashWriteCommand = b'#' + AddHi + AddMe + AddLo\n Data32Bytes = ROMbuffer[address:address + 32]\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n USBbuffer = dev.read(129, 64)\n print('writing', address, ROMsize)\n\n app.lowerLeftLabel.set(str(ROMsize) + ' Bytes Written')\n messagebox.showinfo('Operation Complete', 'Writing Complete.')\n\n\ndef mx1():\n dev.write(1, [10, 0, 7, 63, 0, 65, 85, 85, 170, 42, 170, 85, 85, 85, 128, 85, 85, 170, 42, 170, 85, 85, 85, 16])\n print('Erasing Flash')\n while main_JPN_Read(0) != 255:\n pass\n\n print('Chip erase complete')\n\n\ndef mx2():\n dev.write(1, [35, 0, 0, 32, 1, 2, 3, 4, 5, 6, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85])\n USBbuffer = dev.read(129, 64)\n\n\ndef mx3(address):\n AddHi = address >> 16 & 255\n AddMe = address >> 8 & 255\n AddLo = address & 255\n Data32Bytes = b'UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU'\n AddHi = AddHi.to_bytes(1, 'little')\n AddMe = AddMe.to_bytes(1, 'little')\n AddLo = AddLo.to_bytes(1, 'little')\n FlashWriteCommand = b'#' + AddHi + AddMe + AddLo\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n USBbuffer = dev.read(129, 64)\n\n\ndef main_EMS64_PageSwap():\n dev.write(1, [19])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_EMS64_Burn_ROM():\n main_EMS64_Flash_ROM()\n\n\ndef main_EMS64_Flash_ROM():\n FFtest = ''\n for usbfill in range(32):\n FFtest = FFtest + 'ÿ'\n\n main_LoadROM()\n FlashBlockSize = 131072\n NumOfBlks = int(ROMsize / FlashBlockSize)\n if NumOfBlks == 0:\n NumOfBlks = 1\n print('erasing ', NumOfBlks)\n print('Erasing ROM Area required for flash')\n for blknum in range(0, NumOfBlks):\n main_EMS64_EraseFlashBlock(blknum)\n\n print('Writing ROM Data')\n ROMpos = 0\n waitcount = 0\n for BankNumber in range(0, int(ROMsize / 16384)):\n main_ROMBankSwitch(BankNumber)\n print(BankNumber * 16384, ' of ', ROMsize)\n for ROMAddress in range(16384, 32768, 32):\n if BankNumber == 0:\n ROMAddress = ROMAddress - 16384\n AddHi = ROMAddress >> 8\n AddLo = ROMAddress & 255\n Data32Bytes = ROMbuffer[ROMpos:ROMpos + 32]\n AddHi = AddHi.to_bytes(1, 'little')\n AddLo = AddLo.to_bytes(1, 'little')\n FlashWriteCommand = b'!\\x01\\x02\\xd0' + AddHi + AddLo + b'\\xe8' + AddHi + AddLo + b'\\x1f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n while main_IsFlashBusyEMS() == 1:\n waitcount += 1\n if waitcount == 10:\n print('Error: ', USBoutputPacket, BankNumber, AddHi, AddLo, ROMpos)\n continue\n\n waitcount = 0\n ROMpos += 32\n\n app.lowerLeftLabel.set(str(ROMsize) + ' Bytes Written')\n messagebox.showinfo('Operation Complete', 'Writing Complete.')\n main_ROMBankSwitch(0)\n dev.write(1, [10, 1, 1, 0, 0, 255])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_EMS64_EraseFlashBlock(BlockNum):\n main_ROMBankSwitch(BlockNum * 8)\n print('Erasing Block ' + str(BlockNum))\n dev.write(1, [10, 1, 2, 64, 0, 32, 64, 0, 208])\n USBbuffer = dev.read(129, 64)\n waitcount = 0\n while main_IsFlashBusyEMS() == 1:\n waitcount += 1\n if waitcount == 100000:\n print('Error: ', BlockNum)\n exit()\n continue\n\n dev.write(1, [10, 1, 1, 64, 0, 255])\n USBbuffer = dev.read(129, 64)\n print('Done')\n\n\ndef main_dumpROM():\n global ROMbuffer\n ROMfileName = asksaveasfilename(defaultextension='.GB', filetypes=(('GB ROM File', '*.GB'),\n ('GBC ROM File', '*.GBC'),\n ('GBA ROM File', '*.GBA'),\n ('All Files', '*.*')))\n if ROMfileName:\n ROMfile = open(ROMfileName, 'wb')\n for bankNumber in range(0, int(ROMsize / BankSize)):\n print('Dumping ROM:', int(bankNumber * BankSize), ' of ', ROMsize)\n if bankNumber == 0:\n ROMaddress = 0\n else:\n ROMaddress = BankSize\n main_ROMBankSwitch(bankNumber)\n for packetNumber in range(0, int(BankSize / 64)):\n AddHi = ROMaddress >> 8\n AddLo = ROMaddress & 255\n dev.write(1, [16, 0, 0, AddHi, AddLo])\n ROMbuffer = dev.read(129, 64)\n ROMfile.write(ROMbuffer)\n ROMaddress += 64\n\n ROMfile.close()\n print('Done!')\n\n\ndef main_dumpMXROM():\n global ROMbuffer\n ROMfileName = asksaveasfilename(filetypes=(('GB ROM File', '*.GB'), ('GBC ROM File', '*.GBC'),\n ('GBA ROM File', '*.GBA'), ('All Files', '*.*')))\n if ROMfileName:\n ROMfile = open(ROMfileName, 'wb')\n for bankNumber in range(0, int(ROMsize / BankSize)):\n print('Dumping ROM:', int(bankNumber * BankSize), ' of ', ROMsize)\n if bankNumber == 0:\n ROMaddress = 0\n else:\n ROMaddress = BankSize\n main_MXROMBankSwitch(bankNumber)\n for packetNumber in range(0, int(BankSize / 64)):\n AddHi = ROMaddress >> 8\n AddLo = ROMaddress & 255\n dev.write(1, [16, 0, 0, AddHi, AddLo])\n ROMbuffer = dev.read(129, 64)\n ROMfile.write(ROMbuffer)\n ROMaddress += 64\n\n ROMfile.close()\n print('Done!')\n\n\ndef main_dumpRAM():\n global USBbuffer\n global RAMbuffer\n RAMbuffer = b''\n for bankNumber in range(0, int(RAMsize / 8192)):\n RAMaddress = 40960\n main_RAMBankSwitch(bankNumber)\n for packetNumber in range(0, int(128.0)):\n AddHi = RAMaddress >> 8\n AddLo = RAMaddress & 255\n dev.write(1, [17, 0, 0, AddHi, AddLo])\n USBbuffer = dev.read(129, 64)\n RAMaddress += 64\n RAMbuffer = b''.join([RAMbuffer, USBbuffer])\n\n\ndef main_dumpRAM2():\n global USBbuffer\n global RAMbuffer\n RAMbuffer = b''\n RAMaddress = 40960\n for packetNumber in range(0, int(8.0)):\n AddHi = RAMaddress >> 8\n AddLo = RAMaddress & 255\n dev.write(1, [17, 0, 0, AddHi, AddLo])\n USBbuffer = dev.read(129, 64)\n RAMaddress += 64\n RAMbuffer = b''.join([RAMbuffer, USBbuffer])\n\n print('Done')\n\n\ndef main_BurnRAM():\n global USBbuffer\n RAMaddress = 40960\n Rpos = 0\n for bankNumber in range(0, int(RAMsize / 8192)):\n RAMaddress = 40960\n main_RAMBankSwitch(bankNumber)\n for packetNumber in range(0, int(128)):\n AddHi = RAMaddress >> 8\n AddLo = RAMaddress & 255\n dev.write(1, [18, 0, 0, AddHi, AddLo])\n USBbuffer = dev.read(129, 64)\n dev.write(1, RAMbuffer[Rpos:Rpos + 64])\n USBbuffer = dev.read(129, 64)\n RAMaddress += 64\n Rpos += 64\n\n print('Done')\n\n\ndef main_BurnRAM2():\n global USBbuffer\n Rpos = 0\n RAMaddress = 40960\n for packetNumber in range(0, int(8)):\n AddHi = RAMaddress >> 8\n AddLo = RAMaddress & 255\n dev.write(1, [18, 0, 0, AddHi, AddLo])\n USBbuffer = dev.read(129, 64)\n dev.write(1, RAMbuffer[Rpos:Rpos + 64])\n USBbuffer = dev.read(129, 64)\n RAMaddress += 64\n Rpos += 64\n\n print('Done')\n\n\ndef main_IsFlashBusy():\n dev.write(1, [11, 0])\n temp = dev.read(129, 64)\n if temp[0] == 1:\n return 1\n if temp[0] == 0:\n return 0\n\n\ndef main_IsFlashBusyEMS():\n dev.write(1, [12, 0])\n temp = dev.read(129, 64)\n if temp[0] == 1:\n return 1\n if temp[0] == 0:\n return 0\n\n\ndef main_BV_EraseFlashBlock(BlockNum):\n main_ROMBankSwitch(BlockNum * 8)\n print('Erasing Block ' + str(BlockNum))\n dev.write(1, [10, 0, 6, 10, 170, 169, 5, 85, 86, 10, 170, 128, 10, 170, 169, 5, 85, 86, 64, 0, 48])\n USBbuffer = dev.read(129, 64)\n waitcount = 0\n while main_IsFlashBusy() == 1:\n waitcount += 1\n if waitcount == 100000:\n print('Error: ', BlockNum)\n exit()\n continue\n\n print('Done')\n\n\ndef main_ROMBankSwitch(bankNumber):\n bhi = bankNumber >> 8\n blo = bankNumber & 255\n if bhi > 0:\n dev.write(1, [10, 0, 1, 48, 0, bhi])\n USBbuffer = dev.read(129, 64)\n dev.write(1, [10, 0, 1, 33, 0, blo])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_MXROMBankSwitch(bankNumber):\n blo = bankNumber & 319\n dev.write(1, [10, 0, 1, 63, 0, blo])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_RAMBankSwitch(bankNumber):\n print('Bank:' + str(bankNumber))\n blo = bankNumber & 255\n dev.write(1, [10, 0, 1, 64, 0, blo])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_test():\n main_JPN_F2()\n main_JPN_F4()\n dev.write(1, [10, 0, 2, 1, 32, 1, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n dev.write(1, [10, 0, 2, 1, 32, 2, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n main_JPN_F5(160)\n main_JPN_F5(96)\n main_JPN_F5(224)\n dev.write(1, [10, 0, 2, 1, 32, 2, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n dev.write(1, [10, 0, 2, 1, 32, 2, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n for k in range(16):\n dev.write(1, [10, 0, 16, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_Unlock_ROM():\n main_JPN_F2()\n main_JPN_F4()\n main_JPN_F1(21845, 170)\n main_JPN_F1(10922, 85)\n main_JPN_F1(21845, 96)\n main_JPN_F1(21845, 170)\n main_JPN_F1(10922, 85)\n main_JPN_F1(0, 64)\n\n\ndef main_JPN_Burn_ROM():\n main_JPN_F2()\n main_JPN_F4()\n main_JPN_EraseFlash()\n main_LoadROM()\n addold = 0\n for address in range(0, ROMsize, 32):\n AddHi = address >> 16 & 255\n AddMe = address >> 8 & 255\n AddLo = address & 255\n Data32Bytes = ROMbuffer[address:address + 32]\n AddHi = AddHi.to_bytes(1, 'little')\n AddMe = AddMe.to_bytes(1, 'little')\n AddLo = AddLo.to_bytes(1, 'little')\n FlashWriteCommand = b'\"' + AddHi + AddMe + AddLo\n Data32Bytes = ROMbuffer[address:address + 32]\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n USBbuffer = dev.read(129, 64)\n trying = 0\n while main_JPN_Read(0) & 128 != 128:\n trying = trying + 1\n if trying == 100:\n print('Failed writing to sector', address)\n break\n\n if addold != address >> 13:\n print(address, 'bytes of', ROMsize)\n addold = address >> 13\n\n app.lowerLeftLabel.set(str(ROMsize) + ' Bytes Written')\n messagebox.showinfo('Operation Complete', 'Writing Complete.')\n main_JPN_F1(0, 240)\n main_JPN_F3()\n\n\ndef main_JPN_EraseFlash():\n main_JPN_F1(21845, 170)\n main_JPN_F1(10922, 85)\n main_JPN_F1(21845, 128)\n main_JPN_F1(21845, 170)\n main_JPN_F1(10922, 85)\n main_JPN_F1(21845, 16)\n while main_JPN_Read(0) != 128:\n pass\n\n\ndef main_JPN_F1(Address, Data):\n AddHi = Address >> 8\n AddLo = Address & 255\n dev.write(1, [10, 0, 5, 1, 32, 15, 1, 37, AddHi, 1, 38, AddLo, 1, 39, Data, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_F2():\n dev.write(1, [10, 0, 4, 1, 32, 9, 1, 33, 170, 1, 34, 85, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_F3():\n dev.write(1, [10, 0, 2, 1, 32, 8, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_F4():\n dev.write(1, [10, 0, 9, 1, 32, 10, 1, 37, 98, 1, 38, 4, 1, 39, 0, 1, 63, 165, 1, 32, 1, 1, 63, 165, 1, 32, 2, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_F5(inst):\n dev.write(1, [10, 0, 3, 1, 32, 16, 1, 63, 165, 1, 33, 1])\n USBbuffer = dev.read(129, 64)\n main_JPN_F1(21845, 170)\n main_JPN_F1(10922, 85)\n main_JPN_F1(21845, inst)\n\n\ndef main_JPN_F6(data):\n dev.write(1, [10, 0, 2, 1, 32, 192 & data, 1, 63, 165])\n USBbuffer = dev.read(129, 64)\n\n\ndef main_JPN_F7(inst):\n main_JPN_F1(17749, 170)\n main_JPN_F1(17066, 85)\n main_JPN_F1(17749, inst)\n\n\ndef main_JPN_Read(Address):\n AddHi = Address >> 8\n AddLo = Address & 255\n dev.write(1, [16, 0, 0, AddHi, AddLo])\n ROMbuffer = dev.read(129, 64)\n return ROMbuffer[0]\n\n\ndef JPN_Read(Address):\n AddHi = Address >> 8\n AddLo = Address & 255\n dev.write(1, [16, 0, 0, AddHi, AddLo])\n ROMbuffer = dev.read(129, 64)\n return ROMbuffer\n\n\ndef main_GBA_ReadHeader():\n dev.write(1, [48, 0, 0, 0, 64])\n USBbuffer = dev.read(129, 64)\n print(str(USBbuffer[32:44], 'utf-8'))\n app.ROMtitleLabel.set('ROM Title: ' + str(USBbuffer[32:44], 'utf-8'))\n app.MAPPERtypeLabel.set('GBA Cart: No Mapper')\n fsize = 256\n if main_GBA_GetByte(8388608) == (0, 0, 0, 0, 0, 0, 0, 0):\n fsize = 128\n if main_GBA_GetByte(4194304) == (0, 0, 0, 0, 0, 0, 0, 0):\n fsize = 64\n if main_GBA_GetByte(2097152) == (0, 0, 0, 0, 0, 0, 0, 0):\n fsize = 32\n if main_GBA_GetByte(1048576) == (0, 0, 0, 0, 0, 0, 0, 0):\n fsize = 16\n if main_GBA_GetByte(524288) == (0, 0, 0, 0, 0, 0, 0, 0):\n fsize = 8\n app.ROMsizeLabel.set('ROM Size: ' + str(fsize) + ' Mbits')\n print('Size Autodetected as', fsize, 'Mbits (not 100% accurate)')\n\n\ndef main_GBA_Dump_8():\n global ROMsize\n ROMsize = 1048576\n main_GBA_Dump()\n\n\ndef main_GBA_Dump_16():\n global ROMsize\n ROMsize = 2097152\n main_GBA_Dump()\n\n\ndef main_GBA_Dump_32():\n global ROMsize\n ROMsize = 4194304\n main_GBA_Dump()\n\n\ndef main_GBA_Dump_64():\n global ROMsize\n ROMsize = 8388608\n main_GBA_Dump()\n\n\ndef main_GBA_Dump_128():\n global ROMsize\n ROMsize = 16777216\n main_GBA_Dump()\n\n\ndef main_GBA_GetByte(Address):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [48, 0, Hi, Me, Lo])\n ROMbuffer = dev.read(129, 64)\n return (\n ROMbuffer[0], ROMbuffer[1], ROMbuffer[2], ROMbuffer[3], ROMbuffer[4], ROMbuffer[5], ROMbuffer[6], ROMbuffer[7])\n\n\ndef main_GBA_GetByte(Address):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [48, 0, Hi, Me, Lo])\n ROMbuffer = dev.read(129, 64)\n Tbuff = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n k = 0\n for t in range(1, 64, 2):\n Tbuff[k] = ROMbuffer[t] & 1\n k = k + 1\n\n return Tbuff\n\n\ndef main_GBA_EEPROM_Read(Address):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [56, 0, Hi, Me, Lo])\n ROMbuffer = dev.read(129, 64)\n return ROMbuffer[0:8]\n\n\ndef main_GBA_EEPROM_Write(Address):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [55, 0, Hi, Me, Lo, 0, 0, 0, 0, 0, 0, 0, 0])\n ROMbuffer = dev.read(129, 64)\n print('done')\n\n\ndef main_GBA_EEPROM_WriteFF(Address):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [55, 0, Hi, Me, Lo, 255, 255, 255, 255, 255, 255, 255, 255])\n ROMbuffer = dev.read(129, 64)\n print('done')\n\n\ndef main_GBA_Dump():\n ROMfileName = asksaveasfilename(defaultextension='.GBA', filetypes=(('GBA ROM File', '*.GBA'),\n ('All Files', '*.*')))\n Hi2 = 0\n if ROMfileName:\n ROMfile = open(ROMfileName, 'wb')\n Address = 0\n for Address in range(0, int(ROMsize / 2), 32):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [48, 0, Hi, Me, Lo])\n ROMbuffer = dev.read(129, 64)\n ROMfile.write(ROMbuffer)\n if Hi2 != Hi:\n print(str(Address * 2) + ' Bytes of ' + str(ROMsize))\n Hi2 = Hi\n\n ROMfile.close()\n print('Done!')\n\n\ndef main_GBA_Flash_Erase():\n for sectors in range(0, 255):\n main_GBA_Sector_Erase(sectors)\n\n\ndef main_GBA_Sector_Erase(Sector):\n Shi = Sector >> 1\n Slo = Sector << 7\n Shi = Shi & 255\n Slo = Slo & 255\n dev.write(1, [49, 6, 0, 5, 85, 0, 169, 0, 2, 170, 0, 86, 0, 5, 85, 0, 128, 0, 5, 85, 0, 169, 0, 2, 170, 0, 86, Shi, Slo, 0, 0, 48])\n ROMbuffer = dev.read(129, 64)\n dev.write(1, [51])\n IFB = dev.read(129, 64)\n while IFB[0] == 1:\n dev.write(1, [51])\n IFB = dev.read(129, 64)\n\n print((Sector + 1) * 65536, 'Bytes Erased')\n\n\ndef main_GBA_Flash_ROM():\n if main_GBA_Read_CFI() == 1:\n main_LoadROM()\n Hi2 = 0\n secta = int(ROMsize / 65536) + 1\n for sectors in range(0, secta):\n main_GBA_Sector_Erase(sectors)\n\n for ROMaddress in range(0, ROMsize, 32):\n Address = int(ROMaddress / 2)\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n Data32Bytes = ROMbuffer[ROMaddress:ROMaddress + 32]\n Hi = Hi.to_bytes(1, 'little')\n Me = Me.to_bytes(1, 'little')\n Lo = Lo.to_bytes(1, 'little')\n FlashWriteCommand = b'2' + Hi + Me + Lo + b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n response = dev.read(129, 64)\n if Hi2 != Hi:\n print(ROMaddress, ' bytes of ', ROMsize, 'Written...')\n Hi2 = Hi\n continue\n\n print(ROMsize, ' Written!')\n messagebox.showinfo('Operation Complete', 'Writing Complete.')\n main_GBA_ReadHeader()\n\n\ndef main_GBA_Read_CFI():\n dev.write(1, [49, 1, 0, 0, 85, 0, 152])\n ROMbuffer = dev.read(129, 64)\n dev.write(1, [48, 0, 0, 0, 16])\n ROMbuffer = dev.read(129, 64)\n dev.write(1, [48, 0, 0, 0, 32])\n buffer = dev.read(129, 64)\n if ROMbuffer[0] == 82 and ROMbuffer[2] == 81 and ROMbuffer[4] == 90:\n print('CFI Present')\n print(2 << int(buffer[14] - 1), 'bytes capacity')\n dev.write(1, [49, 1, 0, 0, 0, 0, 240])\n buffer = dev.read(129, 64)\n return 1\n else:\n return 0\n\n\ndef main_GBA_Testcode():\n dev.write(1, [48, 0, 0, 0, 0])\n ROMbuffer = dev.read(129, 64)\n print(ROMbuffer)\n dev.write(1, [49, 3, 0, 5, 85, 0, 169, 0, 2, 170, 0, 86, 0, 5, 85, 0, 136])\n ROMbuffer = dev.read(129, 64)\n dev.write(1, [48, 0, 0, 0, 0])\n ROMbuffer = dev.read(129, 64)\n print(ROMbuffer)\n\n\ndef main_GBA_Dump64kSRAM():\n RAMfileName = asksaveasfilename(defaultextension='.SAV', filetypes=(('GBA Save File', '*.SAV'),\n ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'wb')\n Address = 0\n for Address in range(0, 65536, 64):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [53, 0, Hi, Me, Lo])\n RAMbuffer = dev.read(129, 64)\n RAMfile.write(RAMbuffer)\n\n RAMfile.close()\n print('Done!')\n\n\ndef main_GBA_EEPROM_64k():\n RAMfileName = asksaveasfilename(defaultextension='.SAV', filetypes=(('GBA Save File', '*.SAV'),\n ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'wb')\n Address = 0\n for Address in range(0, 1024):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [56, 0, Hi, Me, Lo])\n RAMbuffer = dev.read(129, 64)\n RAMfile.write(RAMbuffer[0:8])\n\n RAMfile.close()\n print('Done!')\n\n\ndef main_GBA_EEPROM_4k():\n RAMfileName = asksaveasfilename(defaultextension='.SAV', filetypes=(('GBA Save File', '*.SAV'),\n ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'wb')\n Address = 0\n for Address in range(0, 64):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [60, 0, Hi, Me, Lo])\n RAMbuffer = dev.read(129, 64)\n RAMfile.write(RAMbuffer[0:8])\n\n RAMfile.close()\n print('Done!')\n\n\ndef main_GBA_Write64kEEPROM():\n SRAMfileName = askopenfilename(filetypes=(('GBA Save File', '*.SAV'), ('All Files', '*.*')))\n if SRAMfileName:\n SRAMfile = open(SRAMfileName, 'rb')\n SRAMbuffer = SRAMfile.read()\n SRAMsize = len(SRAMbuffer)\n for Address in range(0, 1024):\n Lo2 = Address & 255\n Me2 = (Address & 65280) >> 8\n Data8Bytes = SRAMbuffer[Address * 8:Address * 8 + 8]\n Me = Me2.to_bytes(1, 'little')\n Lo = Lo2.to_bytes(1, 'little')\n WriteCommand = b'7\\x00\\x00' + Me + Lo\n Dataout = WriteCommand + Data8Bytes\n dev.write(1, Dataout)\n RAMbuffer = dev.read(129, 64)\n for WriteDelay in range(0, 10):\n dev.write(1, [56, 0, 0, Me2, Lo2])\n\n SRAMfile.close()\n print('Done!')\n\n\ndef main_GBA_Write4kEEPROM():\n SRAMfileName = askopenfilename(filetypes=(('GBA Save File', '*.SAV'), ('All Files', '*.*')))\n if SRAMfileName:\n SRAMfile = open(SRAMfileName, 'rb')\n SRAMbuffer = SRAMfile.read()\n SRAMsize = len(SRAMbuffer)\n for Address in range(0, 64):\n Lo2 = Address & 255\n Me2 = (Address & 65280) >> 8\n Data8Bytes = SRAMbuffer[Address * 8:Address * 8 + 8]\n Me = Me2.to_bytes(1, 'little')\n Lo = Lo2.to_bytes(1, 'little')\n WriteCommand = b'=\\x00\\x00' + Me + Lo\n Dataout = WriteCommand + Data8Bytes\n dev.write(1, Dataout)\n RAMbuffer = dev.read(129, 64)\n for WriteDelay in range(0, 10):\n dev.write(1, [56, 0, 0, Me2, Lo2])\n\n SRAMfile.close()\n print('Done!')\n\n\ndef main_GBA_Dump64kFLASH():\n RAMfileName = asksaveasfilename(defaultextension='.SAV', filetypes=(('GBA Save File', '*.SAV'),\n ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'wb')\n Address = 0\n dev.write(1, [57, 0, 0, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n for Address in range(0, 65536, 64):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [53, 0, Hi, Me, Lo])\n RAMbuffer = dev.read(129, 64)\n RAMfile.write(RAMbuffer)\n\n RAMfile.close()\n print('Done!')\n\n\ndef main_GBA_Dump128kFLASH():\n RAMfileName = asksaveasfilename(defaultextension='.SAV', filetypes=(('GBA Save File', '*.SAV'),\n ('All Files', '*.*')))\n if RAMfileName:\n RAMfile = open(RAMfileName, 'wb')\n Address = 0\n dev.write(1, [57, 0, 0, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n for Address in range(0, 65536, 64):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [53, 0, Hi, Me, Lo])\n RAMbuffer = dev.read(129, 64)\n RAMfile.write(RAMbuffer)\n\n dev.write(1, [57, 0, 0, 0, 0, 1])\n RAMbuffer = dev.read(129, 64)\n for Address in range(0, 65536, 64):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Hi = (Address & 16711680) >> 16\n dev.write(1, [53, 0, Hi, Me, Lo])\n RAMbuffer = dev.read(129, 64)\n RAMfile.write(RAMbuffer)\n\n RAMfile.close()\n print('Done!')\n\n\ndef main_GBA_FlashSaveErase():\n dev.write(1, [58, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n dev.write(1, [53, 0, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n while RAMbuffer[0] != 255:\n dev.write(1, [53, 0, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n\n print('FlashSave Erased')\n\n\ndef main_GBA_Write64kSRAM():\n SRAMfileName = askopenfilename(filetypes=(('GBA Save File', '*.SAV'), ('All Files', '*.*')))\n if SRAMfileName:\n SRAMfile = open(SRAMfileName, 'rb')\n SRAMbuffer = SRAMfile.read()\n SRAMsize = len(SRAMbuffer)\n for Address in range(0, SRAMsize, 32):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Data32Bytes = SRAMbuffer[Address:Address + 32]\n Me = Me.to_bytes(1, 'little')\n Lo = Lo.to_bytes(1, 'little')\n WriteCommand = b'6\\x00\\x00' + Me + Lo\n Dataout = WriteCommand + Data32Bytes\n dev.write(1, Dataout)\n RAMbuffer = dev.read(129, 64)\n\n SRAMfile.close()\n print('Done!')\n\n\ndef main_GBA_Write128kFLASHRAM():\n SRAMfileName = askopenfilename(filetypes=(('GBA Save File', '*.SAV'), ('All Files', '*.*')))\n if SRAMfileName:\n main_GBA_FlashSaveErase()\n SRAMfile = open(SRAMfileName, 'rb')\n SRAMbuffer = SRAMfile.read()\n SRAMsize = len(SRAMbuffer)\n dev.write(1, [57, 0, 0, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n for Address in range(0, 65535, 32):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Data32Bytes = SRAMbuffer[Address:Address + 32]\n Me = Me.to_bytes(1, 'little')\n Lo = Lo.to_bytes(1, 'little')\n WriteCommand = b';\\x00\\x00' + Me + Lo\n Dataout = WriteCommand + Data32Bytes\n dev.write(1, Dataout)\n RAMbuffer = dev.read(129, 64)\n\n dev.write(1, [57, 0, 0, 0, 0, 1])\n RAMbuffer = dev.read(129, 64)\n for Address in range(65536, 131071, 32):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Data32Bytes = SRAMbuffer[Address:Address + 32]\n Me = Me.to_bytes(1, 'little')\n Lo = Lo.to_bytes(1, 'little')\n WriteCommand = b';\\x00\\x00' + Me + Lo\n Dataout = WriteCommand + Data32Bytes\n dev.write(1, Dataout)\n RAMbuffer = dev.read(129, 64)\n\n SRAMfile.close()\n print('Done!')\n\n\ndef main_GBA_Write64kFLASHRAM():\n SRAMfileName = askopenfilename(filetypes=(('GBA Save File', '*.SAV'), ('All Files', '*.*')))\n if SRAMfileName:\n main_GBA_FlashSaveErase()\n SRAMfile = open(SRAMfileName, 'rb')\n SRAMbuffer = SRAMfile.read()\n SRAMsize = len(SRAMbuffer)\n dev.write(1, [57, 0, 0, 0, 0, 0])\n RAMbuffer = dev.read(129, 64)\n for Address in range(0, SRAMsize, 32):\n Lo = Address & 255\n Me = (Address & 65280) >> 8\n Data32Bytes = SRAMbuffer[Address:Address + 32]\n Me = Me.to_bytes(1, 'little')\n Lo = Lo.to_bytes(1, 'little')\n WriteCommand = b';\\x00\\x00' + Me + Lo\n Dataout = WriteCommand + Data32Bytes\n dev.write(1, Dataout)\n RAMbuffer = dev.read(129, 64)\n\n SRAMfile.close()\n print('Done!')\n\n\ndef main_ELCheapo_Erase():\n print('Erasing...')\n dev.write(1, [10, 1, 6, 10, 170, 170, 5, 85, 85, 10, 170, 128, 10, 170, 170, 5, 85, 85, 10, 170, 16])\n RAMbuffer = dev.read(129, 64)\n while main_ELCheapo_Read(0)[0] != 255:\n pass\n\n print('Erased')\n\n\ndef main_ELCheapo_Read(Address):\n AddHi = Address >> 8\n AddLo = Address & 255\n dev.write(1, [16, 0, 0, AddHi, AddLo])\n ROMbuffer = dev.read(129, 64)\n return ROMbuffer\n\n\ndef main_ELCheapo_Write():\n main_LoadROM()\n print('Writing ROM Data')\n main_ELCheapo_Erase()\n ROMpos = 0\n waitcount = 0\n for BankNumber in range(0, int(ROMsize / 16384)):\n main_ROMBankSwitch(BankNumber)\n print(BankNumber * 16384, ' of ', ROMsize)\n for ROMAddress in range(16384, 32768, 32):\n if BankNumber == 0:\n ROMAddress = ROMAddress - 16384\n AddHi = ROMAddress >> 8\n AddLo = ROMAddress & 255\n Data32Bytes = ROMbuffer[ROMpos:ROMpos + 32]\n AddHi = AddHi.to_bytes(1, 'little')\n AddLo = AddLo.to_bytes(1, 'little')\n FlashWriteCommand = b'$\\x00' + AddHi + AddLo\n USBoutputPacket = FlashWriteCommand + Data32Bytes\n dev.write(1, USBoutputPacket)\n USBbuffer = dev.read(129, 64)\n ROMpos += 32\n\n app.lowerLeftLabel.set(str(ROMsize) + ' Bytes Written')\n messagebox.showinfo('Operation Complete', 'Writing Complete.')\n main_ROMBankSwitch(0)\n\n\nroot = Tk()\nroot.geometry('400x300')\napp = Window(root)\ndev = usb.core.find(idVendor=1133, idProduct=4660)\nif dev is None:\n messagebox.showinfo('USB Error', 'I Cant find your hardware! Check the device is plugged in and the USB driver is installed')\n exit()\nif dev is not None:\n messagebox.showinfo('Welcome', 'Gen3 is a work in progress, please report any bugs or requests to Bennvenn@hotmail.com')\n dev.set_configuration()\n main_CheckVersion()\n root.mainloop()","sub_path":"Source/JoeyJoebags315.py","file_name":"JoeyJoebags315.py","file_ext":"py","file_size_in_byte":56647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"239582321","text":"\"\"\"This file contains all the classes you must complete for this project.\nYou can use the test cases in agent_test.py to help during development, and\naugment the test suite with your own test cases to further test your code.\nYou must test your agent's strength against a set of agents with known\nrelative strength using tournament.py and include the results in your report.\n\"\"\"\nfrom functools import partial\n\nINFINITY_POSITIVE = float('+inf')\nINFINITY_NEGATIVE = float('-inf')\nNO_LEGAL_MOVES = (-1, -1)\n\n\nclass Timeout(Exception):\n \"\"\"Subclass base exception for code clarity.\"\"\"\n pass\n\n\nclass CustomScore:\n def __init__(self, game, player):\n self.player = player\n self.game = game\n\n get_legal_moves = game.get_legal_moves\n self.moves_player = get_legal_moves(player)\n self.moves_opponent = get_legal_moves(game.get_opponent(player))\n\n def _is_winner_or_loser(self):\n if self.game.is_loser(self.player):\n return INFINITY_NEGATIVE\n elif self.game.is_winner(self.player):\n return INFINITY_POSITIVE\n else:\n return None\n\n def relative_moves(self, player_alpha=0.25, opponent_alpha=0.75):\n \"\"\"\n This evaluation function takes into account the relative number of legal moves left to each player\n as well as the state of the game\n If the opponent has more moves left then we get a larger negative number\n filled_squares magnifies this ratio as the game progresses so stakes are higher\n In addition the 0.75 vs. 0.25 help with controlling how aggressive the player is\n This strategy somewhat consistently beats ID_Improved in aggregate\n \"\"\"\n\n total_squares = self.game.height * self.game.width\n filled_squares = total_squares - len(self.game.get_blank_spaces())\n\n moves_player_count = len(self.moves_player)\n moves_opponent_count = len(self.moves_opponent)\n\n # Return maximum scores if no moves left by either player\n if self.player is self.game.inactive_player and moves_opponent_count == 0:\n return INFINITY_POSITIVE\n elif self.player is self.game.active_player and moves_player_count == 0:\n return INFINITY_NEGATIVE\n\n return -1 * filled_squares * (moves_opponent_count + opponent_alpha) / (moves_player_count + player_alpha)\n\n def maximize_diff(self, player_factor=1, opponent_factor=1):\n winner_or_loser = self._is_winner_or_loser()\n if winner_or_loser is not None:\n return winner_or_loser\n\n return len(self.moves_player) * player_factor - len(self.moves_opponent) * opponent_factor\n\n def maximize_diff_progression(self):\n winner_or_loser = self._is_winner_or_loser()\n if winner_or_loser is not None:\n return winner_or_loser\n\n return (1 / len(self.game.get_blank_spaces())) * self.maximize_diff()\n\n\ndef custom_score(game, player):\n \"\"\"Calculate the heuristic value of a game state from the point of view\n of the given player.\n Note: this function should be called from within a Player instance as\n `self.score()` -- you should not need to call this function directly.\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n player : object\n A player instance in the current game (i.e., an object corresponding to\n one of the player objects `game.__player_1__` or `game.__player_2__`.)\n Returns\n -------\n float\n The heuristic value of the current game state to the specified player.\n \"\"\"\n score = CustomScore(game, player)\n return score.relative_moves()\n\n\nclass CustomPlayer:\n \"\"\"Game-playing agent that chooses a move using your evaluation function\n and a depth-limited minimax algorithm with alpha-beta pruning. You must\n finish and test this player to make sure it properly uses minimax and\n alpha-beta to return a good move before the search time limit expires.\n Parameters\n ----------\n search_depth : int (optional)\n A strictly positive integer (i.e., 1, 2, 3,...) for the number of\n layers in the game tree to explore for fixed-depth search. (i.e., a\n depth of one (1) would only explore the immediate sucessors of the\n current state.)\n score_fn : callable (optional)\n A function to use for heuristic evaluation of game states.\n iterative : boolean (optional)\n Flag indicating whether to perform fixed-depth search (False) or\n iterative deepening search (True).\n method : {'minimax', 'alphabeta'} (optional)\n The name of the search method to use in get_move().\n timeout : float (optional)\n Time remaining (in milliseconds) when search is aborted. Should be a\n positive value large enough to allow the function to return before the\n timer expires.\n \"\"\"\n\n def __init__(self, search_depth=3, score_fn=custom_score,\n iterative=True, method='minimax', timeout=10.):\n self.search_depth = search_depth\n self.iterative = iterative\n self.score = score_fn\n self.method = method\n self.time_left = None\n self.TIMER_THRESHOLD = timeout\n self.depths = []\n\n def get_move(self, game, legal_moves, time_left):\n \"\"\"Search for the best move from the available legal moves and return a\n result before the time limit expires.\n This function must perform iterative deepening if self.iterative=True,\n and it must use the search method (minimax or alphabeta) corresponding\n to the self.method value.\n **********************************************************************\n NOTE: If time_left < 0 when this function returns, the agent will\n forfeit the game due to timeout. You must return _before_ the\n timer reaches 0.\n **********************************************************************\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n legal_moves : list<(int, int)>\n A list containing legal moves. Moves are encoded as tuples of pairs\n of ints defining the next (row, col) for the agent to occupy.\n time_left : callable\n A function that returns the number of milliseconds left in the\n current turn. Returning with any less than 0 ms remaining forfeits\n the game.\n Returns\n -------\n (int, int)\n Board coordinates corresponding to a legal move; may return\n (-1, -1) if there are no available legal moves.\n \"\"\"\n\n self.time_left = time_left\n\n # Perform any required initializations, including selecting an initial\n # move from the game board (i.e., an opening book), or returning\n # immediately if there are no legal moves\n move = NO_LEGAL_MOVES\n if len(legal_moves) == 0:\n return move\n\n blank_spaces = len(game.get_blank_spaces())\n board_squares = game.width * game.height\n if blank_spaces == board_squares:\n self.depths.append(0)\n return game.height // 2, game.width // 2\n\n depth = 1\n\n search_methods = {\n 'minimax': partial(self.minimax, game=game),\n 'alphabeta': partial(self.alphabeta, game=game)\n }\n\n try:\n # The search method call (alpha beta or minimax) should happen in\n # here in order to avoid timeout. The try/except block will\n # automatically catch the exception raised by the search method\n # when the timer gets close to expiring\n if self.iterative:\n while True:\n s, move = search_methods[self.method](depth=depth)\n if s == INFINITY_POSITIVE:\n return move\n depth += 1\n else:\n depth = self.search_depth\n return search_methods[self.method](depth=depth)[1]\n except Timeout:\n # Handle any actions required at timeout, if necessary\n self.depths.append(depth)\n return move\n\n def _search_body(self, game, depth, maximizing_player, alpha=None, beta=None):\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n\n player = game.active_player if maximizing_player else game.inactive_player\n\n if depth == 0:\n return self.score(game, player), NO_LEGAL_MOVES\n\n best_score = INFINITY_NEGATIVE if maximizing_player else INFINITY_POSITIVE\n best_move = NO_LEGAL_MOVES\n\n for move in game.get_legal_moves(game.active_player):\n forecast_move = game.forecast_move(move)\n if isinstance(alpha, float) and isinstance(beta, float):\n s, _ = self.alphabeta(forecast_move, depth - 1, alpha, beta, not maximizing_player)\n else:\n s, _ = self.minimax(forecast_move, depth - 1, not maximizing_player)\n if maximizing_player:\n if s > best_score:\n best_score = s\n best_move = move\n if alpha is not None:\n alpha = max(alpha, s)\n\n if beta is not None and s >= beta:\n break\n else:\n if s < best_score:\n best_score = s\n best_move = move\n if beta is not None:\n beta = min(beta, s)\n\n if alpha is not None and s <= alpha:\n break\n\n return best_score, best_move\n\n def minimax(self, game, depth, maximizing_player=True):\n \"\"\"Implement the minimax search algorithm as described in the lectures.\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n Returns\n -------\n float\n The score for the current search branch\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n Notes\n -----\n (1) You MUST use the `self.score()` method for board evaluation\n to pass the project unit tests; you cannot call any other\n evaluation function directly.\n \"\"\"\n return self._search_body(game, depth, maximizing_player)\n\n def alphabeta(self, game, depth, alpha=float(\"-inf\"), beta=float(\"inf\"), maximizing_player=True):\n \"\"\"Implement minimax search with alpha-beta pruning as described in the\n lectures.\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n alpha : float\n Alpha limits the lower bound of search on minimizing layers\n beta : float\n Beta limits the upper bound of search on maximizing layers\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n Returns\n -------\n float\n The score for the current search branch\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n Notes\n -----\n (1) You MUST use the `self.score()` method for board evaluation\n to pass the project unit tests; you cannot call any other\n evaluation function directly.\n \"\"\"\n return self._search_body(game, depth, maximizing_player, alpha, beta)\n","sub_path":"game_agent.py","file_name":"game_agent.py","file_ext":"py","file_size_in_byte":12406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"120781215","text":"##parameters=type_name, RESPONSE\n##title=Redirect to the form for adding the given type.\n\nws_url = context.absolute_url()\n\nif not type_name:\n url = ws_url + '/workspace_view'\nelse:\n url = context.portal_organization.getAddFormURL(type_name, context)\n\nRESPONSE.redirect(url)\n\n","sub_path":"CMF_Extras/trunk/CMFWorkspaces/skins/workspaces/workspace_add_object.py","file_name":"workspace_add_object.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"543994288","text":"import re\nfrom ctypes import *\nfrom traceback import format_exc\nfrom time import sleep\n\nfrom FFxivPythonTrigger import PluginBase, api\nfrom FFxivPythonTrigger.AddressManager import AddressManager\nfrom FFxivPythonTrigger.SaintCoinach import realm\nfrom FFxivPythonTrigger.hook import Hook\nfrom FFxivPythonTrigger.memory import read_ushort, scan_pattern, read_memory, scan_address\nfrom FFxivPythonTrigger.memory.StructFactory import OffsetStruct\nfrom .simulator import Models, Manager, Craft\nfrom .solvers import SkyBuilder23\nimport win32com.client\n\nspeaker = win32com.client.Dispatch(\"SAPI.SpVoice\")\n\nrecipe_sheet = realm.game_data.get_sheet('Recipe')\ncraft_start_sig = \"40 53 48 83 EC ? 48 8B D9 C6 81 ? ? ? ? ? E8 ? ? ? ? 48 8D 4B ?\"\ncraft_status_sig = \"8B 05 ? ? ? ? BE ? ? ? ? 89 44 24 ?\"\n\nCraftStatus = OffsetStruct({\n 'round': (c_uint, 0x18),\n 'current_progress': (c_uint, 0x1c),\n 'current_quality': (c_uint, 0x24),\n 'current_durability': (c_uint, 0x30),\n 'status_id': (c_ushort, 0x38)\n})\n\nregistered_solvers = [\n SkyBuilder23.SkyBuilder23\n]\n\ncallback = lambda ans: speaker.Speak(ans)\n\n\nclass XivCraft(PluginBase):\n name = \"XivCraft\"\n\n def __init__(self):\n super(XivCraft, self).__init__()\n\n class ChatLogRegexProcessor(object):\n def __init__(_self):\n _self.data = dict()\n\n def register(_self, channel_id, regex, callback):\n if channel_id not in _self.data:\n _self.data[channel_id] = set()\n _self.data[channel_id].add((re.compile(regex), callback))\n\n def process(_self, chat_log):\n if chat_log.channel_id in _self.data:\n for regex, callback in _self.data[chat_log.channel_id]:\n result = regex.search(chat_log.message)\n if result: self.create_mission(callback, chat_log, result)\n\n class CraftStartHook(Hook):\n restype = c_int64\n argtypes = [c_int64]\n\n def hook_function(_self, a1):\n ans = _self.original(a1)\n recipe_id = read_ushort(a1 + 880)\n try:\n self._recipe = recipe_sheet[recipe_id] if recipe_id else None\n except Exception:\n self.logger.error(\"error in craft start hook:\\n\" + format_exc())\n return ans\n\n am = AddressManager(self.storage.data, self.logger)\n self.craft_start_hook = CraftStartHook(am.get('craft_start', scan_pattern, craft_start_sig))\n self.craft_status = read_memory(CraftStatus, am.get('craft_status', scan_address, craft_status_sig, cmd_len=6))\n self.storage.save()\n\n self.chat_log_processor = ChatLogRegexProcessor()\n\n self.chat_log_processor.register(2114, \"^(.+)开始练习制作\\ue0bb(.+)。$\", self.craft_start)\n self.chat_log_processor.register(2114, \"^(.+)开始制作“\\ue0bb(.+)”。$\", self.craft_start)\n\n self.chat_log_processor.register(2091, \"^(.+)发动了“(.+)”(。)$\", self.craft_next)\n self.chat_log_processor.register(2114, \"^(.+)发动“(.+)” \\ue06f (成功|失败)$\", self.craft_next)\n # self.chat_log_processor.register(56, \"^@Craft next$\", self.craft_next)\n\n self.chat_log_processor.register(2114, \"^(.+)练习制作\\ue0bb(.+)成功了!$\", self.craft_end)\n self.chat_log_processor.register(2114, \"^(.+)练习制作\\ue0bb(.+)失败了……$\", self.craft_end)\n self.chat_log_processor.register(2114, \"^(.+)停止了练习。$\", self.craft_end)\n self.chat_log_processor.register(2242, \"^(.+)制作“\\ue0bb(.+)”成功!$\", self.craft_end)\n self.chat_log_processor.register(2114, \"^(.+)制作失败了……$\", self.craft_end)\n self.chat_log_processor.register(2114, \"^(.+)中止了制作作业。$\", self.craft_end)\n\n self._recipe = None\n self.solver = None\n self.base_data = None\n self.register_event(\"log_event\", self.chat_log_processor.process)\n\n def get_base_data(self):\n recipe = Models.Recipe(self._recipe)\n me = api.XivMemory.actor_table.get_me()\n me_info = api.XivMemory.player_info\n player = Models.Player(me.level, me_info.craft, me_info.control, me.maxCP)\n return recipe, player\n\n def get_current_craft(self):\n me = api.XivMemory.actor_table.get_me()\n recipe, player = self.base_data\n effects = dict()\n for eid, effect in me.effects.get_items():\n if eid in Manager.effects_id:\n new_effect = Manager.effects_id[eid](effect.param)\n effects[new_effect.name] = new_effect\n return Craft.Craft(\n recipe=recipe,\n player=player,\n craft_round=self.craft_status.round,\n current_progress=self.craft_status.current_progress,\n current_quality=self.craft_status.current_quality,\n current_durability=self.craft_status.current_durability,\n current_cp=me.currentCP,\n status=Manager.status_id[self.craft_status.status_id](),\n effects=effects,\n )\n\n def craft_start(self, chat_log, regex_result):\n recipe, player = self.base_data = self.get_base_data()\n self.logger.info(\"start recipe:\" + recipe.detail_str)\n for solver in registered_solvers:\n if solver.suitable(recipe=recipe, player=player):\n self.solver = solver(recipe=recipe, player=player, logger=self.logger)\n break\n if self.solver is not None:\n self.logger.info(\"solver found, starting to solve...\")\n ans = self.solver.process(None, None)\n if ans is not None and callback is not None: self.create_mission(callback, ans)\n else:\n self.logger.info(\"no solver found, please add a solver for this recipe\")\n\n def craft_next(self, chat_log, regex_result):\n sleep(0.5)\n if self.solver is not None:\n skill = Manager.skills[regex_result.group(2) + ('' if regex_result.group(3) != \"失败\" else ':fail')]()\n craft = self.get_current_craft()\n if skill == \"观察\":\n craft.add_effect(\"观察\", 1)\n craft.merge_effects()\n self.logger.debug(craft)\n ans = self.solver.process(craft, skill)\n self.logger.info(\"suggested skill '%s'\" % ans)\n if ans and callback is not None: self.create_mission(callback, ans)\n\n def craft_end(self, chat_log, regex_result):\n self.solver = None\n self.logger.info(\"end craft\")\n\n def _start(self):\n self.craft_start_hook.enable()\n\n def _onunload(self):\n self.craft_start_hook.uninstall()\n","sub_path":"plugins/XivCraft/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"76384186","text":"#!/usr/bin/env python3\n\nimport json\nimport logging\nimport os\nimport sys\nfrom collections import defaultdict\n\nimport pandas as pd\nfrom ml.rl.preprocessing.normalization import (\n DEFAULT_MAX_QUANTILE_SIZE,\n DEFAULT_MAX_UNIQUE_ENUM,\n DEFAULT_NUM_SAMPLES,\n DEFAULT_QUANTILE_K2_THRESHOLD,\n get_feature_norm_metadata,\n)\nfrom ml.rl.workflow.helpers import parse_args\nfrom ml.rl.workflow.training_data_reader import JSONDataset\n\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n\nNORMALIZATION_BATCH_READ_SIZE = 50000\n\n\ndef create_norm_table(params):\n training_data_path = params[\"training_data_path\"]\n logger.info(\"Generating norm table based on {}\".format(training_data_path))\n\n norm_params = get_norm_params(params[\"norm_params\"])\n dataset = JSONDataset(\n params[\"training_data_path\"], batch_size=NORMALIZATION_BATCH_READ_SIZE\n )\n\n for col in norm_params[\"cols_to_norm\"]:\n logger.info(\"Creating normalization metadata for `{}` column\".format(col))\n norm_metadata = get_norm_metadata(dataset, norm_params, col)\n path = norm_params[\"output_dir\"] + \"{}_norm.json\".format(col)\n with open(os.path.expanduser(path), \"w\") as outfile:\n json.dump(norm_metadata, outfile)\n logger.info(\"`{}` normalization metadata written to {}\".format(col, path))\n\n\ndef get_norm_metadata(dataset, norm_params, norm_col):\n batch_idx, done = 0, False\n batch = dataset.read_batch(batch_idx, astype=\"df\")\n samples_per_feature, samples = defaultdict(int), defaultdict(list)\n\n while not done:\n if not batch or len(batch[norm_col]) == 0:\n logger.info(\"No more data in training data. Breaking.\")\n break\n\n feature_df = batch[norm_col].apply(pd.Series)\n for feature in feature_df:\n values = feature_df[feature].dropna().values\n samples_per_feature[feature] += len(values)\n samples[feature].extend(values)\n\n done = check_samples_per_feature(\n samples_per_feature, norm_params[\"num_samples\"]\n )\n logger.info(\"Samples per feature: {}\".format(samples_per_feature))\n if done:\n logger.info(\"Collected sufficient sample size for all features. Breaking.\")\n\n batch_idx += 1\n batch = dataset.read_batch(batch_idx, astype=\"df\")\n\n output = {}\n for feature, values in samples.items():\n output[feature] = get_feature_norm_metadata(feature, values, norm_params)\n return output\n\n\ndef check_samples_per_feature(samples_per_feature, num_samples):\n for _, v in samples_per_feature.items():\n if v < num_samples:\n return False\n return True\n\n\ndef get_norm_params(norm_params):\n return {\n \"num_samples\": norm_params.get(\"num_samples\", DEFAULT_NUM_SAMPLES),\n \"max_unique_enum_values\": norm_params.get(\n \"max_unique_enum_values\", DEFAULT_MAX_UNIQUE_ENUM\n ),\n \"quantile_size\": norm_params.get(\"quantile_size\", DEFAULT_MAX_QUANTILE_SIZE),\n \"quantile_k2_threshold\": norm_params.get(\n \"quantile_k2_threshold\", DEFAULT_QUANTILE_K2_THRESHOLD\n ),\n \"skip_box_cox\": norm_params.get(\"skip_box_cox\", False),\n \"skip_quantiles\": norm_params.get(\"skip_quantiles\", False),\n \"feature_overrides\": norm_params.get(\"feature_overrides\", None),\n \"cols_to_norm\": norm_params[\"cols_to_norm\"],\n \"output_dir\": norm_params[\"output_dir\"],\n }\n\n\nif __name__ == \"__main__\":\n params = parse_args(sys.argv)\n create_norm_table(params)\n","sub_path":"ml/rl/workflow/create_normalization_metadata.py","file_name":"create_normalization_metadata.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"460582700","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('allauth.urls')),\n path('', include('apps.articles.urls', namespace='articles')),\n path('froala_editor/', include('froala_editor.urls')),\n\n]\n\n","sub_path":"config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"102227836","text":"\n\nimport random\nimport subprocess\nimport sys\nimport time\n\n\nH_SCRIPT = \"hanoi.py\"\nH_OUTPUT = \"hanoi.txt\"\n\nR_OUTPUT = \"run.txt\"\n#R_OUTPUT = None\n\nALGOS = [\n \"backtrack\",\n \"hillclimb\",\n \"astar\",\n \"optrand\",\n]\n\nRODS_RANGE = (3, 9)\nDISKS_RANGE = (3, 9)\n\n\ndef log(string):\n string += \"\\n\"\n stream = open(R_OUTPUT, \"a\") if R_OUTPUT else sys.stdout\n stream.write(string)\n stream.flush()\n\n\ndef main(argv):\n\n log(time.ctime())\n log(\"\")\n\n params = [(3,3),(4,4),(5,5),(6,6)]\n\n for algo in ALGOS:\n deltas = []\n steps_list = []\n for idx in range(len(params)):\n rods, disks = params[idx]\n print(\"Running test #{} for {!r} - {} x {}\"\n .format(idx + 1, algo, rods, disks))\n start = time.time()\n pop = subprocess.Popen([\"python\", H_SCRIPT, rods, disks, algo])\n rcode = pop.wait()\n delta = time.time() - start\n deltas.append(delta if not rcode else -1)\n with open(H_OUTPUT, \"r\") as stream:\n steps = len(stream.readlines())\n if not rcode:\n steps_list.append(steps)\n good = filter(lambda delta: delta != -1, deltas)\n log(algo)\n good=list(good) #may pop\n log(\"Success rate: {}/{}\".format(len(good), len(deltas)))\n if len(good):\n log(\"Average steps: {}\".format(sum(steps_list) / len(steps_list)))\n log(\"Average time: {}\".format(sum(good) / len(good)))\n log(\"Total time: {}\".format(sum(good)))\n log(\"\")\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","sub_path":"Hanoi Tower/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"260945845","text":"import numpy as np\r\nimport sys, os\r\nimport csv\r\nimport math\r\nimport networkx as nx\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport scipy.sparse as sps\r\nimport pickle\r\nimport time\r\n\r\n\r\ndef epsilonGreedy_policy(Q, s, epsilon=.3): ##### epsilon_greedy\r\n \"\"\"\r\n Recall that off-policy learning is learning the value function for\r\n one policy, \\pi, while following another policy, \\mu. Often, \\pi is\r\n the greedy policy for the current action-value-function estimate,\r\n and \\mu is a more exploratory policy, perhaps \\epsilon-greedy.\r\n In order to use the data from \\pi we must take into account the\r\n difference between the two policies, using their relative\r\n probability of taking the actions that were taken.\r\n \"\"\"\r\n A_dict = epsilonGreedy_policy_probs(Q, s, epsilon)\r\n return np.random.choice(list(A_dict.keys()),p =list(A_dict.values())) ### the best_action has the highest probability\r\n\r\ndef epsilonGreedy_policy_probs(Q, s, epsilon=.3):\r\n ############ dict[action] = prob ########\r\n Qsa=Q.loc[(Q['node']== s[0])]##### number_actions at a given state s=(node,t_index) & (Q['t_index']== s[1]) ] ## ? what if node=s[0] has no outgoing nodes, s[0]=node, s[1]=t_index\r\n if len(Qsa) > 0 : #the following works when len(Qsa)==1\r\n #nA=Qsa['action'].nunique() ##Count distict actions\r\n A=Qsa['action'].unique().tolist() ## return an array of action with shape (nA,), convert to list\r\n A_dict = dict([(key, epsilon / len(A)) for key in A])\r\n Qsa['max_Q'] = Qsa.groupby(['node', 't_index'])['Q'].transform('max') ## works,\r\n best_action = Qsa.sort_values('max_Q', ascending=False).groupby(['node', 't_index'], as_index=False).first().at[0,'action']\r\n #print('best_action')\r\n #print(best_action)\r\n #print('A_dict', A_dict )\r\n A_dict[best_action] = epsilon /len(A) + (1.0 - epsilon)\r\n return A_dict\r\n\r\n else:\r\n Qsn = Q.loc[(Q['action'] == s[0])] # & (Q['t_index']== s[1]) ] ## ? what if node=s[0] has no outgoing nodes, s[0]=node, s[1]=t_index\r\n #nN = Qsn['node'].nunique() ##Count distict actions\r\n N = Qsn['node'].unique().tolist() ## return an array of action with shape (nA,), convert to list\r\n N_dict = dict([(key, 1 / len(N)) for key in N]) ## note that use 1 as sum p\r\n #Qsa['max_Q'] = Qsa.groupby(['node', 't_index'])['Q'].transform('max') ## works,\r\n #best_action = Qsa.sort_values('max_Q', ascending=False).groupby(['node', 't_index'], as_index=False).first().at[0, 'action']\r\n # print('best_action',best_action)\r\n #print('N_dict else', N_dict )\r\n #A_dict[best_action] = epsilon / nA + (1.0 - epsilon)\r\n return N_dict\r\n\r\n###### given s, return list of action, (Q-table, NetworkLinks, DG), keep consistent\r\ndef actionList(Q, s, epsilon=.3):\r\n #### number_actions at a given state s=(node,t_index)\r\n A_dict = epsilonGreedy_policy_probs(Q, s, epsilon)\r\n return list(A_dict.keys())\r\n # tindex_t1 = int(math.ceil(s[1] / (interval * 60)))\r\n #Qsa=Q.loc[(Q['node']== s[0])]# & (Q['t_index']== tindex_t1) ] ## ? what if node=s[0] has no outgoing nodes, s[0]=node, s[1]=t_index\r\n #nA=Qsa['action'].nunique() ##Count distict actions\r\n #A=Qsa['action'].unique().tolist() ## return an array of action with shape (nA,), convert to list\r\n #return A\r\n\r\n\r\ndef Qvalue(Q,s,a):\r\n Qsa=Q.loc[((Q[\"node\"] == s[0]) & (Q[\"t_index\"] == math.ceil(s[1] / (interval * 60)))) & (Q['action'] == a)]\r\n Q_value = Qsa['Q'].values[0] if len(Qsa) > 0 else 0\r\n return Q_value\r\n #if len(Qsa)>0:\r\n #return Qsa['Q'].values[0]\r\n #else:\r\n #return 0\r\n########################################################################################\r\n# given a trajectory/episode, extract the emperical policy, reward, state\r\n# precalculate all empericalPolicy_prob\r\n########################################################################################\r\n\r\nmatch_R = 1000# # matching radius, meter\r\npath = r'E:\\00raw trajectory-mapped trajectory' # file path\r\ndayOfMonth = 13 ### data source, from which day\r\n\r\npolicy_interval = 120 ## 30 min\r\n\r\nstudy_hori = 24 ###24 hour\r\ndata_interval = 120 ## 30 min\r\nNum_data_interval = study_hori * 60 / data_interval\r\ninterval = 120\r\nNum_interval = study_hori * 60 / interval\r\n\r\n\r\n\r\ndef load_NetworkGraph():\r\n ####read network from .txt file, including link attributes(linkTT and link length)#########\r\n # path = r'C:\\Users\\Win10S\\Documents\\taxi_apr2017'\r\n fh = open(os.path.join(path,'networkLinks.txt'), 'rb') ##?tab-delimited .txt file,networkLinks,network_intID_wholearea\r\n # G = nx.read_edgelist(fh, nodetype=int, data=(('length',float),('linkTT',float))) ###when nodetype=int, there's an extraL in the node?\r\n DG = nx.read_edgelist(fh, nodetype=int, create_using=nx.DiGraph(), data=(('FID', int), ('length', float), ('speedLim', int), ('linkTT', float))) # data=(('FID',int),('length',float),('speedLim',int),('linkTT',float))\r\n fh.close()\r\n # len(DG) # number of nodes in graph\r\n H = DG.to_undirected() ####convert DG to undirected graph#####\r\n print('done loading network')\r\n # nodes = [n for n in DG.nodes_iter()] ## return the actual from/to node loaded from the .txt file\r\n # edges = [e for e in DG.edges_iter()] #### ?? number_edges(H) ?= number_edges (DG)\r\n #nodes_zero = [i for i in nodes if (DG.out_degree(i) < 1) & (DG.in_degree(i) < 1)] ### 0 node with zero_indegree and zero_outdegree\r\n #nodeOutdegree = DG.out_degree(nodes)\r\n # nodeOutdegree={k:v for k,v in nodeOutdegree.items() if v==1}\r\n #print(nodeOutdegree) ## 4382 nodes with only 1 out_degree, 4442 with only 1 in_degree, 13531 ###13126, average out_degree= 2.2583422215450253\r\n\r\n #print(sum(nodeOutdegree.values()) / len(nodeOutdegree))\r\n #print(len(nodeOutdegree))\r\n return DG,H\r\n\r\ndef cal_profit(dist, TT):\r\n costP = 0.5 #### RMB per min\r\n f0, beta, beta1 =14, 2.5, 3.6 ###starting cost, ## taxi fare, RMB per kilometre\r\n d0, d1 = 3000, 15000 ### 3 kilometres\r\n if dist > d0:\r\n f0 = f0 + 0.001 * (dist - d0) * beta\r\n if dist > d1:\r\n f0 = f0 + 0.001*(d1-d0)*beta + 0.001*(dist-d1)*beta1\r\n return f0 - costP *(TT/60)\r\n\r\n\r\n\r\ndef simulSampleMatch(s, a, epsilon, match_prob,p_dest, cal_profit):\r\n ####### need to make sure that the next it reached can be found in the Qtable(either node or action)\r\n # and can return Qvalue, and are ??connected between s[0] and st1[0]( ?? can calcutelate rt1)\r\n ########### model-based, given a (state, action), return the simulate d next reward/state(# ?? should be in Qtable) #########\r\n ########## time_dependent linkTT between each two connected nodes (undirected/directed graph) ###################################\r\n ############ shortDIST between each two connected nodes (undirected/directed graph) ##################################\r\n ########################################################################################\r\n congestTTpara = 1.7\r\n costP = 0.5\r\n matchPara =0.8\r\n #t_index = math.ceil(s[1]/(interval * 60)) ###\r\n match_prob = match_prob.loc[(match_prob['New_NodeOBJECTID']==s[0])&(match_prob['New_To_NodeOBJECTID']==a)] ###p_ah, check the magnitude, check sum of ...\r\n #print(match_prob)\r\n #### if exist, i.e., if there exists nodes within the matching area ##\r\n # If random in epsilon, choose random action\r\n it1 = a ### ?? should be in Qtable, action node\r\n TT = congestTTpara * nx.shortest_path_length(H, source=s[0], target=a, weight='linkTT')\r\n actual_t1 = s[1] + TT\r\n tindex_t1 = math.ceil(actual_t1 / (interval * 60))\r\n #dist = nx.shortest_path_length(H, source=s[0], target=a, weight='LENT')\r\n rt1 = -costP * (TT / 60)\r\n\r\n if (len(match_prob) > 0 ):\r\n #print('1-if')\r\n # Obtain random number in range [0,1)\r\n random = matchPara * np.random.rand()\r\n if ((random < match_prob['sum_match_prob'].values[0])) : ## sourcenode of link a is state, sinknode is action\r\n #print(match_prob['sum_match_prob'].values[0])\r\n ## if get matched, with passenger from node h\r\n h = np.random.choice(list(match_prob['match_node'].unique())) ### arrival node h\r\n #p_dest = np.load(os.path.join(path, \"apr\" + str(dayOfMonth)+\"_interval\"+str(data_interval)+\"_tindex\" + str(t_index)+\"_p_nodeDest.npy\"))\r\n dest_nodeindex_list = list(np.argwhere(p_dest[h - 1, :] > 0).flat) ### select the row eith entry h, ##return the indices of all the entries in an array matching a boolean condition\r\n #dest_node_list = [x + 1 for x in dest_nodeindex_list] ##nodeID# ?? should be in the Qtalbe\r\n # dest_node_prob =\r\n if len(dest_nodeindex_list) > 0: ### if len(node_dest)==0, select any node in the network as the destination\r\n #print('len')\r\n # s = np.sum(p_dest, axis=0) ##axis=1 sum of each row\r\n it1 = np.random.choice(dest_nodeindex_list)+1 ### ?? should be in Qtable, sample a destination according to non-zero p_dest, ? sum(p) should=1, so select non-zero values and use /sum(p)\r\n TT = congestTTpara * nx.shortest_path_length(H,source=s[0],target= it1,weight= 'linkTT') ##shortTT\r\n #T = undirectG_TT[s[0]][it1]\r\n\r\n actual_t1 = s[1] + TT\r\n tindex_t1 = math.ceil(actual_t1/(interval * 60))\r\n dist = nx.shortest_path_length(H, source=s[0],target = it1,weight='LENT')\r\n rt1 = cal_profit(dist, TT) ####shortDIST, a function of shortestDistance, fare-cost\r\n return (it1, actual_t1), rt1,tindex_t1\r\n #print (st1)\r\n return (it1, actual_t1), rt1, tindex_t1\r\n\r\n\r\n# #######################################################################################\r\ndef n_step_tree_backup(initial_state,match_prob0,p_dest0, Q, max_episode=1, alpha = 0.4, gamma = 1, epsilon = 0.3, num_steps = 10,interval=120, plan_hoir=5):\r\n ## if given different parameter value when define and call function, use the papameter when call function\r\n # max_episode, for each initial state\r\n # Initialization\r\n #Q = Qtable\r\n #Q['Q'] = 0 ### Initialization\r\n Q['Q_pre']=Q['Q']\r\n n_episode = 1\r\n #rewards_per_episode = []\r\n #endt_per_episode = []\r\n #Q_variances = [] ###?\r\n # max_reward = 0\r\n #total_reward = 0\r\n\r\n while n_episode <= max_episode:\r\n # If there's no starting state, just start at state 0\r\n #try:\r\n #s = initial_state # ??Initialize s, starting state, (node,t_index/actual_t)\r\n # except AttributeError:\r\n #s = 0\r\n # initializations\r\n T = float(\"inf\") ##sys.maxint\r\n #tau = 0\r\n actual_t = initial_state[1] ##\r\n #t_index = int(math.ceil(actual_t/(interval * 60)))\r\n #actual_t = (s[1]-1) * interval * 60 ### s=(node,t_index), the actual time, t_index = math.ceil(actual_t/(interval * 60))\r\n terminal_t_index= (plan_hoir*60+start_sec/60)/interval# be careful with the unit\r\n\r\n stored_tindex = {}\r\n stored_actions = {} #### dictionary, dict[step]=\r\n #stored_deltas = {}\r\n stored_states = {}\r\n stored_reward ={}\r\n #stored_Qs = {}\r\n #stored_prob = {}\r\n\r\n step = 0\r\n #?? With prob epsilon, pick a random action, store action a0\r\n stored_states[step] = initial_state\r\n #stored_actions[step] = epsilonGreedy_policy(Q, stored_states[step], epsilon)\r\n stored_reward[step] = 0\r\n #print('stored_actions[step]', stored_actions)\r\n #stored_reward = Q\r\n #stored_Qs[0] = Q[s][stored_actions[0]]\r\n #stored_prob[0] = behaviour_policy_probs(Q, s, mdp.A)[stored_actions[0]]\r\n #for i in range(1, num_steps):\r\n #stored_bp[i] = 0.\r\n\r\n stored_tindex[step] = math.ceil(initial_state[1] / (interval * 60))\r\n #stored_tindex[step+1] = math.ceil(initial_state[1] / (interval * 60)) ##\r\n #tindex_t1= stored_tindex[step]\r\n match_prob = match_prob0 #MATCH_PROB.loc[(MATCH_PROB['data_interval_index'] == stored_tindex[step])] ###p_ah, check the magnitude, check sum of ...\r\n p_dest = p_dest0 #np.load(os.path.join(path, \"apr\" + str(dayOfMonth) + \"_interval\" + str(data_interval) + \"_tindex\" + str(stored_tindex[step]) + \"_p_nodeDest.npy\"))\r\n reward_for_episode = 0\r\n #step_df=pd.DataFrame(columns=['step','node','actualt','sum_reward'])\r\n at1 = epsilonGreedy_policy(Q, stored_states[step], epsilon)\r\n\r\n while True:\r\n #try:\r\n if stored_tindex[step] <= terminal_t_index: ### ? is in terminal_state\r\n print('n_episode:',n_episode,'initial_state',initial_state,'new step:',step) ##, math.ceil(stored_states[step][1]/(interval * 60)), terminal_t_index)\r\n # Take action A_t: ??? arbitrarily or best_action\r\n # try: ###skip this loop when reaches nodes without outgoing nodes\r\n # except KeyError:\r\n # pass\r\n stored_actions[step] = at1##epsilonGreedy_policy(Q, stored_states[step], epsilon)\r\n #print(\"s,a\", stored_states[step],stored_actions[step], step)\r\n #a = stored_actions[step]\r\n # ??? Observe and store the next reward R_{t+1} and next state S_{t+1}\r\n st1, rt1, tindex_t1 = simulSampleMatch(stored_states[step],stored_actions[step], epsilon,match_prob,p_dest, cal_profit) ##??# given s, return next possible state(nodeID, t_index)/reward\r\n # rt1 = mdp.R[st1] ##?#\r\n #actual_t = st1[1] ##\r\n # t_index = math.ceil(actual_t / (interval * 60))\r\n #tindex_t1 = int(math.ceil(st1[1] / (interval * 60)))\r\n #print('st1, rt1', st1, rt1, actual_t, tindex_t1)\r\n\r\n stored_states[step + 1] = st1 ### should be a tuple (nodeID, t_index)\r\n stored_reward[step + 1] = rt1 ### should be nodeID\r\n stored_tindex[step + 1] = tindex_t1\r\n reward_for_episode += rt1\r\n\r\n #print(initial_state[0],step,stored_states[step][0],stored_states[step][1], stored_reward[step])\r\n #step_df.loc[len(step_df)] = [step,stored_states[step][0],stored_states[step][1], reward_for_episode]\r\n\r\n # if st1 is terminal\r\n if tindex_t1 >= terminal_t_index: ##? if newState in END_STATES:\r\n T = step + 1 ###? t_index, actual_t, step, ?\r\n # stored_deltas[t%n] = r - stored_Qs[t%(n+1)]\r\n else:\r\n # Select arbitrarily and store and action as A_t+1\r\n #print('new step action', step + 1,stored_states[step+1])\r\n #print(epsilonGreedy_policy(Q, stored_states[step+1], epsilon))\r\n at1 = epsilonGreedy_policy(Q, stored_states[step+1], epsilon)\r\n stored_actions[step+1] = at1\r\n # tau = t - n + 1\r\n update_step = step - num_steps + 1\r\n #print(step,'update_step',update_step, T)\r\n\r\n if update_step >= 0:\r\n if step + 1 >= T: ##t_index < terminal_t_index:\r\n G = 0 ### ?? reward of the terminal state, should be zero?\r\n else:\r\n ## Q[st1][a]: = Q.loc[((Q[\"node\"] == st1[0]) & (Q[\"t_index\"] == st1[1])) & (Q['action'] == a), \"Q\"].values[0]\r\n ### range(mdp.A) : actionList()\r\n # expectedQ = sum([epsilonGreedy_policy_probs(Q, st1, mdp.A)[a] * Q[st1][a] for a in range(mdp.A)])\r\n #print('actionList', st1, actionList(Q, st1, epsilon))\r\n #print('st1', st1, int(math.ceil(st1[1] / (interval * 60))))\r\n # print(epsilonGreedy_policy_probs(Q, st1, epsilon ))\r\n #try: ###skip this loop when reaches nodes without outgoing nodes\r\n # print(Q.loc[((Q[\"node\"] == st1[0]) & (Q[\"t_index\"] == int(math.ceil(st1[1] / (interval * 60))))) & (Q['action'] == actionList(Q, st1, epsilon)[0]), \"Q\"].values)\r\n #expectedQ = sum([epsilonGreedy_policy_probs(Q, st1, epsilon)[a] * Q.loc[((Q[\"node\"] == st1[0]) & (Q[\"t_index\"] == int(math.ceil(st1[1] / (interval * 60))))) & ( Q['action'] == a), \"Q\"].values[0] for a in actionList(Q, st1, epsilon)])\r\n expectedQ = sum([epsilonGreedy_policy_probs(Q, st1, epsilon)[a] * Qvalue(Q, st1, a) for a in actionList(Q, st1, epsilon)])\r\n\r\n G = stored_reward[step+1] + gamma * expectedQ ##rt1\r\n #except KeyError:\r\n #print('calculate G',G)\r\n # pass\r\n #print('k range', range(update_step, min(update_step + num_steps, T - 1) ),list(reversed(range(update_step, min(update_step + num_steps, T - 1) ))))\r\n for k in list(reversed(range(update_step+1, min(update_step + num_steps, T - 1)+1))): # decreaseing/loop down ###list(reversed(range(10))), or range(8, 0, -1)\r\n ##(update_step+1, min(update_step + num_steps, T - 1)+1)), actually generate[upstate-step+1,..., min()]\r\n # expectedQ = sum([epsilonGreedy_policy_probs(Q, st1, mdp.A)[a] * Q[st1][a] for a in range(mdp.A)])\r\n #print('k loop', k)\r\n ks = stored_states[k]\r\n ka = stored_actions[k]\r\n #print('k loop', k, ks)\r\n #expectedQ = sum([epsilonGreedy_policy_probs(Q, ks, epsilon)[a] * Q.loc[((Q[\"node\"] == ks[0]) & (Q[\"t_index\"] == int(math.ceil(ks[1] / (interval * 60))))) & ( Q['action'] == a), \"Q\"].values[0] for a in actionList(Q, ks, epsilon)])\r\n expectedQ = sum([epsilonGreedy_policy_probs(Q, ks, epsilon)[a] * Qvalue(Q, ks, a) for a in actionList(Q, ks, epsilon)])\r\n #G = stored_reward[k] + gamma * expectedQ - gamma * Q.loc[((Q[\"node\"] == ks[0]) & (Q[\"t_index\"] == int(math.ceil(ks[1] / (interval * 60))))) & ( Q['action'] == ka), \"Q\"].values[0] + gamma * G * epsilonGreedy_policy_probs(Q, stored_states[k], epsilon)[stored_actions[k]] ###??\r\n G = stored_reward[k] + gamma * expectedQ - gamma * Qvalue(Q, ks,ka) + gamma * G * epsilonGreedy_policy_probs(Q, stored_states[k], epsilon)[stored_actions[k]] ###??\r\n\r\n #print('update Q')\r\n Q['Q'] = np.where((Q.node == stored_states[update_step][0]) & ( Q.t_index == math.ceil(stored_states[update_step][1] / (interval * 60))) & (Q.action == stored_actions[update_step]), alpha * G + (1 - alpha) * Q['Q'], Q['Q'])\r\n # if pi is being learned, ensure that pi(.|S_tau) is \\epsilon-greedy wrt Q\r\n\r\n #t_index = math.ceil(stored_states[step][1] / (interval * 60))\r\n #print('st1',st1,t_index, terminal_t_index - 1 )\r\n if tindex_t1 > terminal_t_index : ### t_index , update_step, update_actual_t\r\n break\r\n else:\r\n step += 1\r\n if stored_tindex[step] > stored_tindex[step - 1]:\r\n match_prob = MATCH_PROB.loc[(MATCH_PROB['data_interval_index'] == stored_tindex[step])] ###p_ah, check the magnitude, check sum of ...\r\n p_dest = np.load(os.path.join(path, \"apr\" + str(dayOfMonth) + \"_interval\" + str(data_interval) + \"_tindex\" + str(stored_tindex[step]) + \"_p_nodeDest.npy\"))\r\n\r\n\r\n\r\n # Q_variances.append(np.var(Q))\r\n\r\n # TODO: should we instead do an on-policy run here to calculate the\r\n # average reward for the episode?\r\n #rewards_per_episode.append(reward_for_episode)\r\n #endt_per_episode.append(stored_states[step][1])\r\n #step_df.to_csv(\"n_step_\"+str(initial_state[0])+\"stored_step_part1.csv\")\r\n n_episode += 1\r\n # print \"Episode: %d\" % n_episode\r\n # except KeyError:\r\n # print('keyError')\r\n # break\r\n\r\n return Q, max_episode,reward_for_episode,stored_states[step][1]\r\n\r\n#path = r'C:\\Users\\Win10S\\Documents\\taxi_apr2017'\r\n#path = r'E:\\00raw trajectory-mapped trajectory' # file path\r\n\r\n#Qtable = pd.read_csv(os.path.join(path,\"Qtable_df_\"+str(policy_interval)+\"min.csv\")) ##['node', 'action', 't_index']\r\n#print(Qtable.columns)\r\n\r\nDiG,H = load_NetworkGraph() ## ? check netowrk connectivity\r\n#DG = H\r\n#match_prob = pd.read_csv(\"match_prob.csv\")\r\nMATCH_PROB=pd.read_pickle(os.path.join(path,\"match_prob_2000_interval\"+str(interval)+\"min.pkl\"))\r\nprint(MATCH_PROB.dtypes)\r\n#print(match_prob)\r\nMATCH_PROB=MATCH_PROB.dropna(how='any')\r\nMATCH_PROB['data_interval_index'] =MATCH_PROB.data_interval_index.astype(int) ####this step is important\r\nprint(MATCH_PROB.dtypes)\r\n\r\n#undirectG_TT = np.load(\"undirectG_TT.npy\").item()\r\n#print('undirectG_TT')\r\n#print(df_length.columns) ##['fnode', 'tnode', 'length']\r\n\r\n\r\nstart_sec =5 *3600+1\r\n#outdeg = DiG.out_degree()\r\n#nodes=[n for n in DiG.nodes_iter()]\r\n#initial_state_list=[(n,start_sec) for n in nodes if ((DiG.out_degree(n)) > 0 & (DiG.in_degree(n) >0))] # 1sec as starting time# return the actual from/to node loaded from the .txt file, exclude node with no outgoing links\r\n#print(initial_state_list)\r\n\"\"\"\r\napr_day_trip=pd.read_parquet(os.path.join(path, \"del_triprec_apr\" + str(dayOfMonth) + \".parquet\"),engine='pyarrow') ### write the dataframe to parquet file\r\napr_day_trip=apr_day_trip.dropna(how='any')\r\napr_day_trip['pick_node'] = apr_day_trip.pick_node.astype(int)\r\napr_day_trip['drop_node'] = apr_day_trip.drop_node.astype(int)\r\napr_day_trip['FNODE_ID'] = apr_day_trip.FNODE_ID.astype(int)\r\napr_day_trip['TNODE_ID'] = apr_day_trip.TNODE_ID.astype(int)\r\n#my_list = apr_day_trip[\"FNODE_ID\"].values.tolist()\r\n#uniqueVals = apr_day_trip[\"FNODE_ID\"].unique().tolist()\r\n#initial_node_list = apr_day_trip[\"FNODE_ID\"].unique().tolist()\r\n#initial_node_list=[int(i) for i in initial_node_list_float]\r\n#initial_state_list=[(n,start_sec) for n in initial_node_list if(n >= 5000 & n <10000)]\r\n\r\ninitial_node_list = apr_day_trip[\"FNODE_ID\"].unique().tolist()\r\n#initial_node_list=[int(i) for i in initial_node_list_float]\r\n\"\"\"\r\ninitial_node_list=np.load(os.path.join(path,\"apr\"+str(dayOfMonth)+\"startnodeList.npy\")).tolist() ###subnetwork\r\n#initial_node_list=sorted(initial_node_list)\r\ninitial_state_list=[(n,start_sec) for n in initial_node_list if ( (n >1000) and (n <5000))]\r\n\r\n\r\nQtable = pd.read_csv(os.path.join(path,\"currQ_match_part2.csv\")) ##['node', 'action', 't_index']\r\n###print(Qtable.columns)\r\nQtable=Qtable.drop(columns=['Q'])\r\nQtable.columns =['node','t_index','action','Q']\r\n#Qtable['Q'] = np.random.rand(len(Qtable)) ## sampe from uniform[0,1]\r\n\r\n\r\ni=1\r\n#f = open('workfile.txt', 'w')\r\nresults_df= pd.DataFrame(columns=['ite','initial_i','rewards_per_episode','endt_per_episode','max_diffQ'])\r\n\r\nrewards={}\r\nactual_endt={}\r\nnum_step =1\r\nmatch_prob0 = MATCH_PROB.loc[(MATCH_PROB['data_interval_index'] == math.ceil(start_sec / (interval * 60)))] ###p_ah, check the magnitude, check sum of ...\r\np_dest0 = np.load(os.path.join(path, \"apr\" + str(dayOfMonth) + \"_interval\" + str(data_interval) + \"_tindex\" + str(math.ceil(start_sec / (interval * 60))) + \"_p_nodeDest.npy\"))\r\nt1=time.time()\r\nfor initial_state in initial_state_list:\r\n Q = Qtable\r\n #Q.to_csv(\"Q_pre_match_part1.csv\",index=False)\r\n currQ, max_episode, rewards_per_episode,endt_per_episode = n_step_tree_backup(initial_state,match_prob0,p_dest0, Q, max_episode=1, alpha = 0.4,\r\n gamma = 1, epsilon = 0.3, num_steps = num_step,interval=120, plan_hoir=5)\r\n currQ.to_csv(str(num_step)+\"_step_currQ_match_part1.csv\", index=False)\r\n #rewards[initial_state[0]] = rewards_per_episode\r\n #actual_endt[initial_state[0]]= endt_per_episode\r\n #np.save('n_step_rewards_match_part1.npy', rewards)\r\n #np.save('n_step_actual_endt_part1.npy', actual_endt)\r\n\r\n #Q_pre.rename(columns={'Q':'Q_pre'})\r\n #Q = pd.merge(currQ, Q_pre, how='left', on=['node', 't_index', 'action'])\r\n max_diffQ = (currQ['Q']-currQ['Q_pre']).abs().max()\r\n #df = pd.DataFrame([[i, max_diffQ]],columns=['initial_i','max_diffQ'])\r\n #results_df=results_df.append(df, ignore_index=True)\r\n t2=time.time()\r\n print(t2-t1)\r\n quit()\r\n results_df.loc[len(results_df)] = [i, initial_state[0],rewards_per_episode, endt_per_episode, max_diffQ]\r\n results_df.to_csv(str(num_step)+'_step_results_df_match_part1.csv')\r\n #Qtable = Q[['node','t_index','action','Q']]\r\n Qtable = currQ[['node','t_index','action','Q']]\r\n ## write to .txt file during the loop\r\n ### # Check difF Q ?\r\n #f.write('initial state\\n')\r\n #f.write(max_diffQ)\r\n #f.write(\"\\n\")\r\n i+=1\r\n #f.write(rewards_per_episode)\r\n #print(initial_state)\r\n#f.close()\r\n\r\n\r\nquit()\r\n\r\npath = r'E:\\00raw trajectory-mapped trajectory' # file path\r\n\r\nQtable = pd.read_csv(os.path.join(path,'Qtable_df.csv'))\r\nQtable['Q'] =0\r\ncurrQ = Qtable\r\n#currQ['Q'] = 0\r\nprint(currQ)\r\n\r\nquit()\r\n\r\nQ = Qtable\r\nQ['preQ'] = 0.2\r\n#Q_pre = Q_pre.rename(columns={'Q': 'Q_pre'})\r\n\r\nprint(currQ)\r\nprint(Q)\r\n#Q = pd.merge(currQ, Q_pre, how='left', on=['node','t_index','action'])\r\n\r\n\r\nresults_df= pd.DataFrame(columns=['initial_i','max_diffQ'])\r\n#max_diffQ=(Q['Q']-Q['preQ']).abs().max()\r\ndf=pd.DataFrame([[0, 4]],columns=['initial_i','max_diffQ'])\r\nresults_df=results_df.append(df, ignore_index=True)\r\nresults_df.to_csv('results_df.csv')\r\n#Qtable = Q[['node','t_index','action','Q']]\r\nprint(results_df )\r\n\r\nquit()\r\n\r\ndata=pd.read_csv(\"currQ.csv\")\r\ndata['dfff']=(data['Q']-data['Q_pre']).abs()\r\nprint(data)\r\nprint(data['dfff'].max())\r\nprint(data.loc[data['dfff']>0])\r\nquit()\r\n","sub_path":"n-step-treeBackup-ModelBased-MatchProb-improve.py","file_name":"n-step-treeBackup-ModelBased-MatchProb-improve.py","file_ext":"py","file_size_in_byte":26056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"618648552","text":"import sys\n\ndef penult(filename):\n file = open(filename)\n for line in file:\n list=[]\n for word in line.split():\n list.append(word) \n print(list[-2])\n file.close()\n\npenult(sys.argv[1])\n","sub_path":"Python/complete/penultimateword.py3","file_name":"penultimateword.py3","file_ext":"py3","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"514149247","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 3 15:02:09 2020\n\n@author: wyue\n\"\"\"\n\nclass Solution(object):\n ### Method 1 (My fist approach): Recursion, slower\n \"\"\"\n def validPalindrome(self, s):\n\n DELE = False\n return self.helper(s, 0, len(s)-1, DELE)\n\n def helper(self, s, left, right, DELE):\n if left>=right:\n return True\n else :\n leftChar = s[left]\n rightChar = s[right]\n if leftChar != rightChar:\n if DELE==True:\n return False\n else:\n DELE = True\n return self.helper(s, left+1, right, DELE) or self.helper(s, left, right-1, DELE) \n else:\n return self.helper(s, left+1, right-1, DELE)\n \"\"\"\n #### Method 2 (answer online): Iteration, faster\n def validPalindrome(self, s):\n left = 0\n right = len(s)-1\n while left<=right:\n if s[left] != s[right]:\n return self.isValid(left+1, right, s) or self.isValid(left, right-1, s)\n else:\n left += 1\n right -= 1\n return True\n \n \n def isValid(self, left, right, s):\n while left<=right:\n if s[left] != s[right]:\n return False\n else:\n left += 1\n right -= 1\n \n return True","sub_path":"Algorithms/680. Valid Palindrome II.py","file_name":"680. Valid Palindrome II.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"515920543","text":"import unittest\nfrom unittest.mock import mock_open, patch\nfrom divisors_funcs import no_dupes\n\nclass TestNoDupes(unittest.TestCase):\n \"\"\"Tests the function no_dupes\"\"\"\n def setUp(self):\n \"\"\"Create a list of duplicates and list without.\"\"\"\n self.listdupes = [1, 1, 3, 3, 5, 6, 7, 7]\n self.listnodupes = [1, 3, 5, 6, 7]\n\n def test_dupes(self):\n \"\"\"Test if the function correctly removes duplicates from list.\"\"\"\n test_list = no_dupes(self.listdupes)\n self.assertEqual(test_list, self.listnodupes)\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"test_no_dupes.py","file_name":"test_no_dupes.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"327833916","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom grid_world import standard_grid, negative_grid\nfrom iterative_policy_evaluation import print_values, print_policy\n\nfrom monte_carlo_random import random_action, play_game, SMALL_ENOUGH, GAMMA\n\nLEARNING_RATE = 0.001\n\nif __name__ == '__main__':\n grid = standard_grid()\n\n print(\"rewards:\")\n print_values(grid.rewards, grid)\n\n # init policy\n policy = {\n (2,0): 'U',\n (1,0): 'U',\n (0,0): 'R',\n (0,1): 'R',\n (0,2): 'R',\n (1,2): 'U',\n (2,1): 'L',\n (2,2): 'U',\n (2,3): 'L'\n }\n\n # init gradient descent. Randomize it to learn faster\n the = np.random.rand(4) / 2\n\n #for report\n deltas = []\n t = 1.0\n\n def state_to_features(s):\n x = s[0]; y = s[1]\n return np.array([x - 1, y - 1.5, x * y - 3, 1])\n\n # start training\n for time in range(20000):\n if time % 100 == 0:\n t += 1e-2\n alpha = LEARNING_RATE / t\n biggest_change = 0\n seen_states = set()\n # play game\n states_and_returns = play_game(grid, policy)\n\n # play game\n for s, G in states_and_returns:\n if s not in seen_states:\n old_the = the.copy()\n features = state_to_features(s)\n V_hat = the.dot(features)\n #gradient descent\n the = the + alpha*(G - V_hat) * features\n biggest_change = max(biggest_change, np.abs(old_the - the).sum())\n seen_states.add(s)\n deltas.append(biggest_change)\n\n # show result values\n plt.plot(deltas)\n plt.show()\n\n V = {}\n states = grid.all_states()\n for s in states:\n if s in grid.actions:\n V[s] = the.dot(state_to_features(s))\n else:\n V[s] = 0\n\n print(\"values:\")\n print_values(V, grid)\n print(\"policy\")\n print_policy(policy,grid)","sub_path":"olena_reinforsment_learning/approx_mc_prediction.py","file_name":"approx_mc_prediction.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"454894861","text":"import argparse\n\n#############################################################################\n# Purpose: find shortest cycle back to (-) node of each (+) node. Start point is (+) node for each (a) strand\n# Input: all nodes parsed and renamed from fastg, edges, and weights\n# Output: table of all shortest cycles, a separate adjacency matrix for each, and a weight list for r graphs\n#############################################################################\n\nparser = argparse.ArgumentParser(description='rename reads to have FW and RV')\nparser.add_argument('ifn_edges', metavar='', type=str, help='input fastq files')\n\n\nargs = parser.parse_args()\n\nmin_length = 10000000000\nlinec = 0\nwith open(args.ifn_edges) as edges:\n for line in edges:\n if line[0] == \">\":\n linec += 1\n if linec % 100000 == 0:\n print(linec)\n line = line.split()\n length_str = line[3]\n length = length_str[4:]\n if int(length) < min_length:\n min_length = int(length)\nprint(\"MIN LENGTH:\",min_length)\n ","sub_path":"md/Python/min_length.py","file_name":"min_length.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"552711722","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n ARKspatial\n A QGIS plugin for Archaeological Recording.\n Part of the Archaeological Recording Kit by L - P : Archaeology\n http://ark.lparchaeology.com\n -------------------\n copyright : 2017 by L - P : Heritage LLP\n email : ark@lparchaeology.com\n copyright : 2017 by John Layt\n email : john@layt.net\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nfrom PyQt4.QtCore import pyqtSignal\nfrom PyQt4.QtGui import QComboBox\n\nfrom qgis.core import QgsProject\n\nfrom .snapping_ import Snapping\n\n\nclass SnappingModeCombo(QComboBox):\n\n snappingModeChanged = pyqtSignal(int)\n\n def __init__(self, parent=None):\n\n super(SnappingModeCombo, self).__init__(parent)\n\n self._snapMode = ''\n self._snapType = ''\n\n self.addItem('Off', Snapping.Off)\n self.addItem('Current Layer', Snapping.CurrentLayer)\n self.addItem('All Layers', Snapping.AllLayers)\n self.addItem('Selected Layers', Snapping.SelectedLayers)\n self.setCurrentIndex(0)\n\n self._refresh()\n self.currentIndexChanged.connect(self._changed)\n\n # Make sure we catch changes in the main snapping dialog\n QgsProject.instance().snapSettingsChanged.connect(self._refresh)\n # If a new project is read, update to that project's setting\n QgsProject.instance().readProject.connect(self._refresh)\n self.snappingModeChanged.connect(QgsProject.instance().snapSettingsChanged)\n\n def currentMode(self):\n return self.itemData(self.currentIndex())\n\n # Private API\n\n def _changed(self, idx):\n mode = self.currentMode()\n if mode == Snapping.Off:\n Snapping.setProjectSnappingType(Snapping.Off)\n Snapping.setSnappingMode(Snapping.CurrentLayer)\n else:\n if self._snapMode == Snapping.Off and mode != Snapping.Off:\n Snapping.setProjectSnappingType(self._snapType)\n Snapping.setSnappingMode(mode)\n self._snapMode = mode\n self.snappingModeChanged.emit(mode)\n\n def _refresh(self):\n mode = Snapping.snappingMode()\n if self._snapMode == Snapping.Off and mode == Snapping.CurrentLayer:\n return\n self._snapType = Snapping.projectSnappingType()\n self._snapMode = mode\n idx = self.findData(self._snapMode)\n self.setCurrentIndex(idx)\n","sub_path":"ark/lib/snapping/snapping_mode_combo.py","file_name":"snapping_mode_combo.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"299674985","text":"import os, sys\nsys.path.insert(0, os.path.join(os.getenv('CITY_PATH'), 'src'))\nimport random\nimport logging\nimport sqlite3\nimport unittest\nfrom helperTesting import TestMicroDbBase\nfrom learning.helperImg import ProcessorRandom\nfrom learning.helperDb import createDb, createTablePolygons\nfrom learning.helperKeys import KeyReaderSequence\nfrom learning.dbModify import *\n\n\nclass TestEmptyDb (unittest.TestCase):\n ''' Test that functions don't break on empty databases '''\n\n def setUp (self):\n self.conn = sqlite3.connect(':memory:') # in RAM\n createDb (self.conn)\n\n def tearDown (self):\n self.conn.close()\n\n\n def test_filterByBorder (self):\n c = self.conn.cursor()\n filterByBorder (c, {})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_filterByRatio (self):\n c = self.conn.cursor()\n filterByRatio (c, {})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_filterBySize (self):\n c = self.conn.cursor()\n filterBySize (c, {'size_map_path': 'testdata/mapSize.tiff', 'relpath': '.'})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_filterCustom_carConstraint (self):\n c = self.conn.cursor()\n filterCustom (c, {'car_constraint': 'name = \"dummy\"'})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_thresholdScore (self):\n c = self.conn.cursor()\n thresholdScore (c, params = {})\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_clusterBboxes (self):\n c = self.conn.cursor()\n clusterBboxes (c, params = {})\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_expandBboxes (self):\n ''' Make sure it runs '''\n c = self.conn.cursor()\n expandBboxes (c, params = {})\n\n def test_assignOrientations (self):\n ''' Make sure it runs '''\n c = self.conn.cursor()\n assignOrientations (c, {'size_map_path': 'testdata/mapSize.tiff',\n 'yaw_map_path': 'testdata/mapYaw.tiff',\n 'pitch_map_path': 'testdata/mapPitch.tiff', \n 'relpath': '.'})\n\n def test_merge (self):\n c = self.conn.cursor()\n merge(c, c)\n c.execute('SELECT COUNT(*) FROM cars')\n self.assertEqual (c.fetchone()[0], 0)\n c.execute('SELECT COUNT(*) FROM images')\n self.assertEqual (c.fetchone()[0], 0)\n c.execute('SELECT COUNT(*) FROM matches')\n self.assertEqual (c.fetchone()[0], 0)\n \n\n\n\nclass TestMicroDb (TestMicroDbBase):\n \n def setUp (self):\n super(TestMicroDb, self).setUp()\n\n def _makeDebugParams_ (self, sequence):\n ''' convenience helper function '''\n params = {}\n params['debug'] = True\n params['image_processor'] = ProcessorRandom({'dims': (100,100)})\n params['key_reader'] = KeyReaderSequence(sequence)\n return params\n\n # filterByBorder\n\n # TODO: add a test with polygons\n\n def test_filterByBorder_defaults (self):\n ''' Check default parameters. None of the cars is close to border '''\n c = self.conn.cursor()\n filterByBorder (c, {})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 3)\n\n def test_filterByBorder_loose (self):\n ''' Increased border_thresh_perc to filter out 2 out of 3 cars '''\n c = self.conn.cursor()\n filterByBorder (c, {'border_thresh_perc': 0.3})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 1)\n\n def test_filterByBorder_debug_all (self):\n filterByBorder (self.conn.cursor(), self._makeDebugParams_([32, 32, 32]))\n \n def test_filterByBorder_debug_several (self):\n filterByBorder (self.conn.cursor(), self._makeDebugParams_([32, 27, 32]))\n \n # filterByRatio\n\n def test_filterByRatio_loose (self):\n ''' Very loose ratio_acceptance keeps all the cars, even with bad target_ratio. '''\n c = self.conn.cursor()\n filterByRatio (c, {'target_ratio': 5, 'ratio_acceptance': 1.001})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 3)\n\n def test_filterByRatio_targetRatio (self):\n ''' Impossible target_ratio leaves no cars '''\n c = self.conn.cursor()\n filterByRatio (c, {'target_ratio': 100})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_filterByRatio_ratioAcceptance (self):\n ''' Very tight ratio_acceptance. Only img1.car2 matches target_ratio exactly. '''\n c = self.conn.cursor()\n filterByRatio (c, {'ratio_acceptance': 100})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 1)\n\n def test_filterByRatio_debug_all (self):\n filterByRatio (self.conn.cursor(), self._makeDebugParams_([32, 32, 32]))\n \n def test_filterByRatio_debug_several (self):\n filterByRatio (self.conn.cursor(), self._makeDebugParams_([32, 27]))\n \n # filterBySize\n\n def test_filterBySize_defaults (self):\n ''' The map is 20 almost everywhere. Two cars are close to that. '''\n c = self.conn.cursor()\n filterBySize (c, {'size_map_path': 'testdata/mapSize.tiff', 'relpath': '.', \n 'min_width': 0, 'size_acceptance': 2})\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n # c.execute('SELECT score FROM cars')\n # for (score,) in c.fetchall(): print score\n self.assertEqual (numLeft, 2)\n\n def test_filterBySize_tight (self):\n ''' Run tight size_acceptance. '''\n c = self.conn.cursor()\n params = {'size_map_path': 'testdata/mapSize.tiff', 'relpath': '.', \n 'size_acceptance': 100, 'min_width': 0}\n filterBySize (c, params)\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_filterBySize_loose (self):\n ''' Run loose size_acceptance. '''\n c = self.conn.cursor()\n params = {'size_map_path': 'testdata/mapSize.tiff', 'relpath': '.', \n 'size_acceptance': 1.01, 'min_width': 0}\n filterBySize (c, params)\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 3)\n\n def test_filterBySize_minWidth (self):\n ''' loose size_acceptance won't make a difference, but 'min_width' will filter out the small car. '''\n c = self.conn.cursor()\n params = {'size_map_path': 'testdata/mapSize.tiff', 'relpath': '.',\n 'size_acceptance': 1.01, 'min_width': 10}\n filterBySize (c, params)\n c.execute('SELECT COUNT(*) FROM cars WHERE score > 0.5')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 2)\n\n def test_filterBySize_debug_all (self):\n params = self._makeDebugParams_([32, 32, 32])\n params['size_map_path'] = 'testdata/mapSize.tiff'\n params['relpath'] = '.'\n filterBySize (self.conn.cursor(), params)\n \n def test_filterBySize_debug_several (self):\n params = self._makeDebugParams_([32, 27])\n params['size_map_path'] = 'testdata/mapSize.tiff'\n params['relpath'] = '.'\n filterBySize (self.conn.cursor(), params)\n \n # filterCustom\n\n def test_filterCustom_carConstraint (self):\n c = self.conn.cursor()\n params = {'car_constraint': 'name = \"vehicle\" AND \"width\" >= 20'}\n filterCustom (c, params)\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 1)\n\n def test_filterCustom_impossibleConstraint (self):\n c = self.conn.cursor()\n params = {'car_constraint': 'name = \"sedan\" AND \"width\" >= 20'}\n filterCustom (c, params)\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_filterCustom_imageConstraint (self):\n c = self.conn.cursor()\n params = {'image_constraint': 'imagefile IN (\"img1\", \"img3\")'}\n filterCustom (c, params)\n c.execute('SELECT COUNT(*) FROM images')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 2)\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 2)\n\n def test_filterCustom_carAndImageConstraint (self):\n c = self.conn.cursor()\n params = {'image_constraint': 'imagefile IN (\"img1\", \"img3\")', \n 'car_constraint': 'name = \"vehicle\"'}\n filterCustom (c, params)\n c.execute('SELECT COUNT(*) FROM images')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 2)\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 1)\n\n\n # thresholdScore\n\n def test_thresholdScore_loose (self):\n ''' Low 'score_threshold' keeps all cars '''\n c = self.conn.cursor()\n thresholdScore (c, params = {'score_threshold': 0.5})\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 3)\n\n def test_thresholdScore_tight (self):\n ''' High 'score_threshold' filters out all cars '''\n c = self.conn.cursor()\n thresholdScore (c, params = {'score_threshold': 1.5})\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 0)\n\n def test_thresholdScore_medium (self):\n ''' Cars in img1 are set low score, so they are filtered out by average 'score_threshold' '''\n c = self.conn.cursor()\n c.execute('UPDATE cars SET score=? WHERE imagefile=?', (0, 'img1'))\n thresholdScore (c, params = {'score_threshold': 0.5})\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 1)\n\n # expandBboxes\n\n def test_expandBboxes_noRatio (self):\n ''' Expand each side by 100%. Don't keep the ratio.\n Original carid0=(6,6), carid1=(20,15), carid2=(16,16) '''\n c = self.conn.cursor()\n expandBboxes (c, params = {'expand_perc': 1, 'keep_ratio': False})\n c.execute('SELECT width,height FROM cars WHERE id = 1')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (12,12))\n c.execute('SELECT width,height FROM cars WHERE id = 2')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (40,30))\n c.execute('SELECT width,height FROM cars WHERE id = 3')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (32,32))\n\n def test_expandBboxes_4to3Ratio (self):\n ''' Expand each side by 100%. Keep the ratio to default height:width = 3:4.\n Original carid0=(6,6), carid1=(20,15), carid2=(16,16) '''\n c = self.conn.cursor()\n expandBboxes (c, params = {'expand_perc': 1, 'keep_ratio': True, 'target_ratio': 0.75})\n c.execute('SELECT width,height FROM cars WHERE id = 1')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (12,9))\n c.execute('SELECT width,height FROM cars WHERE id = 2')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (40,30))\n c.execute('SELECT width,height FROM cars WHERE id = 3')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (32,24))\n\n def test_expandBboxes_1to1Ratio (self):\n ''' Expand each side by 100%. Keep the ratio to 1:1.\n Original carid0=(6,6), carid1=(20,15), carid2=(16,16) '''\n c = self.conn.cursor()\n expandBboxes (c, params = {'expand_perc': 1, 'keep_ratio': True, 'target_ratio': 1})\n c.execute('SELECT width,height FROM cars WHERE id = 1')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (12,12))\n c.execute('SELECT width,height FROM cars WHERE id = 2')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (30,30))\n c.execute('SELECT width,height FROM cars WHERE id = 3')\n (width,height) = c.fetchone()\n self.assertEqual ((width,height), (32,32))\n\n def test_expandBboxes_debug_all (self):\n expandBboxes (self.conn.cursor(), self._makeDebugParams_(6*[32])) # one per car and one per image\n \n def test_expandBboxes_debug_several (self):\n expandBboxes (self.conn.cursor(), self._makeDebugParams_([32, 27]))\n \n\n # clusterBboxes\n\n def test_clusterBboxes_tight (self):\n ''' Tight 'cluster_threshold' won't let car1 (sedan) and car2 (vehicle) get merged. '''\n c = self.conn.cursor()\n clusterBboxes (c, {'cluster_threshold': 0})\n c.execute('SELECT COUNT(*) FROM cars')\n (numLeft,) = c.fetchone()\n self.assertEqual (numLeft, 3)\n\n def test_clusterBboxes_loose (self):\n ''' Loose 'cluster_threshold' merges intersecting car1 (sedan) and car2 (vehicle). '''\n c = self.conn.cursor()\n clusterBboxes (c, {'cluster_threshold': 1000})\n c.execute('SELECT name FROM cars')\n names = c.fetchall()\n self.assertEqual (len(names), 2)\n self.assertEqual (names[0][0], 'sedan')\n self.assertEqual (names[1][0], 'vehicle')\n\n def test_clusterBboxes_debug_all (self):\n clusterBboxes (self.conn.cursor(), self._makeDebugParams_([32, 32, 32]))\n \n def test_clusterBboxes_debug_several (self):\n clusterBboxes (self.conn.cursor(), self._makeDebugParams_([32, 27]))\n\n # assignOrientations\n\n def test_assignOrientations (self):\n ''' Make sure it runs '''\n c = self.conn.cursor()\n assignOrientations (c, {'size_map_path': 'testdata/mapSize.tiff',\n 'yaw_map_path': 'testdata/mapYaw.tiff',\n 'pitch_map_path': 'testdata/mapPitch.tiff',\n 'relpath': '.'})\n c.execute('SELECT yaw FROM cars')\n yaw_entries = c.fetchall()\n c.execute('SELECT pitch FROM cars')\n pitch_entries = c.fetchall()\n self.assertEqual (yaw_entries[0][0], -69)\n self.assertEqual (yaw_entries[1][0], 140)\n self.assertEqual (yaw_entries[2][0], -69)\n for (pitch,) in pitch_entries:\n self.assertEqual (pitch, 51)\n\n # merge\n\n def test_merge_same (self):\n c = self.conn.cursor()\n createTablePolygons(c)\n s = 'polygons(carid,x,y)'\n c.execute('INSERT INTO %s VALUES (?,?,?)' % s, (1,1,1))\n c.execute('INSERT INTO %s VALUES (?,?,?)' % s, (1,1,3))\n c.execute('INSERT INTO %s VALUES (?,?,?)' % s, (1,3,1))\n merge(c, c)\n # cars\n c.execute('SELECT name,x1 FROM cars')\n car_entries = c.fetchall()\n self.assertEqual (len(car_entries), 6)\n self.assertEqual (car_entries[0], ('sedan', 24))\n self.assertEqual (car_entries[1], ('vehicle', 44))\n self.assertEqual (car_entries[2], ('vehicle', 24))\n self.assertEqual (car_entries[3], ('sedan', 24))\n self.assertEqual (car_entries[4], ('vehicle', 44))\n self.assertEqual (car_entries[5], ('vehicle', 24))\n # polygons\n c.execute('SELECT x,y FROM polygons WHERE carid = 1')\n polygon_entries = c.fetchall()\n self.assertEqual (len(polygon_entries), 3)\n self.assertEqual (polygon_entries[0], (1,1))\n self.assertEqual (polygon_entries[1], (1,3))\n self.assertEqual (polygon_entries[2], (3,1))\n c.execute('SELECT x,y FROM polygons WHERE carid = 4')\n polygon_entries = c.fetchall()\n self.assertEqual (len(polygon_entries), 3)\n self.assertEqual (polygon_entries[0], (1,1))\n self.assertEqual (polygon_entries[1], (1,3))\n self.assertEqual (polygon_entries[2], (3,1))\n c.execute('SELECT x,y FROM polygons WHERE carid NOT IN (1,4)')\n polygon_entries = c.fetchall()\n self.assertEqual (len(polygon_entries), 0)\n # images\n c.execute('SELECT imagefile FROM images')\n image_entries = c.fetchall()\n self.assertEqual (len(image_entries), 3) # duplicate images\n self.assertEqual (image_entries[0], ('img1',))\n self.assertEqual (image_entries[1], ('img2',))\n self.assertEqual (image_entries[2], ('img3',))\n #c.execute('SELECT id,carid,match FROM matches')\n #match_entries = c.fetchall()\n #self.assertEqual (len(match_entries), 6)\n\n def test_merge_addEmpty (self):\n # create and empty db\n conn_empty = sqlite3.connect(':memory:') # in RAM\n createDb (conn_empty)\n cursor_empty = conn_empty.cursor()\n # merge\n c = self.conn.cursor()\n merge(c, cursor_empty)\n # cars\n c.execute('SELECT name,x1 FROM cars')\n car_entries = c.fetchall()\n self.assertEqual (len(car_entries), 3)\n # images\n c.execute('SELECT imagefile FROM images')\n image_entries = c.fetchall()\n self.assertEqual (len(image_entries), 3)\n # # matches\n # c.execute('SELECT id,carid,match FROM matches')\n # match_entries = c.fetchall()\n # self.assertEqual (len(match_entries), 3)\n # close\n conn_empty.close()\n\n def test_merge_toEmpty (self):\n # create and empty db\n conn_empty = sqlite3.connect(':memory:') # in RAM\n createDb (conn_empty)\n cursor_empty = conn_empty.cursor()\n # merge\n c = self.conn.cursor()\n merge(cursor_empty, c)\n # cars\n c.execute('SELECT name,x1 FROM cars')\n car_entries = c.fetchall()\n self.assertEqual (len(car_entries), 3)\n self.assertEqual (car_entries[0], ('sedan', 24))\n self.assertEqual (car_entries[1], ('vehicle', 44))\n self.assertEqual (car_entries[2], ('vehicle', 24))\n # images\n c.execute('SELECT imagefile,src FROM images')\n image_entries = c.fetchall()\n self.assertEqual (len(image_entries), 3)\n self.assertEqual (image_entries[0], ('img1','src'))\n self.assertEqual (image_entries[1], ('img2','src'))\n self.assertEqual (image_entries[2], ('img3','src'))\n # matches\n c.execute('''SELECT imagefile,name FROM cars WHERE id IN \n (SELECT carid FROM matches WHERE match == 2)''')\n match_entries = c.fetchall()\n self.assertEqual (len(match_entries), 2)\n self.assertEqual (match_entries[0], ('img1','vehicle'))\n self.assertEqual (match_entries[1], ('img2','vehicle'))\n # close\n conn_empty.close()\n\n\n\nif __name__ == '__main__':\n logging.basicConfig (level=logging.ERROR)\n unittest.main()\n","sub_path":"test/learning/test_dbModify.py","file_name":"test_dbModify.py","file_ext":"py","file_size_in_byte":19590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"623035901","text":"#---------------------------------------------------------------------------\n# Name: etg/slider.py\n# Author: Kevin Ollivier\n# Robin Dunn\n#\n# Created: 16-Sept-2011\n# Copyright: (c) 2011 by Kevin Ollivier\n# Copyright: (c) 2011-2020 by Total Control Software\n# License: wxWindows License\n#---------------------------------------------------------------------------\n\nimport etgtools\nimport etgtools.tweaker_tools as tools\n\nPACKAGE = \"wx\"\nMODULE = \"_core\"\nNAME = \"slider\" # Base name of the file to generate to for this script\nDOCSTRING = \"\"\n\n# The classes and/or the basename of the Doxygen XML files to be processed by\n# this script.\nITEMS = [ 'wxSlider' ]\n\n#---------------------------------------------------------------------------\n\ndef run():\n # Parse the XML file(s) building a collection of Extractor objects\n module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)\n etgtools.parseDoxyXML(module, ITEMS)\n\n #-----------------------------------------------------------------\n # Tweak the parsed meta objects in the module object as needed for\n # customizing the generated code and docstrings.\n\n def addDefaults(func):\n func.find('value').default = '0'\n func.find('minValue').default = '0'\n func.find('maxValue').default = '100'\n\n\n c = module.find('wxSlider')\n assert isinstance(c, etgtools.ClassDef)\n addDefaults(c.find('wxSlider'))\n addDefaults(c.find('Create'))\n\n module.addGlobalStr('wxSliderNameStr', c)\n\n c.addPyMethod('GetRange', '(self)', 'return (self.GetMin(), self.GetMax())')\n\n tools.fixWindowClass(c)\n\n #-----------------------------------------------------------------\n tools.doCommonTweaks(module)\n tools.runGenerators(module)\n\n\n#---------------------------------------------------------------------------\nif __name__ == '__main__':\n run()\n\n","sub_path":"etg/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"417317980","text":"import requests\nimport json\nfrom src import config\nimport time\nimport hashlib\nimport random\nfrom loguru import logger\n\nlogger.add(f'log/{__name__}.log', format='{time} {level} {message}', level='DEBUG', rotation='10 MB', compression='zip')\n\n\ns = requests.Session()\nsert_path = 'src/cert.pem'\nkey_path = 'src/dec.key'\n# Сам сертификат выдает support\n# Приватный ключ через тектсовик вытащил из серта pem, затем командой\n# \"openssl rsa -in my.key_encrypted -out my.key_decrypted\" (со вводом пароля) расшифровал закрытый ключ\ns.cert = (sert_path, key_path)\nuser = {'retry': 0} # Для записи локальных переменных в глобальную\n\n\ndef create_anonimus_pay():\n print('\\nCheck anonimus payment methods:\\n')\n print('/do/payment/anonymous...', end='')\n url = config.anonimus_pay_url\n payload = {\n \"sign\": \"16088965AB36DAA41E401BD948E13BBC\",\n \"serviceCode\": f\"{config.service_code}\",\n \"amount\": \"2500\",\n \"comission\": \"0\",\n \"properties\": [\n {\n \"name\": \"ПОЗЫВНОЙ\",\n \"value\": f\"{random.randint(10, 20)}\"\n }\n ],\n \"shopToken\": \"1a4c0d33-010c-4365-9c65-4c7f9bb415d5\"\n }\n # Рассчет подписи\n sign_str = payload['serviceCode'] + '&' + payload['amount'] + '&' + payload['comission'] + '&' + payload['properties'][0]['name'] + '&' + payload['properties'][0]['value'] + '&' + payload['shopToken'] + '&' + config.sec_key\n pre_sign = (hashlib.md5(f\"{sign_str}\".encode('utf-8')).hexdigest()).upper()\n sign = (hashlib.md5(f\"{pre_sign}\".encode('utf-8')).hexdigest()).upper()\n payload['sign'] = sign\n headers = {\n 'Content-Type': 'application/json',\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0\",\n }\n r = s.post(url, data=json.dumps(payload), headers=headers)\n #logger.info(f'r.text: {r.text}')\n\n if r.status_code == 200:\n request = r.json()\n try:\n user['sign'] = request['sign']\n user['shopToken'] = request['shopToken']\n user['regPayNum'] = request['regPayNum']\n user['payUrl'] = request['payUrl']\n user['methodType'] = request['methodType']\n\n # Открываем полученную ссылку, чтоб перехватить Cookies\n s.get(user['payUrl'], headers=headers)\n user['cookies'] = s.cookies.get_dict()\n\n if user['sign'] and user['methodType'] == 'GET' and user['shopToken'] and 'https://demo-acq.bisys.ru/cardpay/card?order=' in user['payUrl'] and user['regPayNum']:\n print('OK')\n else:\n print(f'Something wrong!\\nrequest_status_code: {r.status_code}\\nrequest: {request}')\n except KeyError:\n print(f'Something wrong! Key Error. Url: {url}, request: {request}')\n\n # print(f'sign: {sign}\\nshopToken: {shopToken}\\nregPayNum: {regPayNum}\\npayurl: {payurl}\\nmethodType: {methodType}')\n else:\n print(f'\\ncreate_anonimus_pay: http error. request status code: {r.status_code}')\n\n\ndef payment_created_pay():\n #logger.info('Trying to payment created pay')\n print('Trying to payment created pay...\\nSend a POST request...', end='')\n order = user['payUrl'].replace('https://demo-acq.bisys.ru/cardpay/card?order=', '')\n payload = {\n \"form\": \"default\",\n \"operation\": \"pay\",\n \"order\": f\"{order}\",\n \"type\": \"visa\",\n \"pan\": \"4000000000000002\",\n \"exp\": \"01 21\",\n \"holder\": \"hard support\",\n \"secret\": \"123\"\n }\n\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Referer\": f\"{user['payUrl']}\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0\",\n \"Cookies\": f\"{user['cookies']}\"\n }\n\n url = config.acq_pay_url\n r = s.post(url, data=payload, headers=headers)\n if r.status_code == 200:\n print('Response code == 200 OK')\n else:\n print(f'Something wrong!\\nrequest_status_code: {r.status_code}\\nrequest_text: {r.text}\\n')\n\n\ndef check_pay_status():\n url = config.payment_state_url\n #logger.info('Check payment state...')\n print('Check payment state...', end='')\n payload = {\n \"sign\": \"AE13A1572E1A3594A0A956EB751D7F6D\",\n \"regPayNum\": f\"{user['regPayNum']}\",\n \"shopToken\": f\"{config.shopToken}\"\n }\n headers = {\n \"Content-Type\": \"application/json\"\n }\n sign_str = payload['regPayNum'] + '&' + payload['shopToken'] + '&' + config.sec_key\n pre_sign = (hashlib.md5(f\"{sign_str}\".encode('utf-8')).hexdigest()).upper()\n sign = (hashlib.md5(f\"{pre_sign}\".encode('utf-8')).hexdigest()).upper()\n payload['sign'] = sign\n\n r = s.post(url, data=json.dumps(payload), headers=headers)\n request = r.json()\n payment_state = request['state']\n if payment_state == 'payed':\n print('OK\\n')\n elif payment_state == 'created':\n if user['retry'] <= 3:\n print(f'Payment state: {payment_state}. Retry...')\n time.sleep(5)\n user['retry'] += 1\n check_pay_status()\n else:\n print(f\"Платеж {user['regPayNum']} висит в статусе 'created'\")\n else:\n print(f'Something wrong! payment state: {payment_state}, response: {request}')\n\n","sub_path":"anonimus_pay.py","file_name":"anonimus_pay.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"221130631","text":"#!/usr/bin/env python\n\"\"\"\ntest docstring\n\"\"\"\ndef threeSumClosest(num, target):\n ns = sorted(num)\n i = 0\n absmin = 99999999\n while i < len(ns)-2:\n a = ns[i]\n start, end = i+1, len(ns)-1\n while start target:\n end -= 1\n else:\n start += 1\n if absmin > abs(sum-target):\n absmin = abs(sum-target)\n closest = sum\n i += 1\n print(closest)\n return closest\n\nprint(threeSumClosest([1,1,1,0], 100))\n","sub_path":"3sumclose.py","file_name":"3sumclose.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"428924395","text":"import os\nfrom flask import Flask, flash, render_template, redirect, url_for\n\napp = Flask(__name__)\n\nclass Person(object):\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n@app.errorhandler(404)\ndef not_found(e):\n return render_template('404.html')\n\n@app.route('/test')\ndef test():\n flash('Test endpoint flash.')\n return redirect(url_for('index'))\n\n@app.route('/')\ndef index():\n user = Person('John', 18)\n return render_template('index.html', title='Template Tutorial', mylist=[1, 2, 3], person=user, mybool=False, myemptylist=[])\n\nif __name__ == '__main__':\n app.secret_key = os.urandom(32)\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"496787232","text":"import brownie\nfrom brownie import accounts, Bridge\n\n\ndef test_bridge_validatorpowers_total_validator_power(simple_validator_set):\n totalPower = sum([l[1] for l in simple_validator_set])\n bridge = accounts[0].deploy(Bridge, simple_validator_set)\n assert totalPower == bridge.totalValidatorPower()\n\n\ndef test_bridge_validatorpowers_validator_power(simple_validator_set):\n bridge = accounts[0].deploy(Bridge, simple_validator_set)\n for [address, power] in simple_validator_set:\n assert bridge.validatorPowers(address) == power\n\n\ndef test_bridge_update_validator_powers_success(simple_validator_set):\n new_validator_power = [\"0x652D89a66Eb4eA55366c45b1f9ACfc8e2179E1c5\", 150]\n bridge = accounts[0].deploy(Bridge, simple_validator_set)\n assert bridge.totalValidatorPower() == 400\n tx = bridge.updateValidatorPowers([new_validator_power])\n assert tx.status == 1\n assert bridge.totalValidatorPower() == 450\n for [address, power] in simple_validator_set:\n if address == new_validator_power[0]:\n assert bridge.validatorPowers(address) == new_validator_power[1]\n else:\n assert bridge.validatorPowers(address) == power\n\n\ndef test_bridge_update_validator_powers_multi_success(simple_validator_set):\n new_validator_powers = [\n [\"0x652D89a66Eb4eA55366c45b1f9ACfc8e2179E1c5\", 150],\n [\"0x88e1cd00710495EEB93D4f522d16bC8B87Cb00FE\", 0],\n [\"0x85109F11A7E1385ee826FbF5dA97bB97dba0D76f\", 200],\n ]\n bridge = accounts[0].deploy(Bridge, simple_validator_set)\n assert bridge.totalValidatorPower() == 400\n tx = bridge.updateValidatorPowers(new_validator_powers)\n assert tx.status == 1\n assert bridge.totalValidatorPower() == 550\n for [address, power] in simple_validator_set:\n for [addr2, new_power] in new_validator_powers:\n if addr2 == address:\n assert bridge.validatorPowers(address) == new_power\n break\n else:\n assert bridge.validatorPowers(address) == power\n\n\ndef test_bridge_update_validator_powers_not_owner(simple_validator_set):\n bridge = accounts[0].deploy(Bridge, simple_validator_set)\n start_total_validator_power = 400\n with brownie.reverts(\"Ownable: caller is not the owner\"):\n tx = bridge.updateValidatorPowers(\n [[\"0x652D89a66Eb4eA55366c45b1f9ACfc8e2179E1c5\", 150]], {\"from\": accounts[1]}\n )\n assert tx.status == 0\n assert bridge.totalValidatorPower() == start_total_validator_power\n for [address, power] in simple_validator_set:\n assert bridge.validatorPowers(address) == power\n","sub_path":"tests/bridge/test_bridge_validatorpowers.py","file_name":"test_bridge_validatorpowers.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"9755237","text":"from sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.orm import sessionmaker, backref, relationship\n\nfrom base import Base\n\n\nclass Member(Base):\n\n __tablename__ = 'members'\n\n uid = Column(\n Integer,\n primary_key = True,\n )\n name = Column(\n String,\n )\n famName = Column(\n String,\n )\n organizations = relationship(\n \"OrganizationMember\",\n back_populates = \"members\",\n )\n","sub_path":"models/member.py","file_name":"member.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"299033889","text":"#!/usr/bin/python3\n\nimport sys\n\nf = open(sys.argv[1], \"r\")\nfor i in f:\n\tc = i.rstrip().split(\"\\t\")\n\tif len(c) == 204:\n\t\tprint(i.rstrip(),\"0\",sep=\"\\t\")\n\telse:\n\t\tprint(i,end=\"\")\nf.close()\n","sub_path":"fixmatrix.py","file_name":"fixmatrix.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"449327692","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom django.http import HttpResponse\nfrom rango.models import Category #starting to put in ordered pages\nfrom rango.models import Page\nfrom rango.forms import CategoryForm, PageForm\nfrom rango.forms import UserForm, UserProfileForm\nfrom django.contrib.auth import authenticate, login\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout\nfrom datetime import datetime\n\ndef index (request): #Responsible for the main page view\n request.session.set_test_cookie()\n # Query the database for a list of ALL categories currently stored.\n # Order the categories by no. likes in descending order.\n # Retrieve the top 5 only - or all if less than 5.\n # Place the list in our context_dict dictionary\n # that will be passed to the template engine.\n\n category_list = Category.objects.order_by('-likes')[:5] #Order by method - descending order\n #context_dict = {'categories': category_list}\n\n page_list = Page.objects.order_by('-views')[:5] #order by views\n #context_dict = {'boldmessage': \"Crunchy, creamy, cookie, candy, cupcake!\"}\n\n context_dict = {'categories': category_list, 'pages': page_list}\n\n visitor_cookie_handler(request)\n #visitor_cookie_handler(request, response)\n\n context_dict['visits'] = request.session['visits']\n\n response = render(request, 'rango/index.html', context=context_dict)\n return response\n #return render(request, 'rango/index.html', context = context_dict)\n #return HttpResponse(\"Rango says hey there partner! \")\n\ndef about(request):\n\n if request.session.test_cookie_worked():\n print(\"TEST COOKIE WORKED!\")\n request.session.delete_test_cookie()\n\n visitor_cookie_handler(request)\n #context_dict['visits'] = request.session['visits']\n #response = render(request, 'rango/about.html', {}, context=context_dict)\n\n\n #context_dict = { 'Rango says here is the about page.'}\n\n print(request.method)\n\n print(request.user)\n # return response\n\n return render(request, 'rango/about.html',{})\n\n #return HttpResponse(\"Rango says here is the about page. View index page\") #The HTML link is a reference back to the starter page\n\n\ndef show_category (request, category_name_slug):\n# Create a context dictionary which we can pass\n# to the template rendering engine.\n context_dict = {}\n\n try:\n # Can we find a category name slug with the given name?\n # If we can't, the .get() method raises a DoesNotExist exception.\n # So the .get() method returns one model instance or raises an exception\n\n category = Category.objects.get(slug=category_name_slug)\n\n # Retrieve all of the associated pages.\n # Note that filter() will return a list of page objects or an empty list\n\n pages = Page.objects.filter(category=category)\n\n # Adds our results list to the template context under name pages.\n\n context_dict['pages'] = pages\n\n # We also add the category object from\n # the database to the context dictionary.\n # We'll use this in the template to verify that the category exists.\n\n context_dict['category'] = category\n\n except Category.DoesNotExist:\n # We get here if we didn't find the specified category.\n # Don't do anything\n # the template will display the \"no category\" message for us\n\n context_dict ['category'] = None\n context_dict ['pages'] = None\n\n # Go render the response and return it to the client\n\n return render(request, 'rango/category.html', context_dict )\n\ndef add_category(request):\n form = CategoryForm()\n\n #A HTTP POST?\n if request.method == 'POST': #User submitted data via form\n form = CategoryForm(request.POST)\n\n # Have we been provided with a valid form?\n if form.is_valid():\n #Save the new category to the database\n form.save(commit=True)\n #print(category, category.slug)\n\n #Now that the category is saved\n #We could give the confirmation message\n #But since the most recent category added is on the Index page\n #Then we can direct the user back to the index page\n return index(request)\n else:\n #The supplied form contained errors -\n #Just print them to the terminal.\n print(form.errors)\n\n #Will handle the bad form, new form or no form supplied cases\n #Render the form with error messages (if any)\n return render(request, 'rango/add_category.html', {'form': form})\n\ndef add_page(request, category_name_slug):\n try:\n category = Category.objects.get(slug=category_name_slug)\n except Category.DoesNotExist:\n category = None\n\n form = PageForm()\n if request.method == 'POST':\n form = PageForm(request.POST)\n if form.is_valid():\n if category:\n page = form.save(commit=False)\n page.category = category\n page.views = 0\n page.save()\n return show_category(request, category_name_slug)\n\n else:\n print(form.errors)\n\n context_dict = {'form': form, 'category': category}\n return render(request, 'rango/add_page.html', context_dict)\n\n\ndef register(request):\n registered = False\n if request.method == 'POST':\n user_form = UserForm(data=request.POST)\n profile_form = UserProfileForm(data=request.POST)\n\n if user_form.is_valid() and profile_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n\n profile = profile_form.save(commit=False)\n profile.user = user\n if 'picture' in request.FILES:\n profile.picture = request.FILES['picture']\n profile.save()\n registered = True\n else:\n print(user_form.errors, profile_form.errors)\n else:\n ## ON the PDF of tangowithdjango19,the e.g is like that:\n # else:\n # print(user_form.errors, profile_form.errors)\n # \telse:\n # user_form = UserForm()\n # \tprofile_form = UserProfileForm()\n\n user_form = UserForm()\n profile_form = UserProfileForm()\n\n return render(request,\n 'rango/register.html',\n {'user_form': user_form,\n 'profile_form': profile_form,\n 'registered': registered\n })\n\ndef user_login(request):\n if request.method == 'POST':\n #POST.get because returns none if not exist\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n #Check if combo valid\n user = authenticate(username=username, password=password)\n\n #If we have a user object, details correct\n if user:\n #Account active?\n if user.is_active:\n #valid\n login(request, user)\n return HttpResponseRedirect(reverse('index'))\n else:\n #Inactive account used\n return HttpResponse(\"Your Rango account is disabled\")\n else:\n #Bad login details provided\n print(\"Invalid login details: {0}, {1}\".format(username, password))\n return HttpResponse(\"Invalid login details supplied.\")\n #Request not in POST, so display login form\n else:\n return render(request, 'rango/login.html', {})\n\n@login_required\ndef restricted(request):\n return HttpResponse(\"Since you're logged in, you can see this text!\")\n\n@login_required\ndef user_logout(request):\n #Know user has already logged in\n logout(request)\n #Take back to homepage\n return HttpResponseRedirect(reverse('index'))\n\n#Helper method\ndef get_server_side_cookie(request, cookie, default_val=None):\n val = request.session.get(cookie)\n if not val:\n val = default_val\n return val\n\ndef visitor_cookie_handler(request):\n #get number of visits to the site\n #use COOKIES.get() to obtain the visits cookie\n #If cookie exists, value returned is casted to an int\n #If no cookie, default value of 1\n visits = int(get_server_side_cookie(request,'visits', '1'))\n\n last_visit_cookie = get_server_side_cookie(request,'last_visit', str(datetime.now()))\n last_visit_time = datetime.strptime(last_visit_cookie[:-7],'%Y-%m-%d %H:%M:%S')\n #If more than a day since last visit\n if (datetime.now() - last_visit_time).days > 0:\n visits = visits + 1\n #update count\n request.session['last_visit'] = str(datetime.now())\n #response.set_cookie('last_visit', str(datetime.now()))\n else:\n visits = 1\n request.session['last_visit'] = last_visit_cookie\n #response.set_cookie('last_visit', last_visit_cookie)\n\n request.session['visits'] = visits\n #response.set_cookie('visits', visits)\n\n\n","sub_path":"tango_with_django_project/rango/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"285462586","text":"import numpy as np\n\n# numpy 행렬 추가\narray1 = np.array([1,2,3])\narray2 = np.array([4,5,6])\narray3 = np.concatenate([array1,array2])\n\nprint(array3.shape)\nprint(array3)\n\n# 형태 바꾸기\narray4 = np.array([1,2,3,4])\narray5 = array4.reshape((2,2))\n\nprint(array5)\n\n# 행렬 형태로 만든 후 배열 세로로 합치기\narray6 = np.arange(4).reshape((1,4))\narray7 = np.arange(8).reshape((2,4))\n\n# axis?? => basic_5 에서 진행\narray8 = np.concatenate([array6, array7], axis=0)\n\nprint(array6)\nprint(array7)\nprint(array8)\n\n\n\n","sub_path":"Python_Grammer/Python_numpy_define/numpy_basic_3.py","file_name":"numpy_basic_3.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"198607576","text":"from const import *\nfrom tinydb import TinyDB, Query\nfrom datetime import datetime\nimport pickle\nimport os\n\ntinyDB = TinyDB(DATABASE, ensure_ascii=False)\ndevice_cache = {} # {session_id: Device}\nclosed_group_cache = {} # {closed_group_id: ClosedGroup}\n\n\nclass DatabaseModel:\n def __init__(self, table, doc_id=None):\n self.table = table\n self.doc_id = doc_id\n self.need_to_save = False\n\n def from_mapping(self, mapping):\n pass\n\n def to_mapping(self):\n pass\n\n def save(self):\n self.need_to_save = True\n\n def saved_to_db(self, doc_id):\n if doc_id:\n self.doc_id = doc_id\n self.need_to_save = False\n\n\nclass Device(DatabaseModel):\n def __init__(self, doc_id=None, session_id=None, tokens=None):\n super().__init__(PUBKEY_TOKEN_TABLE, doc_id)\n self.session_id = session_id\n self.tokens = set(tokens) if tokens else set()\n\n def from_mapping(self, mapping):\n self.session_id = mapping[PUBKEY]\n self.tokens = set(mapping[TOKEN])\n\n def to_mapping(self):\n return {PUBKEY: self.session_id,\n TOKEN: list(self.tokens)}\n\n def save(self):\n device_cache[self.session_id] = self\n super().save()\n\n\nclass ClosedGroup(DatabaseModel):\n def __init__(self, doc_id=None, closed_group_id=None, members=None):\n super().__init__(CLOSED_GROUP_TABLE, doc_id)\n self.closed_group_id = closed_group_id\n self.members = set(members) if members else set()\n\n def from_mapping(self, mapping):\n self.closed_group_id = mapping[CLOSED_GROUP]\n self.members = set(mapping[MEMBERS])\n\n def to_mapping(self):\n return {CLOSED_GROUP: self.closed_group_id,\n MEMBERS: list(self.members)}\n\n def save(self):\n closed_group_cache[self.closed_group_id] = self\n super().save()\n\n\ndef load_cache():\n device_table = tinyDB.table(PUBKEY_TOKEN_TABLE)\n devices = device_table.all()\n for device_mapping in devices:\n device = Device(doc_id=device_mapping.doc_id)\n device.from_mapping(device_mapping)\n device_cache[device.session_id] = device\n\n closed_group_table = tinyDB.table(CLOSED_GROUP_TABLE)\n closed_groups = closed_group_table.all()\n for closed_group_mapping in closed_groups:\n closed_group = ClosedGroup(doc_id=closed_group_mapping.doc_id)\n closed_group.from_mapping(closed_group_mapping)\n closed_group_cache[closed_group.closed_group_id] = closed_group\n\n\ndef flush():\n\n def batch_flush(items, table):\n items_need_to_save = []\n items_need_to_update = []\n mappings = []\n for item in items:\n if item.need_to_save:\n items_need_to_save.append(item)\n mappings.append(item.to_mapping())\n if item.doc_id:\n items_need_to_update.append(item.doc_id)\n tinyDB.table(table).remove(doc_ids=items_need_to_update)\n doc_ids = tinyDB.table(table).insert_multiple(mappings)\n for i in range(len(items_need_to_save)):\n items_need_to_save[i].saved_to_db(doc_ids[i])\n\n batch_flush(device_cache.copy().values(), PUBKEY_TOKEN_TABLE)\n batch_flush(closed_group_cache.copy().values(), CLOSED_GROUP_TABLE)\n\n\ndef migrate_database_if_needed():\n def migrate(old_db_name, new_table_name, json_structure):\n db_map = None\n if os.path.isfile(old_db_name):\n with open(old_db_name, 'rb') as old_db:\n db_map = dict(pickle.load(old_db))\n old_db.close()\n if db_map is not None and len(db_map) > 0:\n items = []\n for key, value in db_map.items():\n item = {}\n for key_name, value_name in json_structure.items():\n item[key_name] = key\n item[value_name] = list(value)\n items.append(item)\n tinyDB.table(new_table_name).insert_multiple(items)\n os.remove(old_db_name)\n\n migrate(PUBKEY_TOKEN_DB_V2, PUBKEY_TOKEN_TABLE, {PUBKEY: TOKEN})\n migrate(CLOSED_GROUP_DB, CLOSED_GROUP_TABLE, {CLOSED_GROUP: MEMBERS})\n\n\ndef store_data(last_statistics_date, now, ios_pn_number, android_pn_number, total_message_number, closed_group_message_number):\n db = tinyDB.table(STATISTICS_TABLE)\n fmt = \"%Y-%m-%d %H:%M:%S\"\n db.insert({START_DATE: last_statistics_date.strftime(fmt),\n END_DATE: now.strftime(fmt),\n IOS_PN_NUMBER: ios_pn_number,\n ANDROID_PN_NUMBER: android_pn_number,\n TOTAL_MESSAGE_NUMBER: total_message_number,\n CLOSED_GROUP_MESSAGE_NUMBER: closed_group_message_number})\n\n\ndef get_data(start_date, end_date):\n db = tinyDB.table(STATISTICS_TABLE)\n\n def try_to_convert_datetime(date_str):\n formats = [\"%Y-%m-%d %H:%M:%S\", \"%Y-%m-%d\"]\n for fmt in formats:\n try:\n return datetime.strptime(date_str, fmt)\n except ValueError:\n pass\n\n def test_func(val, date_str, ascending):\n date_1 = try_to_convert_datetime(val)\n date_2 = try_to_convert_datetime(date_str)\n return date_1 > date_2 if ascending else date_1 < date_2\n\n data_query = Query()\n if start_date and end_date:\n return db.search(data_query[START_DATE].test(test_func, start_date, True) &\n data_query[END_DATE].test(test_func, end_date, False))\n elif start_date:\n return db.search(data_query[START_DATE].test(test_func, start_date, True))\n else:\n return db.all()\n\n\ndef get_device(session_id):\n return device_cache.get(session_id, None)\n\n\ndef get_closed_group(closed_group_id):\n return closed_group_cache.get(closed_group_id, None)\n","sub_path":"databaseHelper.py","file_name":"databaseHelper.py","file_ext":"py","file_size_in_byte":5758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"511867527","text":"\"\"\"\nSee https://github.com/zsimic/pickley\n\"\"\"\n\nimport logging\nimport logging.config\nimport os\nimport sys\n\nimport click\nimport runez\n\nfrom pickley import system\nfrom pickley.delivery import copy_venv, move_venv\nfrom pickley.lock import SoftLockException\nfrom pickley.package import DELIVERERS, PACKAGERS\nfrom pickley.settings import short\nfrom pickley.uninstall import uninstall_existing\n\n\nLOG = logging.getLogger(__name__)\n\n\n@runez.click.group()\n@click.pass_context\n@runez.click.version(message=\"%(version)s\")\n@runez.click.debug()\n@runez.click.dryrun(\"-n\")\n@click.option(\"--base\", \"-b\", metavar=\"PATH\", help=\"Base installation folder to use (default: folder containing pickley)\")\n@click.option(\"--index\", \"-i\", metavar=\"PATH\", help=\"Pypi index to use\")\n@click.option(\"--config\", \"-c\", metavar=\"PATH\", help=\"Extra config to load\")\n@click.option(\"--python\", \"-P\", metavar=\"PATH\", help=\"Python interpreter to use\")\n@click.option(\"--delivery\", \"-d\", type=click.Choice(DELIVERERS.names()), help=\"Delivery method to use\")\n@click.option(\"--packager\", \"-p\", help=\"Packager to use (one of: %s)\" % \",\".join(PACKAGERS.names()))\ndef main(ctx, debug, dryrun, base, index, config, python, delivery, packager):\n \"\"\"\n Package manager for python CLIs\n \"\"\"\n if any(opt in sys.argv for opt in ctx.help_option_names): # pragma: no cover\n return\n\n runez.log.setup(\n dryrun=dryrun,\n debug=debug,\n console_format=\"%(levelname)s %(message)s\" if debug else \"%(message)s\",\n console_level=logging.WARNING,\n console_stream=sys.stderr,\n locations=None,\n )\n # Disable logging.config, as pip tries to get smart and configure all logging...\n runez.log.silence(\"pip\")\n logging.config.dictConfig = lambda x: None\n\n if base:\n base = runez.resolved_path(base)\n if not os.path.exists(base):\n sys.exit(\"Can't use %s as base: folder does not exist\" % short(base))\n system.SETTINGS.set_base(base)\n\n system.SETTINGS.load_config(config=config, delivery=delivery, index=index, packager=packager)\n system.DESIRED_PYTHON = python\n\n\n@main.command()\n@click.option(\"--force\", \"-f\", is_flag=True, help=\"Force check, even if checked recently\")\n@click.option(\"--verbose\", \"-v\", is_flag=True, help=\"Show more information\")\n@click.argument(\"packages\", nargs=-1, required=False)\ndef check(force, verbose, packages):\n \"\"\"\n Check whether specified packages need an upgrade\n \"\"\"\n code = 0\n packages = system.resolved_package_specs(packages, auto_complete=True)\n if not packages:\n print(\"No packages installed\")\n\n else:\n for name in packages:\n p = PACKAGERS.resolved(name)\n p.refresh_desired(force=force)\n if not p.desired.valid:\n LOG.error(p.desired.representation(verbose))\n code = 1\n elif not p.current.version or not p.current.valid:\n print(p.desired.representation(verbose, note=\"is not installed\"))\n code = 1\n elif p.current.version != p.desired.version:\n print(p.current.representation(verbose, note=\"can be upgraded to %s\" % p.desired.version))\n code = 1\n else:\n print(p.current.representation(verbose, note=\"is installed\"))\n\n sys.exit(code)\n\n\n@main.command()\n@click.option(\"--verbose\", \"-v\", is_flag=True, help=\"Show more information\")\ndef list(verbose):\n \"\"\"\n List installed packages\n \"\"\"\n packages = system.resolved_package_specs(None, auto_complete=True)\n if not packages:\n print(\"No packages installed\")\n\n else:\n for name in packages:\n p = PACKAGERS.resolved(name)\n print(p.current.representation(verbose))\n\n\n@main.command()\n@click.option(\"--force\", \"-f\", is_flag=True, help=\"Force installation, even if already installed\")\n@click.argument(\"packages\", nargs=-1, required=True)\ndef install(force, packages):\n \"\"\"\n Install a package from pypi\n \"\"\"\n system.setup_audit_log()\n packages = system.resolved_package_specs(packages)\n for name in packages:\n p = PACKAGERS.resolved(name)\n p.install(force=force)\n\n\n@main.command()\n@click.option(\"--all\", is_flag=True, help=\"Uninstall everything pickley-installed, including pickley itself\")\n@click.option(\"--force\", \"-f\", is_flag=True, help=\"Force installation, even if already installed\")\n@click.argument(\"packages\", nargs=-1, required=False)\ndef uninstall(all, force, packages):\n \"\"\"\n Uninstall packages\n \"\"\"\n if packages and all:\n sys.exit(\"Either specify packages to uninstall, or --all (but not both)\")\n\n if not packages and not all:\n sys.exit(\"Specify packages to uninstall, or --all\")\n\n if packages and system.PICKLEY in packages:\n sys.exit(\"Run 'uninstall --all' if you wish to uninstall pickley itself (and everything it installed)\")\n\n system.setup_audit_log()\n package_specs = system.resolved_package_specs(packages, auto_complete=all)\n errors = 0\n for package_spec in package_specs:\n p = PACKAGERS.resolved(package_spec)\n if not force and not p.current.file_exists:\n errors += 1\n LOG.error(\"%s was not installed with pickley\", package_spec)\n continue\n\n eps = p.entry_points\n ep_uninstalled = 0\n ep_missed = 0\n meta_deleted = runez.delete(system.SETTINGS.meta.full_path(package_spec.dashed), fatal=False)\n if not eps and force:\n eps = {package_spec.dashed: \"\"}\n if eps and meta_deleted >= 0:\n for entry_point in eps:\n path = system.SETTINGS.base.full_path(entry_point)\n handler = runez.delete if meta_deleted > 0 else uninstall_existing\n r = handler(path, fatal=False)\n if r < 0:\n ep_missed += 1\n elif r > 0:\n ep_uninstalled += 1\n\n if ep_missed or meta_deleted < 0:\n # Error was already reported\n errors += 1\n continue\n\n if ep_uninstalled + meta_deleted == 0:\n system.inform(\"Nothing to uninstall for %s\" % package_spec)\n continue\n\n message = \"Would uninstall\" if runez.DRYRUN else \"Uninstalled\"\n message = \"%s %s\" % (message, package_spec)\n if ep_uninstalled > 1:\n message += \" (%s entry points)\" % ep_uninstalled\n system.inform(message)\n\n if all and not errors:\n runez.delete(system.SETTINGS.meta.path)\n\n if errors:\n sys.exit(1)\n\n\n@main.command()\n@click.argument(\"source\", required=True)\n@click.argument(\"destination\", required=True)\ndef copy(source, destination):\n \"\"\"\n Copy file or folder, relocate venvs accordingly (if any)\n \"\"\"\n copy_venv(source, destination)\n print(\"Copied %s -> %s\" % (short(source), short(destination)))\n\n\n@main.command()\n@click.argument(\"source\", required=True)\n@click.argument(\"destination\", required=True)\ndef move(source, destination):\n \"\"\"\n Copy file or folder, relocate venvs accordingly (if any)\n \"\"\"\n move_venv(source, destination)\n print(\"Moved %s -> %s\" % (short(source), short(destination)))\n\n\n@main.command()\n@click.option(\"--build\", \"-b\", default=\"./build\", show_default=True, help=\"Folder to use as build cache\")\n@click.option(\"--dist\", \"-d\", default=\"./dist\", show_default=True, help=\"Folder where to produce package\")\n@click.option(\"--symlink\", \"-s\", help=\"Create symlinks for debian-style packaging, example: root:root/usr/local/bin\")\n@click.option(\"--relocatable/--absolute\", is_flag=True, default=False, help=\"Create a relocatable venv or not\")\n@click.option(\"--sanity-check\", default=\"--version\", show_default=True, help=\"Args to invoke produced package for sanity check\")\n@click.argument(\"folder\", required=True)\ndef package(build, dist, symlink, relocatable, sanity_check, folder):\n \"\"\"\n Package a project from source checkout\n \"\"\"\n build = runez.resolved_path(build)\n\n root = None\n target_dist = dist\n if target_dist.startswith(\"root/\"):\n # Special case: we're targeting 'root/...' probably for a debian, use target in that case to avoid venv relocation issues\n target = target_dist[4:]\n if os.path.isdir(target):\n root = target_dist[:4]\n target_dist = target\n LOG.debug(\"debian mode: %s -> %s\", dist, target)\n\n folder = runez.resolved_path(folder)\n\n if not os.path.isdir(folder):\n sys.exit(\"Folder %s does not exist\" % short(folder))\n\n system.SETTINGS.set_base(build)\n\n setup_py = os.path.join(folder, \"setup.py\")\n if not os.path.exists(setup_py):\n sys.exit(\"No setup.py in %s\" % short(folder))\n\n with runez.CurrentFolder(folder):\n # Some setup.py's assume their working folder is the folder where they're in\n name = system.run_python(setup_py, \"--name\", fatal=False, dryrun=False)\n if not name:\n sys.exit(\"Could not determine package name from %s\" % short(setup_py))\n\n package_spec = system.PackageSpec(name)\n runez.Anchored.add(folder)\n p = PACKAGERS.resolved(package_spec)\n p.build_folder = build\n p.dist_folder = runez.resolved_path(target_dist)\n p.relocatable = relocatable\n p.source_folder = folder\n p.package()\n\n p.create_symlinks(symlink, root=root)\n p.sanity_check(sanity_check)\n\n if p.executables:\n overview = \"produced: %s\" % runez.represented_args(p.executables)\n\n else:\n overview = \"package has no entry-points\"\n\n print(\"Packaged %s successfully, %s\" % (short(folder), overview))\n runez.Anchored.pop(folder)\n\n\n@main.command()\n@click.option(\"--diagnostics\", \"-d\", is_flag=True, help=\"Show diagnostics info\")\ndef settings(diagnostics):\n \"\"\"\n Show settings\n \"\"\"\n if diagnostics:\n prefix = getattr(sys, \"prefix\", None)\n base_prefix = getattr(sys, \"base_prefix\", None)\n print(\"python : %s\" % short(system.target_python(desired=system.INVOKER, fatal=None), meta=False))\n print(\"sys.executable : %s\" % short(sys.executable, meta=False))\n print(\"sys.prefix : %s\" % short(prefix, meta=False))\n if base_prefix:\n print(\"sys.base_prefix: %s\" % short(base_prefix, meta=False))\n if not system.SETTINGS.meta.path.startswith(system.PICKLEY_PROGRAM_PATH):\n print(\"pickley : %s\" % short(system.PICKLEY_PROGRAM_PATH, meta=False))\n print(\"\")\n\n print(system.SETTINGS.represented())\n\n\n@main.command(name=\"auto-upgrade\")\n@click.option(\"--force\", \"-f\", is_flag=True, help=\"Force auto-upgrade check, even if recently checked\")\n@click.argument(\"package\", required=True)\ndef auto_upgrade(force, package):\n \"\"\"\n Auto-upgrade a package\n \"\"\"\n package = system.PackageSpec(package)\n p = PACKAGERS.resolved(package)\n if not p.current.valid:\n sys.exit(\"%s is not currently installed\" % package)\n\n ping = system.SETTINGS.meta.full_path(package.dashed, \".ping\")\n if not force and runez.is_younger(ping, system.SETTINGS.version_check_seconds):\n # We checked for auto-upgrade recently, no need to check again yet\n print(\"Skipping auto-upgrade, checked recently\")\n sys.exit(0)\n\n runez.touch(ping)\n\n try:\n p.internal_install()\n\n except SoftLockException:\n print(\"Skipping auto-upgrade, %s is currently being installed by another process\" % package)\n sys.exit(0)\n","sub_path":"src/pickley/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":11421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"548398526","text":"########## 批量加水印文字 #########\nimport os\nimport sys\nfrom PIL import Image, ImageFont, ImageDraw\n\ndef add_watermark(image_file):\n image = Image.open(image_file)\n draw_txt = ImageDraw.Draw(image)\n\n im_size = image.size\n print('原始图片尺寸:', im_size)\n if im_size[0] > im_size[1]: # 如果是横版\n txt_size = int(im_size[0] * 0.05)\n else:\n txt_size = int(im_size[1] * 0.05)\n print('水印文字尺寸:', txt_size)\n\n # 设置字体和文字大小\n chi_font = ImageFont.truetype('./font/fzstk.ttf', size=txt_size)\n\n # 直接在照片上写文字\n draw_txt.text(xy=(im_size[0] // 2 - txt_size // 2, im_size[1] - int(txt_size * 1.2)),\n text='@AdsRyen',\n font=chi_font)\n\n name = os.path.basename(image_file)\n new_name = os.path.join('.\\output', name)\n image.save(new_name, quality=99)\n\nif __name__ == '__main__':\n\n ### 循环读入照片\n files = os.listdir('.\\input')\n for file in files:\n image_file = os.path.join('.\\input', file)\n print(image_file)\n add_watermark(image_file)\n","sub_path":"size-marker.py","file_name":"size-marker.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"437680941","text":"def caesar_encrypt(plaintext, offset):\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n ciphertext = \"\"\n for char in plaintext:\n if char in alphabet:\n position = alphabet.find(char)\n new_position = (position + offset) % 26\n new_char = alphabet[new_position]\n #print(char, \"-->\", new_char)\n ciphertext = ciphertext + new_char\n else:\n ciphertext = ciphertext + char\n #print(char, \"unchanged\")\n return ciphertext\n\n\n# print(caesar_encrypt(\"abc\", 1))\n# print(caesar_encrypt(\"xyz\", 1))\n# print(caesar_encrypt(\"hello\", 10))\n# print(caesar_encrypt(\"Hello!!\", 10))\n# print(caesar_encrypt(\"Hello!!\", 36))\nprint(caesar_encrypt(\"Hello!!\", -1))\n\n\ndef caesar_decrypt(ciphertext, offset):\n plaintext = caesar_encrypt(ciphertext, -offset)\n return plaintext\n\ndef caesar_break(ciphertext):\n for offset in range(1,26): #go over all possible offsets\n maybe = caesar_decrypt(ciphertext, offset)\n print(offset, maybe)\n\n\ncommon_words = [\"The\", \" the \", \" to \", \" is \", \" a \" ,\" I \" , \"I \", \" no \", \" yes \"]\n\n# Caesar Cipher - decryption\n#what is this quote and who said it?\n#try to decrypt (you don't know the offset!...)\nquote = 'jxu gkuijyed ev mxujxuh q secfkjuh sqd jxyda yi de cehu ydjuhuijydw jxqd jxu gkuijyed ev mxujxuh q ikrcqhydu sqd imyc'","sub_path":"Lesson 6/caesar_encrypt.py","file_name":"caesar_encrypt.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"264101929","text":"#!/usr/bin/python\n# Author: Hernán David Carvajal \n# Tested in python-3.4.3\n\nimport sys\nimport os\nimport time\nimport math\n\nimport pyximport\npyximport.install()\n\nfrom .boxCovering.cythonGreedyColoring import *\n\n\ndef fractal_dimension(g, iterations=1000, debug=True):\n \"\"\"\n This method computes the fractal dimension (D) of a network performing a box\n covering and analysing the relation between the minimum number of boxes (Nb)\n required to cover the graph and the dimension of each box (Lb).\n Then, given the relation:\n\n Nb ~ Lb raised to D\n\n To get the minimum number of boxes required to cover a graph given a box\n length, this method repeat the box covering several times (10.000 by\n default) and calculate the average value.\n\n Parameters\n ------------\n g: A networkit graph\n iterations: The number of times that the box covering algorithm will be run\n debug: If this variable is set to True the results of each iteration are\n saved into a file called results.csv\n\n Returns\n -----------\n A float value representing the fractal dimension of the network.\n \"\"\"\n diameter = int(nk.distance.Diameter.exactDiameter(g))\n num_nodes = g.numberOfNodes()\n results = np.empty((iterations, diameter+1), dtype=int)\n\n # print(\"Results: \\n\", len(results))\n\n for i in range(iterations):\n if diameter > 0:\n result = number_of_boxes(g)\n else:\n result = [num_nodes]\n results[i, :] = result[:]\n\n if debug:\n datetime = time.strftime(\"%d-%m-%Y_%H%M%S\")\n filename = g.getName() + \"_covering_\" + datetime + \".csv\"\n np.savetxt(filename, results, fmt='%i')\n\n boxes_length = np.arange(1, diameter+2)\n mean_nodes_per_box = results.mean(axis=0)\n\n # Fit a line and calculate the slope\n log_box_length = np.log(boxes_length)\n log_mean_number_of_nodes = np.log(mean_nodes_per_box)\n\n slope, intercept = np.polyfit(log_box_length, log_mean_number_of_nodes, 1)\n\n return math.fabs(slope)\n\n\ndef main(n=100, iterations=100):\n\n import networkx as nx\n g = nk.nxadapter.nx2nk(nx.erdos_renyi_graph(n, 0.6))\n\n print(fractal_dimension(g, iterations, False))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"modules/dimension/fractalDimension.py","file_name":"fractalDimension.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"227178039","text":"# -*- coding: UTF-8 -*-\n\nimport unittest\n\nfrom model.gamestate import *\nfrom quick_game_settings import QuickGameSettings\nfrom presenter_mock import PresenterMock\nfrom constants import BOUNDS\n\n\nclass SysSettingsMock:\n def __init__(self, *args):\n self.quick_game = QuickGameMock(*args)\n\n\nclass QuickGameMock:\n def __init__(self, def_time_sec, def_words_per_player, def_players):\n self.def_time_sec = def_time_sec\n self.def_words_per_player = def_words_per_player\n self.def_players = def_players\n\n\nclass QuickGameSettingsTest(unittest.TestCase):\n def setUp(self):\n self.settings = SysSettingsMock(13, 17, 7)\n self.gamestate = GameState(None, None, None,\n Phase.QUICK_GAME_SETTINGS, None, None, None)\n self.presenter = PresenterMock(Phase.WELCOME)\n self.presenter.settings = self.settings\n\n def test_load_defaults(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.assertEqual(screen.PROPS['time'].prop, 13)\n self.assertEqual(screen.PROPS['words'].prop, 17)\n self.assertEqual(screen.PROPS['players'].prop, 7)\n\n @unittest.expectedFailure # till issue 131 fix\n def test_load_gamestate(self):\n self.gamestate.settings = Settings(time_per_round_sec=7,\n words_number=13)\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.assertEqual(screen.PROPS['time'].prop, 7)\n self.assertEqual(screen.PROPS['words'].prop, 13)\n self.assertEqual(screen.PROPS['players'].prop, 7)\n\n def test_create_game(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.presenter.new_phase = Phase.EDIT_PLAYERS\n screen.next_view()\n self.assertIsInstance(self.gamestate.hat, Hat)\n self.assertEqual(len(self.gamestate.hat.words), 7*17)\n self.assertEqual(len(self.gamestate.players.players), 7)\n for player in self.gamestate.players.players:\n self.assertEqual(len(player.words), 17)\n self.assertEqual(self.gamestate.settings.words_number, 17)\n self.assertEqual(self.gamestate.settings.time_per_round_sec, 13)\n self.assertIsInstance(self.gamestate.players.players_select_strategy,\n OddStrategy)\n self.assertTrue(self.presenter.is_phase_changed)\n\n def test_selecting_odd_strategy(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.presenter.new_phase = Phase.EDIT_PLAYERS\n screen.next_view()\n self.assertIsInstance(self.gamestate.players.players_select_strategy,\n OddStrategy)\n\n def test_selecting_traditional_strategy(self):\n self.presenter.settings.quick_game.def_players = 16\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.presenter.new_phase = Phase.EDIT_PLAYERS\n screen.next_view()\n self.assertIsInstance(self.gamestate.players.players_select_strategy,\n TraditionalStrategy)\n\n def test_go_back(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n screen.go_back()\n self.assertTrue(self.presenter.is_phase_changed)\n\n def test_reading_properties(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n screen.PROPS['time'].inp.focus = True\n screen.PROPS['time'].inp.text = '245'\n screen.PROPS['time'].inp.focus = False\n screen.PROPS['words'].inp.focus = True\n screen.PROPS['words'].inp.text = '57'\n screen.PROPS['words'].inp.focus = False\n screen.PROPS['players'].inp.focus = True\n screen.PROPS['players'].inp.text = '7'\n screen.PROPS['players'].inp.focus = False\n self.assertEqual(screen.PROPS['time'].prop, 245)\n self.assertEqual(screen.PROPS['words'].prop, 57)\n self.assertEqual(screen.PROPS['players'].prop, 7)\n\n def test_change_properties(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n for i in range(5):\n screen.PROPS['time'].plus_btn.dispatch('on_release')\n for i in range(3):\n screen.PROPS['time'].minus_btn.dispatch('on_release')\n for i in range(5):\n screen.PROPS['words'].plus_btn.dispatch('on_release')\n for i in range(7):\n screen.PROPS['words'].minus_btn.dispatch('on_release')\n for i in range(6):\n screen.PROPS['players'].plus_btn.dispatch('on_release')\n for i in range(4):\n screen.PROPS['players'].minus_btn.dispatch('on_release')\n self.assertEqual(screen.PROPS['time'].prop, 23)\n self.assertEqual(screen.PROPS['words'].prop, 15)\n self.assertEqual(screen.PROPS['players'].prop, 9)\n\n def test_bounds(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n for i in range(10):\n screen.PROPS['time'].minus_btn.dispatch('on_release')\n self.assertEqual(screen.PROPS['time'].prop, 5)\n screen.PROPS['time'].inp.focus = True\n screen.PROPS['time'].inp.text = str(BOUNDS['time'][1]+10)\n screen.PROPS['time'].inp.focus = False\n self.assertEqual(screen.PROPS['time'].prop, BOUNDS['time'][1])\n for i in range(57):\n screen.PROPS['words'].plus_btn.dispatch('on_release')\n self.assertEqual(screen.PROPS['words'].prop, 60)\n screen.PROPS['words'].inp.focus = True\n screen.PROPS['words'].inp.text = '0'\n screen.PROPS['words'].inp.focus = False\n self.assertEqual(screen.PROPS['words'].prop, BOUNDS['words'][0])\n\n def test_invalid_input(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.assertEqual(screen.PROPS['time'].prop, 13)\n screen.PROPS['time'].inp.focus = True\n screen.PROPS['time'].inp.text = 'abracadabra'\n screen.PROPS['time'].inp.focus = False\n self.assertEqual(screen.PROPS['time'].prop, 13)\n\n def test_keyboard_translations(self):\n screen = QuickGameSettings(self.gamestate, self.presenter)\n self.presenter.new_phase = Phase.EDIT_PLAYERS\n screen.PROPS['time'].inp.focus = True\n self.assertTrue(screen.PROPS['time'].inp.focus)\n self.assertFalse(screen.PROPS['words'].inp.focus)\n screen.PROPS['time'].inp.dispatch('on_text_validate')\n self.assertTrue(screen.PROPS['words'].inp.focus)\n screen.PROPS['words'].inp.dispatch('on_text_validate')\n self.assertTrue(screen.PROPS['players'].inp.focus)\n screen.PROPS['players'].inp.dispatch('on_text_validate')\n self.assertTrue(self.presenter.is_phase_changed)\n\n\nif __name__ == '__main__':\n from kivy.lang import Builder\n import os\n import gettext\n Builder.load_file('ui/quick_game_settings.kv')\n PATH = os.path.abspath('.')\n LOCALE_PATH = os.path.join(PATH, 'locales')\n gettext.bindtextdomain('thehat', LOCALE_PATH)\n lang = gettext.translation('thehat', LOCALE_PATH, ['ru_RU'],\n codeset='utf-8')\n lang.install(True)\n unittest.main()\n","sub_path":"ui/quick_game_settings_test.py","file_name":"quick_game_settings_test.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"135787750","text":"import socket\n\nHOST = 'localhost'\nPORT = 50000\nBUFSIZE = 4096\n\nclient = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nclient.sendto(b'Hey! ',(HOST,PORT))\n\n#サーバーからのメッセージの受信\ndata = client.recv(BUFSIZE)\nprint(data.decode('UTF-8'))\n\n#ソケットのクローズ\nclient.close()\n","sub_path":"sample/client0udp.py","file_name":"client0udp.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"498424319","text":"#!/usr/bin/env python\n\n\"\"\"\ncalculate_bills - Given an input amount and available bill currencies, \ncalculate the smallest number of bills able to match the desired amount\n\nThis program read its input from stdin. \nTeeeeeeet consists of several data sets. \nThe first line of the input contains the number of data sets which is a positive \ninteger and is not bigger than 20. The following lines describe the data sets, one data set per line.\nFor each data set the first number represents the target value and every other subsequent number \nis an available bill denomination. The numbers will be separated by spaces.\n\"\"\"\n\nimport sys\n\n# Display usage message and exit\ndef usage(msg=None):\n if msg: print('Error => %s\\n' %msg)\n print('Usage: %s ' %sys.argv[0])\n print('\\nList currencies is an optional argument. They will be obtained from stdin if no argument is passed.')\n print('\\n### Without arguments:\\nYou will be asked for several inputs. First will be the number of datasets.')\n print('Then the datasets itself with the following format: number_to_achieve bill_optional_numbers (separated by space)')\n print('\\n### With arguments:\\nList currencies format:\\n\\tThe first argument contains the number of data sets to calculate. \\n\\tThe following lists are the datasets where first number is the amount to achieve and the following numbers are available bill currencies.')\n print('\\nExample:\\n\\t%s 44,13,9,1 38,9,5,5 10,13,9,3\\n\\t4\\n\\t6\\n\\terror' %sys.argv[0])\n sys.exit(2)\n\n# Function to read input from stdin displaying a message compatible with both python 2 and 3\ndef stdin_msg(mes):\n # print('%s' %sys.version_info[0])\n if sys.version_info[0]>2:\n try: return input(mes) \n except KeyboardInterrupt: return None\n else:\n try: return raw_input(mes)\n except KeyboardInterrupt: return None\n\n# Function to get datasets from stdin\ndef get_stdin():\n datasets=[]\n try: num=int(stdin_msg('Indicate number of datasets to calculate (number between 1 and 20): '))\n except: usage('You have to indicate a number')\n\n # Validate number of datasets indicated on stdin\n if int(num) > 20 or int(num) < 1: usage('Number of data sets have to be between 1 and 20')\n n=1\n while n<=num:\n # For each num (datasets number) obtain it's value from stdin\n rawset=stdin_msg('Dataset %d (format: amount bill_1 bill_2 ...): ' %n).rstrip()\n try: dset=[int(c) for c in rawset.split(' ')] \n except: usage('You need to input numbers separated by space')\n validate_list(dset)\n datasets.append(dset)\n n+=1 \n return datasets\n\n# Function to validate each dataset list\ndef validate_list(dlist):\n if len(dlist)<2: usage('You need at least 2 numbers on each dataset (amount to achieve and bill currency number)')\n if len(dlist) > 102: usage('Maximum number of bills type(100) exceeded: %d\\n' %len(dlist)-1)\n if dlist[0]>4000000000: usage('Maximum amount target reached(4 billion): %d\\n' %dlist[0])\n if min(dlist)<0: usage('Negative amount not supported on dataset: %s\\n' %dlist)\n\n# Function to get datasets from argument parameter\n# TODO: argparse migration when input is standarized \ndef get_input():\n dnum=len(sys.argv)-1\n if dnum<1 or dnum>20: usage('Number of data sets have to be between 1 and 20')\n \n datasets=[] # Initialize list of datasets to validate\n i=1\n while i <= dnum:\n try: dlist=[int(c) for c in sys.argv[i].split(',')]\n except: usage('Invalid dataset format: %s\\n' %sys.argv[i])\n validate_list(dlist)\n datasets.append(dlist)\n i+=1\n return datasets\n\n# Main calculator function that will call itself in order to obtain a valid answer\ndef recursive_calc(amount,billnumbers,billused):\n global bestresult,recursivenum,minpossiblenumber\n recursivenum+=1\n if sum(billused)==amount: \n # We got a result set! Check if it's the best and keep it on results\n if not bestresult or len(billused)amount: \n # We have gone beyond amount, no need to continue this way\n pass\n elif billnumbers==[]: \n # We have run out of bills to try further combinations, no need to continue\n pass\n elif bestresult and (len(billused)+1)>=len(bestresult):\n # Do not continue if we already achieved a better result in the past\n # print('Hey, we already did better with %d bills used solution. No need to continue with current since we already use %d bills' %(len(bestresult),len(billused)))\n pass\n elif bestresult and len(bestresult)<=minpossiblenumber: \n # Do not contiue if we have already achieved the best possible result outcome in terms of bills number\n pass\n else:\n remaining=int(amount-sum(billused))\n if max(billnumbers)>remaining: \n # See if there are available bills (billnumbers) that can be removed alerady since they are bigger than curren remaining amount\n # print('Time to cleanup bills available (max is %d). Currently %d bill numbers. %d remaining' %(max(billnumbers),len(billnumbers),remaining))\n billnumbers=[x for x in billnumbers if x <= remaining] \n\n # Avoid work when no bill numbers are left after bill list possible reduction\n if len(billnumbers)>0:\n\n # Try fastfowrard on cases where its safe to avoid unnecessary recursive iterations when remaining amount is \"far\"\n maxn=(remaining-(max(billnumbers)*min(billnumbers)))//max(billnumbers)\n tmpused=billused\n if maxn>10: # Only move forward if it's worth it\n tmpused=billused+[max(billnumbers)]*maxn\n# print('maxn=%d maxbill=%d remaining=%d sum(tmpused)=%d amount=%d' %(maxn,max(billnumbers),remaining,sum(tmpused),amount))\n\n if sum(tmpused)==amount:\n # Check again after possible tmpused change if it has reached the correct answer\n if not bestresult or len(tmpused)1:\n for num in recursive_calc(amount,billnumbers[1:],billused): yield num \n\n# Out of recursive function includding initial caller and some global variables init and handling\ndef dset_calc(dataset):\n # Creating some global variables that will be used in the recursive function for increased perfromance (avoid unnecessary actions)\n global bestresult,recursivenum,minpossiblenumber\n bestresult=[]\n recursivenum=0\n\n if len(dataset)==1: return \"error\"\n\n # print('\\nStarting work with dataset: %s' %dataset)\n # Identify desired amount and available bill numbers starting with highest bill\n amount=dataset.pop(0)\n billnumbers=list(set(dataset))\n billnumbers.sort(reverse=True)\n # print('Amount: %d BillNumbers: %s' %(amount,billnumbers))\n\n # One of the global variables is the minimum possible bill number to be used inside recursiveness to avoid unnecessary calculations when we alreay have it\n minpossiblenumber=amount//max(billnumbers)\n if (amount%max(billnumbers))>0: minpossiblenumber+=1\n # print('Best case scenario the answer would be %d bills' %minpossiblenumber)\n\n # And here the initial call to the recursive function\n solutions=[ s for s in recursive_calc(amount,billnumbers,[]) ]\n\n # Solution validation... when no answer return error.\n if not solutions: return \"error\"\n ds_result=min(solutions,key=len)\n\n # Performance validation to check result and recursive iterations. Very useful on debugging\n print('Answer achieved after %d recursive iterations. %d bills' %(recursivenum,len(ds_result)))\n\n # Finally return just the number of bills\n return ds_result\n\n# Main function\ndef main():\n if len(sys.argv)==1:\n datasets=get_stdin()\n print('')\n else:\n datasets=get_input()\n \n for dset in datasets: \n # Execute the solution for each dataset\n print('Starting to work with dataset: %s' %dset)\n try:result=dset_calc(dset)\n except KeyboardInterrupt: break \n\n if result=='error': print('Result: error')\n else:\n if len(result)>14: print('Result: %s bills needed => Starting with %s and ending with %s' %(len(result), result[:7], result[-7:]))\n else: print('Result: %s bills needed => %s' %(len(result), result))\n print('')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"calculate_bills.py","file_name":"calculate_bills.py","file_ext":"py","file_size_in_byte":8870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"583738084","text":"from PyQt5.QtWidgets import QVBoxLayout, QLabel, QFrame\nfrom PyQt5.QtCore import Qt\n\n\nclass MatterInfoFrame(QFrame):\n def __init__(self, *args, **kwargs):\n super(MatterInfoFrame, self).__init__(*args, **kwargs)\n self.setWindowFlag(Qt.WindowTransparentForInput)\n self.setWindowFlag(Qt.WindowDoesNotAcceptFocus)\n self.setWindowFlag(Qt.WindowStaysOnTopHint)\n self.setStyleSheet(\"background-color: white; border: 2px solid black;\")\n\n self.text = QLabel()\n self.text.setStyleSheet(\"border: 0px; padding: 0px; margin: 0px;\")\n\n vbox = QVBoxLayout()\n vbox.addWidget(self.text, alignment=Qt.AlignBaseline)\n self.setLayout(vbox)\n\n def set_info(self, sim_objects):\n\n info_text = \"\"\n counter = 0\n for o in sim_objects:\n if counter > 0:\n info_text += \"\\n\\n\"\n info_text += str(o.type).upper()\n if o.type == \"particle\" and o.get_carried_status():\n info_text += \" (carried)\"\n if o.type == \"tile\" and o.get_tile_status():\n info_text += \"(carried)\"\n info_text += \"\\nid: %s\" % str(o.get_id())\n info_text += \"\\ncoordinates: %s\" % str(o.coordinates)\n info_text += \"\\ncolor: %s\" % str(o.color)\n info_text += \"\\nmemory:\"\n mem = o.read_whole_memory()\n for x in mem:\n info_text += \"\\n\\t\"+str(x)+\": \"+str(mem[x])\n counter += 1\n self.text.setText(info_text)\n self.adjustSize()\n","sub_path":"lib/visualization/MatterInfoFrame.py","file_name":"MatterInfoFrame.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"198897802","text":"#!/usr/bin/env python3\n\"\"\"Detect single-character XOR\"\"\"\n# \"Now that the party is jumping\"\n\nfrom typing import List\n\nfrom m03 import break_single_byte_xor, mostprobable\n\ndef findxoredstring(cyphertext: List[bytes]) -> bytes:\n candidates = []\n for line in cyphertext:\n line = break_single_byte_xor(line)\n if line:\n candidates.append(line)\n return mostprobable(candidates)\n\ndef main() -> None:\n with open(\"data/04.txt\", \"r\") as f:\n data = [bytes.fromhex(line) for line in f.read().splitlines()]\n\n print(findxoredstring(data).decode())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"m04.py","file_name":"m04.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"41556432","text":"import csv\nfrom pathlib import Path\nfrom alive_progress import alive_bar\n\n'''\nCombines all CSV data for this dataset into\na single records.csv file\n'''\ndef process(source: Path, destination: Path):\n # print(source.name)\n destination.mkdir(exist_ok=True)\n with alive_bar() as bar:\n with open(destination / 'records.csv', 'w') as export:\n # declare writer\n writer = csv.writer(export)\n # get first file in source\n first_file = [f for f in source.iterdir() if f.match('*.csv')][0]\n # write the header row\n with open(first_file, 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n # ONLY write the first row (header row)\n writer.writerow(row)\n break\n # write the other rows\n for csvfile in source.iterdir():\n if(csvfile.match('*.csv')):\n with open(csvfile, 'r') as f:\n reader = csv.reader(f)\n # skip the first row (header)\n next(reader)\n for row in reader:\n writer.writerow(row)\n bar()\n","sub_path":"bundler/bundle/grade_distribution.py","file_name":"grade_distribution.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"412467068","text":"##########################################################################\n# \n# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n# \n# * 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 with\n# the distribution.\n# \n# * Neither the name of John Haddon nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n##########################################################################\n\nimport GafferUI\n\nclass _Section( GafferUI.CompoundPlugValueWidget ) :\n\n\tdef __init__( self, plug, collapsed, label, summary, names, **kw ) :\n\t\n\t\tGafferUI.CompoundPlugValueWidget.__init__( self, plug, collapsed, label, summary, **kw )\n\t\t\n\t\tself.__names = names\n\t\t\t\t\n\tdef _childPlugs( self ) :\n\t\n\t\treturn [ self.getPlug()[name] for name in self.__names ]\n\nclass SectionedCompoundPlugValueWidget( GafferUI.PlugValueWidget ) :\n\n\tdef __init__( self, plug, sections, **kw ) :\n\t\n\t\tself.__column = GafferUI.ListContainer( spacing = 8 )\n\t\n\t\tGafferUI.PlugValueWidget.__init__( self, self.__column, plug, **kw )\n\t\t\n\t\twith self.__column :\n\t\t\tfor section in sections :\n\t\t\t\t_Section(\n\t\t\t\t\tself.getPlug(),\n\t\t\t\t\tcollapsed = section.get( \"collapsed\", True ),\n\t\t\t\t\tlabel = section[\"label\"],\n\t\t\t\t\tsummary = section.get( \"summary\", None ),\n\t\t\t\t\tnames = section[\"names\"],\n\t\t\t\t)\n\t\n\tdef hasLabel( self ) :\n\t\n\t\treturn True\n\t\n\tdef childPlugValueWidget( self, childPlug, lazy=True ) :\n\t\n\t\tfor section in self.__column :\n\t\t\tresult = section.childPlugValueWidget( childPlug, lazy )\n\t\t\tif result is not None :\n\t\t\t\treturn result\n\t\t\t\t\n\t\treturn None\n\t\n\tdef setReadOnly( self, readOnly ) :\n\t\n\t\tif readOnly == self.getReadOnly() :\n\t\t\treturn\n\t\t\t\n\t\tGafferUI.PlugValueWidget.setReadOnly( self, readOnly )\n\t\t\n\t\tfor section in self.__column :\n\t\t\tsection.setReadOnly( readOnly )\n\t\t\t\n\tdef _updateFromPlug( self ) :\n\t\n\t\tpass\t\n","sub_path":"python/GafferUI/SectionedCompoundPlugValueWidget.py","file_name":"SectionedCompoundPlugValueWidget.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"99189475","text":"#this will be one-stop service: from tif to classified images for inspection\nimport os\nimport sys\nimport csv\nimport shutil\nimport numpy as np\nimport colorama\nfrom asap_to_jpg import asap_to_image\nfrom segment import gen_txt_for_dir, segment\nfrom prediction_evaluate import get_predictions_result\nfrom prediction_convert import prediction_convert\nfrom jpg_to_cell import get_cells\nfrom Xception_classify import xception_init, xception_predict\nfrom Xception_convert import xception_convert, dict_to_csv\nfrom confusion_matrix import confusion_matrix, generate_xlsx\nfrom xml_to_asap import gen_asap_xml\nfrom utils import scan_files, scan_subdirs, copy_files, remove_files\n\ncolorama.init()\n\n# configuration #######################################################################################################\ninput_tif_files = \"/home/sakulaki/yolo-yuli/one_stop_test/yantian_kfb/kfb\"\noutput_tif_608s = \"/home/sakulaki/yolo-yuli/one_stop_test/yantian_kfb/608\"\ndarknet_dir = \"/home/sakulaki/yolo-yuli/darknet\"\ndet_segment = 0.05\ndet_classify = 0.1\nsave_path = \"/home/sakulaki/yolo-yuli/one_stop_test/yantian_kfb/jpg\"\n\n# cut tif file to 608x608 images. For each tif, it will generate a folder to put 608 images ###########################\nprint(colorama.Fore.GREEN + \"[INFO] cut 608 images from tif file\" + colorama.Fore.WHITE)\nos.makedirs(output_tif_608s, exist_ok=True)\nif len(sys.argv) > 1 and sys.argv[1] == \"yeah\":\n asap_to_image(input_tif_files, output_tif_608s)\n\n# for each tif, run segmentation and classification, generate jpg/xml for labelme #####################################\ntif_names = scan_subdirs(output_tif_608s)\nnot_run = True\nfor tif_name in tif_names:\n if not_run:\n not_run = False\n else:\n break\n print(colorama.Fore.RED + \"[INFO] ########################################\" + colorama.Fore.WHITE)\n image_path = os.path.join(output_tif_608s, tif_name)\n \n # get the list of 608 image full pathnames ########################################################################\n images = scan_files(image_path)\n\n # generate txt file for current tif ###############################################################################\n print(colorama.Fore.GREEN + \"[INFO] generate txt for \" + tif_name + colorama.Fore.WHITE)\n gen_txt_for_dir(images, output_tif_608s, tif_name)\n\n # run darknet test ################################################################################################\n darknet_path = darknet_dir\n segment(darknet_path, image_path)\n os.remove(image_path+\".txt\")\n\n # evaluate predictions and convert coordinates to xmls ############################################################\n print(colorama.Fore.GREEN + \"[INFO] evaluate predictions and write coordinates into xmls\" + colorama.Fore.WHITE)\n result_dir = os.path.join(darknet_path, \"results\")\n classes_list = [\"ASCUS\", \"LSIL\", \"ASCH\", \"HSIL\", \"SCC\"]\n dict_pic_info = get_predictions_result(result_dir, classes_list)\n img_size = 608\n segment_xml_path = os.path.join(output_tif_608s, tif_name+\"_segment\")\n det = det_segment\n prediction_convert(dict_pic_info, classes_list, img_size, segment_xml_path, det)\n\n # copy xmls from segment folder to jpg folder, for purpose of cropping images #####################################\n print(colorama.Fore.GREEN + \"[INFO] copy xmls from segment folder to jpg folder\" + colorama.Fore.WHITE)\n xmls = scan_files(segment_xml_path, postfix=\".xml\")\n for xml in xmls:\n shutil.copy(xml, image_path)\n # copy_files(segment_xml_path, image_path, postfix=\".xml\")\n\n # crop cells out of 608 jpgs and save into numpy array, based on predicted xmls ###################################\n print(colorama.Fore.GREEN + \"[INFO] crop cells out of 608 jpgs and save into numpy array, based on xmls\" + colorama.Fore.WHITE)\n classes_dict = {\"HSIL\":0, \"ASCH\":0, \"LSIL\":0, \"ASCUS\":0, \"SCC\":0}\n files_list = scan_files(image_path, postfix=\".xml\")\n img_size = 299\n cell_numpy, cell_numpy_index = get_cells(files_list, classes_dict, img_size)\n print(cell_numpy.shape)\n print(colorama.Fore.BLUE + \"segmentation result: {}\".format(sorted(classes_dict.items())) + colorama.Fore.WHITE)\n\n # delete xmls_segment from jpg folder and copy jpgs to segment folder #############################################\n print(colorama.Fore.GREEN + \"[INFO] delete xmls_segment from jpg folder and copy jpgs to segment folder\" + colorama.Fore.WHITE)\n xmls = scan_files(image_path, postfix=\".xml\")\n for xml in xmls:\n os.remove(xml)\n jpg = os.path.join(image_path, os.path.basename(os.path.splitext(xml)[0])+\".jpg\")\n shutil.copy(jpg, segment_xml_path)\n #remove_files(image_path, postfix=\".xml\")\n \n # run classification ##############################################################################################\n print(colorama.Fore.GREEN + \"[INFO] run classification\" + colorama.Fore.WHITE) \n model = xception_init()\n predictions = xception_predict(cell_numpy, batch_size=20, model=model)\n print(predictions.shape)\n # del cell_numpy\n\n # generate new dict_pic_info mapping ##############################################################################\n print(colorama.Fore.GREEN + \"[INFO] generate new dict_pic_info mapping\" + colorama.Fore.WHITE)\n classes_all = (\"ACTINO\", \"ADC\", \"AGC1\", \"AGC2\", \"ASCH\", \"ASCUS\", \"CC\", \"EC\", \"FUNGI\", \"GEC\", \"HSIL\", \"LSIL\", \n \"MC\", \"RC\", \"SC\", \"SCC\", \"TRI\", \"VIRUS\")\n # segment_in_classify: {class_i:[segment, classify]}\n segment_in_classify = {\"ACTINO\":[0,0], \"ADC\":[0,0], \"AGC1\":[0,0], \"AGC2\":[0,0], \"ASCH\":[0,0], \"ASCUS\":[0,0], \n \"CC\":[0,0], \"EC\":[0,0], \"FUNGI\":[0,0], \"GEC\":[0,0], \"HSIL\":[0,0], \"LSIL\":[0,0], \"MC\":[0,0], \n \"RC\":[0,0], \"SC\":[0,0], \"SCC\":[0,0], \"TRI\":[0,0], \"VIRUS\":[0,0]} \n index = 0\n dict_pic_info_all = {}\n for prediction in predictions:\n i = np.argmax(prediction)\n class_i = classes_all[i]\n segment_in_classify[class_i][1] += 1\n if cell_numpy_index[index][1] == class_i:\n segment_in_classify[class_i][0] += 1\n x_y, i_of_x_y = cell_numpy_index[index][0].rsplit(\"_\", 1)\n i_of_x_y = int(i_of_x_y)\n space_i = dict_pic_info[x_y][i_of_x_y].find(\" \", 3)\n cell_info = dict_pic_info[x_y][i_of_x_y][:space_i] + \" \" + str(i) + \" \" + str(prediction[i]) + dict_pic_info[x_y][i_of_x_y][space_i:]\n if not x_y in dict_pic_info_all:\n dict_pic_info_all[x_y] = [cell_info,]\n else:\n dict_pic_info_all[x_y].append(cell_info)\n index += 1\n print(colorama.Fore.BLUE + \"segment_in_classify: {}\".format(sorted(segment_in_classify.items())) + colorama.Fore.WHITE)\n\n # generate xmls, based on classification results ##################################################################\n print(colorama.Fore.GREEN + \"[INFO] generate xmls based on classification\" + colorama.Fore.WHITE)\n img_size = 608\n classify_xml_path = os.path.join(output_tif_608s, tif_name+\"_classify\")\n det = det_classify\n xception_convert(dict_pic_info_all, classes_all, img_size, classify_xml_path, det)\n\n # copy jpgs from jpg folder to xmls_classify folder ###############################################################\n print(colorama.Fore.GREEN + \"[INFO] copy jpgs from jpg folder to xmls_classify folder\" + colorama.Fore.WHITE)\n xmls = scan_files(classify_xml_path, postfix=\".xml\")\n for xml in xmls:\n jpg = os.path.join(image_path, os.path.basename(os.path.splitext(xml)[0])+\".jpg\")\n shutil.copy(jpg, classify_xml_path)\n\n # write auto_labeling info into csv ###############################################################################\n print(colorama.Fore.GREEN + \"[INFO] write auto_labeling info into csv\" + colorama.Fore.WHITE)\n csv_file_s = os.path.join(output_tif_608s, tif_name+\"_s.csv\")\n with open(csv_file_s, \"w\") as csv_file:\n writer = csv.writer(csv_file)\n for key,value in dict_pic_info.items():\n writer.writerow([key, value])\n csv_file_c = os.path.join(output_tif_608s, tif_name+\"_c.csv\")\n dict_to_csv(dict_pic_info_all, classes_list, classes_all, csv_file_c)\n\n # generate confusion matrix #######################################################################################\n print(colorama.Fore.GREEN + \"[INFO] generate confusion matrix\" + colorama.Fore.WHITE)\n matrix = confusion_matrix(classes_all, cell_numpy_index, predictions)\n xlsx = os.path.join(output_tif_608s, tif_name+\".xlsx\")\n generate_xlsx(classes_all, matrix, xlsx)\n\n # generate asap_xml from labelimg_xmls\n print(colorama.Fore.GREEN + \"[INFO] generate asap xml from labelimg xmls\" + colorama.Fore.WHITE)\n xml_asap_segment = os.path.join(output_tif_608s, tif_name+\"_segment.xml\")\n gen_asap_xml(xml_asap_segment, segment_xml_path)\n xml_asap_classify = os.path.join(output_tif_608s, tif_name+\"_classify.xml\")\n gen_asap_xml(xml_asap_classify, classify_xml_path)\n\n # move current directories upwards ################################################################################\n print(colorama.Fore.GREEN + \"[INFO] move current directories upwards\" + colorama.Fore.WHITE)\n save_path_i = os.path.join(save_path, tif_name)\n os.makedirs(save_path_i, exist_ok=True)\n os.system(\"mv {} {}\".format(image_path, save_path_i))\n os.system(\"mv {} {}\".format(segment_xml_path, save_path_i))\n os.system(\"mv {} {}\".format(classify_xml_path, save_path_i))\n os.system(\"mv {} {}\".format(csv_file_s, save_path_i))\n os.system(\"mv {} {}\".format(csv_file_c, save_path_i))\n os.system(\"mv {} {}\".format(xlsx, save_path_i))\n os.system(\"mv {} {}\".format(xml_asap_segment, save_path_i))\n os.system(\"mv {} {}\".format(xml_asap_classify, save_path_i))\n","sub_path":"archived/auto_label/api_xception.py","file_name":"api_xception.py","file_ext":"py","file_size_in_byte":9859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"238569780","text":"from django.http import JsonResponse\nfrom django.shortcuts import render\nfrom api.models import Company, Vacancy\nfrom django.http import HttpResponse\n\ndef greeting(request):\n return HttpResponse(\"\"\"

Welcome to our website!

\n

There you can find the most valuable companies

\n

If you are searching for the job, we can provide list of vacancies

\"\"\")\n\ndef all_companies(request):\n companies = Company.objects.all()\n companies_json = [company.short() for company in companies]\n return JsonResponse(companies_json, safe=False)\n\ndef company_detail(request, id):\n try:\n company = Company.objects.get(id=id)\n company_json = company.full()\n except Company.DoesNotExist as e:\n return JsonResponse({'error': str(e)})\n return JsonResponse(company_json)\n\ndef vacancies_of_company(request, id):\n try:\n company = Company.objects.get(id=id)\n except Company.DoesNotExist as e:\n return JsonResponse({'error': str(e)})\n vacancies = company.vacancy_set.all()\n vacancies_json = [vacancy.short() for vacancy in vacancies]\n return JsonResponse(vacancies_json, safe=False)\n\ndef all_vacancies(request):\n vacancies = Vacancy.objects.all()\n vacancies_json = [vacancy.short() for vacancy in vacancies]\n return JsonResponse(vacancies_json,safe=False)\n\ndef vacancy_detail(request, id):\n try:\n vacancy = Vacancy.objects.get(id=id)\n vacancy_json = vacancy.full()\n except Vacancy.DoesNotExist as e:\n return JsonResponse({'error': str(e)})\n return JsonResponse(vacancy_json)\n\ndef top_ten_vacancies(request):\n vacancies = Vacancy.objects.order_by('-salary')\n top = [vacancy.full() for vacancy in vacancies[:10]]\n return JsonResponse(top, safe=False)\n\n","sub_path":"week11/hh_back/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"569634954","text":"import datetime as dt\nfrom trading.events import MarketEvent\nfrom trading.data import BacktestDataHandler\nfrom futures_backtest.data_utils.quantgo_utils import get_data_multi\n\n\nclass FuturesBacktestData(BacktestDataHandler):\n def __init__(self, events, products, start_date, end_date, start_time=dt.time(hour=3), end_time=dt.time(hour=20),\n second_bars=True):\n\n super(FuturesBacktestData, self).__init__(events, products, start_date, end_date,\n start_time=start_time, end_time=end_time)\n self.second_bars = second_bars\n self.symbols = [product.symbol for product in self.products]\n self.curr_day = dt.datetime(year=start_date.year, month=start_date.month, day=start_date.day)\n self.curr_day_data = None\n self.curr_day_index = 0\n self.curr_dt = None\n self.last_bar = {}\n self._load_day_data() # load the\n\n def _load_day_data(self):\n \"\"\"\n Updates the current_day_data.\n Loads the data for all self.symbols for self.curr_day.\n\n \"\"\"\n self.curr_day_data = get_data_multi(self.symbols, self.curr_day,\n download=False,\n second_bars=True,\n start_time=self.start_time,\n end_time=self.end_time)\n\n self.curr_day_data_it = self.curr_day_data.iterrows()\n\n def update(self):\n \"\"\"\n\n :return:\n \"\"\"\n if self.curr_day > self.end_date:\n self.continue_backtest = False\n return\n try:\n self._push_next_data()\n except (StopIteration, AttributeError, ValueError):\n self.curr_day += dt.timedelta(days=1)\n self._load_day_data()\n self.update()\n\n def _push_next_data(self):\n \"\"\"\n Push the next tick from curr_day_data to latest_data (for all symbols).\n \"\"\"\n timestamp, self.last_bar = next(self.curr_day_data_it)\n self.curr_dt = timestamp.to_datetime()\n self.events.put(MarketEvent(self.curr_dt, self.last_bar))","sub_path":"futures_backtest/data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"493417120","text":"#! /usr/bin/env python\n# by caozj\n# Jun 5, 2019\n# 7:50:50 PM\n\n\nimport os\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nos.environ[\"PYTHONHASHSEED\"] = \"0\"\nimport time\nimport random\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport keras.backend as K\nfrom autoencoder import Dhaka\nimport Cell_BLAST as cb\nimport utils\n\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--input\", dest=\"input\", type=str, required=True)\n parser.add_argument(\"-g\", \"--genes\", dest=\"genes\", type=str, required=True)\n parser.add_argument(\"-o\", \"--output\", dest=\"output\", type=str, required=True)\n\n parser.add_argument(\"--n-latent\", dest=\"n_latent\", type=int, default=3)\n parser.add_argument(\"--n-epochs\", dest=\"n_epochs\", type=int, default=100)\n # Reducing epoch number to the maximum of author recommendation,\n # because Dhaka does not support early stopping and we see\n # numerical instability with larger number of epochs.\n\n parser.add_argument(\"-s\", \"--seed\", dest=\"seed\", type=int, default=None) # Not exactly be reproducible though\n parser.add_argument(\"-d\", \"--device\", dest=\"device\", type=str, default=None)\n parser.add_argument(\"--clean\", dest=\"clean\", type=str, default=None)\n cmd_args = parser.parse_args()\n cmd_args.output_path = os.path.dirname(cmd_args.output)\n if not os.path.exists(cmd_args.output_path):\n os.makedirs(cmd_args.output_path)\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = utils.pick_gpu_lowest_memory() \\\n if cmd_args.device is None else cmd_args.device\n if cmd_args.seed is not None:\n np.random.seed(cmd_args.seed)\n random.seed(cmd_args.seed)\n tf.set_random_seed(cmd_args.seed)\n tf_config = tf.ConfigProto()\n tf_config.gpu_options.allow_growth = True\n sess = tf.Session(graph=tf.get_default_graph(), config=tf_config)\n K.set_session(sess)\n return cmd_args\n\n\ndef main(cmd_args):\n dataset = cb.data.ExprDataSet.read_dataset(\n cmd_args.input, sparsify=True\n ).normalize(target=100000) # Example data seem to be normalized to 100,000\n if cmd_args.clean:\n dataset = utils.clean_dataset(dataset, cmd_args.clean)\n if cmd_args.genes is not None:\n dataset = dataset[:, dataset.uns[cmd_args.genes]]\n dataset = np.log2(dataset.exprs.toarray() + 1)\n mat_file = os.path.join(cmd_args.output_path, \"matrix.txt.gz\")\n res_file = os.path.join(cmd_args.output_path, \"output_datafile\")\n np.savetxt(mat_file, dataset)\n start_time = time.time()\n Dhaka.Dhaka(\n mat_file, latent_dim=cmd_args.n_latent,\n N_starts=1, epochs=cmd_args.n_epochs, output_datafile=res_file,\n to_cluster=0, gene_selection=0, to_plot=0, relative_expression=0\n )\n cb.data.write_hybrid_path(\n time.time() - start_time,\n \"//\".join([cmd_args.output, \"time\"])\n )\n cb.data.write_hybrid_path(\n np.loadtxt(res_file + \".txt\"),\n \"//\".join([cmd_args.output, \"latent\"])\n )\n os.remove(mat_file)\n os.remove(res_file + \".txt\")\n\n\nif __name__ == \"__main__\":\n main(parse_args())\n print(\"Done!\")\n","sub_path":"Evaluation/run_Dhaka.py","file_name":"run_Dhaka.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"252169155","text":"from data_aug.data_aug import *\nfrom data_aug.multi_yielder import *\nfrom data_aug.timer_wrapper import timer_wrapper\nfrom data_aug.base_task import task, config_setting\n\n\n@timer_wrapper\ndef multi_generator(files_lists):\n for item in multi_yield(files_lists, task, process_mode, 16):\n print('Image : {} augmentation completely successfully...'.format(item))\n\n\nif __name__ == '__main__':\n # process_mode : 188s\n # thread_mode : 361s\n\n need_aug_num = 1\n ROOT_PATH = '/media/yons/data/dataset/images/helmet_worker/VOC2020'\n\n # create data augmentation sequence\n seq = Sequence([RandomHSV(30, 30, 20),\n RandomHorizontalFlip(p=0.5),\n RandomNoise(p=0.4, mode='gaussian'),\n RandomLight(p=0.5, light=(0.5, 1.5)),\n RandomRotate(3),\n RandomScale(scale=0.05, diff=False),\n RandomTranslate(translate=0.05, diff=False)])\n\n source_pic_root_path = os.path.join(ROOT_PATH, 'JPEGImages')\n source_xml_root_path = os.path.join(ROOT_PATH, 'Annotations')\n target_pic_root_path = os.path.join(ROOT_PATH, 'JPEGImages_target')\n target_xml_root_path = os.path.join(ROOT_PATH, 'Annotations_target')\n paths = [source_pic_root_path, source_xml_root_path, target_pic_root_path, target_xml_root_path]\n\n files_lists = config_setting(paths, seq, need_aug_num, visualizaiton=False)\n multi_generator(files_lists)\n","sub_path":"Multi_ImageAugmentation_voc2020.py","file_name":"Multi_ImageAugmentation_voc2020.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"427879106","text":"'''\n\b Created on Sat Feb 15 2020\n\b\n\b Copyright (c) 2020 QiuDog\n'''\n\nimport docker\nimport logging\nimport asyncio\n\nclass CoreDNS():\n \n def __init__(self, docker_url, container):\n try:\n self.__client = docker.DockerClient(base_url=docker_url)\n self.__coredns = self.__client.containers.get(container)\n self.__logging = self.__coredns.logs(follow=True, stream=True, tail=0)\n self.__loop = asyncio.get_event_loop()\n except Exception as e:\n logging.error('Docker error')\n logging.error(e)\n\n def domains(self):\n for line in self.__logging:\n line = line.decode('utf-8')\n if 'NOERROR' in line:\n domain = line.split()[-1][:-1]\n if '.' in domain:\n yield domain\n\n def get_domain(self):\n return next(self.domains())\n\n async def a_get_domain(self):\n return await self.__loop.run_in_executor(None, self.get_domain)\n\nif __name__ == '__main__':\n from dotenv import load_dotenv\n import os, sys, signal\n import asyncio\n load_dotenv()\n\n def signal_handler(signal, frame):\n sys.exit(0)\n signal.signal(signal.SIGINT, signal_handler)\n\n coreDNS = CoreDNS(docker_url=os.getenv('DOCKER_ADDR'), container='coredns')\n loop = asyncio.get_event_loop()\n cr1 = coreDNS.a_get_domain()\n cr2 = coreDNS.a_get_domain()\n tasks = [\n asyncio.ensure_future(cr1), \n asyncio.ensure_future(cr2)\n ]\n loop.run_until_complete(asyncio.wait(tasks))\n\n for task in tasks:\n print(task.result())\n","sub_path":"coredns.py","file_name":"coredns.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"226684415","text":"from pathlib import Path\nimport glob\nfrom importlib.resources import path, contents\n\nimport fiona\nimport numpy as np\nimport pandas as pd\n\nfrom .distance_calc import get_distances\n\ndef address_search(longitude: float, latitude: float, distance: float):\n with path(\"backend\", \"data\") as data_dir:\n files = [bytes(Path(file).absolute()) for file in glob.glob(str(data_dir.joinpath(\"parcels/*.shp\").absolute()))]\n all_distances = np.array([]) \n county_addresses = []\n for file in files:\n with fiona.open(file.decode()) as data:\n record_length = len(data)\n distances = get_distances(file, latitude, longitude, distance, record_length)\n record_positions = np.where(distances <= distance)\n with fiona.open(file.decode()) as data:\n file_records = []\n for location in record_positions[0].tolist():\n try:\n file_records.append(data[location][\"properties\"])\n except:\n print(type(location))\n print(location)\n print(file)\n county_addresses += file_records\n all_distances = np.concatenate([all_distances, distances[record_positions[0]]])\n data = pd.DataFrame(county_addresses)\n data[\"DISTANCE\"] = all_distances\n return data\n\n","sub_path":"webapp/backend/backend/geotools/path_calc.py","file_name":"path_calc.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"407474710","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport ConfigParser\nfrom hermes_python.hermes import Hermes\nfrom hermes_python.ontology import *\nimport io\n\nimport simplejson\nimport requests\nimport time \n\nCONFIGURATION_ENCODING_FORMAT = \"utf-8\"\nCONFIG_INI = \"config.ini\"\n\nclass SnipsConfigParser(ConfigParser.SafeConfigParser):\n def to_dict(self):\n return {section : {option_name : option for option_name, option in self.items(section)} for section in self.sections()}\n\n\ndef read_configuration_file(configuration_file):\n try:\n with io.open(configuration_file, encoding=CONFIGURATION_ENCODING_FORMAT) as f:\n conf_parser = SnipsConfigParser()\n conf_parser.readfp(f)\n return conf_parser.to_dict()\n except (IOError, ConfigParser.Error) as e:\n return dict()\n\ndef subscribe_intent_callback(hermes, intentMessage):\n conf = read_configuration_file(CONFIG_INI)\n action_wrapper(hermes, intentMessage, conf)\n\n\ndef action_wrapper(hermes, intentMessage, conf):\n\n addon_name = conf['global']['favorite_addon1'] \n movie_name = intentMessage.slots.tv_name.first().value\n addr_ = conf['global']['ip']\n port_ =conf['global']['port']\n \n def openAddon():\n request = \"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"Addons.ExecuteAddon\\\", \\\"params\\\": { \\\"addonid\\\": \\\"plugin.video.\" + addon_name + \"\\\", \\\"params\\\":{\\\"action\\\":\\\"alert\\\"}}, \\\"id\\\": \\\"1\\\"}\"\n url = \"http://\" + addr_ + \":\" + port_ + \"/jsonrpc?request=\" + request\n response = requests.get(url)\n json_data = simplejson.loads(response.text)\n \n\n def searchMovie():\n print(\"o\")\n request = \"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"Files.GetDirectory\\\", \\\"params\\\": { \\\"directory\\\": \\\"plugin://plugin.video.exodus/?action=tvSearchterm%26name=\" + movie_name + \"\\\"}, \\\"id\\\": 1 }\"\n url = \"http://\" + addr_ + \":\" + port_ + \"/jsonrpc?request=\" + request\n response = requests.get(url)\n json_data = simplejson.loads(response.text)\n\n try: \n openAddon()\n time.sleep(3)\n searchMovie()\n hermes.publish_end_session(intentMessage.session_id, \"\")\n except requests.exceptions.RequestException:\n hermes.publish_end_session(intentMessage.session_id, \"Erreur de connection.\")\n except Exception:\n hermes.publish_end_session(intentMessage.session_id, \"Erreur de l'application.\")\n\n\n\n\n\nif __name__ == \"__main__\":\n with Hermes(\"localhost:1883\") as h:\n h.subscribe_intent(\"Ianou:Search-tvshow\", subscribe_intent_callback) \\\n .start()","sub_path":"action-Search-tvshow.py","file_name":"action-Search-tvshow.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"378478411","text":"'''\n\nyxhu@ASLP-NPU in Sogou inc.\n\n'''\n\n\n\nimport torch.nn as nn\nimport torch \nimport torch.nn.functional as F\nimport os\nimport sys\nsys.path.append(os.path.dirname(__file__))\nfrom conv_stft import ConvSTFT, ConviSTFT\nfrom show import show_params\n\n\nclass FTB(nn.Module):\n\n def __init__(self, input_dim=257, in_channel=9, r_channel=5):\n\n super(FTB, self).__init__()\n self.in_channel = in_channel\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_channel, r_channel, kernel_size=[1,1]),\n nn.BatchNorm2d(r_channel),\n nn.ReLU()\n )\n \n self.conv1d = nn.Sequential(\n nn.Conv1d(r_channel*input_dim, in_channel, kernel_size=9,padding=4),\n nn.BatchNorm1d(in_channel),\n nn.ReLU()\n )\n self.freq_fc = nn.Linear(input_dim, input_dim, bias=False)\n\n self.conv2 = nn.Sequential(\n nn.Conv2d(in_channel*2, in_channel, kernel_size=[1,1]),\n nn.BatchNorm2d(in_channel),\n nn.ReLU()\n )\n\n def forward(self, inputs):\n '''\n inputs should be [Batch, Ca, Dim, Time]\n '''\n # T-F attention \n conv1_out = self.conv1(inputs)\n B, C, D, T= conv1_out.size()\n reshape1_out = torch.reshape(conv1_out,[B, C*D, T])\n conv1d_out = self.conv1d(reshape1_out)\n conv1d_out = torch.reshape(conv1d_out, [B, self.in_channel,1,T])\n \n # now is also [B,C,D,T]\n att_out = conv1d_out*inputs\n \n # tranpose to [B,C,T,D]\n att_out = torch.transpose(att_out, 2, 3)\n freqfc_out = self.freq_fc(att_out)\n att_out = torch.transpose(freqfc_out, 2, 3)\n\n cat_out = torch.cat([att_out, inputs], 1)\n outputs = self.conv2(cat_out)\n return outputs\n\n\nclass InforComu(nn.Module):\n \n def __init__(self, src_channel, tgt_channel):\n \n super(InforComu, self).__init__()\n self.comu_conv = nn.Conv2d(src_channel, tgt_channel, kernel_size=(1,1))\n \n def forward(self, src, tgt):\n \n outputs=tgt*torch.tanh(self.comu_conv(src))\n return outputs\n\n\nclass GLayerNorm2d(nn.Module):\n \n def __init__(self, in_channel, eps=1e-12):\n super(GLayerNorm2d, self).__init__()\n self.eps = eps \n self.beta = nn.Parameter(torch.ones([1, in_channel,1,1]))\n self.gamma = nn.Parameter(torch.zeros([1, in_channel,1,1]))\n \n def forward(self,inputs):\n mean = torch.mean(inputs,[1,2,3], keepdim=True)\n var = torch.var(inputs,[1,2,3], keepdim=True)\n outputs = (inputs - mean)/ torch.sqrt(var+self.eps)*self.beta+self.gamma\n return outputs\n\nclass TSB(nn.Module):\n\n def __init__(self, input_dim=257, channel_amp=9, channel_phase=8):\n super(TSB, self).__init__()\n \n self.ftb1 = FTB(input_dim=input_dim,\n in_channel=channel_amp,\n )\n self.amp_conv1 = nn.Sequential(\n nn.Conv2d(channel_amp, channel_amp, kernel_size=(5,5), padding=(2,2)),\n nn.BatchNorm2d(channel_amp),\n nn.ReLU()\n )\n self.amp_conv2 = nn.Sequential(\n nn.Conv2d(channel_amp, channel_amp, kernel_size=(1,25), padding=(0,12)),\n nn.BatchNorm2d(channel_amp),\n nn.ReLU()\n )\n self.amp_conv3 = nn.Sequential(\n nn.Conv2d(channel_amp, channel_amp, kernel_size=(5,5), padding=(2,2)),\n nn.BatchNorm2d(channel_amp),\n nn.ReLU()\n )\n \n self.ftb2 = FTB(input_dim=input_dim,\n in_channel=channel_amp,\n )\n\n self.phase_conv1 = nn.Sequential(\n nn.Conv2d(channel_phase, channel_phase, kernel_size=(5,5), padding=(2,2)),\n GLayerNorm2d(channel_phase),\n )\n self.phase_conv2 = nn.Sequential(\n nn.Conv2d(channel_phase, channel_phase, kernel_size=(1,25), padding=(0,12)),\n GLayerNorm2d(channel_phase),\n )\n\n self.p2a_comu = InforComu(channel_phase, channel_amp)\n self.a2p_comu = InforComu(channel_amp, channel_phase)\n\n def forward(self, amp, phase):\n '''\n amp should be [Batch, Ca, Dim, Time]\n amp should be [Batch, Cr, Dim, Time]\n \n '''\n \n amp_out1 = self.ftb1(amp)\n amp_out2 = self.amp_conv1(amp_out1)\n amp_out3 = self.amp_conv2(amp_out2)\n amp_out4 = self.amp_conv3(amp_out3)\n amp_out5 = self.ftb2(amp_out4)\n \n phase_out1 = self.phase_conv1(phase)\n phase_out2 = self.phase_conv2(phase_out1)\n \n amp_out = self.p2a_comu(phase_out2, amp_out5)\n phase_out = self.a2p_comu(amp_out5, phase_out2)\n \n return amp_out, phase_out\n\nclass PHASEN(nn.Module):\n\n def __init__(\n self,\n win_len=400,\n win_inc=100,\n fft_len=512,\n win_type='hanning', \n num_blocks=3,\n channel_amp=24,\n channel_phase=12,\n rnn_nums=300\n ):\n super(PHASEN, self).__init__() \n self.num_blocks = 3\n self.feat_dim = fft_len // 2 +1 \n \n self.win_len = win_len\n self.win_inc = win_inc\n self.fft_len = fft_len \n self.win_type = win_type \n\n fix = True\n self.stft = ConvSTFT(self.win_len, self.win_inc, self.fft_len, self.win_type, feature_type='complex', fix=fix)\n self.istft = ConviSTFT(self.win_len, self.win_inc, self.fft_len, self.win_type, feature_type='complex', fix=fix)\n \n self.amp_conv1 = nn.Sequential(\n nn.Conv2d(2, channel_amp, \n kernel_size=[7,1],\n padding=(3,0)\n ),\n nn.BatchNorm2d(channel_amp),\n nn.ReLU(),\n nn.Conv2d(channel_amp, channel_amp, \n kernel_size=[1,7],\n padding=(0,3)\n ),\n nn.BatchNorm2d(channel_amp),\n nn.ReLU(),\n )\n self.phase_conv1 = nn.Sequential(\n nn.Conv2d(2, channel_phase, \n kernel_size=[3,5],\n padding=(1,2)\n ),\n nn.Conv2d(channel_phase, channel_phase, \n kernel_size=[3,25],\n padding=(1, 12)\n ),\n )\n\n self.tsbs = nn.ModuleList()\n for idx in range(self.num_blocks):\n self.tsbs.append(\n TSB(input_dim=self.feat_dim,\n channel_amp=channel_amp,\n channel_phase=channel_phase\n )\n )\n \n self.amp_conv2 = nn.Sequential(\n nn.Conv2d(channel_amp, 8, kernel_size=[1, 1]),\n nn.BatchNorm2d(8),\n nn.ReLU(),\n )\n self.phase_conv2 = nn.Sequential(\n nn.Conv1d(channel_phase,2,kernel_size=[1,1])\n )\n self.rnn = nn.GRU(\n self.feat_dim * 8,\n rnn_nums,\n bidirectional=True\n )\n self.fcs = nn.Sequential(\n nn.Linear(rnn_nums*2,600),\n nn.ReLU(),\n nn.Linear(600,600),\n nn.ReLU(),\n nn.Linear(600,514//2),\n nn.Sigmoid()\n )\n show_params(self)\n \n def get_params(self, weight_decay=0.0):\n # add L2 penalty\n weights, biases = [], []\n for name, param in self.named_parameters():\n if 'bias' in name:\n biases += [param]\n else:\n weights += [param]\n params = [{\n 'params': weights,\n 'weight_decay': weight_decay,\n }, {\n 'params': biases,\n 'weight_decay': 0.0,\n }]\n return params\n\n\n def forward(self, inputs):\n # [B, D*2, T]\n cmp_spec = self.stft(inputs)\n cmp_spec = torch.unsqueeze(cmp_spec, 1)\n\n # to [B, 2, D, T]\n cmp_spec = torch.cat([\n cmp_spec[:,:,:self.feat_dim,:],\n cmp_spec[:,:,self.feat_dim:,:],\n ],\n 1)\n\n # to [B, 1, D, T]\n amp_spec = torch.sqrt(\n torch.abs(cmp_spec[:,0])**2+\n torch.abs(cmp_spec[:,1])**2,\n )\n amp_spec = torch.unsqueeze(amp_spec, 1)\n \n spec = self.amp_conv1(cmp_spec)\n phase = self.phase_conv1(cmp_spec)\n s_spec = spec\n s_phase = phase\n for idx, layer in enumerate(self.tsbs):\n if idx != 0:\n spec += s_spec\n phase += s_phase\n spec, phase = layer(spec, phase)\n spec = self.amp_conv2(spec)\n\n spec= torch.transpose(spec, 1,3)\n B, T, D, C = spec.size()\n spec = torch.reshape(spec, [B, T, D*C])\n spec = self.rnn(spec)[0]\n spec = self.fcs(spec)\n \n spec = torch.reshape(spec, [B,T,D,1]) \n spec = torch.transpose(spec, 1,3)\n \n phase = self.phase_conv2(phase)\n # norm to 1\n phase = phase/(torch.sqrt(\n torch.abs(phase[:,0])**2+\n torch.abs(phase[:,1])**2)\n +1e-8).unsqueeze(1)\n \n est_spec = amp_spec * spec * phase \n est_spec = torch.cat([est_spec[:,0], est_spec[:,1]], 1)\n est_wav = self.istft(est_spec)\n est_wav = torch.squeeze(est_wav, 1)\n #t = amp_spec \n return est_spec, est_wav# , [t[0], spec[0], phase[0]]\n \n def loss(self, est, labels, mode='Mix'):\n '''\n mode == 'Mix'\n est: [B, F*2, T]\n labels: [B, F*2,T]\n mode == 'SiSNR'\n est: [B, T]\n labels: [B, T]\n '''\n if mode == 'SiSNR':\n if labels.dim() == 3:\n labels = torch.squeeze(labels,1)\n if est.dim() == 3:\n est = torch.squeeze(est,1)\n return -si_snr(est, labels) \n elif mode == 'Mix':\n b, d, t = est.size()\n gth_cspec = self.stft(labels)\n est_cspec = est \n gth_mag_spec = torch.sqrt(\n gth_cspec[:, :self.feat_dim, :]**2\n +gth_cspec[:, self.feat_dim:, :]**2\n )\n est_mag_spec = torch.sqrt(\n est_cspec[:, :self.feat_dim, :]**2\n +est_cspec[:, self.feat_dim:, :]**2\n )\n \n # power compress \n gth_cprs_mag_spec = gth_mag_spec**0.3\n est_cprs_mag_spec = est_mag_spec**0.3\n amp_loss = F.mse_loss(\n gth_cprs_mag_spec, est_cprs_mag_spec\n )*d\n compress_coff = (gth_cprs_mag_spec/(1e-8+gth_mag_spec)).repeat(1,2,1)\n phase_loss = F.mse_loss(\n gth_cspec*compress_coff,\n est_cspec*compress_coff\n )*d\n \n all_loss = amp_loss*0.5 + phase_loss*0.5\n return all_loss, amp_loss, phase_loss\n\ndef remove_dc(data):\n mean = torch.mean(data, -1, keepdim=True) \n data = data - mean\n return data\ndef l2_norm(s1, s2):\n #norm = torch.sqrt(torch.sum(s1*s2, 1, keepdim=True))\n #norm = torch.norm(s1*s2, 1, keepdim=True)\n \n norm = torch.sum(s1*s2, -1, keepdim=True)\n return norm \n\ndef si_snr(s1, s2, eps=1e-8):\n #s1 = remove_dc(s1)\n #s2 = remove_dc(s2)\n s1_s2_norm = l2_norm(s1, s2)\n s2_s2_norm = l2_norm(s2, s2)\n s_target = s1_s2_norm/(s2_s2_norm+eps)*s2\n e_nosie = s1 - s_target\n target_norm = l2_norm(s_target, s_target)\n noise_norm = l2_norm(e_nosie, e_nosie)\n snr = 10*torch.log10((target_norm)/(noise_norm+eps)+eps)\n return torch.mean(snr)\n\n\n\ndef test_ftb():\n torch.manual_seed(20)\n inputs = torch.randn([10,9, 257, 100])\n net = FTB()\n print(net(inputs).shape)\n\ndef test_tsb():\n torch.manual_seed(20)\n inputs = torch.randn([10,9, 257, 100])\n phase = torch.randn([10,8,257,100])\n net = TSB()\n out1, out2 = net(inputs, phase)\n print(out1.shape, out2.shape)\n\ndef test_PHASEN():\n torch.manual_seed(20)\n inputs = torch.randn([10,1,16000*4])\n wav_label = torch.randn([10, 16000*4])\n net = PHASEN()\n est_spec, est_wav = net(inputs)\n print(est_spec.shape, est_wav.shape)\n sisnr = net.loss(est_wav, wav_label, mode='SiSNR')\n Mix = net.loss(est_spec, wav_label, mode='Mix')\n print('mix:',Mix, 'SNR:', sisnr)\n\n#test_ftb()\n#test_tsb()\n#test_PHASEN()\n\nif __name__ == '__main__':\n test_PHASEN()\n\n","sub_path":"model/phasen.py","file_name":"phasen.py","file_ext":"py","file_size_in_byte":13864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"97058021","text":"import trio\nimport triogram\n\n\ndef text_message(update):\n return \"message\" in update and \"text\" in update[\"message\"]\n\n\nasync def echo(bot):\n \"\"\"\n Waits for new messages and sends the received text back.\n \"\"\"\n async with bot.sub(text_message) as updates:\n async for update in updates:\n await bot.api.send_message(\n params={\n \"chat_id\": update[\"message\"][\"chat\"][\"id\"],\n \"text\": update[\"message\"][\"text\"],\n }\n )\n\n\nasync def echo_once(bot):\n \"\"\"\n Waits for a new message and sends the received text back exactly once.\n \"\"\"\n update = await bot.wait(text_message)\n await bot.api.send_message(\n params={\n \"chat_id\": update[\"message\"][\"chat\"][\"id\"],\n \"text\": update[\"message\"][\"text\"],\n }\n )\n\n\nasync def main():\n \"\"\"\n Starts the bot and event handlers.\n \"\"\"\n bot = triogram.make_bot()\n async with bot, trio.open_nursery() as nursery:\n nursery.start_soon(bot)\n nursery.start_soon(echo, bot)\n nursery.start_soon(echo_once, bot)\n\n\nif __name__ == \"__main__\":\n trio.run(main)\n","sub_path":"examples/echo.py","file_name":"echo.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"122658776","text":"from datetime import datetime\nfrom time import mktime\nimport __builtin__\n\n\nclass CampaignStats(object):\n class Builder:\n def __init__(\n self,\n syntax_errors,\n hard_bounces,\n soft_bounces,\n unsubscribes,\n abuse_reports,\n forwards,\n forwards_opens,\n opens,\n unique_opens,\n clicks,\n unique_clicks,\n users_who_clicked,\n emails_sent,\n unique_likes,\n recipient_likes,\n facebook_likes,\n last_open=None,\n last_click=None\n ):\n self.__syntax_errors = syntax_errors\n self.__hard_bounces = hard_bounces\n self.__soft_bounces = soft_bounces\n self.__unsubscribes = unsubscribes\n self.__abuse_reports = abuse_reports\n self.__forwards = forwards\n self.__forwards_opens = forwards_opens\n self.__opens = opens\n self.__last_open = last_open\n self.__unique_opens = unique_opens\n self.__clicks = clicks\n self.__unique_clicks = unique_clicks\n self.__last_click = last_click\n self.__users_who_clicked = users_who_clicked\n self.__emails_sent = emails_sent\n self.__unique_likes = unique_likes\n self.__recipient_likes = recipient_likes\n self.__facebook_likes = facebook_likes\n\n def build(self):\n return CampaignStats(syntax_errors=self.__syntax_errors, hard_bounces=self.__hard_bounces, soft_bounces=self.__soft_bounces, unsubscribes=self.__unsubscribes, abuse_reports=self.__abuse_reports, forwards=self.__forwards, forwards_opens=self.__forwards_opens, opens=self.__opens, last_open=self.__last_open, unique_opens=self.__unique_opens, clicks=self.__clicks, unique_clicks=self.__unique_clicks, last_click=self.__last_click, users_who_clicked=self.__users_who_clicked, emails_sent=self.__emails_sent, unique_likes=self.__unique_likes, recipient_likes=self.__recipient_likes, facebook_likes=self.__facebook_likes)\n\n def set_abuse_reports(self, abuse_reports):\n self.__abuse_reports = abuse_reports\n return self\n\n def set_clicks(self, clicks):\n self.__clicks = clicks\n return self\n\n def set_emails_sent(self, emails_sent):\n self.__emails_sent = emails_sent\n return self\n\n def set_facebook_likes(self, facebook_likes):\n self.__facebook_likes = facebook_likes\n return self\n\n def set_forwards(self, forwards):\n self.__forwards = forwards\n return self\n\n def set_forwards_opens(self, forwards_opens):\n self.__forwards_opens = forwards_opens\n return self\n\n def set_hard_bounces(self, hard_bounces):\n self.__hard_bounces = hard_bounces\n return self\n\n def set_last_click(self, last_click):\n self.__last_click = last_click\n return self\n\n def set_last_open(self, last_open):\n self.__last_open = last_open\n return self\n\n def set_opens(self, opens):\n self.__opens = opens\n return self\n\n def set_recipient_likes(self, recipient_likes):\n self.__recipient_likes = recipient_likes\n return self\n\n def set_soft_bounces(self, soft_bounces):\n self.__soft_bounces = soft_bounces\n return self\n\n def set_syntax_errors(self, syntax_errors):\n self.__syntax_errors = syntax_errors\n return self\n\n def set_unique_clicks(self, unique_clicks):\n self.__unique_clicks = unique_clicks\n return self\n\n def set_unique_likes(self, unique_likes):\n self.__unique_likes = unique_likes\n return self\n\n def set_unique_opens(self, unique_opens):\n self.__unique_opens = unique_opens\n return self\n\n def set_unsubscribes(self, unsubscribes):\n self.__unsubscribes = unsubscribes\n return self\n\n def set_users_who_clicked(self, users_who_clicked):\n self.__users_who_clicked = users_who_clicked\n return self\n\n def update(self, campaign_stats):\n if isinstance(campaign_stats, CampaignStats):\n self.set_syntax_errors(campaign_stats.syntax_errors)\n self.set_hard_bounces(campaign_stats.hard_bounces)\n self.set_soft_bounces(campaign_stats.soft_bounces)\n self.set_unsubscribes(campaign_stats.unsubscribes)\n self.set_abuse_reports(campaign_stats.abuse_reports)\n self.set_forwards(campaign_stats.forwards)\n self.set_forwards_opens(campaign_stats.forwards_opens)\n self.set_opens(campaign_stats.opens)\n self.set_last_open(campaign_stats.last_open)\n self.set_unique_opens(campaign_stats.unique_opens)\n self.set_clicks(campaign_stats.clicks)\n self.set_unique_clicks(campaign_stats.unique_clicks)\n self.set_last_click(campaign_stats.last_click)\n self.set_users_who_clicked(campaign_stats.users_who_clicked)\n self.set_emails_sent(campaign_stats.emails_sent)\n self.set_unique_likes(campaign_stats.unique_likes)\n self.set_recipient_likes(campaign_stats.recipient_likes)\n self.set_facebook_likes(campaign_stats.facebook_likes)\n elif isinstance(campaign_stats, dict):\n for key, value in campaign_stats.iteritems():\n getattr(self, 'set_' + key)(value)\n else:\n raise TypeError(campaign_stats)\n return self\n\n def __init__(\n self,\n syntax_errors,\n hard_bounces,\n soft_bounces,\n unsubscribes,\n abuse_reports,\n forwards,\n forwards_opens,\n opens,\n unique_opens,\n clicks,\n unique_clicks,\n users_who_clicked,\n emails_sent,\n unique_likes,\n recipient_likes,\n facebook_likes,\n last_open=None,\n last_click=None\n ):\n if syntax_errors is None:\n raise ValueError('syntax_errors is required')\n if not isinstance(syntax_errors, int):\n raise TypeError(getattr(__builtin__, 'type')(syntax_errors))\n self.__syntax_errors = syntax_errors\n\n if hard_bounces is None:\n raise ValueError('hard_bounces is required')\n if not isinstance(hard_bounces, int):\n raise TypeError(getattr(__builtin__, 'type')(hard_bounces))\n self.__hard_bounces = hard_bounces\n\n if soft_bounces is None:\n raise ValueError('soft_bounces is required')\n if not isinstance(soft_bounces, int):\n raise TypeError(getattr(__builtin__, 'type')(soft_bounces))\n self.__soft_bounces = soft_bounces\n\n if unsubscribes is None:\n raise ValueError('unsubscribes is required')\n if not isinstance(unsubscribes, int):\n raise TypeError(getattr(__builtin__, 'type')(unsubscribes))\n self.__unsubscribes = unsubscribes\n\n if abuse_reports is None:\n raise ValueError('abuse_reports is required')\n if not isinstance(abuse_reports, int):\n raise TypeError(getattr(__builtin__, 'type')(abuse_reports))\n self.__abuse_reports = abuse_reports\n\n if forwards is None:\n raise ValueError('forwards is required')\n if not isinstance(forwards, int):\n raise TypeError(getattr(__builtin__, 'type')(forwards))\n self.__forwards = forwards\n\n if forwards_opens is None:\n raise ValueError('forwards_opens is required')\n if not isinstance(forwards_opens, int):\n raise TypeError(getattr(__builtin__, 'type')(forwards_opens))\n self.__forwards_opens = forwards_opens\n\n if opens is None:\n raise ValueError('opens is required')\n if not isinstance(opens, int):\n raise TypeError(getattr(__builtin__, 'type')(opens))\n self.__opens = opens\n\n if last_open is not None:\n if not isinstance(last_open, datetime):\n raise TypeError(getattr(__builtin__, 'type')(last_open))\n self.__last_open = last_open\n\n if unique_opens is None:\n raise ValueError('unique_opens is required')\n if not isinstance(unique_opens, int):\n raise TypeError(getattr(__builtin__, 'type')(unique_opens))\n self.__unique_opens = unique_opens\n\n if clicks is None:\n raise ValueError('clicks is required')\n if not isinstance(clicks, int):\n raise TypeError(getattr(__builtin__, 'type')(clicks))\n self.__clicks = clicks\n\n if unique_clicks is None:\n raise ValueError('unique_clicks is required')\n if not isinstance(unique_clicks, int):\n raise TypeError(getattr(__builtin__, 'type')(unique_clicks))\n self.__unique_clicks = unique_clicks\n\n if last_click is not None:\n if not isinstance(last_click, datetime):\n raise TypeError(getattr(__builtin__, 'type')(last_click))\n self.__last_click = last_click\n\n if users_who_clicked is None:\n raise ValueError('users_who_clicked is required')\n if not isinstance(users_who_clicked, int):\n raise TypeError(getattr(__builtin__, 'type')(users_who_clicked))\n self.__users_who_clicked = users_who_clicked\n\n if emails_sent is None:\n raise ValueError('emails_sent is required')\n if not isinstance(emails_sent, int):\n raise TypeError(getattr(__builtin__, 'type')(emails_sent))\n self.__emails_sent = emails_sent\n\n if unique_likes is None:\n raise ValueError('unique_likes is required')\n if not isinstance(unique_likes, int):\n raise TypeError(getattr(__builtin__, 'type')(unique_likes))\n self.__unique_likes = unique_likes\n\n if recipient_likes is None:\n raise ValueError('recipient_likes is required')\n if not isinstance(recipient_likes, int):\n raise TypeError(getattr(__builtin__, 'type')(recipient_likes))\n self.__recipient_likes = recipient_likes\n\n if facebook_likes is None:\n raise ValueError('facebook_likes is required')\n if not isinstance(facebook_likes, int):\n raise TypeError(getattr(__builtin__, 'type')(facebook_likes))\n self.__facebook_likes = facebook_likes\n\n def __eq__(self, other):\n if self.syntax_errors != other.syntax_errors:\n return False\n if self.hard_bounces != other.hard_bounces:\n return False\n if self.soft_bounces != other.soft_bounces:\n return False\n if self.unsubscribes != other.unsubscribes:\n return False\n if self.abuse_reports != other.abuse_reports:\n return False\n if self.forwards != other.forwards:\n return False\n if self.forwards_opens != other.forwards_opens:\n return False\n if self.opens != other.opens:\n return False\n if self.last_open != other.last_open:\n return False\n if self.unique_opens != other.unique_opens:\n return False\n if self.clicks != other.clicks:\n return False\n if self.unique_clicks != other.unique_clicks:\n return False\n if self.last_click != other.last_click:\n return False\n if self.users_who_clicked != other.users_who_clicked:\n return False\n if self.emails_sent != other.emails_sent:\n return False\n if self.unique_likes != other.unique_likes:\n return False\n if self.recipient_likes != other.recipient_likes:\n return False\n if self.facebook_likes != other.facebook_likes:\n return False\n return True\n\n def __hash__(self):\n return hash((self.syntax_errors,self.hard_bounces,self.soft_bounces,self.unsubscribes,self.abuse_reports,self.forwards,self.forwards_opens,self.opens,self.last_open,self.unique_opens,self.clicks,self.unique_clicks,self.last_click,self.users_who_clicked,self.emails_sent,self.unique_likes,self.recipient_likes,self.facebook_likes,))\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __repr__(self):\n field_reprs = []\n field_reprs.append('syntax_errors=' + repr(self.syntax_errors))\n field_reprs.append('hard_bounces=' + repr(self.hard_bounces))\n field_reprs.append('soft_bounces=' + repr(self.soft_bounces))\n field_reprs.append('unsubscribes=' + repr(self.unsubscribes))\n field_reprs.append('abuse_reports=' + repr(self.abuse_reports))\n field_reprs.append('forwards=' + repr(self.forwards))\n field_reprs.append('forwards_opens=' + repr(self.forwards_opens))\n field_reprs.append('opens=' + repr(self.opens))\n if self.last_open is not None:\n field_reprs.append('last_open=' + repr(self.last_open))\n field_reprs.append('unique_opens=' + repr(self.unique_opens))\n field_reprs.append('clicks=' + repr(self.clicks))\n field_reprs.append('unique_clicks=' + repr(self.unique_clicks))\n if self.last_click is not None:\n field_reprs.append('last_click=' + repr(self.last_click))\n field_reprs.append('users_who_clicked=' + repr(self.users_who_clicked))\n field_reprs.append('emails_sent=' + repr(self.emails_sent))\n field_reprs.append('unique_likes=' + repr(self.unique_likes))\n field_reprs.append('recipient_likes=' + repr(self.recipient_likes))\n field_reprs.append('facebook_likes=' + repr(self.facebook_likes))\n return 'CampaignStats(' + ', '.join(field_reprs) + ')'\n\n def __str__(self):\n field_reprs = []\n field_reprs.append('syntax_errors=' + repr(self.syntax_errors))\n field_reprs.append('hard_bounces=' + repr(self.hard_bounces))\n field_reprs.append('soft_bounces=' + repr(self.soft_bounces))\n field_reprs.append('unsubscribes=' + repr(self.unsubscribes))\n field_reprs.append('abuse_reports=' + repr(self.abuse_reports))\n field_reprs.append('forwards=' + repr(self.forwards))\n field_reprs.append('forwards_opens=' + repr(self.forwards_opens))\n field_reprs.append('opens=' + repr(self.opens))\n if self.last_open is not None:\n field_reprs.append('last_open=' + repr(self.last_open))\n field_reprs.append('unique_opens=' + repr(self.unique_opens))\n field_reprs.append('clicks=' + repr(self.clicks))\n field_reprs.append('unique_clicks=' + repr(self.unique_clicks))\n if self.last_click is not None:\n field_reprs.append('last_click=' + repr(self.last_click))\n field_reprs.append('users_who_clicked=' + repr(self.users_who_clicked))\n field_reprs.append('emails_sent=' + repr(self.emails_sent))\n field_reprs.append('unique_likes=' + repr(self.unique_likes))\n field_reprs.append('recipient_likes=' + repr(self.recipient_likes))\n field_reprs.append('facebook_likes=' + repr(self.facebook_likes))\n return 'CampaignStats(' + ', '.join(field_reprs) + ')'\n\n @property\n def abuse_reports(self):\n return self.__abuse_reports\n\n def as_dict(self):\n return {'syntax_errors': self.syntax_errors, 'hard_bounces': self.hard_bounces, 'soft_bounces': self.soft_bounces, 'unsubscribes': self.unsubscribes, 'abuse_reports': self.abuse_reports, 'forwards': self.forwards, 'forwards_opens': self.forwards_opens, 'opens': self.opens, 'last_open': self.last_open, 'unique_opens': self.unique_opens, 'clicks': self.clicks, 'unique_clicks': self.unique_clicks, 'last_click': self.last_click, 'users_who_clicked': self.users_who_clicked, 'emails_sent': self.emails_sent, 'unique_likes': self.unique_likes, 'recipient_likes': self.recipient_likes, 'facebook_likes': self.facebook_likes}\n\n @property\n def clicks(self):\n return self.__clicks\n\n @property\n def emails_sent(self):\n return self.__emails_sent\n\n @property\n def facebook_likes(self):\n return self.__facebook_likes\n\n @property\n def forwards(self):\n return self.__forwards\n\n @property\n def forwards_opens(self):\n return self.__forwards_opens\n\n @property\n def hard_bounces(self):\n return self.__hard_bounces\n\n @property\n def last_click(self):\n return self.__last_click\n\n @property\n def last_open(self):\n return self.__last_open\n\n @property\n def opens(self):\n return self.__opens\n\n @classmethod\n def read(cls, iprot):\n init_kwds = {}\n\n iprot.readStructBegin()\n while True:\n ifield_name, ifield_type, _ifield_id = iprot.readFieldBegin()\n if ifield_type == 0: # STOP\n break\n elif ifield_name == 'syntax_errors':\n init_kwds['syntax_errors'] = iprot.readI32()\n elif ifield_name == 'hard_bounces':\n init_kwds['hard_bounces'] = iprot.readI32()\n elif ifield_name == 'soft_bounces':\n init_kwds['soft_bounces'] = iprot.readI32()\n elif ifield_name == 'unsubscribes':\n init_kwds['unsubscribes'] = iprot.readI32()\n elif ifield_name == 'abuse_reports':\n init_kwds['abuse_reports'] = iprot.readI32()\n elif ifield_name == 'forwards':\n init_kwds['forwards'] = iprot.readI32()\n elif ifield_name == 'forwards_opens':\n init_kwds['forwards_opens'] = iprot.readI32()\n elif ifield_name == 'opens':\n init_kwds['opens'] = iprot.readI32()\n elif ifield_name == 'last_open':\n try:\n init_kwds['last_open'] = iprot.readDateTime()\n except (TypeError,):\n pass\n elif ifield_name == 'unique_opens':\n init_kwds['unique_opens'] = iprot.readI32()\n elif ifield_name == 'clicks':\n init_kwds['clicks'] = iprot.readI32()\n elif ifield_name == 'unique_clicks':\n init_kwds['unique_clicks'] = iprot.readI32()\n elif ifield_name == 'last_click':\n try:\n init_kwds['last_click'] = iprot.readDateTime()\n except (TypeError,):\n pass\n elif ifield_name == 'users_who_clicked':\n init_kwds['users_who_clicked'] = iprot.readI32()\n elif ifield_name == 'emails_sent':\n init_kwds['emails_sent'] = iprot.readI32()\n elif ifield_name == 'unique_likes':\n init_kwds['unique_likes'] = iprot.readI32()\n elif ifield_name == 'recipient_likes':\n init_kwds['recipient_likes'] = iprot.readI32()\n elif ifield_name == 'facebook_likes':\n init_kwds['facebook_likes'] = iprot.readI32()\n iprot.readFieldEnd()\n iprot.readStructEnd()\n\n return cls(**init_kwds)\n\n @property\n def recipient_likes(self):\n return self.__recipient_likes\n\n def replace(self, syntax_errors=None, hard_bounces=None, soft_bounces=None, unsubscribes=None, abuse_reports=None, forwards=None, forwards_opens=None, opens=None, last_open=None, unique_opens=None, clicks=None, unique_clicks=None, last_click=None, users_who_clicked=None, emails_sent=None, unique_likes=None, recipient_likes=None, facebook_likes=None):\n if syntax_errors is None:\n syntax_errors = self.syntax_errors\n if hard_bounces is None:\n hard_bounces = self.hard_bounces\n if soft_bounces is None:\n soft_bounces = self.soft_bounces\n if unsubscribes is None:\n unsubscribes = self.unsubscribes\n if abuse_reports is None:\n abuse_reports = self.abuse_reports\n if forwards is None:\n forwards = self.forwards\n if forwards_opens is None:\n forwards_opens = self.forwards_opens\n if opens is None:\n opens = self.opens\n if last_open is None:\n last_open = self.last_open\n if unique_opens is None:\n unique_opens = self.unique_opens\n if clicks is None:\n clicks = self.clicks\n if unique_clicks is None:\n unique_clicks = self.unique_clicks\n if last_click is None:\n last_click = self.last_click\n if users_who_clicked is None:\n users_who_clicked = self.users_who_clicked\n if emails_sent is None:\n emails_sent = self.emails_sent\n if unique_likes is None:\n unique_likes = self.unique_likes\n if recipient_likes is None:\n recipient_likes = self.recipient_likes\n if facebook_likes is None:\n facebook_likes = self.facebook_likes\n return self.__class__(syntax_errors=syntax_errors, hard_bounces=hard_bounces, soft_bounces=soft_bounces, unsubscribes=unsubscribes, abuse_reports=abuse_reports, forwards=forwards, forwards_opens=forwards_opens, opens=opens, last_open=last_open, unique_opens=unique_opens, clicks=clicks, unique_clicks=unique_clicks, last_click=last_click, users_who_clicked=users_who_clicked, emails_sent=emails_sent, unique_likes=unique_likes, recipient_likes=recipient_likes, facebook_likes=facebook_likes)\n\n @property\n def soft_bounces(self):\n return self.__soft_bounces\n\n @property\n def syntax_errors(self):\n return self.__syntax_errors\n\n @property\n def unique_clicks(self):\n return self.__unique_clicks\n\n @property\n def unique_likes(self):\n return self.__unique_likes\n\n @property\n def unique_opens(self):\n return self.__unique_opens\n\n @property\n def unsubscribes(self):\n return self.__unsubscribes\n\n @property\n def users_who_clicked(self):\n return self.__users_who_clicked\n\n def write(self, oprot):\n oprot.writeStructBegin('CampaignStats')\n\n oprot.writeFieldBegin('syntax_errors', 8, -1)\n oprot.writeI32(self.syntax_errors)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('hard_bounces', 8, -1)\n oprot.writeI32(self.hard_bounces)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('soft_bounces', 8, -1)\n oprot.writeI32(self.soft_bounces)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('unsubscribes', 8, -1)\n oprot.writeI32(self.unsubscribes)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('abuse_reports', 8, -1)\n oprot.writeI32(self.abuse_reports)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('forwards', 8, -1)\n oprot.writeI32(self.forwards)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('forwards_opens', 8, -1)\n oprot.writeI32(self.forwards_opens)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('opens', 8, -1)\n oprot.writeI32(self.opens)\n oprot.writeFieldEnd()\n\n if self.last_open is not None:\n oprot.writeFieldBegin('last_open', 12, -1)\n oprot.writeDateTime(self.last_open)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('unique_opens', 8, -1)\n oprot.writeI32(self.unique_opens)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('clicks', 8, -1)\n oprot.writeI32(self.clicks)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('unique_clicks', 8, -1)\n oprot.writeI32(self.unique_clicks)\n oprot.writeFieldEnd()\n\n if self.last_click is not None:\n oprot.writeFieldBegin('last_click', 12, -1)\n oprot.writeDateTime(self.last_click)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('users_who_clicked', 8, -1)\n oprot.writeI32(self.users_who_clicked)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('emails_sent', 8, -1)\n oprot.writeI32(self.emails_sent)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('unique_likes', 8, -1)\n oprot.writeI32(self.unique_likes)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('recipient_likes', 8, -1)\n oprot.writeI32(self.recipient_likes)\n oprot.writeFieldEnd()\n\n oprot.writeFieldBegin('facebook_likes', 8, -1)\n oprot.writeI32(self.facebook_likes)\n oprot.writeFieldEnd()\n\n oprot.writeFieldStop()\n\n oprot.writeStructEnd()\n\n return self\n","sub_path":"py/src/yochimp/models/campaign/campaign_stats.py","file_name":"campaign_stats.py","file_ext":"py","file_size_in_byte":24703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"154502456","text":"# Copyright (c) 2020 Karl Sundequist Blomdahl \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport tensorflow as tf\nimport unittest\n\nfrom .model_fn import model_fn\nfrom .layers import NUM_FEATURES\n\nclass ModelFnTest(unittest.TestCase):\n def setUp(self):\n self.batch_size = 16\n self.features = tf.compat.v1.placeholder(tf.float16, [self.batch_size, 19, 19, NUM_FEATURES])\n self.labels = {\n 'lz_features': tf.compat.v1.placeholder(tf.float16, [self.batch_size, 19, 19, 18]),\n 'value': tf.compat.v1.placeholder(tf.float32, [self.batch_size, 1]),\n 'policy': tf.compat.v1.placeholder(tf.float32, [self.batch_size, 362]),\n 'next_policy': tf.compat.v1.placeholder(tf.float32, [self.batch_size, 362]),\n 'boost': tf.compat.v1.placeholder(tf.float32, [self.batch_size, 1]),\n 'ownership': tf.compat.v1.placeholder(tf.float32, [self.batch_size, 361]),\n 'has_ownership': tf.compat.v1.placeholder(tf.float32, [self.batch_size, 1]),\n }\n self.spec = model_fn(self.features, self.labels, self.mode, self.params)\n\n @property\n def mode(self):\n return tf.estimator.ModeKeys.TRAIN\n\n @property\n def params(self):\n return {\n 'num_blocks': 6,\n 'num_channels': 64,\n 'learning_rate': 1e-4,\n 'num_samples': 8,\n 'model_name': 'test'\n }\n\n def tearDown(self):\n tf.compat.v1.reset_default_graph()\n\n def test_mode(self):\n self.assertEqual(self.spec.mode, self.mode)\n\n def test_shape(self):\n self.assertEqual(self.spec.loss.shape, [])\n\n def test_data_type(self):\n self.assertEqual(self.spec.loss.dtype, tf.float32)\n\n\nclass LzModelFnTest(ModelFnTest, unittest.TestCase):\n @property\n def params(self):\n return {\n 'num_blocks': 6,\n 'num_channels': 64,\n 'learning_rate': 1e-4,\n 'num_samples': 8,\n 'lz_weights': 'fixtures/d645af9.gz',\n 'model_name': 'test'\n }\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"contrib/trainer/dream_tf/test_model_fn.py","file_name":"test_model_fn.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"99345060","text":"a= int(input())\nb= {}\n\nfor _ in range(a):\n w = input()\n if w in b.keys():\n b[w]+=1\n else:\n b.update({w:1})\n\nprint(len(b.keys()))\nprint(*b.values())\n\n","sub_path":"task1unicode.py","file_name":"task1unicode.py","file_ext":"py","file_size_in_byte":158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"470398112","text":"# 游戏的精灵类\nimport pygame as pg\nfrom settings import *\nvec = pg.math.Vector2\n\nclass Spritesheet:\n def __init__(self,filename):\n self.spritesheet = pg.image.load(filename).convert()\n\n def get_image(self,x,y,width,height):\n image = pg.Surface((width,height))\n image.blit(self.spritesheet,(0,0),(x,y,width,height))\n image = pg.transform.scale(image,(width//2,height//2))\n return image\n\nclass Player(pg.sprite.Sprite):\n def __init__(self,game):\n pg.sprite.Sprite.__init__(self)\n self.game = game\n self.walking = False\n self.jumping = False\n self.current_frame = 0\n self.last_update = 0\n self.load_images()\n self.image =self.standing_frames[0]\n self.rect = self.image.get_rect()\n self.rect.center = (WIDTH/2 , HEIGHT/2)\n self.pos = vec(WIDTH/2,HEIGHT/2)\n self.vel = vec(0,0)\n self.acc = vec(0,0)\n\n def load_images(self):\n self.standing_frames = [self.game.spritesheet.get_image(0,360,70,70),\n self.game.spritesheet.get_image(0,216,70,70)]\n for frame in self.standing_frames:\n frame.set_colorkey(BLACK)\n self.walk_frames_r = [self.game.spritesheet.get_image(0,864,70,70),\n self.game.spritesheet.get_image(0,792,70,70)]\n self.walk_frames_l = []\n for frame in self.walk_frames_r:\n self.walk_frames_l.append(pg.transform.flip(frame,True,False))\n self.jump_frame = self.game.spritesheet.get_image(0,720,70,70)\n\n def jump(self):\n self.rect.x += 1\n hits = pg.sprite.spritecollide(self,self.game.platforms,False)\n self.rect.x -=1\n if hits:\n self.vel.y = -15\n\n def update(self):\n self.animate()\n self.acc = vec(0,0.5)\n keys = pg.key.get_pressed()\n if keys[pg.K_LEFT]:\n self.acc.x = -PLAYER_ACC\n if keys[pg.K_RIGHT]:\n self.acc.x = PLAYER_ACC\n\n if keys[pg.K_SPACE]:\n self.jump()\n self.game.jump_sound.play()\n\n self.acc.x += self.vel.x * PLAYER_FRICTION\n self.vel += self.acc\n if abs(self.vel.x) < 0.1:\n self.vel.x = 0\n self.pos += self.vel + 0.5*self.acc\n\n #出格返回\n if self.pos.x > WIDTH:\n self.pos.x = 0\n if self.pos.x < 0:\n self.pos.x = WIDTH\n self.rect.midbottom = self.pos\n\n def animate(self):\n now = pg.time.get_ticks()\n if self.vel.x != 0:\n self.walking = True\n else:\n self.walking = False\n\n if self.walking:\n if now - self.last_update > 200 :\n self.last_update = now\n self.current_frame = (self.current_frame + 1) % len(self.walk_frames_l)\n bottom = self.rect.bottom\n if self.vel.x > 0:\n self.image = self.walk_frames_r[self.current_frame]\n else:\n self.image = self.walk_frames_l[self.current_frame]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n\n if not self.jumping and not self.walking:\n if now - self.last_update > 350 :\n self.last_update = now\n self.current_frame = (self.current_frame + 1) % len(self.standing_frames)\n bottom = self.rect.bottom\n self.image = self.standing_frames[self.current_frame]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n\n\nclass Platform(pg.sprite.Sprite):\n def __init__(self,x,y,w,h):\n pg.sprite.Sprite.__init__(self)\n self.image = pg.Surface((w,h))\n self.image.fill((BLUE))\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"557932764","text":"from django.core.management import BaseCommand\nfrom ContentScraper.utils import get_fear_and_greed_data\nfrom ContentScraper.models import Fear_and_Greed_Index\nfrom django.utils.timezone import now\nimport logging\n\nLOGLEVEL = logging.INFO\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=LOGLEVEL)\nlogger = logging.getLogger(__name__)\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n logger.info('Updating Fear and Greed Index')\n data = get_fear_and_greed_data()['data'][0]\n fgi = Fear_and_Greed_Index(\n value=data['value'],\n value_classification=data['value_classification'],\n update_time=now()\n )\n fgi.save()\n logger.info('Done Updating Fear and Greed Index')","sub_path":"ContentScraper/management/commands/UpdateFearAndGreed.py","file_name":"UpdateFearAndGreed.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"557063849","text":"import json\n\nmimetype = 'application/json'\nheaders = {\n 'Content-Type': mimetype,\n 'Accept': mimetype\n}\n\n\ndef test_error_radius(client):\n\n error_data = {\n \"count\": 5,\n \"position\": {\"lat\": 45.222, \"lng\": 333.33}\n }\n res = client.post('/search', data=json.dumps(error_data), headers=headers)\n assert res.status_code == 400\n assert res.json['error'] == \"radius is required\"\n\n\ndef test_error_count(client):\n\n error_data = {\n \"radius\": 543,\n \"position\": {\"lat\": 45.222, \"lng\": 333.33}\n }\n res = client.post('/search', data=json.dumps(error_data), headers=headers)\n assert res.status_code == 400\n assert res.json['error'] == \"count is required\"\n\n\ndef test_error_position(client):\n\n error_data = {\n \"radius\": 543,\n \"count\": 3\n }\n res = client.post('/search', data=json.dumps(error_data), headers=headers)\n assert res.status_code == 400\n assert res.json['error'] == \"position is required\"\n\n\ndef test_error_lat(client):\n\n error_data = {\n \"radius\": 543,\n \"count\": 3,\n \"position\": {\"lng\": 45.222}\n }\n res = client.post('/search', data=json.dumps(error_data), headers=headers)\n assert res.status_code == 400\n assert res.json['error'] == \"position should have lat, lng\"\n\n\ndef test_error_tags_type(client):\n\n error_data = {\n \"radius\": 543,\n \"count\": 3,\n \"tags\": \"not valid type\",\n \"position\": {\"lng\": 45.222, \"lat\": 45.33}\n }\n res = client.post('/search', data=json.dumps(error_data), headers=headers)\n assert res.status_code == 400\n assert res.json['error'] == \"tags should be a list\"\n\n\ndef test_return_structure(client):\n\n valid_data = {\n \"radius\": 200,\n \"count\": 5,\n \"position\": {\"lng\": 45.222, \"lat\": 45.33}\n }\n res = client.post('/search', data=json.dumps(valid_data), headers=headers)\n assert res.status_code == 200\n assert isinstance(res.json['products'], list)\n\n\ndef test_crash(client):\n\n error_data = {\n \"radius\": 200,\n \"count\": \"OOOPPPPSSSS\",\n \"position\": {\"lng\": 45.222, \"lat\": 45.33}\n }\n res = client.post('/search', data=json.dumps(error_data), headers=headers)\n assert res.status_code == 503\n assert res.json['error'] == 'service unavailable'\n\n\ndef test_tags(client):\n\n stockholm = {\n \"radius\": 2000,\n \"count\": 50,\n \"tags\": [\"women\"],\n \"position\": {\"lng\": 18.06, \"lat\": 59.33}\n }\n res = client.post('/search', data=json.dumps(stockholm), headers=headers)\n assert res.status_code == 200\n tags = set(map(lambda x: x.get('tag'), res.json['products']))\n assert len(tags) == 1","sub_path":"tests/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"26310337","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport argparse\nimport textwrap\nimport platform\n\nfrom tools.helpers import manager as helpers_manager\nfrom tools import extraction_tool, case_manager\nfrom engine import process_engine\nfrom modules import manager as modules_manager\n\nfrom utility import database\nfrom utility import database_sqlite # for standalone version\nfrom utility import errors\nfrom utility import loggers\n\n\nclass CarpeTool(extraction_tool.ExtractionTool,\n case_manager.CaseManager):\n \"\"\"Carpe CLI tool.\n\n Attributes:\n dependencies_check (bool): 나중에 넣자\n\n \"\"\"\n NAME = 'CARPE Forensics'\n VERSION = '20200903'\n DESCRIPTION = textwrap.dedent('\\n'.join([\n '',\n 'CARPE Forensics',\n 'files, recursing a directory (e.g. mount point) or storage media ',\n 'image or device.',\n '',\n 'More information can be gathered from here:',\n ' https://carpeforensic.com'\n '']))\n EPILOG = textwrap.dedent('\\n'.join([\n '',\n 'Example usage:',\n '',\n 'Run the tool against a storage media image (full kitchen sink)',\n ' --modules shellbag_connector --cid c1c16a681937b345f1990d10a9d0fdfcc8 --eid e666666666666666666666666666666668',\n '']))\n\n def __init__(self):\n \"\"\"Initializes a CarpeTool.\n\n Args:\n input:\n\n \"\"\"\n super(CarpeTool, self).__init__()\n\n self._cursor = None\n self.dependencies_check = True\n self.rds_check = None\n self.list_modules = False\n self.list_advanced_modules = False\n self.show_info = False\n\n def ParseArguments(self, arguments):\n \"\"\"Parses the command line arguments.\n\n Args:\n arguments (list[str]): command line arguments.\n\n \"\"\"\n #TODO: logger 설정\n loggers.ConfigureLogging()\n\n argument_parser = argparse.ArgumentParser(\n description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n self.AddBasicOptions(argument_parser)\n\n ### Info argument group\n info_group = argument_parser.add_argument_group('informational arguments')\n\n self.AddInformationalOptions(info_group)\n\n ### Moudule argument group\n module_group = argument_parser.add_argument_group(\n 'module arguments')\n\n argument_helper_names = ['artifact_definitions', 'modules', 'advanced_modules']\n helpers_manager.ArgumentHelperManager.AddCommandLineArguments(\n module_group, names=argument_helper_names)\n\n self.AddTimeZoneOption(module_group)\n self.AddStorageMediaImageOptions(module_group)\n self.AddVSSProcessingOptions(module_group)\n self.AddCredentialOptions(module_group)\n\n argument_parser.add_argument(\n '--cid', '--case_id', action='store', dest='case_id', type=str,\n default=None, help='Enter your case id')\n\n argument_parser.add_argument(\n '--eid', '--evdnc_id', '--evidence_id', action='store', dest='evidence_id', type=str,\n default=None, help='Enter your evidence id')\n\n # check standalone mode\n argument_parser.add_argument(\n '--sqlite', '--standalone', action='store_true', dest='standalone_check', default=False, help=(\n 'Define process mode to be processed.'\n )\n )\n\n argument_parser.add_argument(\n '--sig-check', '--signature-check', action='store_true', dest='signature_check',\n default=False, help=(\n 'Define Signature Check to be processed.'\n )\n )\n\n argument_parser.add_argument(\n '--rds-check', action='store_true', dest='rds_check',\n default=False, help=(\n 'Define RDS Check to be processed.'\n ))\n\n ### source path\n argument_parser.add_argument(\n 'source', action='store', metavar='SOURCE', nargs='?',\n default=None, type=str, help=(\n 'Path to a source device, file or directory. If the source is '\n 'a supported storage media device or image file, archive file '\n 'or a directory, the files within are processed recursively.'))\n\n ### output path\n argument_parser.add_argument(\n 'output_file', metavar='OUTPUT', nargs='?', type=str,\n default=None, help='Path to a output file.')\n\n try:\n options = argument_parser.parse_args(arguments)\n except UnicodeEncodeError:\n # If we get here we are attempting to print help in a non-Unicode terminal.\n self._output_writer.Write('\\n')\n self._output_writer.Write(argument_parser.format_help())\n return False\n\n try:\n self.ParseOptions(options)\n except errors.BadConfigOption as exception:\n self._output_writer.Write('ERROR: {0!s}\\n'.format(exception))\n self._output_writer.Write('\\n')\n self._output_writer.Write(argument_parser.format_usage())\n return False\n\n loggers.ConfigureLogging(\n debug_output=self._debug_mode, filename=self._log_file,\n quiet_mode=self._quiet_mode)\n\n return True\n\n def ParseOptions(self, options):\n \"\"\"Parses the options.\n\n Args:\n options (argparse.Namespace): command line arguments.\n\n Raises:\n BadConfigOption: if the options are invalid.\n \"\"\"\n # Check the list options first otherwise required options will raise.\n argument_helper_names = ['artifact_definitions', 'modules', 'advanced_modules']\n helpers_manager.ArgumentHelperManager.ParseOptions(\n options, self, names=argument_helper_names)\n\n self.list_modules = self._module_filter_expression == 'list'\n self.list_advanced_modules = self._advanced_module_filter_expression == 'list'\n self.case_id = getattr(options, 'case_id', False)\n self.evidence_id = getattr(options, 'evidence_id', False)\n\n self.standalone_check = getattr(options, 'standalone_check', False)\n self.signature_check = getattr(options, 'signature_check', False)\n self.rds_check = getattr(options, 'rds_check', False)\n self.show_info = getattr(options, 'show_info', False)\n self.show_troubleshooting = getattr(options, 'show_troubleshooting', False)\n self.dependencies_check = getattr(options, 'dependencies_check', True)\n\n if (self.list_modules or self.show_info or self.show_troubleshooting or\n self.list_timezones or self.list_advanced_modules):\n return\n self._ParseTimezoneOption(options)\n self._ParseInformationalOptions(options)\n self._ParseLogFileOptions(options)\n self._ParseStorageMediaOptions(options)\n\n\n def ExtractDataFromSources(self):\n self._output_writer.Write('Processing started.\\n')\n\n investigator = {'investigator1': 'jeong byeongchan',\n 'investigator2': 'joun jihun',\n 'investigator3': 'kim junho',\n 'investigator4': 'youn woosung',\n 'department': 'DFRC'\n }\n\n self.AddInvestigatorInformation(investigator)\n\n # Create a database connection\n try:\n if self.standalone_check:\n self._cursor = database_sqlite.Database(\n self.case_id,\n self.evidence_id,\n self._source_path,\n self._output_file_path)\n self._cursor.initialize()\n self._output_writer.Write(\"Standalone version\")\n else:\n self._cursor = database.Database()\n self._cursor.open()\n except Exception as exception:\n self._output_writer.Write('Failed tor connect to the database: {0!s}'.format(exception))\n return\n\n if platform.system() == 'Windows':\n self._root_tmp_path = self._output_file_path + os.sep + 'tmp'\n if not os.path.exists(self._root_tmp_path):\n os.mkdir(self._root_tmp_path)\n\n # set storage path and temp path\n try:\n self.CreateStorageAndTempPath(\n cursor=self._cursor,\n case_id=self.case_id,\n evd_id=self.evidence_id)\n except Exception as exception:\n self._output_writer.Write(str(exception))\n return False\n\n # scan source\n scan_context = self.ScanSource(self._source_path)\n self._source_type = scan_context.source_type\n\n # detect operating_system\n # # skpark(lnk) e111111111111111111111111111111111\n # self._partition_list = {'p1': 'p19cadd320aefe40dfa5c85ebc38ff7613',\n # 'p2': 'p143490fa32b8a4f00a4b21d0ca1ac9530',\n # 'p3': 'p1ac280f9e9d864f84ab2bf4d68b5088ab',\n # 'p4': 'p1cdd828002bec46c6843905786daaac6f'}\n\n ## skpark(ewf) e111111111111111111111111111111114\n #self._partition_list = {'p1': 'p18e6c2dd56b5c405fb7c6738a9d7241ba',\n # 'p2': 'p13eac5c34d91b480da914d8b3e309bda0',\n # 'p3': 'p1b9fd2dda0cf4499e99902bbed321ad74',\n # 'p4': 'p10377ea5b2dad4aa3a22fbbac2a7574e6'}\n\n ## email - test e222222222222222222222222222222222\n #self._partition_list = {'p1': 'p1f7af5047f1674818abc63de056ab1939',\n # 'p2': 'p1e3748f626c224f41ab513f782c37e5c7'}\n\n ## email - test e222222222222222222222222222222223\n #self._partition_list = {'p1': 'p1bf219158859742a5a939ab2c51873161',\n # 'p2': 'p1a0229b45eaf341c8b81153d445b538c4'}\n\n ## defa - test e222222222222222222222222222222224\n #self._partition_list = {'p1': 'p15ef2746ec60b4943a70ac79f5fcb3606',\n # 'p2': 'p1d09897bb7b334b79a2e1c21aa3ea2896'}\n\n ## filehistory - e111111111111111111111111111111117\n #self._partition_list = {'p1': 'p10acede86e2a747578712f5facf06abe6',\n # 'p2': 'p1951b89fd680d4ac390a5803e7ef75f26'}\n\n ## skpark(RAW) e111111111111111111111111111111118\n #self._partition_list = {'p1': 'p14b939fec88c5402180526f248b13b061',\n # 'p2': 'p15b56b52b93aa4792ac5e52cf88862425',\n # 'p3': 'p174739d4e0f774e2996f918818e2895b1',\n # 'p4': 'p110675c58eb344fdfbe0a34ff2fd7a15b'}\n\n # # 미나레지스트리 e666666666666666666666666666666667\n # self._partition_list = {'p1': 'p1eda9ba33b1104c34af8547f1202a8568'}\n\n ## superfetch - e222222222222222222222222222222225\n #self._partition_list = {'p1': 'p1fcf83303585e4bafb1c9fc2ec8db05a9',\n # 'p2': 'p1efe18b8b20094fc18177741a6b994728'}\n\n # Opera\n # self._partition_list = {'p1' : 'p195955defbb674458850527ac4e85d969'}\n\n # # Web\n # self._partition_list = {'p1': 'p1bb5a0d873b874c40a04f9ee80158dad4',\n # 'p2': 'p1f1a5000d57b04ea59aea665acd5c3ba4'}\n\n # # mobile_test\n # self._partition_list = {'p1': 'p10c82e8a81d3541a2a86f1b5f55c146aa'}\n\n # skpark(RAW) e111111111111111111111111111111118\n self._partition_list = {'p1': 'p1606ca11e8b9444f5bc55a266b0211962',\n 'p2': 'p1b2e2f08896cb4c4885d2e8f9f6cdd21b',\n 'p3': 'p13b32b5dbfc1840bab7890aa1c4f8fb66',\n 'p4': 'p12de9eb3fb63540678af72b208242dab1'}\n\n # set configuration\n configuration = self._CreateProcessingConfiguration()\n\n # set signature check options\n if self.signature_check:\n self._signature_tool.ParseSignatureOptions()\n self._signature_tool.SetScanner(self._signature_tool.signature_specifications)\n\n from datetime import datetime\n\n now = datetime.now()\n print('\\n[%s-%s-%s %s:%s:%s] Start Analyze Image' % (\n now.year, now.month, now.day, now.hour, now.minute, now.second))\n\n if self.rds_check:\n self.LoadReferenceDataSet()\n\n # # After analyzing of an IMAGE, Put the partition information into the partition_info TABLE.\n #self.InsertImageInformation()\n\n # print partition_list\n print(self._partition_list)\n\n # # After analyzing of filesystem, Put the block and file information into the block_info and file_info TABLE.\n #self.InsertFileInformation()\n\n # create process\n engine = process_engine.ProcessEngine()\n\n # determine operating system\n self._Preprocess(engine)\n\n\n # set modules\n engine.SetProcessModules(module_filter_expression=configuration.module_filter_expression)\n\n # parse Artifacts\n engine.Process(configuration)\n\n\n # # set advanced modules\n engine.SetProcessAdvancedModules(advanced_module_filter_expression=configuration.advanced_module_filter_expression)\n #\n engine.ProcessAdvancedModules(configuration)\n\n self._cursor.close()\n\n now = datetime.now()\n print('[%s-%s-%s %s:%s:%s] Finish Analyze Image' % (\n now.year, now.month, now.day, now.hour, now.minute, now.second))\n\n def ShowInfo(self):\n \"\"\"Show information about available modules, options, etc.\"\"\"\n\n self._output_writer.Write('{0:=^80s}\\n'.format(' CARPE Forensics information '))\n\n module_list = self._GetModuleData()\n for header, data in module_list.items():\n self._output_writer.Write('[ {0:s} ]\\n'.format(header))\n for name, desc in sorted(data):\n if header == 'Modules':\n name = name[:-10]\n\n _column_width = len(name)\n _maximum_row_width = 80 - _column_width -4\n\n format_string = ' {{0:>{0:d}s}} : {{1:s}}\\n'.format(_column_width)\n desc = desc.replace('\\n', '')\n if len(desc) < _maximum_row_width:\n self._output_writer.Write(format_string.format(name, desc))\n else:\n format_string2 = ' {{0:<{0:d}s}}{{1:s}}\\n'.format(_column_width + 3)\n words = desc.split()\n current = 0\n\n lines = []\n word_buffer = []\n for word in words:\n current += len(word) + 1\n if current >= _maximum_row_width:\n current = len(word)\n lines.append(' '.join(word_buffer))\n word_buffer = [word]\n else:\n word_buffer.append(word)\n lines.append(' '.join(word_buffer))\n self._output_writer.Write(format_string.format(name, lines[0]))\n for line in lines[1:]:\n self._output_writer.Write(format_string2.format('', line))\n self._output_writer.Write('\\n')\n\n #self._output_writer.Write(data)\n def _GetModuleData(self):\n \"\"\"Retrieves the version vand various module information\n\n\n Returns:\n dict[str, list[str]]: available modules.\n \"\"\"\n return_dict = {}\n\n return_dict['Versions'] = [\n ('CARPE Forensics', self.VERSION),\n ('python', sys.version)]\n\n modules_information = modules_manager.ModulesManager.GetModulesInformation()\n\n return_dict['Modules'] = modules_information\n\n return return_dict","sub_path":"tools/carpe_tool.py","file_name":"carpe_tool.py","file_ext":"py","file_size_in_byte":15851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"574805362","text":"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\nimport statsmodels.tsa.api as smt\r\n\r\nfrom statsmodels.graphics.tsaplots import plot_acf # import ACF plot\r\nfrom statsmodels.graphics.tsaplots import plot_pacf # import PACF plot\r\nfrom statsmodels.stats.diagnostic import acorr_ljungbox # import Ljung-Box Test\r\nfrom statsmodels.tsa.arima_process import arma_generate_sample # simulate ARMA process\r\n\r\n\r\n\r\ndef get_data(fileName):\r\n df = pd.read_csv(fileName + '.csv')\r\n df.index = df['t']\r\n df = df.drop(columns=['t'])\r\n return df\r\n\r\n\r\n# Plot funtion to dsiplay both the time sereis, acf and pacf\r\n# as deafualt it displays 25 lags,\r\n# This code was adapted from the blog Seanabu.com\r\ndef tsplot(y, lags=25, figsize=(10, 8), style='bmh'):\r\n if not isinstance(y, pd.Series):\r\n y = pd.Series(y)\r\n with plt.style.context(style):\r\n plt.figure(figsize=figsize) # Set the size of the figure\r\n\r\n layout = (2, 2)\r\n ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2)\r\n acf_ax = plt.subplot2grid(layout, (1, 0))\r\n pacf_ax = plt.subplot2grid(layout, (1, 1))\r\n\r\n y.plot(ax=ts_ax)\r\n ts_ax.set_title('Time Series Analysis Plots')\r\n plot_acf(y, lags=lags, ax=acf_ax)\r\n plot_pacf(y, lags=lags, ax=pacf_ax, method='ywm')\r\n\r\n plt.tight_layout()\r\n\r\n return\r\n\r\n\r\n# Plot function to displaythe standardized residuals, ACF and Ljung-Box test-\r\n# statiticics p-values. As deafualt it displays 25 lags,\r\n# This code was adapted from the blog Seanabu.com\r\ndef tsdiag(arimaResiduals, afcFags=25, lbLags=10, figsize=(10, 8), style='bmh'):\r\n if not isinstance(arimaResiduals, pd.Series):\r\n arimaFittedvVlues = pd.Series(arimaResiduals)\r\n\r\n with plt.style.context(style):\r\n plt.figure(figsize=figsize) # Set the size of the figure\r\n\r\n layout = (3, 1)\r\n sr_ax = plt.subplot2grid(layout, (0, 0))\r\n acf_ax = plt.subplot2grid(layout, (1, 0))\r\n lb_ax = plt.subplot2grid(layout, (2, 0))\r\n\r\n # Create the standard residual plot\r\n sr_ax.plot(arimaFittedvVlues)\r\n sr_ax.set_title(\"Standardizede Residuals\")\r\n sr_ax.set_xlabel(\"Time\")\r\n\r\n # Crate the ACF plot\r\n plot_acf(arimaResiduals, lags=afcFags, ax=acf_ax)\r\n\r\n # Create the Ljung-Box statitics plot\r\n lb = acorr_ljungbox(arimaResiduals, lags=lbLags)\r\n lbPvalue = lb[1] # get the pvalue from the ljungbox test\r\n\r\n lb_ax.scatter(np.arange(lbLags), lbPvalue, facecolors='none', edgecolors='b')\r\n lb_ax.set_ylim(-0.1, 1)\r\n lb_ax.axhline(y=0.05, linestyle='--')\r\n lb_ax.set_title(\"p values for Ljung-Box Statistic\")\r\n lb_ax.set_ylabel(\"p values\")\r\n lb_ax.set_xlabel(\"lags\")\r\n\r\n plt.tight_layout()\r\n return\r\n\r\n\r\n# The function apply the numpy function cumsum multiple times on the same\r\n# the same array. Used for simulating the integrated part in ARIMA models.\r\ndef cusumRepeat(arma, d):\r\n if d == 0:\r\n return (arma)\r\n\r\n return (cusumRepeat(np.cumsum(arma), d - 1))\r\n\r\n\r\n# Function to simulate ARIMA model as the python package statsmodels only\r\n# supports simulations of ARMA models\r\ndef simArima(n,sigma, ar=np.array([0]), ma=np.array([0]), d=0):\r\n if sigma == None:\r\n print('[WARNING] Sigma is set to 1!')\r\n sigma = 1\r\n if np.array_equal(ar, np.array([0])) and np.array_equal(ma, np.array([0])):\r\n print(\r\n \"Neither autoregressive parameters and moving average parameters are set. At least one need to be speficifyed\")\r\n return -1\r\n\r\n ar = np.r_[1, -ar] # add zero-lag and negate\r\n ma = np.r_[1, ma] # add zero-lag\r\n\r\n arimaSim = arma_generate_sample(ar, ma, n, sigma=sigma)\r\n\r\n # Apply integration to the arma simulation\r\n if d > 0:\r\n arimaSim = cusumRepeat(arimaSim, d)\r\n\r\n return arimaSim","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"166689488","text":"#!/usr/bin/env python\n\nrange1=[]\nfor i in range(1,256):\n range1.append(\"192.168.\" + str(i) + \".1\")\n\nrange2 = []\nfor i in range(1,256):\n for j in range(1,256):\n range2.append(\"10.\" + str(i) + \".\" + str(j) + \".1\")\n\n#write generated IP addresses to file lists.txt\n\nwith open(\"lists.txt\",\"w+\") as f:\n f.write('\\n'.join(range1))\n f.write('\\n'.join(range2))\n","sub_path":"internalIPlistGen.py","file_name":"internalIPlistGen.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"603424657","text":"class Solution:\n '''\n 单调栈\n maintain stack with increasing values, stack[i] = sum of nums[0:i]\n sums[i] - sums[j] >= k meaning sum(nums[j:i]) >= k\n '''\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n sums = [0]*(len(nums)+1)\n for i in range(len(nums)):\n sums[i+1] = sums[i] + nums[i]\n stack = []\n result = float('inf')\n for i in range(len(nums)+1):\n currSum = sums[i]\n while stack and currSum - sums[stack[0]] >= k:\n length = i - stack.pop(0)\n result = min(result, length)\n while stack and currSum < sums[stack[-1]]:\n stack.pop()\n stack.append(i)\n return result if result != float('inf') else -1\n\n# Cleaner solution \n# class Solution: \n# def shortestSubarray(self, nums, k):\n# N = len(nums)\n# B = [0] * (N + 1)\n# for i in range(N): \n# B[i + 1] = B[i] + nums[i]\n# d = []\n# res = N + 1\n# for i in range(N + 1):\n# while d and B[i] - B[d[0]] >= k: \n# res = min(res, i - d.pop(0))\n# while d and B[i] <= B[d[-1]]: \n# d.pop()\n# d.append(i)\n# return res if res <= N else -1","sub_path":"862.ShortestSubarraywithSumatLeastK.py","file_name":"862.ShortestSubarraywithSumatLeastK.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"570819880","text":"#!/usr/bin/env python\n\n\"\"\"\nrequest_handler.py: \n - Sends requests to the Blizzard API and returns the responses\n\"\"\"\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\n\nfrom settings import ID, SECRET\nfrom io_handler import parse_user_input, get_region_info, get_expansion_info\n\ndef get_api_data(message):\n exp_pack, char_name, region, realm = parse_user_input(message.content.split(\" \"))\n expansion_index = get_expansion_info(exp_pack)\n api_namespace, api_locale, api_region_short = get_region_info(region)\n\n path = '/oauth/token?grant_type=client_credentials&client_id={0}&client_secret={1}'.format(ID, SECRET)\n base_url = 'https://{0}.battle.net{1}'.format(api_region_short, path)\n\n session = requests.Session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n response = session.get(base_url)\n json = response.json() # access token info\n token = json['access_token']\n\n access_url = f'https://{api_region_short}.api.blizzard.com/profile/wow/character/{realm}/{char_name}?namespace={api_namespace}&locale={api_locale}&access_token={token}'\n char_response = session.get(access_url)\n \n access_url = f'https://{api_region_short}.api.blizzard.com/profile/wow/character/{realm}/{char_name}/encounters/raids?namespace={api_namespace}&locale={api_locale}&access_token={token}'\n exp_response = session.get(access_url)\n exp_response = [exp_response, expansion_index]\n return char_response, exp_response","sub_path":"src/request_handler.py","file_name":"request_handler.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"63246221","text":"import os\r\nimport re\r\n\r\n\r\n# Only log-in attempts with email addresses that match this pattern will be accepted.\r\nAUTH_EMAIL_PATTERN = re.compile(os.getenv('AUTH_EMAIL_PATTERN', '.+@buffalo.edu$'))\r\n\r\n\r\n# Prevent Flask-RESTful from adding to error responses.\r\nERROR_404_HELP = False\r\n\r\n\r\n# List of extensions to be enabled; if empty, a default list of extensions will be enabled.\r\nENABLED_EXTENSIONS = list(filter(None, re.split(' *, *', os.getenv('ENABLED_EXTENSIONS', ''))))\r\n\r\n\r\nSECRET_KEY = os.getenv('SECRET_KEY', 'placeholder')\r\n\r\n\r\n# Client IDs and secrets for OAuth.\r\nGOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')\r\nGOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')\r\nSLACK_CLIENT_ID = os.getenv('SLACK_CLIENT_ID')\r\nSLACK_CLIENT_SECRET = os.getenv('SLACK_CLIENT_SECRET')\r\n\r\n\r\nSQLALCHEMY_DATABASE_URI = os.getenv(\r\n 'DATABASE_URI', 'sqlite:///{}'.format(os.path.abspath('database.sqlite3')))\r\nSQLALCHEMY_TRACK_MODIFICATIONS = False\r\n\r\n\r\nUPLOAD_FOLDER = os.path.abspath('uploads')\r\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"354187689","text":"\"\"\"\r\nPlatform: win10 64-bits\r\npython: 3.6\r\n\"\"\"\r\nimport numpy as np \r\n\r\nfrom CS231n.layers import *\r\nfrom CS231n.RNN_layers import *\r\n\r\nclass CaptioningRNN(object):\r\n \"\"\"\r\n A CaptioningRNN produces captions from image features using a recurrent neural network. \r\n\r\n The RNN receives input vectors of size D, has a vocab size of V, works on sequences of length \r\n T, has an RNN hidden dimension of H, uses word vectors of dimension W, and operates on minibatch\r\n of size N. \r\n\r\n Note that we donot use any REGULARIZATION for the CaptionningRNN. \r\n \"\"\"\r\n def __init__(self, word_to_idx, input_dim=512, wordvec_dim=128,hidden_dim=128,cell_type='RNN',dtype=np.float32):\r\n \"\"\"\r\n Construct a new CaptioningRNN instance. \r\n\r\n Inputs: \r\n - word_to_idx:A dictionary giving the vocabulary. It cantains V entries, and maps \r\n each string to a unique integer in the range [0,V-1]\r\n - input_dim: Dimension D of input image feature vectors. \r\n - wordvec_dim: Dimension W of word vectors. \r\n - hidden_dim: Dimension H for the hidden state of the RNN. \r\n - cell_type: What type of RNN to use; either 'RNN' or 'LSTM'.\r\n - dtype: numpy datatype to use; use float32 for training and float64 \r\n for numeric gradient checking.\r\n \"\"\"\r\n if cell_type not in {'RNN', 'LSTM'}:\r\n raise ValueError('Invalid cell_type \"%s\"' % cell_type)\r\n \r\n self.cell_type = cell_type\r\n self.dtype = dtype \r\n self.word_to_idx = word_to_idx\r\n self.idx_to_word = {i: w for w, i in word_to_idx.items()}\r\n self.params = {}\r\n\r\n vocab_size = len(word_to_idx)\r\n\r\n self._null = word_to_idx[''] # index for ''\r\n self._start = word_to_idx.get('', None) # index for ''\r\n self._end = word_to_idx.get('', None) # index for ''\r\n\r\n # initialize word vectros \r\n self.params['W_embed'] = np.random.randn(vocab_size, wordvec_dim)\r\n self.params['W_embed'] /= 100 \r\n\r\n # initialzie CNN -> hidden state projection parameters \r\n self.params['W_proj'] = np.random.randn(input_dim, hidden_dim)\r\n self.params['W_proj'] /= np.sqrt(input_dim)\r\n self.params['b_proj'] = np.zeros(hidden_dim)\r\n\r\n # initialzie parameters for the RNN \r\n dim_mul = {'LSTM': 4, 'RNN':1}[cell_type]\r\n self.params['Wx'] = np.random.randn(wordvec_dim, dim_mul * hidden_dim)\r\n self.params['Wx'] /= np.sqrt(wordvec_dim)\r\n self.params['Wh'] = np.random.randn(hidden_dim, dim_mul*hidden_dim)\r\n self.params['Wh'] /= np.sqrt(hidden_dim)\r\n self.params['b'] = np.zeros(dim_mul * hidden_dim)\r\n\r\n # initialze output to vocab weights \r\n self.params['W_vocab'] = np.random.randn(hidden_dim, vocab_size)\r\n self.params['W_vocab'] /= np.sqrt(hidden_dim)\r\n self.params['b_vocab'] = np.zeros(vocab_size)\r\n\r\n # cast parameters to correct dtype \r\n for k, v in self.params.items():\r\n self.params[k] = v.astype(self.dtype)\r\n def loss(self, features, captions):\r\n \"\"\"\r\n Compute training-time loss for the RNN. We input image features and ground-truth captions for those images, \r\n and use an RNN (or LSTM) to compute loss and gradients on all parameters. \r\n \r\n Inputs:\r\n - features: input image features, of shape (N, D)\r\n - captions: ground-truth captions; an array of shape (N, T) where each element \r\n is in the range 0 <= y[i, t] < V.\r\n \r\n Returns a tuple of:\r\n - loss: scalar loss \r\n - grads: dictionary of gradients parallel to self.params \r\n \"\"\"\r\n # NOTE:\r\n # cut captions into two pieces: captions_in has everything but the last word \r\n # and will be input to the RNN; captions_out has everythong but the first word\r\n # and this is what we will expect the RNN to generate. These are offset by one \r\n # relative to each other because the RNN should produce word(t+1) after \r\n # receiving word t. The first element of captions_in will be the START token, \r\n # and the first element of captions_out will be the fitst word. \r\n captions_in = captions[:, :-1]\r\n captions_out = captions[:, 1:] # expected output\r\n\r\n # mask\r\n mask = (captions_out != self._null)\r\n\r\n # weight and bias for the affine transform from image features to initial hidden state. \r\n W_proj, b_proj = self.params['W_proj'], self.params['b_proj']\r\n\r\n # Word embedding matrix\r\n W_embed = self.params['W_embed']\r\n\r\n # Input-to-hidden, hidden-to-hidden, and biases for the RNN \r\n Wx, Wh, b = self.params['Wx'], self.params['Wh'], self.params['b']\r\n\r\n # Weight and bias for the hidden-to-vocab transformation. \r\n W_vocab, b_vocab = self.params['W_vocab'], self.params['b_vocab']\r\n\r\n loss, grads = 0.0, {}\r\n #############################################################################\r\n # TODO: \r\n # Implement the forward and backward passes for the CaptioningRNN. #\r\n # In the forward pass you will need to do the following: #\r\n # \r\n # (1) Use an affine transformation to compute the initial hidden state #\r\n # from the image features. This should produce an array of shape (N, H) #\r\n # #\r\n # (2) Use a word embedding layer to transform the words in captions_in #\r\n # from indices to vectors, giving an array of shape (N, T, D). #\r\n # \r\n # (3) Use either a vanilla RNN or LSTM (depending on self.cell_type) to #\r\n # process the sequence of input word vectors and produce hidden state #\r\n # vectors for all timesteps, producing an array of shape (N, T, H). #\r\n # \r\n # (4) Use a (temporal) affine transformation to compute scores over the #\r\n # vocabulary at every timestep using the hidden states, giving an #\r\n # array of shape (N, T, V). #\r\n # \r\n # (5) Use (temporal) softmax to compute loss using captions_out, ignoring #\r\n # the points where the output word is using the mask above. #\r\n # #\r\n # In the backward pass you will need to compute the gradient of the loss #\r\n # with respect to all model parameters. Use the loss and grads variables #\r\n # defined above to store loss and gradients: \r\n # grads[k] should give the gradients for self.params[k]. #\r\n #############################################################################\r\n # step 1: get initial hidden state\r\n initial_h = features.dot(W_proj) + b_proj # of shape [N, H]\r\n\r\n # step 2: transform the words from indices to vectors\r\n embed_word, embed_word_cache = word_embedding_forward(captions_in, W_embed) # of shape (N, T, D)\r\n\r\n # step 3: RNN or LSTM\r\n if self.cell_type == 'RNN':\r\n h, h_cache = RNN_forward(embed_word, initial_h, Wx, Wh, b)\r\n elif self.cell_type == 'LSTM':\r\n h, h_cache = LSTM_forward(embed_word, initial_h, Wx, Wh, b)\r\n \r\n # step 4: compute scores using a temporal affine transformation\r\n affine_forward_out, affine_forward_cache = temporal_affine_forward(h, W_vocab, b_vocab)\r\n\r\n # step 5: compute loss \r\n loss, dscore = temporal_softmax_loss(affine_forward_out, captions_out, mask, verbose=False)\r\n\r\n # backprop \r\n daffine_out, grads['W_vocab'], grads['b_vocab'] = temporal_affine_backward(dscore, affine_forward_cache)\r\n\r\n if self.cell_type == 'RNN':\r\n dword_vector, dh0, grads['Wx'], grads['Wh'], grads['b'] = RNN_backward(daffine_out, h_cache)\r\n elif self.cell_type == 'LSTM':\r\n dword_vector, dh0, grads['Wx'], grads['Wh'], grads['b'] = LSTM_backward(daffine_out, h_cache)\r\n \r\n grads['W_embed'] = word_embedding_backward(dword_vector, embed_word_cache)\r\n grads['W_proj'] = features.T.dot(dh0)\r\n grads['b_proj'] = np.sum(dh0, axis=0)\r\n\r\n return loss, grads\r\n def sample(self, features, max_length=30):\r\n \"\"\"\r\n Run a test-time forward pass for the model, sampling captions for input features vectors. \r\n\r\n At each timestep, we embed the current word, pass it and the previous hidden state to the RNN \r\n to get the next hiiden state, use the hidden state to get scores for all vocab words, and \r\n choose the word with highest score as the next word. The initial hidden state is computed \r\n by applying an affine transform to the input iamges features, and the initial word is the \r\n token. \r\n\r\n For LSTM you will also have to keep track of the cell statel. in that case, the inital cell\r\n state should be zero. \r\n\r\n Inputs: \r\n - features: array of input imagegs features of shape (N, D)\r\n - max_length: maximum length T of generated captions \r\n - Returns:\r\n - captions: array of shape (N, max_length) giving sampled captions, where each element is\r\n an integer in the range (0,V), the first element of captions should be the sampled \r\n word, not the token. \r\n \"\"\"\r\n N = features.shape[0]\r\n captions = self._null * np.ones((N,max_length), dtype=np.int32)\r\n\r\n # Unpack parameters \r\n W_proj, b_proj = self.params['W_proj'], self.params['b_proj']\r\n W_embed = self.params['W_embed']\r\n Wx, Wh, b = self.params['Wx'], self.params['Wh'], self.params['b']\r\n W_vocab, b_vocab = self.params['W_vocab'], self.params['b_vocab']\r\n\r\n ###########################################################################\r\n # TODO: Implement test-time sampling for the model. You will need to #\r\n # initialize the hidden state of the RNN by applying the learned affine #\r\n # transform to the input image features. The first word that you feed to #\r\n # the RNN should be the token; its value is stored in the #\r\n # variable self._start. At each timestep you will need to do to: #\r\n # \r\n # (1) Embed the previous word using the learned word embeddings #\r\n # \r\n # (2) Make an RNN step using the previous hidden state and the embedded #\r\n # current word to get the next hidden state. #\r\n # \r\n # (3) Apply the learned affine transformation to the next hidden state to #\r\n # get scores for all words in the vocabulary #\r\n # \r\n # (4) Select the word with the highest score as the next word, writing it #\r\n # to the appropriate slot in the captions variable #\r\n # #\r\n # For simplicity, you do not need to stop generating after an token #\r\n # is sampled, but you can if you want to. #\r\n # #\r\n # HINT: \r\n # You will not be able to use the rnn_forward or lstm_forward #\r\n # functions; you'll need to call rnn_step_forward or lstm_step_forward in #\r\n # a loop. #\r\n ###########################################################################\r\n (N, D) = features.shape\r\n prev_h = features.dot(W_proj) + b_proj\r\n prev_c = np.zeros(prev_h.shape)\r\n\r\n # self._start is the index of the word ''\r\n current_word_index = [self._start]*N \r\n\r\n for i in range(max_length):\r\n \r\n x = W_embed[current_word_index] # get word_vector from word_index \r\n \r\n if self.cell_type == 'RNN':\r\n next_h, _ = RNN_step_forward(x, prev_h, Wx, Wh, b)\r\n elif self.cell_type == 'LSTM':\r\n next_h, next_c, _ = LSTM_step_forward(x, prev_h, prev_c, Wx, Wx, b)\r\n prev_c = next_c # update cell state, of shape (N, H)\r\n prev_h = next_h # update the hidden state, of shape (N, H)\r\n\r\n next_h = np.expand_dims(next_h, axis=1) # of shape (N, 1, H)\r\n score, _ = temporal_affine_forward(next_h, W_vocab, b_vocab)\r\n captions[:,i] = list(np.argmax(score, axis=2))\r\n current_word_index = captions[:,i]\r\n \r\n return captions \r\n","sub_path":"notebook/Assignment3/CS231n/classifiers/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":12996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"144234922","text":"\"\"\"Naive Bayes classifier.\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\n\nfrom classifier import Classifier\nfrom commons.datamodel import DataModel\n\n\nclass NaiveBayesClassifier(Classifier):\n # Reads the data and stores in class variables\n def __init__(self):\n self.model = None\n self.training_data = None\n self.testing_data = None\n\n def trainModel(self, training_data: DataModel):\n count_vect = CountVectorizer(stop_words='english')\n X_train_counts = count_vect.fit_transform(training_data.data)\n\n self.model = MultinomialNB()\n self.model.fit(X_train_counts, self.training_data.target)\n\n def classify(self, testing_data: DataModel):\n count_vect = CountVectorizer(stop_words='english')\n X_test_data = count_vect.transform(testing_data.data)\n return self.model.predict(X_test_data)\n # score = metrics.accuracy_score(predict, self.testing_data.target)\n # print(\"Accuracy: {}\".format(score))\n","sub_path":"src/classifier/naiveBayesClassifier.py","file_name":"naiveBayesClassifier.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"408587161","text":"from flask import Flask, render_template, url_for, redirect, session, jsonify\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport folium\nfrom folium.plugins import HeatMap, MarkerCluster\nimport json\nfrom datetime import datetime as dt\n\ndef mapa_global(df, df_alcpp, df_estaciones, geo_data, loc_ini = [19.43,-99.14], tiles='Stamen Toner'):\n \"\"\"\n Funcion para graficar delitos cometidos, estaciones de policia, estaciones de metrobus y colonias\n\n args:\n df : pandas.DataFrame\n df_alcpp : pandas.DataFrame\n df_estaciones : pandas.DataFrame\n geo_data : poly\n loc_ini : list - opcional\n tiles : string - opcional\n \n outs:\n map_it : folium.Map\n \"\"\"\n map_it = folium.Map(location = loc_ini,tiles=tiles,zoom_start=11)\n\n for i in range(0,len(df_estaciones)):\n folium.Circle( radius=80,location=[ df_estaciones.stop_lat.values[i], df_estaciones.stop_lon.values[i] ], tooltip=df_estaciones.stop_name[i], \n color='red').add_to(map_it)\n \n map_cluster = MarkerCluster().add_to(map_it)\n\n for indx, row in df.iterrows():\n\n if row.categoria_delito == 'ROBO DE VEHÍCULO CON Y SIN VIOLENCIA':\n color = 'crimson'\n icon = 'automobile'\n elif row.categoria_delito == 'ROBO A TRANSEUNTE EN VÍA PÚBLICA CON Y SIN VIOLENCIA':\n color = 'green'\n icon = 'male'\n elif row.categoria_delito == 'ROBO A NEGOCIO CON VIOLENCIA':\n color = 'purple'\n icon = 'shopping-bag'\n else:\n color = 'darkgreen'\n icon = 'motorcycle'\n \n folium.Marker(location = [row.latitud,row.longitud],\n icon=folium.Icon(color=color, icon=icon, prefix='fa'),\n popup=dt.strftime(row.fecha_hechos,'%Y-%m-%d %H:%M:%S')).add_to(map_cluster)\n\n\n\n for indx, row in df_alcpp.iterrows():\n folium.Circle(\n radius=120,\n location=[row.Latitud, row.Longitud],\n popup=str(row['Nombre y sede']),\n color='blue',\n ).add_to(map_it)\n \n folium.GeoJson(\n geo_data).add_to(map_it)\n folium.LayerControl().add_to(map_it)\n \n return map_it\n\n\ndef mapa_delito(geo_point, nombre, tiles='Stamen Toner'):\n \"\"\"\n Funcion para graficar delitos cometidos, estaciones de policia, estaciones de metrobus y colonias\n args:\n df : pandas.DataFrame\n loc_ini : list - opcional\n tiles : string - opcional\n outs:\n map_it : folium.Map\n \"\"\"\n map_it = folium.Map(location = geo_point['location'],tiles=tiles,zoom_start=13, prefer_cavas = True)\n \n map_cluster = MarkerCluster().add_to(map_it)\n\n if geo_point['delito'] == 'R. Vehiculo' or geo_point['delito'] == 'R. Vehículo':\n color = 'crimson'\n icon = 'automobile'\n elif geo_point['delito'] == 'R. Transeunte':\n color = 'green'\n icon = 'male'\n elif geo_point['delito'] == 'R. Negocio':\n color = 'purple'\n icon = 'shopping-bag'\n elif geo_point['delito'] == 'R. Repartidor':\n color = 'darkgreen'\n icon = 'motorcycle'\n elif geo_point['delito'] == 'R. Metro':\n color = 'darkrblue'\n icon = 'subway'\n else:\n color = 'black'\n icon = 'exclamation-circle'\n \n folium.Marker(location = geo_point['location'],\n icon=folium.Icon(color=color, icon=icon, prefix='fa'),\n popup= geo_point['tiempo']).add_to(map_cluster)\n \n htmlname = 'mapas/{}.html'.format(nombre)\n map_it.save('templates/{}'.format(htmlname))\n\n return htmlname","sub_path":"mapea_delitos.py","file_name":"mapea_delitos.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"210303870","text":"#################################################################################\n# WaterTAP Copyright (c) 2020-2023, The Regents of the University of California,\n# through Lawrence Berkeley National Laboratory, Oak Ridge National Laboratory,\n# National Renewable Energy Laboratory, and National Energy Technology\n# Laboratory (subject to receipt of any required approvals from the U.S. Dept.\n# of Energy). All rights reserved.\n#\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and license\n# information, respectively. These files are also available online at the URL\n# \"https://github.com/watertap-org/watertap/\"\n#################################################################################\n\"\"\"\nModified CSTR model which includes vapor and liquid phase outlets.\n\nThis is copied from the standard IDAES CSTR with the addition of mass transfer\nterms and extra port for second phase.\n\nAssumptions:\n * Steady-state only\n * Liquid phase property package has a single phase named Liq\n * Vapor phase property package has a single phase named Vap\n * Liquid and vapor phase properties need not have the same component lists\n\nModel formulated from:\n\nRosen, C. and Jeppsson, U., 2006.\nAspects on ADM1 Implementation within the BSM2 Framework.\nDepartment of Industrial Electrical Engineering and Automation, Lund University, Lund, Sweden, pp.1-35.\n\"\"\"\n\n# Import Pyomo libraries\nfrom pyomo.common.config import ConfigBlock, ConfigValue, In, Bool\nfrom pyomo.environ import (\n Reference,\n Var,\n Constraint,\n Param,\n units as pyunits,\n check_optimal_termination,\n log,\n Suffix,\n NonNegativeReals,\n)\n\n\n# Import IDAES cores\nfrom idaes.core import (\n ControlVolume0DBlock,\n declare_process_block_class,\n MaterialBalanceType,\n EnergyBalanceType,\n MaterialFlowBasis,\n MomentumBalanceType,\n UnitModelBlockData,\n useDefault,\n)\nfrom idaes.core.util.config import (\n is_physical_parameter_block,\n is_reaction_parameter_block,\n)\n\nimport idaes.logger as idaeslog\nfrom idaes.core.util import scaling as iscale\nfrom idaes.core.solvers import get_solver\nfrom idaes.core.util.model_statistics import degrees_of_freedom\nfrom idaes.core.util.constants import Constants\nfrom idaes.core.util.exceptions import ConfigurationError, InitializationError\nfrom idaes.core.util.tables import create_stream_table_dataframe\n\n__author__ = \"Alejandro Garciadiego, Andrew Lee, Xinhong Liu\"\n\n\n@declare_process_block_class(\"AD\")\nclass ADData(UnitModelBlockData):\n \"\"\"\n AD Unit Model Class\n \"\"\"\n\n CONFIG = UnitModelBlockData.CONFIG()\n\n CONFIG.declare(\n \"material_balance_type\",\n ConfigValue(\n default=MaterialBalanceType.useDefault,\n domain=In(MaterialBalanceType),\n description=\"Material balance construction flag\",\n doc=\"\"\"Indicates what type of mass balance should be constructed,\n**default** - MaterialBalanceType.useDefault.\n**Valid values:** {\n**MaterialBalanceType.useDefault - refer to property package for default\nbalance type\n**MaterialBalanceType.none** - exclude material balances,\n**MaterialBalanceType.componentPhase** - use phase component balances,\n**MaterialBalanceType.componentTotal** - use total component balances,\n**MaterialBalanceType.elementTotal** - use total element balances,\n**MaterialBalanceType.total** - use total material balance.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"energy_balance_type\",\n ConfigValue(\n default=EnergyBalanceType.useDefault,\n domain=In(EnergyBalanceType),\n description=\"Energy balance construction flag\",\n doc=\"\"\"Indicates what type of energy balance should be constructed,\n**default** - EnergyBalanceType.useDefault.\n**Valid values:** {\n**EnergyBalanceType.useDefault - refer to property package for default\nbalance type\n**EnergyBalanceType.none** - exclude energy balances,\n**EnergyBalanceType.enthalpyTotal** - single enthalpy balance for material,\n**EnergyBalanceType.enthalpyPhase** - enthalpy balances for each phase,\n**EnergyBalanceType.energyTotal** - single energy balance for material,\n**EnergyBalanceType.energyPhase** - energy balances for each phase.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"momentum_balance_type\",\n ConfigValue(\n default=MomentumBalanceType.pressureTotal,\n domain=In(MomentumBalanceType),\n description=\"Momentum balance construction flag\",\n doc=\"\"\"Indicates what type of momentum balance should be constructed,\n**default** - MomentumBalanceType.pressureTotal.\n**Valid values:** {\n**MomentumBalanceType.none** - exclude momentum balances,\n**MomentumBalanceType.pressureTotal** - single pressure balance for material,\n**MomentumBalanceType.pressurePhase** - pressure balances for each phase,\n**MomentumBalanceType.momentumTotal** - single momentum balance for material,\n**MomentumBalanceType.momentumPhase** - momentum balances for each phase.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"has_heat_transfer\",\n ConfigValue(\n default=False,\n domain=Bool,\n description=\"Heat transfer term construction flag\",\n doc=\"\"\"Indicates whether terms for heat transfer should be constructed,\n**default** - False.\n**Valid values:** {\n**True** - include heat transfer terms,\n**False** - exclude heat transfer terms.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"has_pressure_change\",\n ConfigValue(\n default=False,\n domain=Bool,\n description=\"Pressure change term construction flag\",\n doc=\"\"\"Indicates whether terms for pressure change should be\nconstructed,\n**default** - False.\n**Valid values:** {\n**True** - include pressure change terms,\n**False** - exclude pressure change terms.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"has_equilibrium_reactions\",\n ConfigValue(\n default=False,\n domain=Bool,\n description=\"Equilibrium reaction construction flag\",\n doc=\"\"\"Indicates whether terms for equilibrium controlled reactions\nshould be constructed,\n**default** - True.\n**Valid values:** {\n**True** - include equilibrium reaction terms,\n**False** - exclude equilibrium reaction terms.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"has_phase_equilibrium\",\n ConfigValue(\n default=False,\n domain=Bool,\n description=\"Phase equilibrium construction flag\",\n doc=\"\"\"Indicates whether terms for phase equilibrium should be\nconstructed,\n**default** = False.\n**Valid values:** {\n**True** - include phase equilibrium terms\n**False** - exclude phase equilibrium terms.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"has_heat_of_reaction\",\n ConfigValue(\n default=False,\n domain=Bool,\n description=\"Heat of reaction term construction flag\",\n doc=\"\"\"Indicates whether terms for heat of reaction terms should be\nconstructed,\n**default** - False.\n**Valid values:** {\n**True** - include heat of reaction terms,\n**False** - exclude heat of reaction terms.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"liquid_property_package\",\n ConfigValue(\n default=useDefault,\n domain=is_physical_parameter_block,\n description=\"Property package to use for liquid phase\",\n doc=\"\"\"Property parameter object used to define property calculations\nfor the liquid phase,\n**default** - useDefault.\n**Valid values:** {\n**useDefault** - use default package from parent model or flowsheet,\n**PropertyParameterObject** - a PropertyParameterBlock object.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"liquid_property_package_args\",\n ConfigBlock(\n implicit=True,\n description=\"Arguments to use for constructing liquid phase properties\",\n doc=\"\"\"A ConfigBlock with arguments to be passed to liquid phase\nproperty block(s) and used when constructing these,\n**default** - None.\n**Valid values:** {\nsee property package for documentation.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"vapor_property_package\",\n ConfigValue(\n default=useDefault,\n domain=is_physical_parameter_block,\n description=\"Property package to use for vapor phase\",\n doc=\"\"\"Property parameter object used to define property calculations\nfor the vapor phase,\n**default** - useDefault.\n**Valid values:** {\n**useDefault** - use default package from parent model or flowsheet,\n**PropertyParameterObject** - a PropertyParameterBlock object.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"vapor_property_package_args\",\n ConfigBlock(\n implicit=True,\n description=\"Arguments to use for constructing vapor phase properties\",\n doc=\"\"\"A ConfigBlock with arguments to be passed to vapor phase\nproperty block(s) and used when constructing these,\n**default** - None.\n**Valid values:** {\nsee property package for documentation.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"reaction_package\",\n ConfigValue(\n default=None,\n domain=is_reaction_parameter_block,\n description=\"Reaction package to use for control volume\",\n doc=\"\"\"Reaction parameter object used to define reaction calculations,\n**default** - None.\n**Valid values:** {\n**None** - no reaction package,\n**ReactionParameterBlock** - a ReactionParameterBlock object.}\"\"\",\n ),\n )\n CONFIG.declare(\n \"reaction_package_args\",\n ConfigBlock(\n implicit=True,\n description=\"Arguments to use for constructing reaction packages\",\n doc=\"\"\"A ConfigBlock with arguments to be passed to a reaction block(s)\nand used when constructing these,\n**default** - None.\n**Valid values:** {\nsee reaction package for documentation.}\"\"\",\n ),\n )\n\n def build(self):\n \"\"\"\n Begin building model (pre-DAE transformation).\n Args:\n None\n Returns:\n None\n \"\"\"\n # Call UnitModel.build to setup dynamics\n super(ADData, self).build()\n\n self.scaling_factor = Suffix(direction=Suffix.EXPORT)\n\n # Check phase lists match assumptions\n if self.config.vapor_property_package.phase_list != [\"Vap\"]:\n raise ConfigurationError(\n f\"{self.name} Anaerobic digestor model requires that the vapor \"\n f\"phase property package have a single phase named 'Vap'\"\n )\n if self.config.liquid_property_package.phase_list != [\"Liq\"]:\n raise ConfigurationError(\n f\"{self.name} Anaerobic digestor model requires that the liquid \"\n f\"phase property package have a single phase named 'Liq'\"\n )\n\n # Check for at least one common component in component lists\n if not any(\n j in self.config.vapor_property_package.component_list\n for j in self.config.liquid_property_package.component_list\n ):\n raise ConfigurationError(\n f\"{self.name} Anaerobic digestor model requires that the liquid \"\n f\"and vapor phase property packages have at least one \"\n f\"common component.\"\n )\n\n self.liquid_phase = ControlVolume0DBlock(\n dynamic=self.config.dynamic,\n has_holdup=self.config.has_holdup,\n property_package=self.config.liquid_property_package,\n property_package_args=self.config.liquid_property_package_args,\n reaction_package=self.config.reaction_package,\n reaction_package_args=self.config.reaction_package_args,\n )\n\n self.liquid_phase.add_state_blocks(\n has_phase_equilibrium=self.config.has_phase_equilibrium\n )\n\n self.liquid_phase.add_reaction_blocks(\n has_equilibrium=self.config.has_equilibrium_reactions\n )\n\n # Separate liquid and vapor phases means that phase equilibrium will\n # be handled at the unit model level, thus has_phase_equilibrium is\n # False, but has_mass_transfer is True.\n self.liquid_phase.add_material_balances(\n balance_type=self.config.material_balance_type,\n has_rate_reactions=True,\n has_equilibrium_reactions=self.config.has_equilibrium_reactions,\n has_phase_equilibrium=self.config.has_phase_equilibrium,\n has_mass_transfer=True,\n )\n\n # Need to include enthalpy transfer term for the mass transfer\n self.liquid_phase.add_energy_balances(\n balance_type=self.config.energy_balance_type,\n has_heat_transfer=True,\n has_enthalpy_transfer=True,\n )\n\n self.liquid_phase.add_momentum_balances(\n balance_type=self.config.momentum_balance_type,\n has_pressure_change=self.config.has_pressure_change,\n )\n\n # ---------------------------------------------------------------------\n # Add single state block for vapor phase\n tmp_dict = dict(**self.config.vapor_property_package_args)\n tmp_dict[\"has_phase_equilibrium\"] = False\n tmp_dict[\"defined_state\"] = False\n self.vapor_phase = self.config.vapor_property_package.build_state_block(\n self.flowsheet().time, doc=\"Vapor phase properties\", **tmp_dict\n )\n\n # ---------------------------------------------------------------------\n # Check flow basis is compatable\n # TODO : Could add code to convert flow bases, but not now\n t_init = self.flowsheet().time.first()\n if (\n self.vapor_phase[t_init].get_material_flow_basis()\n != self.liquid_phase.properties_out[t_init].get_material_flow_basis()\n ):\n raise ConfigurationError(\n f\"{self.name} vapor and liquid property packages must use the \"\n f\"same material flow basis.\"\n )\n\n self.liquid_phase.add_geometry()\n\n # Add Ports\n self.add_inlet_port(name=\"inlet\", block=self.liquid_phase, doc=\"Liquid feed\")\n self.add_outlet_port(\n name=\"liquid_outlet\", block=self.liquid_phase, doc=\"Bottoms stream\"\n )\n self.add_outlet_port(\n name=\"vapor_outlet\",\n block=self.vapor_phase,\n doc=\"Vapor stream from reactor\",\n )\n\n # ---------------------------------------------------------------------\n # Add unit level constraints\n # First, need the union and intersection of component lists\n all_comps = (\n self.vapor_phase.component_list\n | self.liquid_phase.properties_out.component_list\n )\n common_comps = (\n self.vapor_phase.component_list\n & self.liquid_phase.properties_out.component_list\n )\n\n # Get units for unit conversion\n vunits = self.config.vapor_property_package.get_metadata().get_derived_units\n lunits = self.config.liquid_property_package.get_metadata().get_derived_units\n flow_basis = self.vapor_phase[t_init].get_material_flow_basis()\n if flow_basis == MaterialFlowBasis.molar:\n fb = \"flow_mole\"\n elif flow_basis == MaterialFlowBasis.mass:\n fb = \"flow_mass\"\n else:\n raise ConfigurationError(\n f\"{self.name} AnaerobicDigestor only supports mass or molar \"\n f\"basis for MaterialFlowBasis.\"\n )\n\n # Add object references\n self.volume_liquid = Reference(self.liquid_phase.volume[:])\n\n self.volume_AD = Var(\n self.flowsheet().time,\n initialize=3700,\n domain=NonNegativeReals,\n units=lunits(\"volume\"),\n doc=\"Total volume of anaerobic digestor\",\n )\n\n self.volume_vapor = Var(\n self.flowsheet().time,\n initialize=300,\n domain=NonNegativeReals,\n units=lunits(\"volume\"),\n doc=\"Volume of the gas\",\n )\n\n self.k_p = Param(\n initialize=5e4,\n mutable=True,\n units=pyunits.m**3 / pyunits.day / pyunits.bar,\n doc=\"friction parameter\",\n )\n\n self.KH_co2 = Var(\n self.flowsheet().time,\n initialize=0.02715,\n domain=NonNegativeReals,\n units=pyunits.kmol / pyunits.m**3 * pyunits.bar**-1,\n doc=\"CO2 Henry's law coefficient\",\n )\n self.KH_ch4 = Var(\n self.flowsheet().time,\n initialize=0.00116,\n domain=NonNegativeReals,\n units=pyunits.kmol / pyunits.m**3 * pyunits.bar**-1,\n doc=\"CH4 Henry's law coefficient\",\n )\n self.KH_h2 = Var(\n self.flowsheet().time,\n initialize=7.38e-4,\n domain=NonNegativeReals,\n units=pyunits.kmol / pyunits.m**3 * pyunits.bar**-1,\n doc=\"H2 Henry's law coefficient\",\n )\n self.K_La = Param(\n initialize=200,\n units=pyunits.day**-1,\n mutable=True,\n doc=\"Gas-liquid transfer coefficient\",\n )\n self.electricity_consumption = Var(\n self.flowsheet().time,\n units=pyunits.kW,\n bounds=(0, None),\n doc=\"Electricity consumption of unit\",\n )\n # The value is taken from Maravelias' data\n self.energy_electric_flow_vol_inlet = Param(\n initialize=0.029,\n units=pyunits.kWh / pyunits.m**3,\n mutable=True,\n doc=\"Electricity intensity with respect to inlet flow\",\n )\n\n def CO2_Henrys_law_rule(self, t):\n return log(\n self.KH_co2[t] / (pyunits.kmol / pyunits.m**3 * pyunits.bar**-1)\n ) == (\n log(0.035)\n + -19410\n / pyunits.mole\n * pyunits.joule\n / (Constants.gas_constant)\n * (\n (1 / self.config.vapor_property_package.temperature_ref)\n - (1 / self.vapor_phase[t].temperature)\n )\n )\n\n self.CO2_Henrys_law = Constraint(\n self.flowsheet().time,\n rule=CO2_Henrys_law_rule,\n doc=\"CO2 Henry's law coefficient constraint\",\n )\n\n def Ch4_Henrys_law_rule(self, t):\n return log(\n self.KH_ch4[t] / (pyunits.kmol / pyunits.m**3 * pyunits.bar**-1)\n ) == (\n log(0.0014)\n + -14240\n / pyunits.mole\n * pyunits.joule\n / (Constants.gas_constant)\n * (\n (1 / self.config.vapor_property_package.temperature_ref)\n - (1 / self.vapor_phase[t].temperature)\n )\n )\n\n self.Ch4_Henrys_law = Constraint(\n self.flowsheet().time,\n rule=Ch4_Henrys_law_rule,\n doc=\"Ch4 Henry's law coefficient constraint\",\n )\n\n def H2_Henrys_law_rule(self, t):\n return log(\n self.KH_h2[t] / (pyunits.kmol / pyunits.m**3 * pyunits.bar**-1)\n ) == (\n log(7.8e-4)\n + -4180\n / pyunits.mole\n * pyunits.joule\n / (Constants.gas_constant)\n * (\n (1 / self.config.vapor_property_package.temperature_ref)\n - (1 / self.vapor_phase[t].temperature)\n )\n )\n\n self.H2_Henrys_law = Constraint(\n self.flowsheet().time,\n rule=H2_Henrys_law_rule,\n doc=\"H2 Henry's law coefficient constraint\",\n )\n\n def outlet_P_rule(self, t):\n return self.vapor_phase[t].pressure == (\n sum(\n self.vapor_phase[t].pressure_sat[j]\n for j in self.config.vapor_property_package.component_list\n )\n )\n\n self.outlet_P = Constraint(\n self.flowsheet().time,\n rule=outlet_P_rule,\n doc=\"Outlet vapor phase pressure\",\n )\n\n # Material balances\n def rule_material_balance(self, t, j):\n if j in common_comps:\n # Component is in equilibrium\n # Mass transfer equals vapor flowrate\n return self.liquid_phase.mass_transfer_term[\n t, \"Liq\", j\n ] == -self.vapor_phase[t].get_material_flow_terms(\"Vap\", j)\n\n elif j == \"S_IC\":\n # Mass transfer term is zero, no vapor flowrate\n return self.liquid_phase.mass_transfer_term[\n t, \"Liq\", j\n ] == -self.vapor_phase[t].get_material_flow_terms(\"Vap\", \"S_co2\")\n\n elif j in self.liquid_phase.properties_out.component_list:\n # No mass transfer term\n # Set vapor flowrate to an arbitary small value\n return self.liquid_phase.mass_transfer_term[t, \"Liq\", j] == 0 * lunits(\n fb\n )\n\n self.unit_material_balance = Constraint(\n self.flowsheet().time,\n self.liquid_phase.properties_out.component_list,\n rule=rule_material_balance,\n doc=\"Unit level material balances\",\n )\n\n def Sh2_conc_rule(self, t):\n return self.liquid_phase.mass_transfer_term[t, \"Liq\", \"S_h2\"] == -1 * (\n pyunits.convert(self.K_La, to_units=1 / pyunits.s)\n * (\n self.liquid_phase.properties_out[t].conc_mass_comp[\"S_h2\"]\n - 16\n * pyunits.kg\n / pyunits.kmol\n * pyunits.convert(\n self.KH_h2[t],\n to_units=pyunits.kmol / pyunits.m**3 * pyunits.Pa**-1,\n )\n * self.vapor_phase[t].pressure_sat[\"S_h2\"]\n )\n * self.volume_liquid[t]\n )\n\n self.Sh2_conc = Constraint(\n self.flowsheet().time,\n rule=Sh2_conc_rule,\n doc=\"Mass transfer rate of H2 gas vap\",\n )\n\n def Sch4_conc_rule(self, t):\n return self.liquid_phase.mass_transfer_term[t, \"Liq\", \"S_ch4\"] == -1 * (\n pyunits.convert(self.K_La, to_units=1 / pyunits.s)\n * (\n self.liquid_phase.properties_out[t].conc_mass_comp[\"S_ch4\"]\n - 64\n * pyunits.kg\n / pyunits.kmol\n * pyunits.convert(\n self.KH_ch4[t],\n to_units=pyunits.kmol / pyunits.m**3 * pyunits.Pa**-1,\n )\n * self.vapor_phase[t].pressure_sat[\"S_ch4\"]\n )\n * self.volume_liquid[t]\n )\n\n self.Sch4_conc = Constraint(\n self.flowsheet().time,\n rule=Sch4_conc_rule,\n doc=\"Mass transfer rate of CH4 gas vap\",\n )\n\n def Sco2_conc_rule(self, t):\n return self.liquid_phase.mass_transfer_term[t, \"Liq\", \"S_IC\"] == -1 * (\n pyunits.convert(self.K_La, to_units=1 / pyunits.s)\n * 12\n * pyunits.kg\n / pyunits.kmol\n * (\n self.liquid_phase.reactions[t].conc_mol_co2\n - pyunits.convert(\n self.KH_co2[t],\n to_units=pyunits.kmol / pyunits.m**3 * pyunits.Pa**-1,\n )\n * self.vapor_phase[t].pressure_sat[\"S_co2\"]\n )\n * self.volume_liquid[t]\n )\n\n self.Sco2_conc = Constraint(\n self.flowsheet().time,\n rule=Sco2_conc_rule,\n doc=\"Mass transfer rate of CO2 gas vap\",\n )\n\n def flow_vol_vap_rule(self, t):\n return self.vapor_phase[t].flow_vol == (\n pyunits.convert(\n self.k_p, to_units=pyunits.m**3 / pyunits.s / pyunits.Pa\n )\n * (self.vapor_phase[t].pressure - 101325 * pyunits.Pa)\n ) * (self.vapor_phase[t].pressure) / (101325 * pyunits.Pa)\n\n self.flow_vol_vap = Constraint(\n self.flowsheet().time,\n rule=flow_vol_vap_rule,\n doc=\"Vol flow\",\n )\n\n def ad_total_volume_rule(self, t):\n return self.volume_AD[t] == (self.volume_liquid[t] + self.volume_vapor[t])\n\n self.ad_total_volume = Constraint(\n self.flowsheet().time,\n rule=ad_total_volume_rule,\n doc=\"Total anaerobic digestor volume\",\n )\n # Add AD performance equation\n def ad_performance_eqn_rule(self, t, r):\n return self.liquid_phase.rate_reaction_extent[t, r] == (\n self.volume_liquid[t] * self.liquid_phase.reactions[t].reaction_rate[r]\n )\n\n self.ad_performance_eqn = Constraint(\n self.flowsheet().time,\n self.config.reaction_package.rate_reaction_idx,\n rule=ad_performance_eqn_rule,\n doc=\"AD performance equation\",\n )\n # Temperature equality constraint\n def rule_temperature_balance(self, t):\n return self.liquid_phase.properties_out[t].temperature == pyunits.convert(\n self.vapor_phase[t].temperature, to_units=lunits(\"temperature\")\n )\n\n self.unit_temperature_equality = Constraint(\n self.flowsheet().time,\n rule=rule_temperature_balance,\n doc=\"Unit level temperature equality\",\n )\n\n if (\n self.config.has_pressure_change is True\n and self.config.momentum_balance_type != MomentumBalanceType.none\n ):\n self.deltaP = Reference(self.liquid_phase.deltaP[:])\n\n # Pressure balance constraint\n def rule_pressure_balance(self, t):\n return (\n self.deltaP[t]\n == self.vapor_outlet.pressure[t]\n - self.liquid_phase.properties_in[t].pressure\n )\n\n self.unit_pressure_balance = Constraint(\n self.flowsheet().time,\n rule=rule_pressure_balance,\n doc=\"Unit level pressure balance\",\n )\n\n # Unit level energy balance\n # Energy leaving in vapor phase must be equal and opposite to enthalpy\n # transfer from liquid phase\n def rule_energy_balance(self, t):\n return self.liquid_phase.enthalpy_transfer[\n t\n ] + self.liquid_phase.properties_in[t].get_enthalpy_flow_terms(\n \"Liq\"\n ) == self.liquid_phase.properties_out[\n t\n ].get_enthalpy_flow_terms(\n \"Liq\"\n ) + self.vapor_phase[\n t\n ].get_enthalpy_flow_terms(\n \"Vap\"\n )\n\n self.unit_enthalpy_balance = Constraint(\n self.flowsheet().time,\n rule=rule_energy_balance,\n doc=\"Unit level enthalpy_balance\",\n )\n\n # Electricity constraint\n def rule_electricity_consumption(self, t):\n return self.electricity_consumption[t] == (\n self.energy_electric_flow_vol_inlet\n * pyunits.convert(\n self.liquid_phase.properties_in[t].flow_vol,\n to_units=pyunits.m**3 / pyunits.hr,\n )\n )\n\n self.unit_electricity_consumption = Constraint(\n self.flowsheet().time,\n rule=rule_electricity_consumption,\n doc=\"Unit level electricity consumption\",\n )\n\n # Set references to balance terms at unit level\n self.heat_duty = Reference(self.liquid_phase.heat[:])\n\n iscale.set_scaling_factor(self.KH_co2, 1e2)\n iscale.set_scaling_factor(self.KH_ch4, 1e2)\n iscale.set_scaling_factor(self.KH_h2, 1e2)\n iscale.set_scaling_factor(self.volume_AD, 1e-2)\n iscale.set_scaling_factor(self.volume_vapor, 1e-2)\n iscale.set_scaling_factor(self.liquid_phase.rate_reaction_generation, 1e4)\n iscale.set_scaling_factor(self.liquid_phase.mass_transfer_term, 1e2)\n iscale.set_scaling_factor(self.liquid_phase.heat, 1e0)\n iscale.set_scaling_factor(self.liquid_phase.rate_reaction_extent, 1e4)\n iscale.set_scaling_factor(self.liquid_phase.enthalpy_transfer, 1e0)\n iscale.set_scaling_factor(self.liquid_phase.volume, 1e-2)\n iscale.set_scaling_factor(self.electricity_consumption, 1e0)\n for i, c in self.ad_performance_eqn.items():\n iscale.constraint_scaling_transform(c, 1e2)\n\n def _get_stream_table_contents(self, time_point=0):\n return create_stream_table_dataframe(\n {\n \"Liquid Inlet\": self.inlet,\n \"Liquid Outlet\": self.liquid_outlet,\n \"Vapor Outlet\": self.vapor_outlet,\n },\n time_point=time_point,\n )\n\n def _get_performance_contents(self, time_point=0):\n # TODO: add aggregated quantities/key metrics\n var_dict = {\"Volume\": self.volume_AD[time_point]}\n if hasattr(self, \"heat_duty\"):\n var_dict[\"Heat Duty\"] = self.heat_duty[time_point]\n if hasattr(self, \"deltaP\"):\n var_dict[\"Pressure Change\"] = self.deltaP[time_point]\n\n return {\"vars\": var_dict}\n\n def calculate_scaling_factors(self):\n super().calculate_scaling_factors()\n\n common_comps = (\n self.vapor_phase.component_list\n & self.liquid_phase.properties_out.component_list\n )\n\n # TODO: improve this later; for now, this resolved some scaling issues for modified adm1 test file\n if \"S_IP\" in self.config.liquid_property_package.component_list:\n iscale.set_scaling_factor(self.liquid_phase.heat, 1e-6)\n iscale.set_scaling_factor(\n self.liquid_phase.properties_out[0].conc_mass_comp[\"S_IP\"], 1e-5\n )\n iscale.set_scaling_factor(\n self.liquid_phase.properties_out[0].conc_mass_comp[\"S_IN\"], 1e-5\n )\n\n for t, v in self.flow_vol_vap.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.properties_out[t].flow_vol,\n default=1,\n warning=True,\n ),\n )\n\n for (t, j), v in self.unit_material_balance.items():\n if j in common_comps:\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.mass_transfer_term[t, \"Liq\", j],\n default=1,\n warning=True,\n ),\n )\n else:\n pass # no need to scale this constraint\n\n for t, v in self.unit_temperature_equality.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.properties_out[t].temperature,\n default=1,\n warning=True,\n ),\n )\n\n for t, v in self.unit_enthalpy_balance.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.enthalpy_transfer[t], default=1, warning=True\n ),\n )\n\n for t, v in self.outlet_P.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.properties_out[t].pressure,\n default=1,\n warning=True,\n ),\n )\n for t, v in self.Sh2_conc.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.properties_out[t].conc_mass_comp[\"S_h2\"],\n default=1,\n warning=True,\n ),\n )\n for t, v in self.Sch4_conc.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.properties_out[t].conc_mass_comp[\"S_ch4\"],\n default=1,\n warning=True,\n ),\n )\n for t, v in self.Sco2_conc.items():\n iscale.constraint_scaling_transform(\n v,\n iscale.get_scaling_factor(\n self.liquid_phase.properties_out[t].conc_mass_comp[\"S_ch4\"],\n default=1,\n warning=True,\n ),\n )\n\n # TO DO: fix initialization\n def initialize_build(\n self,\n liquid_state_args=None,\n vapor_state_args=None,\n outlvl=idaeslog.NOTSET,\n solver=None,\n optarg=None,\n ):\n \"\"\"\n Initialization routine for anaerobic digestor unit model.\n\n Keyword Arguments:\n liquid_state_args : a dict of arguments to be passed to the\n liquid property packages to provide an initial state for\n initialization (see documentation of the specific property\n package) (default = none).\n vapor_state_args : a dict of arguments to be passed to the\n vapor property package to provide an initial state for\n initialization (see documentation of the specific property\n package) (default = none).\n outlvl : sets output level of initialization routine\n optarg : solver options dictionary object (default=None, use\n default solver options)\n solver : str indicating which solver to use during\n initialization (default = None, use default IDAES solver)\n\n Returns:\n None\n \"\"\"\n if optarg is None:\n optarg = {}\n\n # Check DOF\n if degrees_of_freedom(self) != 0:\n raise InitializationError(\n f\"{self.name} degrees of freedom were not 0 at the beginning \"\n f\"of initialization. DoF = {degrees_of_freedom(self)}\"\n )\n\n # Set solver options\n init_log = idaeslog.getInitLogger(self.name, outlvl, tag=\"unit\")\n solve_log = idaeslog.getSolveLogger(self.name, outlvl, tag=\"unit\")\n\n solverobj = get_solver(solver, optarg)\n\n # ---------------------------------------------------------------------\n # Initialize liquid phase control volume block\n\n for t, v in self.liquid_phase.properties_out[0].conc_mass_comp.items():\n v.fix()\n\n flags = self.liquid_phase.initialize(\n outlvl=outlvl,\n optarg=optarg,\n solver=solver,\n state_args=liquid_state_args,\n hold_state=True,\n )\n init_log.info_high(\"Initialization Step 1 Complete.\")\n\n for t, v in self.liquid_phase.properties_out[0].conc_mass_comp.items():\n v.unfix()\n\n # ---------------------------------------------------------------------\n # Initialize vapor phase state block\n\n for t, v in self.vapor_phase[0].conc_mass_comp.items():\n v.fix()\n\n self.vapor_phase.initialize(\n outlvl=outlvl,\n optarg=optarg,\n solver=solver,\n state_args=vapor_state_args,\n hold_state=False,\n )\n for t, v in self.vapor_phase[0].conc_mass_comp.items():\n v.unfix()\n\n init_log.info_high(\"Initialization Step 2 Complete.\")\n # ---------------------------------------------------------------------\n # # Solve unit model\n with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:\n self.liquid_phase.reactions[0.0].pKW.fix()\n self.liquid_phase.reactions[0.0].pK_a_co2.fix()\n self.liquid_phase.reactions[0.0].pK_a_IN.fix()\n self.liquid_phase.reactions[0.0].Dissociation.deactivate()\n self.liquid_phase.reactions[0.0].CO2_acid_base_equilibrium.deactivate()\n self.liquid_phase.reactions[0.0].IN_acid_base_equilibrium.deactivate()\n self.KH_co2.fix()\n self.KH_ch4.fix()\n self.KH_h2.fix()\n self.CO2_Henrys_law.deactivate()\n self.Ch4_Henrys_law.deactivate()\n self.H2_Henrys_law.deactivate()\n\n results = solverobj.solve(self, tee=slc.tee)\n\n if not check_optimal_termination(results):\n init_log.warning(\n f\"Trouble solving unit model {self.name}, trying one more time\"\n )\n results = solverobj.solve(self, tee=slc.tee)\n init_log.info_high(\n \"Initialization Step 3 {}.\".format(idaeslog.condition(results))\n )\n\n # ---------------------------------------------------------------------\n # Release states\n self.liquid_phase.release_state(flags, outlvl)\n\n self.liquid_phase.reactions[0.0].pKW.unfix()\n self.liquid_phase.reactions[0.0].pK_a_co2.unfix()\n self.liquid_phase.reactions[0.0].pK_a_IN.unfix()\n self.liquid_phase.reactions[0.0].Dissociation.activate()\n self.liquid_phase.reactions[0.0].CO2_acid_base_equilibrium.activate()\n self.liquid_phase.reactions[0.0].IN_acid_base_equilibrium.activate()\n self.KH_co2.unfix()\n self.KH_ch4.unfix()\n self.KH_h2.unfix()\n self.CO2_Henrys_law.activate()\n self.Ch4_Henrys_law.activate()\n self.H2_Henrys_law.activate()\n\n if not check_optimal_termination(results):\n raise InitializationError(\n f\"{self.name} failed to initialize successfully. Please check \"\n f\"the output logs for more information.\"\n )\n\n init_log.info(\"Initialization Complete: {}\".format(idaeslog.condition(results)))\n","sub_path":"watertap/unit_models/anaerobic_digestor.py","file_name":"anaerobic_digestor.py","file_ext":"py","file_size_in_byte":38334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"473687446","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n# @Time : 2017/11/1 ~ 2019/9/1\n# @Author : Allen Woo\nimport time\nfrom apps.app import mdbs, cache, app\nfrom apps.configs.sys_config import PLUG_IN_CONFIG_CACHE_KEY, CONFIG_CACHE_TIMEOUT\n\n\ndef import_plugin_config(plugin_name, config):\n \"\"\"\n 导入插件配置到数据库,已存在的则更新时间\n :param plugin_name 插件名\n :param CONFIG:dict\n :return:\n \"\"\"\n current_time = time.time()\n for k, v in config.items():\n if \"value_type\" not in v:\n assert Exception(\n 'Plugin configuration import database error, missing \"value_type\"')\n\n if \"reactivate\" not in v:\n v[\"reactivate\"] = True\n if \"info\" not in v:\n v[\"info\"] = \"\"\n\n # 查找相同的配置\n r = mdbs[\"sys\"].db.plugin_config.find_one(\n {\n \"plugin_name\": plugin_name,\n \"key\": k,\n \"value_type\": v[\"value_type\"]\n })\n if not r:\n # 如果不存在\n mdbs[\"sys\"].db.plugin_config.insert_one(\n {\n \"plugin_name\": plugin_name,\n \"key\": k,\n \"value_type\": v[\"value_type\"],\n \"value\": v[\"value\"],\n \"reactivate\": v[\"reactivate\"],\n \"info\": v[\"info\"],\n \"update_time\": time.time()\n })\n elif r and r[\"update_time\"] < current_time:\n # 存在, 而且比当前时间前的(防止同时启动多个进程时错乱,导致下面程序当旧数据清理)\n mdbs[\"sys\"].db.plugin_config.update_one(\n {\n \"_id\": r[\"_id\"],\n \"update_time\": {\"$lt\": current_time}},\n {\n \"$set\": {\n \"update_time\": current_time,\n \"reactivate\": v[\"reactivate\"],\n \"info\": v[\"info\"]}\n })\n\n # 删除已不需要的配置\n mdbs[\"sys\"].db.plugin_config.delete_many(\n {\"plugin_name\": plugin_name, \"update_time\": {\"$lt\": current_time}})\n # 更新插件配置缓存, # 删除缓存,达到更新缓存\n cache.delete(key=PLUG_IN_CONFIG_CACHE_KEY)\n\n\n@cache.cached(timeout=CONFIG_CACHE_TIMEOUT, key=PLUG_IN_CONFIG_CACHE_KEY)\ndef get_all_config():\n \"\"\"\n 从数据库中查询当前的配置返回\n :return:\n \"\"\"\n all_configs = mdbs[\"sys\"].db.plugin_config.find({})\n configs = {}\n for config in all_configs:\n configs.setdefault(config[\"plugin_name\"], {})\n configs[config[\"plugin_name\"]][config[\"key\"]] = config[\"value\"]\n return configs\n\n\ndef get_plugin_config(plugin_name, key):\n \"\"\"\n 获取网站动态配置中对应的project中key的值\n :return:\n \"\"\"\n with app.app_context():\n return get_all_config()[plugin_name][key]\n\n\ndef get_plugin_configs(plugin_name):\n \"\"\"\n 获取网站动态配置中对应的project\n :return:\n \"\"\"\n with app.app_context():\n return get_all_config()[plugin_name]\n","sub_path":"apps/core/plug_in/config_process.py","file_name":"config_process.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"629608160","text":"import rospy\nimport time\n\nfrom bwi_msgs.srv import QuestionDialog, QuestionDialogResponse, \\\n QuestionDialogRequest\nfrom functools import partial\nfrom qt_gui.plugin import Plugin\nfrom python_qt_binding.QtGui import QFont, QHBoxLayout, QLabel, QLineEdit, \\\n QPushButton, QTextBrowser, QVBoxLayout, \\\n QWidget\nfrom python_qt_binding.QtCore import SIGNAL\n\nclass QuestionDialogPlugin(Plugin):\n\n def __init__(self, context):\n super(QuestionDialogPlugin, self).__init__(context)\n # Give QObjects reasonable names\n self.setObjectName('QuestionDialogPlugin')\n\n font_size = rospy.get_param(\"~font_size\", 40)\n\n # Create QWidget\n self._widget = QWidget()\n self._widget.setFont(QFont(\"Times\", font_size, QFont.Bold))\n self._layout = QVBoxLayout(self._widget)\n self._text_browser = QTextBrowser(self._widget)\n self._layout.addWidget(self._text_browser)\n self._button_layout = QHBoxLayout()\n self._layout.addLayout(self._button_layout)\n\n # layout = QVBoxLayout(self._widget)\n # layout.addWidget(self.button)\n self._widget.setObjectName('QuestionDialogPluginUI')\n if context.serial_number() > 1:\n self._widget.setWindowTitle(self._widget.windowTitle() +\n (' (%d)' % context.serial_number()))\n context.add_widget(self._widget)\n\n # Setup service provider\n self.service = rospy.Service('question_dialog', QuestionDialog,\n self.service_callback)\n self.response_ready = False\n self.response = None\n self.buttons = []\n self.text_label = None\n self.text_input = None\n\n self.connect(self._widget, SIGNAL(\"update\"), self.update)\n self.connect(self._widget, SIGNAL(\"timeout\"), self.timeout)\n\n def shutdown_plugin(self):\n self.service.shutdown()\n\n def service_callback(self, req):\n self.response_ready = False\n self.request = req\n self._widget.emit(SIGNAL(\"update\"))\n # Start timer against wall clock here instead of the ros clock.\n start_time = time.time()\n while not self.response_ready:\n if self.request != req:\n # The request got preempted by a new request.\n return QuestionDialogResponse(QuestionDialogRequest.PREEMPTED, \"\")\n if req.timeout != QuestionDialogRequest.NO_TIMEOUT:\n current_time = time.time()\n if current_time - start_time > req.timeout:\n self._widget.emit(SIGNAL(\"timeout\"))\n return QuestionDialogResponse(\n QuestionDialogRequest.TIMED_OUT, \"\")\n time.sleep(0.2)\n return self.response\n\n def update(self):\n self.clean()\n req = self.request\n self._text_browser.setText(req.message)\n if req.type == QuestionDialogRequest.DISPLAY:\n # All done, nothing more too see here.\n self.response = QuestionDialogResponse(\n QuestionDialogRequest.NO_RESPONSE, \"\")\n self.response_ready = True\n elif req.type == QuestionDialogRequest.CHOICE_QUESTION:\n for index, options in enumerate(req.options):\n button = QPushButton(options, self._widget)\n button.clicked.connect(partial(self.handle_button, index))\n self._button_layout.addWidget(button)\n self.buttons.append(button)\n elif req.type == QuestionDialogRequest.TEXT_QUESTION:\n self.text_label = QLabel(\"Enter here: \", self._widget)\n self._button_layout.addWidget(self.text_label)\n self.text_input = QLineEdit(self._widget)\n self.text_input.editingFinished.connect(self.handle_text)\n self._button_layout.addWidget(self.text_input)\n\n def timeout(self):\n self._text_browser.setText(\"Oh no! The request timed out.\")\n self.clean()\n\n def clean(self):\n while self._button_layout.count():\n item = self._button_layout.takeAt(0)\n item.widget().deleteLater()\n self.buttons = []\n self.text_input = None\n self.text_label = None\n\n def handle_button(self, index):\n self.response = QuestionDialogResponse(index, \"\")\n self.clean()\n self.response_ready = True\n\n def handle_text(self):\n self.response = QuestionDialogResponse(\n QuestionDialogRequest.TEXT_RESPONSE,\n self.text_input.text())\n self.clean()\n self.response_ready = True\n\n def save_settings(self, plugin_settings, instance_settings):\n # TODO save intrinsic configuration, usually using:\n # instance_settings.set_value(k, v)\n pass\n\n def restore_settings(self, plugin_settings, instance_settings):\n # TODO restore intrinsic configuration, usually using:\n # v = instance_settings.value(k)\n pass\n\n #def trigger_configuration(self):\n # Comment in to signal that the plugin has a way to configure\n # This will enable a setting button (gear icon) in each dock widget title bar\n # Usually used to open a modal configuration dialog\n","sub_path":"ros_alfred/src/segbot_gui/src/segbot_gui/plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"156667938","text":"from collections import OrderedDict\n\na = dict()\na['e'] = 1\na['a'] = 2\na.update({'banana': 3, 'apple':4, 'pear': 1, 'orange': 2})\n\na = OrderedDict(sorted(a.items(), key=lambda x:x[1]))\nprint(a)\nd = a.popitem(0)\nprint(d[1])\nprint(\"a\" < \"aa\")","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"107709406","text":"# https://programmers.co.kr/learn/courses/30/lessons/68645\r\n\r\ndef solution(n):\r\n lst = [[0]*n for _ in range(n)]\r\n\r\n for i in range(n):\r\n lst[i][0] = i+1\r\n\r\n for i in range(n):\r\n lst[-1][i] = n + i\r\n\r\n pos = (n-1,n-1)\r\n dir = (-1,-1)\r\n\r\n for i in range(2*n,n*(n+1)//2 + 1):\r\n if lst[pos[0]+dir[0]][pos[1]+dir[1]] != 0:\r\n if dir == (-1,-1):\r\n dir = (1,0)\r\n elif dir == (1,0):\r\n dir = (0,1)\r\n else:\r\n dir = (-1,-1)\r\n pos = (pos[0] + dir[0], pos[1] + dir[1])\r\n lst[pos[0]][pos[1]] = i\r\n\r\n answer = []\r\n for i,v in enumerate(lst):\r\n answer += v[:i+1]\r\n return answer\r\n\r\nprint(solution(5))\r\n","sub_path":"Level 2/삼각 달팽이.py","file_name":"삼각 달팽이.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"289280510","text":"#! /usr/bin/env python\nimport ROOT\nimport optparse\nimport json\nimport sys\nimport os\nimport time\nfrom array import *\nfrom math import sqrt\nfrom math import isnan\n\ndef normalize(hist):\n hist.Scale(1./hist.Integral())\n\ndef main():\n \n #configuration\n usage = 'usage: %prog [options]'\n parser = optparse.OptionParser(usage)\n parser.add_option('-l', '--lumi', dest='lumi' , help='lumi [/pb]', default=35922., type=float)\n parser.add_option('--var', dest='var', default='j_mult_charged', help='observable [default: %default]')\n parser.add_option('--sel', dest='sel', default='1', help='selection [default: %default]')\n parser.add_option('--bin', dest='bin', default='20,0,20', help='selection [default: %default]')\n parser.add_option('-n', '--nevents', dest='nevents', help='number of events for draw', default=ROOT.TVirtualTreePlayer.kMaxEntries, type=long)\n (opt, args) = parser.parse_args()\n \n ROOT.TH1.SetDefaultSumw2(True)\n \n eosdir = '/eos/user/m/mseidel/analysis/TopJetShapes/b312177_new/Chunks/'\n \n t_data_bf = ROOT.TChain('tjsev')\n for trigger in ['SingleElectron', 'SingleMuon']:\n for run in ['B', 'C', 'D', 'E', 'F']:\n if t_data_bf.GetEntries() > opt.nevents: break\n t_data_bf.Add(eosdir+'Data13TeV_'+trigger+'_2016'+run+'_*.root')\n \n t_data_gh = ROOT.TChain('tjsev')\n for trigger in ['SingleElectron', 'SingleMuon']:\n for run in ['G', 'H']:\n if t_data_gh.GetEntries() > opt.nevents: break\n t_data_gh.Add(eosdir+'Data13TeV_'+trigger+'_2016'+run+'_*.root')\n\n t_mc = ROOT.TChain('tjsev')\n for i in range(137):\n if t_mc.GetEntries() > opt.nevents: break\n t_mc.Add(eosdir+'MC13TeV_TTJets_'+str(i)+'.root')\n print('t_mc.GetEntries()', t_mc.GetEntries())\n\n t_data_bf.Draw(opt.var+' >> h_data_bf('+opt.bin+')', 'reco_sel == 1 & ' + opt.sel, \"\", opt.nevents)\n h_data_bf = ROOT.gDirectory.Get(\"h_data_bf\")\n normalize(h_data_bf)\n h_data_bf.SetLineColor(ROOT.kBlack)\n h_data_bf.SetMarkerColor(ROOT.kBlack)\n h_data_bf.SetMarkerStyle(20)\n h_data_bf.SetTitle('')\n h_data_bf.GetXaxis().SetTitle('N_{ch}')\n h_data_bf.GetYaxis().SetRangeUser(0.01, h_data_bf.GetMaximum()*1.6)\n \n t_data_gh.Draw(opt.var+' >> h_data_gh('+opt.bin+')', 'reco_sel == 1 & ' + opt.sel, \"\", opt.nevents)\n h_data_gh = ROOT.gDirectory.Get(\"h_data_gh\")\n normalize(h_data_gh)\n h_data_gh.SetLineColor(ROOT.kGray)\n h_data_gh.SetMarkerColor(ROOT.kGray)\n h_data_gh.SetMarkerStyle(20)\n\n t_mc.Draw(opt.var+' >> h_mc_bf('+opt.bin+')', '(reco_sel == 1 & period == 1 & '+opt.sel+')*weight[0]', \"\", opt.nevents)\n h_mc_bf = ROOT.gDirectory.Get(\"h_mc_bf\")\n normalize(h_mc_bf)\n h_mc_bf.SetLineColor(ROOT.kRed+1)\n \n t_mc.Draw(opt.var+' >> h_mc_gh('+opt.bin+')', '(reco_sel == 1 & period == 2 & '+opt.sel+')*weight[0]', \"\", opt.nevents)\n h_mc_gh = ROOT.gDirectory.Get(\"h_mc_gh\")\n normalize(h_mc_gh)\n h_mc_gh.SetLineColor(ROOT.kBlue+1)\n h_mc_gh.SetLineStyle(7)\n \n # Plot\n ROOT.gStyle.SetOptStat(0)\n c = ROOT.TCanvas('c','c',500,500)\n c.SetBottomMargin(0.0)\n c.SetLeftMargin(0.0)\n c.SetTopMargin(0)\n c.SetRightMargin(0.00)\n c.cd()\n \n p1=ROOT.TPad('p1','p1',0.0,0.32,1.0,1.0)\n p1.SetRightMargin(0.05)\n p1.SetLeftMargin(0.12)\n p1.SetTopMargin(0.06)\n p1.SetBottomMargin(0.01)\n p1.Draw()\n p1.cd()\n \n h_data_bf.GetYaxis().SetLabelSize(0.05)\n h_data_bf.Draw()\n h_data_gh.Draw('same')\n h_mc_bf.Draw('same,hist')\n h_mc_gh.Draw('same,hist')\n \n legend = ROOT.TLegend(0.5,0.6,0.85,0.9)\n legend.SetLineWidth(0)\n legend.SetFillStyle(0)\n legend.AddEntry(h_data_bf, 'Data B-F, mean = %.2f'%(h_data_bf.GetMean()), \"pl\")\n legend.AddEntry(h_data_gh, 'Data GH, mean = %.2f'%(h_data_gh.GetMean()), \"pl\")\n legend.AddEntry(h_mc_bf, 'MC B-F, mean = %.2f'%(h_mc_bf.GetMean()), \"l\")\n legend.AddEntry(h_mc_gh, 'MC GH, mean = %.2f'%(h_mc_gh.GetMean()), \"l\")\n legend.Draw()\n \n c.cd()\n p2 = ROOT.TPad('p2','p2',0.0,0.2,1.0,0.32)\n p2.Draw()\n p2.SetBottomMargin(0.02)\n p2.SetRightMargin(0.05)\n p2.SetLeftMargin(0.12)\n p2.SetTopMargin(0.00)\n p2.cd()\n \n ratio_bf = h_mc_bf.Clone()\n ratio_bf.Divide(h_data_bf)\n ratio_bf.SetTitle('')\n ratio_bf.SetXTitle(h_data_bf.GetXaxis().GetTitle())\n ratio_bf.SetYTitle('MC/data')\n ratio_bf.SetFillColor(ROOT.kGray)\n ratio_bf.GetXaxis().SetTitleSize(0.2)\n ratio_bf.GetXaxis().SetTitleOffset(0.8)\n ratio_bf.GetXaxis().SetLabelSize(0.18)\n ratio_bf.GetYaxis().SetTitleSize(0.16/0.6)\n ratio_bf.GetYaxis().SetTitleOffset(0.3*0.6)\n ratio_bf.GetYaxis().SetLabelSize(0.16/0.6)\n ratio_bf.GetYaxis().SetRangeUser(0.4,1.6)\n ratio_bf.GetYaxis().SetNdivisions(503)\n ratio_bf.Draw()\n \n ratio_gh = h_mc_gh.Clone()\n ratio_gh.Divide(h_data_gh)\n ratio_gh.Draw('same')\n \n c.cd()\n p3 = ROOT.TPad('p3','p3',0.0,0.0,1.0,0.2)\n p3.Draw()\n p3.SetBottomMargin(0.4)\n p3.SetRightMargin(0.05)\n p3.SetLeftMargin(0.12)\n p3.SetTopMargin(0.01)\n p3.cd()\n \n ratio_periods = ratio_bf.Clone()\n ratio_periods.Divide(ratio_gh)\n ratio_periods.SetYTitle('B-F/GH ')\n ratio_periods.GetYaxis().SetRangeUser(0.88,1.12)\n ratio_periods.GetYaxis().SetTitleSize(0.16)\n ratio_periods.GetYaxis().SetTitleOffset(0.3)\n ratio_periods.GetYaxis().SetLabelSize(0.16)\n ratio_periods.Draw()\n \n filename = filter(str.isalnum, opt.var) + '_' + filter(str.isalnum, opt.sel)\n c.Print('quickplots/%s.pdf'%(filename))\n c.Print('quickplots/%s.png'%(filename))\n\n\nif __name__ == \"__main__\":\n\tsys.exit(main())\n","sub_path":"TopAnalysis/test/TopJSAnalysis/quickDataMCPlotRuns.py","file_name":"quickDataMCPlotRuns.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"467225535","text":"from json_functions import load_config\n\n\n\"\"\"\nThis file contains constants useful for interacting with the hardware\nChanging constants may cause hard-to-debug problems\n\"\"\"\n\n\n\"\"\"\nENGINES PINS\nIF YOU'RE WONDERING WHY THIS ORDER PLEASE READ :\nlynxmotion_ssc-32u_usb_user_guide.pdf\n\"\"\"\nVERT_REAR_R = 0\nHORI_REAR_R = 1\nVERT_MIDDLE_R = 2\nHORI_MIDDLE_R = 3\nVERT_FRONT_R = 4\nHORI_FRONT_R = 5\nKNEE_REAR_R = 6\nKNEE_MIDDLE_R = 7\nKNEE_FRONT_R = 8\nVERT_REAR_L = 16\nHORI_REAR_L = 17\nVERT_MIDDLE_L = 18\nHORI_MIDDLE_L = 19\nVERT_FRONT_L = 20\nHORI_FRONT_L = 21\nKNEE_REAR_L = 22\nKNEE_MIDDLE_L = 23\nKNEE_FRONT_L = 24\n\n\nENGINES_DICT_REVERSED = {\n VERT_REAR_R : \"VERT_REAR_R\",\n HORI_REAR_R : \"HORI_REAR_R\",\n VERT_MIDDLE_R : \"VERT_MIDDLE_R\",\n HORI_MIDDLE_R : \"HORI_MIDDLE_R\",\n VERT_FRONT_R : \"VERT_FRONT_R\",\n HORI_FRONT_R : \"HORI_FRONT_R\",\n KNEE_REAR_R : \"KNEE_REAR_R\",\n KNEE_MIDDLE_R : \"KNEE_MIDDLE_R\",\n KNEE_FRONT_R : \"KNEE_FRONT_R\",\n VERT_REAR_L : \"VERT_REAR_L\",\n HORI_REAR_L : \"HORI_REAR_L\",\n VERT_MIDDLE_L : \"VERT_MIDDLE_L\",\n HORI_MIDDLE_L : \"HORI_MIDDLE_L\",\n VERT_FRONT_L : \"VERT_FRONT_L\",\n HORI_FRONT_L : \"HORI_FRONT_L\",\n KNEE_REAR_L : \"KNEE_REAR_L\",\n KNEE_MIDDLE_L : \"KNEE_MIDDLE_L\",\n KNEE_FRONT_L : \"KNEE_FRONT_L\"\n}\n\n\n\"\"\"DO NOT CHANGE THOSE ARRAYS\"\"\"\nENGINES_KNEE = [\n KNEE_FRONT_R, KNEE_FRONT_L,\n KNEE_MIDDLE_R, KNEE_MIDDLE_L,\n KNEE_REAR_R, KNEE_REAR_L\n]\n\nENGINES_HORI = [\n HORI_FRONT_R, HORI_FRONT_L,\n HORI_MIDDLE_R, HORI_MIDDLE_L,\n HORI_REAR_R, HORI_REAR_L\n]\n\nENGINES_VERT = [\n VERT_FRONT_R, VERT_FRONT_L,\n VERT_MIDDLE_R, VERT_MIDDLE_L,\n VERT_REAR_R, VERT_REAR_L\n]\n\nENGINES_FRONT = [\n VERT_FRONT_L, VERT_FRONT_R,\n HORI_FRONT_L, HORI_FRONT_R,\n KNEE_FRONT_L, KNEE_FRONT_R\n]\n\nENGINES_MIDDLE = [\n VERT_MIDDLE_L, VERT_MIDDLE_R,\n HORI_MIDDLE_L, HORI_MIDDLE_R,\n KNEE_MIDDLE_L, KNEE_MIDDLE_R\n]\n\nENGINES_REAR = [\n VERT_REAR_L, VERT_REAR_R,\n HORI_REAR_L, HORI_REAR_R,\n KNEE_REAR_L, KNEE_REAR_R\n]\n\n\"\"\"CONSTANTS TO IMPROVE READABILITY\"\"\"\n\n\"\"\"ENGINE TYPE\"\"\"\nKNEE = 0\nHORI = 1\nVERT = 2\n\n\"\"\"ENGINE ZONES\"\"\"\nFRONT = 0\nMIDDLE = 1\nREAR = 2\n\n\"\"\"MIN/MAX OF THE ENGINE\"\"\"\nMIN = 0\nMAX = 1\n\n\"\"\"SIDE\"\"\"\nLEFT = 0\nRIGHT = 1\n\nARR = load_config()\n\nINDEX_TO_ENGINE_NAME = [\n \"MIN_KNEE_FRONT_LEFT\",\n \"MAX_KNEE_FRONT_LEFT\",\n \"MIN_KNEE_FRONT_RIGHT\",\n \"MAX_KNEE_FRONT_RIGHT\",\n \"MIN_KNEE_MIDDLE_LEFT\",\n \"MAX_KNEE_MIDDLE_LEFT\",\n \"MIN_KNEE_MIDDLE_RIGHT\",\n \"MAX_KNEE_MIDDLE_RIGHT\",\n \"MIN_KNEE_REAR_LEFT\",\n \"MAX_KNEE_REAR_LEFT\",\n \"MIN_KNEE_REAR_RIGHT\",\n \"MAX_KNEE_REAR_RIGHT\",\n \"MIN_HORI_FRONT_LEFT\",\n \"MAX_HORI_FRONT_LEFT\",\n \"MIN_HORI_FRONT_RIGHT\",\n \"MAX_HORI_FRONT_RIGHT\",\n \"MIN_HORI_MIDDLE_LEFT\",\n \"MAX_HORI_MIDDLE_LEFT\",\n \"MIN_HORI_MIDDLE_RIGHT\",\n \"MAX_HORI_MIDDLE_RIGHT\",\n \"MIN_HORI_REAR_LEFT\",\n \"MAX_HORI_REAR_LEFT\",\n \"MIN_HORI_REAR_RIGHT\",\n \"MAX_HORI_REAR_RIGHT\",\n \"MIN_VERT_FRONT_LEFT\",\n \"MAX_VERT_FRONT_LEFT\",\n \"MIN_VERT_FRONT_RIGHT\",\n \"MAX_VERT_FRONT_RIGHT\",\n \"MIN_VERT_MIDDLE_LEFT\",\n \"MAX_VERT_MIDDLE_LEFT\",\n \"MIN_VERT_MIDDLE_RIGHT\",\n \"MAX_VERT_MIDDLE_RIGHT\",\n \"MIN_VERT_REAR_LEFT\",\n \"MAX_VERT_REAR_LEFT\",\n \"MIN_VERT_REAR_RIGHT\",\n \"MAX_VERT_REAR_RIGHT\",\n]\n\nMIN_MAX_ENGINES = [\n [ # KNEE\n [\n [ARR[\"MIN_KNEE_FRONT_LEFT\"], ARR[\"MAX_KNEE_FRONT_LEFT\"]], # FRONT LEFT\n [ARR[\"MIN_KNEE_FRONT_RIGHT\"], ARR[\"MAX_KNEE_FRONT_RIGHT\"]] # FRONT RIGHT\n ],\n [\n [ARR[\"MIN_KNEE_MIDDLE_LEFT\"], ARR[\"MAX_KNEE_MIDDLE_LEFT\"]], # MIDDLE LEFT\n [ARR[\"MIN_KNEE_MIDDLE_RIGHT\"], ARR[\"MAX_KNEE_MIDDLE_RIGHT\"]] # MIDDLE RIGHT\n ],\n [\n [ARR[\"MIN_KNEE_REAR_LEFT\"], ARR[\"MAX_KNEE_REAR_LEFT\"]], # REAR LEFT\n [ARR[\"MIN_KNEE_REAR_RIGHT\"], ARR[\"MAX_KNEE_REAR_RIGHT\"]], # REAR RIGHT\n ]\n ],\n [ # HORI\n [\n [ARR[\"MIN_HORI_FRONT_LEFT\"], ARR[\"MAX_HORI_FRONT_LEFT\"]], # FRONT LEFT\n [ARR[\"MIN_HORI_FRONT_RIGHT\"], ARR[\"MAX_HORI_FRONT_RIGHT\"]] # FRONT RIGHT\n ],\n [\n [ARR[\"MIN_HORI_MIDDLE_LEFT\"], ARR[\"MAX_HORI_MIDDLE_LEFT\"]], # MIDDLE LEFT\n [ARR[\"MIN_HORI_MIDDLE_RIGHT\"], ARR[\"MAX_HORI_MIDDLE_RIGHT\"]] # MIDDLE RIGHT\n ],\n [\n [ARR[\"MIN_HORI_REAR_LEFT\"], ARR[\"MAX_HORI_REAR_LEFT\"]], # REAR LEFT\n [ARR[\"MIN_HORI_REAR_RIGHT\"], ARR[\"MAX_HORI_REAR_RIGHT\"]] # REAR RIGHT\n ]\n ],\n [ # VERT\n [\n [ARR[\"MIN_VERT_FRONT_LEFT\"], ARR[\"MAX_VERT_FRONT_LEFT\"]], # FRONT LEFT\n [ARR[\"MIN_VERT_FRONT_RIGHT\"], ARR[\"MAX_VERT_FRONT_RIGHT\"]], # FRONT RIGHT\n ],\n [\n [ARR[\"MIN_VERT_MIDDLE_LEFT\"], ARR[\"MAX_VERT_MIDDLE_LEFT\"]], # MIDDLE LEFT\n [ARR[\"MIN_VERT_MIDDLE_RIGHT\"], ARR[\"MAX_VERT_MIDDLE_RIGHT\"]], # MIDDLE RIGHT\n ],\n [\n [ARR[\"MIN_VERT_REAR_LEFT\"], ARR[\"MAX_VERT_REAR_LEFT\"]], # REAR LEFT\n [ARR[\"MIN_VERT_REAR_RIGHT\"], ARR[\"MAX_VERT_REAR_RIGHT\"]], # REAR RIGHT\n ]\n ]\n]\n\"\"\"\nExample :\nIf you want to access max knee middle left:\nMIN_MAX_ENGINES[KNEE][MIDDLE][LEFT][MAX]\n\"\"\"\n","sub_path":"Client/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"525371861","text":"N = int(input())\n(*A,) = map(int, input().split())\ncount = 0\nfor i in range(N):\n minj = i\n for j in range(i + 1, N):\n if A[j] < A[minj]:\n minj = j\n A[i], A[minj] = A[minj], A[i]\n if i != minj:\n count += 1\nprint(*A)\nprint(count)\n","sub_path":"ALDS1/02B_SelectionSort.py","file_name":"02B_SelectionSort.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"23488658","text":"# CloudVision\n# Author: alekssamos\n# Copyright 2020, released under GPL.\n# Add-on that gets description of current navigator object based on visual features,\n# the computer vision heavy computations are made in the cloud.\n# VISIONBOT.RU\nCloudVisionVersion = \"2.0.3\"\nimport sys\nimport os\nimport tempfile\nimport subprocess\nfrom xml.parsers import expat\nfrom collections import namedtuple\ntry:\n\tfrom cBytesIO import BytesIO ## 2\n\tfrom cStringIO import StringIO ## 2\nexcept ImportError:\n\tfrom io import BytesIO ## 3\n\tfrom io import StringIO ## 3\nimport configobj\nimport tones\ntry:\n\timport validate\nexcept ImportError:\n\timport configobj.validate as validate\nimport wx\nimport config\nimport globalPluginHandler\nimport gui\nimport scriptHandler\nfrom threading import Timer\nimport speech\nimport api\nfrom logHandler import log\nimport languageHandler\nimport addonHandler\naddonHandler.initTranslation()\nimport textInfos.offsets\nimport ui\nfrom globalCommands import SCRCAT_OBJECTNAVIGATION\nfrom time import sleep\nfrom math import sqrt\n\nimport base64\nif sys.version_info.major == 2:\n\timport urllib as ur, urllib as up\nelif sys.version_info.major == 3:\n\timport urllib.request as ur, urllib.parse as up\n\nclass SettingsDialog(gui.SettingsDialog):\n\ttitle = _(\"CloudVision Settings\")\n\n\tdef makeSettings(self, sizer):\n\t\tsettingsSizerHelper = gui.guiHelper.BoxSizerHelper(self, sizer=sizer)\n\n\t\tself.sound = wx.CheckBox(self, label=_(\"&Play sound during recognition\"))\n\t\tself.sound.SetValue(getConfig()[\"sound\"])\n\t\tsettingsSizerHelper.addItem(self.sound)\n\n\t\tself.textonly = wx.CheckBox(self, label=_(\"Recognize &text\"))\n\t\tself.textonly.SetValue(getConfig()[\"textonly\"])\n\t\tsettingsSizerHelper.addItem(self.textonly)\n\n\t\tself.imageonly = wx.CheckBox(self, label=_(\"Recognize &images\"))\n\t\tself.imageonly.SetValue(getConfig()[\"imageonly\"])\n\t\tsettingsSizerHelper.addItem(self.imageonly)\n\n\t\tself.qronly = wx.CheckBox(self, label=_(\"Read &QR / bar code\"))\n\t\tself.qronly.SetValue(getConfig()[\"qronly\"])\n\t\tsettingsSizerHelper.addItem(self.qronly)\n\n\t\tself.trtext = wx.CheckBox(self, label=_(\"Translate text\"))\n\t\tself.trtext.SetValue(getConfig()[\"trtext\"])\n\t\tsettingsSizerHelper.addItem(self.trtext)\n\n\t\tlangs = sorted(supportedLocales)\n\t\tcurlang = getConfig()['language']\n\t\ttry:\n\t\t\tselect = langs.index(curlang)\n\t\texcept ValueError:\n\t\t\tselect = langs.index('en')\n\t\tchoices = [languageHandler.getLanguageDescription(locale) or locale for locale in supportedLocales]\n\t\tself.language = settingsSizerHelper.addLabeledControl(_(\"Select image description language, other languages than english are more prone to translation errors\"), wx.Choice, choices=choices)\n\t\tself.language.SetSelection(select)\n\t\tdef on_open_visionbot_ru_button(self):\n\t\t\timport webbrowser as wb\n\t\t\twb.open(\"https://visionbot.ru/?fromaddon=1&addonversion=\"+CloudVisionVersion)\n\t\tself.open_visionbot_ru_button = wx.Button(self, label=_(\"Open site\")+\" VISIONBOT.RU\")\n\t\tself.open_visionbot_ru_button.Bind(wx.EVT_BUTTON, on_open_visionbot_ru_button)\n\t\tsettingsSizerHelper.addItem(self.open_visionbot_ru_button)\n\t\t\n\tdef postInit(self):\n\t\tself.sound.SetFocus()\n\n\tdef onOk(self, event):\n\t\tif not self.textonly.IsChecked() and not self.imageonly.IsChecked():\n\t\t\tself.textonly.SetValue(True)\n\t\t\tself.imageonly.SetValue(True)\n\t\tgetConfig()[\"sound\"] = self.sound.IsChecked()\n\t\tgetConfig()[\"textonly\"] = self.textonly.IsChecked()\n\t\tgetConfig()[\"imageonly\"] = self.imageonly.IsChecked()\n\t\tgetConfig()[\"trtext\"] = self.trtext.IsChecked()\n\t\tgetConfig()[\"qronly\"] = self.qronly.IsChecked()\n\t\tgetConfig()[\"language\"] = supportedLocales[self.language.GetSelection()]\n\n\t\ttry:\n\t\t\tgetConfig().write()\n\t\texcept IOError:\n\t\t\tlog.error(\"Error writing CloudVision configuration\", exc_info=True)\n\t\t\tgui.messageBox(e.strerror, _(\"Error saving settings\"), style=wx.OK | wx.ICON_ERROR)\n\n\t\tsuper(SettingsDialog, self).onOk(event)\n\nclass GlobalPlugin(globalPluginHandler.GlobalPlugin):\n\tdef __init__(self):\n\t\tsuper(globalPluginHandler.GlobalPlugin, self).__init__()\n\t\tself.CloudVisionSettingsItem = gui.mainFrame.sysTrayIcon.preferencesMenu.Append(wx.ID_ANY,\n\t\t\t_(\"Cloud Vision settings...\"))\n\t\tgui.mainFrame.sysTrayIcon.Bind(\n\t\t\twx.EVT_MENU, lambda evt: gui.mainFrame._popupSettingsDialog(SettingsDialog), self.CloudVisionSettingsItem)\n\n\tdef terminate(self):\n\t\ttry:\n\t\t\tgui.mainFrame.sysTrayIcon.preferencesMenu.RemoveItem(\n\t\t\t\tself.CloudVisionSettingsItem)\n\t\texcept:\n\t\t\tpass\n\n\ttmr = None\n\tlast_resp = \"\"\n\tisVirtual = False\n\tisWorking = False\n\n\tdef beep_start(self, thrc=False):\n\t\tif thrc and not self.isWorking: return False\n\t\tself.isWorking = True\n\t\ttones.beep(500, 100)\n\t\tself.bp = Timer(1, self.beep_start, [True])\n\t\tself.bp.start()\n\t\treturn True\n\n\tdef beep_stop(self):\n\t\tself.isWorking = False\n\t\tself.bp.cancel()\n\t\treturn True\n\n\n\tdef thr_analyzeObject(self, gesture, api_url, img_str, lang, s=0, n=0, t=0, q=0):\n\t\tif s: self.beep_start()\n\t\tfor ii in range(2):\n\t\t\ttry:\n\t\t\t\tresp = ur.urlopen(api_url, up.urlencode({\"v\":CloudVisionVersion, \"n\":n, \"t\":t, \"s\":s, \"q\":q, \"lang\":lang, \"img_str\":img_str}).encode('utf-8'), timeout=60).read().decode('utf-8')\n\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tresp = \"\"\n\t\tself.isWorking = False\n\t\tif resp: self.last_resp = resp\n\t\tif not resp.strip(): resp = _(\"Error\")\n\t\tif s: self.beep_stop()\n\t\tif not self.isVirtual:\n\t\t\tspeech.cancelSpeech()\n\t\t\tui.message(_('Analysis completed: ') + resp)\n\t\telse:\n\t\t\tui.browseableMessage(resp, _(\"CloudVision result\"))\n\t\tself.isVirtual = False\n\n\tdef script_analyzeObject(self, gesture):\n\t\tif not self.isVirtual: self.isVirtual = scriptHandler.getLastScriptRepeatCount()>0\n\t\tif self.isVirtual: return True\n\t\tif self.isWorking: return False\n\t\tself.isWorking = True\n\t\tapi_url = \"https://visionbot.ru/addon/index.php\"\n\t\tif self.tmr: self.tmr.cancel()\n\t\tspeech.cancelSpeech()\n\t\tui.message(_(\"Analyzing navigator object\"))\n\t\ttry: nav = api.getNavigatorObject()\n\t\texcept: return False\n\n\t\tif not nav.location:\n\t\t\tspeech.cancelSpeech()\n\t\t\tui.message(_(\"This navigator object is not analyzable\"))\n\t\t\treturn\n\t\tleft, top, width, height = nav.location\n\n\t\tbmp = wx.EmptyBitmap(width, height)\n\t\tmem = wx.MemoryDC(bmp)\n\t\tmem.Blit(0, 0, width, height, wx.ScreenDC(), left, top)\n\t\timage = bmp.ConvertToImage()\n\t\ttry: body = BytesIO()\n\t\texcept TypeError: body = StringIO()\n\t\tif wx.__version__ == '3.0.2.0': # Maintain compatibility with old version of WXPython\n\t\t\timage.SaveStream(body, wx.BITMAP_TYPE_PNG)\n\t\telse: # Used in WXPython 4.0\n\t\t\timage.SaveFile(body, wx.BITMAP_TYPE_PNG)\n\n\t\timg_str = base64.b64encode(body.getvalue())\n\n\t\tsound = getConfig()['sound']\n\t\ts=0\n\t\tif sound: s=1\n\t\ttextonly = getConfig()['textonly']\n\t\timageonly = getConfig()['imageonly']\n\t\tn=0\n\t\tif textonly and not imageonly: n=1\n\t\tif not textonly and imageonly: n=2\n\t\ttrtext = getConfig()['trtext']\n\t\tt=0\n\t\tif trtext: t=1\n\t\tqronly = getConfig()['qronly']\n\t\tq=0\n\t\tif qronly: q=1\n\t\tlang = getConfig()['language']\n\n\t\tself.tmr = Timer(0.1, self.thr_analyzeObject, [gesture, api_url, img_str, lang, s, n, t, q])\n\t\tself.tmr.start()\n\n\tscript_analyzeObject.__doc__ = _(\"Gives a description on how current navigator object looks like visually,\\n\"\n\t\"if you press twice quickly, a virtual viewer will open.\")\n\tscript_analyzeObject.category = _('Cloud Vision')\n\n\tdef script_copylastresult(self, gesture):\n\t\tif not self.last_resp:\n\t\t\tui.message(_(\"Text Not Found.\"))\n\t\t\treturn False\n\t\ttry: unc = unicode\n\t\texcept NameError: unc = str\n\t\tif api.copyToClip(unc(self.last_resp)):\n\t\t\tui.message(_(\"Result copyed in clipboard.\\n\") + self.last_resp)\n\t\t\treturn True\n\t\treturn False\n\n\tscript_copylastresult.__doc__ = _('Copy last result in clipboard.')\n\tscript_copylastresult.category = _('Cloud Vision')\n\n\t__gestures = {\n\t\t\"kb:NVDA+Control+I\": \"analyzeObject\",\n\t}\n\nsupportedLocales = [\n\t\"bg\",\n\t\"ca\",\n\t\"cs\",\n\t\"da\",\n\t\"de\",\n\t\"el\",\n\t\"en\",\n\t\"es\",\n\t\"fi\",\n\t\"fr\",\n\t\"hu\",\n\t\"id\",\n\t\"it\",\n\t\"ja\",\n\t\"ko\",\n\t\"lt\",\n\t\"lv\",\n\t\"nb_r\",\n\t\"nl\",\n\t\"pl\",\n\t\"pt\",\n\t\"ro\",\n\t\"ru\",\n\t\"sk\",\n\t\"sl\",\n\t\"sr\",\n\t\"sv\",\n\t\"tg\",\n\t\"tr\",\n\t\"uk\",\n\t\"vi\",\n\t\"zh_CN\"\n]\n\ndef getDefaultLanguage():\n\tlang = languageHandler.getLanguage()\n\n\tif lang not in supportedLocales and \"_\" in lang:\n\t\tlang = lang.split(\"_\")[0]\n\t\n\tif lang not in supportedLocales:\n\t\tlang = \"en\"\n\n\treturn lang\n\n_config = None\nconfigspec = StringIO(u\"\"\"\nsound=boolean(default=False)\ntextonly=boolean(default=True)\nimageonly=boolean(default=True)\nqronly=boolean(default=False)\ntrtext=boolean(default=False)\nlanguage=string(default={defaultLanguage})\n\"\"\".format(defaultLanguage=getDefaultLanguage()))\ndef getConfig():\n\tglobal _config\n\tif not _config:\n\t\tpath = os.path.join(config.getUserDefaultConfigPath(), \"CloudVision.ini\")\n\t\t_config = configobj.ConfigObj(path, configspec=configspec)\n\t\tval = validate.Validator()\n\t\t_config.validate(val)\n\treturn _config","sub_path":"addon/globalPlugins/CloudVision/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"252945386","text":"# -*- coding: utf-8 -*\nimport tensorflow as tf\nimport numpy as np\nimport random\nimport time\nimport gc\nimport os\n\nfrom operator import mul\nfrom Settings import *\n\nimport DataGenerator\nimport RRNN\n\n#Modified on 19-5-13 pm-15:16\ndef run():\n\t# 1.Get instance of data generator to prepare training or testing data.\n\tDA=DataGenerator.data_generator(path_train_dataset)\n\ttotal_steps=int((DA.len-p_NSTEPS)/(p_JUMP*BATCH_SIZE))\n\n\t# 2.Define the front end of RRNN and input(tf.placeholder) of whole network.\n\tdiminput = 303\n\tW = {\"h1\" : tf.Variable(tf.random_normal([diminput,p_DIMHIDDEN]),name=\"W_h1\")}\n\tb = {\"b1\" : tf.Variable(tf.random_normal([p_DIMHIDDEN]),name=\"B_b1\")}\n\n\tA= tf.placeholder(\"float\", [None,p_NSTEPS,diminput])\n\tB= tf.placeholder(\"float\", [None,p_NSTEPS,diminput])\n\n\tA1 = tf.transpose(A,[1,0,2])\n\tB1=tf.transpose(B,[1,0,2])\n\n\t# [nsteps,None,diminput] -> [nsteps*None,diminput]\n\tA1 = tf.reshape(A1,[-1,diminput])\n\tB1 = tf.reshape(B1,[-1,diminput])\n\n\t# -> [nsteps*None,dimhidden]\n\tHA = tf.matmul(A1,W[\"h1\"])+b[\"b1\"]\n\tHB = tf.matmul(B1,W[\"h1\"])+b[\"b1\"]\n\t# len(H_1)=28 ,H_1[i] -> [None,dimhidden]\n\tHA = tf.split(HA,p_NSTEPS,0)\n\tHB = tf.split(HB,p_NSTEPS,0)\n\ty= tf.placeholder(\"float\", [None, p_NSTEPS])\n\n\tmy_lstm_rmc=RRNN.lstm_rmc(p_MEM_SLOTS,p_MEM_SIZE,p_NUM_HEAD)\n\tlogit=my_lstm_rmc.inference(HA,HB)\n\n\t#pred=tf.layers.dense(logit[0][-1],units=10)\n\tpred=logit[0]\n\n\t#[nsteps,batch_size] -> [batch_size,nsteps]\n\tpred=tf.transpose(pred,[1,0])\n\n\tcost = tf.reduce_mean(tf.pow(tf.subtract(pred, y), 2.))\n\n\tif p_IS_learning_decay:\n\t\t#Using learning rate decay\n\t\tglobal_step=tf.get_variable('global_step',[],initializer=tf.constant_initializer(0),trainable=False)\n\n\t\tlearning_rate_stable = tf.train.exponential_decay(p_LR,\n\t\t\t\t\tglobal_step,decay_steps=total_steps,decay_rate=p_Decay_rate,staircase=True)\n\n\t\toptm = tf.train.AdagradOptimizer(learning_rate_stable).minimize(cost,global_step=global_step)\n\telse:\n\t\t\t#Do not use \n\t\toptm = tf.train.AdagradOptimizer(learning_rate).minimize(cost)\n\taccr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred,1), tf.argmax(y,1)), tf.float32))\n\ttf.summary.scalar('loss',cost)\n\n\n\t# 3.Load the network weight\n\tsess=tf.Session()\n\tinit=tf.global_variables_initializer()\n\tsaver=tf.train.Saver(tf.global_variables())\n\tsess.run(init)\n\tsaver.restore(sess,path_weight)\n\n\t# 4.Test the convergence effect(针对某数据集测试拟合收敛效果):\n\ts=time.time()\n\t#reset data generator index.\n\tif DA.index!=0:\n\t\tDA.index=0\n\tac_1=0\n\tac_2=0\n\tac_3=0\n\tbatch_size=1\n \n\t\n\tl=[np.eye(p_MEM_SLOTS,p_NUM_HEAD*p_MEM_SIZE) for i in range(batch_size)]\n\tinit_state=np.stack(l,0)\n\tACC_3=0.0\n\tfor i in range(total_steps):\n\t\t# When testing,'jump' equals 'nsteps'\n\t\tbatch_A, batch_B ,batch_R= DA.next_batch(batch_size,p_NSTEPS,p_NSTEPS)\n\t\tfeeds = {A: batch_A, B: batch_B, y:batch_R,my_lstm_rmc._init_state:init_state}\n\t\tlos=sess.run(cost,feed_dict=feeds)\n\t\tif los < 0.03:\n\t\t\tac_3+=1\n\t\t\tif los < 0.02:\n\t\t\t\tac_2+=1\n\t\t\t\tif los < 0.01:\n\t\t\t\t\tac_1+=1\n\t\tACC_3=ac_3 / float(i+1)\n\t\tif i % (int(total_steps/10))==0 and i!=0:\n\t\t\tprint('Current accuracy is:{}'.format(ACC_3))\n \n\tprint('Take {} sec.'.format(time.time()-s))\n\tprint('For all samples,Loss < 0.03 takes {:.2f} %'.format(100*ACC_3))\n\tprint('For all samples,Loss < 0.02 takes {:.2f} %'.format(100*float(ac_2) / ac_3 * ACC_3))\n\tprint('For all samples,Loss < 0.01 takes {:.2f} %'.format(100*float(ac_1) / ac_3 * ACC_3))\n\nif __name__=='__main__':\n\tprint('Preparing for testing,this may take several seconds.')\n\trun()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"508628412","text":"from tkinter import *\nfrom tkinter import ttk\nimport Functions\n#Create the form\nform = Tk(className='user input')\nform.geometry(\"500x600\")\n#create labels\nfeature_string1 = StringVar()\nfeature_string1.set(\"Select feature 1:\")\nfeatures_label1 = Label(form, textvariable = feature_string1)\nfeatures_label1.place(x = 30, y = 30)\n\nfeature_string2 = StringVar()\nfeature_string2.set(\"Select feature 2:\")\nfeatures_label2 = Label(form, textvariable = feature_string2)\nfeatures_label2.place(x = 30, y = 80)\n\nclass_string1 = StringVar()\nclass_string1.set(\"Select class 1:\")\nclass_label1 = Label(form, textvariable = class_string1)\nclass_label1.place(x = 30, y = 130)\n\nclass_string2 = StringVar()\nclass_string2.set(\"Select class 2:\")\nclass_label2 = Label(form, textvariable = class_string2)\nclass_label2.place(x = 30, y = 180)\n\neta_string = StringVar()\neta_string.set(\"Enter learning rate(eta):\")\neta_label = Label(form, textvariable = eta_string)\neta_label.place(x = 30, y = 230)\n\nm_string = StringVar()\nm_string.set(\"Enter number of epochs(m):\")\nm_label = Label(form, textvariable = m_string)\nm_label.place(x = 30, y = 280)\n\nmse_string = StringVar()\nmse_string.set(\"Enter MSE Threshold:\")\nmse_label = Label(form, textvariable = mse_string)\nmse_label.place(x = 30, y = 330)\n\n#create combo boxes\nf1_combo = ttk.Combobox(form, values = [\"X1\", \"X2\", \"X3\", \"X4\"])\nf1_combo.current(0)\nf1_combo.place(x = 250, y = 30)\n\nf2_combo = ttk.Combobox(form, values = [\"X1\", \"X2\", \"X3\", \"X4\"])\nf2_combo.current(0)\nf2_combo.place(x = 250, y = 80)\n\nc1_combo = ttk.Combobox(form, values = [\"C1\", \"C2\", \"C3\"])\nc1_combo.current(0)\nc1_combo.place(x = 250, y = 130)\n\nc2_combo = ttk.Combobox(form, values = [\"C1\", \"C2\", \"C3\"])\nc2_combo.current(0)\nc2_combo.place(x = 250, y = 180)\n#create textboxes\neta_str = StringVar(form, value='0.0')\neta_entry = ttk.Entry(form, textvariable = eta_str)\neta_entry.place(x = 250, y = 230)\n\nm_str = StringVar(form, value= '1')\nm_entry = ttk.Entry(form, textvariable = m_str)\nm_entry.place(x = 250, y = 280)\n\nmse_str = StringVar(form, value= '0.01')\nmse_entry = ttk.Entry(form, textvariable = mse_str)\nmse_entry.place(x = 250, y = 330)\n\n#create checkbox\nb_string = StringVar()\nb_string.set(\"Add bias\")\ncheck_var = IntVar()\nb_check = ttk.Checkbutton(form, textvariable = b_string, variable = check_var)\nb_check.place(x = 30, y = 380)\n#global_data_variables\nf1 = 'X1'\nf2 = 'X2'\nc1 = 'C1'\nc2 = 'C2'\neta = 0.0\nm = 1\nb = 0\nmse = 0.01\n#save after complete input\ndef save():\n global f1\n global f2\n global c1\n global c2\n global eta\n global m\n global b\n global mse\n f1 = f1_combo.get()\n f2 = f2_combo.get()\n c1 = c1_combo.get()\n c2 = c2_combo.get()\n eta = float(eta_entry.get())\n m = int(m_entry.get())\n b = int(check_var.get())\n mse = float(mse_entry.get())\n print(f1, f2, c1, c2, eta, m, b, mse)\n#save button\nsave_b = Button(form, text = 'Save', command = save)\nsave_b.place(x = 30, y = 430)\n#train button\ntrain_b = Button(form, text = 'Train', command = lambda : Functions.train(c1, c2, f1, f2, m, eta, b, mse))\ntrain_b.place(x = 230, y = 430)\n#testing button\ntest_b = Button(form, text = 'Test', command = lambda : Functions.test(c1, c2, f1, f2, b))\ntest_b.place(x = 30, y = 480)\n#display button\ndisplay_b = Button(form, text = 'Dispaly plot', command = lambda : Functions.display_plot(c1, c2, f1, f2))\ndisplay_b.place(x = 230, y = 480)\nform.mainloop()\n\n","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"225313450","text":"# Imports\nfrom sys import path\npath.append(\"../distill-and-select\")\n\nimport torch\nimport pickle\nimport os.path\nimport numpy as np\nfrom model.feature_extractor import FeatureExtractor\nfrom model.students import FineGrainedStudent, CoarseGrainedStudent\nfrom model.selector import SelectorNetwork\nfrom utils import load_video, collate_eval\nfrom pathlib import Path\n\n# Configurations\nPERCENTAGE = 0.75 # Percentage for re-ranking\nTARGET_DIR = \"/mydata/UCF101\"\nQUERY_DIR = \"/mydata/UCF101_Query\"\nFEATURE_DIR = \"/mydata/UCF101_Feature_Data\"\nGROUND_TRUTH = \"ucf101_groundtruth.pickle\"\n\n# Ref: https://gist.github.com/bwhite/3726239 - Start\ndef precision_at_k(r, k):\n assert k >= 1\n r = np.asarray(r)[:k] != 0\n if r.size != k:\n raise ValueError('Relevance score length < k')\n return np.mean(r)\n\n\ndef average_precision(r):\n r = np.asarray(r) != 0\n out = [precision_at_k(r, k + 1) for k in range(r.size) if r[k]]\n if not out:\n return 0.\n return np.mean(out)\n\n\ndef mean_average_precision(rs):\n return np.mean([average_precision(r) for r in rs])\n# Ref: https://gist.github.com/bwhite/3726239 - End\n\n\ndef get_mAP(results):\n return mean_average_precision(results)\n\n\ndef get_binary_relevance(results, ground_truth):\n relevance_results = [1 if result in ground_truth else 0 for result in results]\n return relevance_results\n\n\ndef get_ground_truth(video_id, groundtruth):\n category = video_id.split(\"_\")[1]\n return groundtruth[category]\n\n\ndef get_video_list(inp_dir):\n video_lst = []\n\n # Iterating over the video directory\n for filename in os.listdir(inp_dir):\n # Ensuring that it is a video file.\n if filename.endswith(\".avi\"):\n video_lst.append(filename)\n\n return video_lst\n\n\nif __name__ == '__main__':\n relevance_2_lst, relevance_4_lst, relevance_8_lst, relevance_16_lst = [], [], [], []\n\n # Creating features directory if it does not exist\n os.makedirs(FEATURE_DIR, exist_ok=True)\n # Clearing the results file, if it exists\n if Path(\"dns_results.txt\").exists():\n os.remove(\"dns_results.txt\")\n\n # Obtaining the list of videos\n target_lst = get_video_list(TARGET_DIR)\n query_lst = get_video_list(QUERY_DIR)\n\n # Feature extraction network used in the experiments\n feature_extractor = FeatureExtractor(dims=512)\n\n # Fine-grained Students\n fg_att_student = FineGrainedStudent(pretrained=True, attention=True)\n fg_bin_student = FineGrainedStudent(pretrained=True, binarization=True)\n\n # Coarse-grained Students\n cg_student = CoarseGrainedStudent(pretrained=True)\n\n # Selector Networks\n selector_att = SelectorNetwork(pretrained=True, attention=True)\n selector_bin = SelectorNetwork(pretrained=True, binarization=True)\n\n # Setting the model in evalution mode\n selector_att.eval()\n\n # Loading the ground truth\n with open(GROUND_TRUTH, 'rb') as handle:\n groundtruth = pickle.load(handle)\n\n # Iterating over the query\n for query in query_lst:\n print(\"eval_dns_test_set.py :: processing query :: \", query)\n\n try:\n # Check if video features are present\n if not os.path.isfile(FEATURE_DIR + \"/\" + query + \".pickle\"):\n # Extracting query features\n print(\"eval_dns_test_set.py :: Extracting query features for the query :: \", query)\n query_video = torch.from_numpy(load_video(QUERY_DIR + \"/\" + query, cc_size=224, rs_size=256))\n video_features = feature_extractor(query_video)\n max_len = video_features.size(0)\n max_reg = video_features.size(1)\n padded_videos = video_features.new(*(1, max_len, max_reg, 512)).fill_(0)\n length = video_features.size(0)\n padded_videos[0, :length] = video_features\n\n # Saving the features as a pickle file\n with open(FEATURE_DIR + \"/\" + query + \".pickle\", 'wb') as f:\n pickle.dump(padded_videos, f)\n\n # Load preconstructed features\n with open(FEATURE_DIR + \"/\" + query + \".pickle\", 'rb') as f:\n padded_videos = pickle.load(f)\n\n # Extracting query video representations for the student and selector networks\n query_fg_features = fg_att_student.index_video(padded_videos)\n query_cg_features = cg_student.index_video(padded_videos)\n query_sn_features = selector_att.index_video(padded_videos)\n\n similarity_lst, result_lst = [], []\n # Iterating over the target\n for targ in target_lst:\n\n # Skipping the query video\n if targ == query:\n continue\n\n try:\n # Check if video features are present\n if not os.path.isfile(FEATURE_DIR + \"/\" + targ + \".pickle\"):\n # Extracting the video features\n print(\"eval_dns_test_set.py :: Extracting query features for the targ :: \", targ)\n targ_video = torch.from_numpy(load_video(TARGET_DIR + \"/\" + targ, cc_size=224, rs_size=256))\n video_features = feature_extractor(targ_video)\n max_len = video_features.size(0)\n max_reg = video_features.size(1)\n padded_videos = video_features.new(*(1, max_len, max_reg, 512)).fill_(0)\n length = video_features.size(0)\n padded_videos[0, :length] = video_features\n\n # Saving the features as a pickle file\n with open(FEATURE_DIR + \"/\" + targ + \".pickle\", 'wb') as f:\n pickle.dump(padded_videos, f)\n\n # Load preconstructed features\n with open(FEATURE_DIR + \"/\" + targ + \".pickle\", 'rb') as f:\n padded_videos = pickle.load(f)\n\n # Extracting coarse grained features\n cg_features = cg_student.index_video(padded_videos)\n\n # Obtaining selector features\n sn_features = selector_att.index_video(padded_videos)\n\n # Obtaining the coarse grained similarity\n coarse_similarity = cg_student.calculate_video_similarity(query_cg_features, cg_features)\n\n # Obtaining the selector scores\n selector_features = torch.cat([query_sn_features, sn_features, coarse_similarity], 1)\n selector_scores = selector_att(selector_features).squeeze(-1).detach().numpy()[0]\n similarity_lst.append(selector_scores)\n\n except:\n print(\"eval_dns_test_set.py :: Exception occurred processing targ :: \", targ)\n\n # Ranking the results based on the coarse grained selector scores\n ranked_selector_scores_lst = np.argsort(np.array(similarity_lst))[::-1][:len(similarity_lst)]\n\n # Obtaining a percentage of the results for re-ranking\n percent_ranked_selector_scores_lst = ranked_selector_scores_lst[\n :int(PERCENTAGE * len(ranked_selector_scores_lst))]\n\n print(\"eval_dns_test_set.py :: Re-ranking the results for query :: \", query)\n # Re-ranking the results\n if len(percent_ranked_selector_scores_lst):\n for idx in percent_ranked_selector_scores_lst:\n targ = target_lst[idx]\n\n # Check if video features are present\n if not os.path.isfile(FEATURE_DIR + \"/\" + targ + \".pickle\"):\n print(\"eval_dns_test_set.py :: Pre-constructed features not available while ranking. Skipping for raking for targ :: \", targ)\n continue\n\n try:\n # Load preconstructed features\n with open(FEATURE_DIR + \"/\" + targ + \".pickle\", 'rb') as f:\n padded_videos = pickle.load(f)\n\n # Extracting fine grained features\n fg_features = fg_att_student.index_video(padded_videos)\n\n # Obtaining the fine grained similarity\n fine_similarity = fg_att_student.calculate_video_similarity(query_fg_features, fg_features)\n fine_similarity = fine_similarity.squeeze(-1).detach().numpy()[0]\n\n # Updating the similarity scores with the fine grained scores\n similarity_lst[idx] = fine_similarity\n except:\n print(\"eval_dns_test_set.py :: Exception occurred re-ranking targ :: \", targ)\n\n # Obtaining the final ranked results\n ranked_selector_scores_lst = np.argsort(np.array(similarity_lst))[::-1][:len(similarity_lst)]\n\n # Obtaining the ground truth\n ground_truth = get_ground_truth(query, groundtruth)\n\n # Creating a result list based on the index\n for idx in ranked_selector_scores_lst:\n result_lst.append(target_lst[idx].split(\"/\")[-1])\n\n # Writing results to the file\n with open('dns_results.txt', 'a+') as f:\n f.write(query + \"=\" + str(result_lst[:16]) + \"\\n\")\n\n # Obtaining the relevance of the results\n relevance_2_lst.append(get_binary_relevance(result_lst[:2], ground_truth))\n relevance_4_lst.append(get_binary_relevance(result_lst[:4], ground_truth))\n relevance_8_lst.append(get_binary_relevance(result_lst[:8], ground_truth))\n relevance_16_lst.append(get_binary_relevance(result_lst[:16], ground_truth))\n\n except Exception as e:\n print(\"eval_dns_test_set.py :: Exception occurred processing query :: \", query)\n print(\"eval_dns_test_set.py :: Exception :: \" + str(e))\n\n # Writing relevalnce lists\n with open('dns_ucf_relevance_2_lst.pkl', 'wb') as fp:\n pickle.dump(relevance_2_lst, fp)\n with open('dns_ucf_relevance_4_lst.pkl', 'wb') as fp:\n pickle.dump(relevance_4_lst, fp)\n with open('dns_ucf_relevance_8_lst.pkl', 'wb') as fp:\n pickle.dump(relevance_8_lst, fp)\n with open('dns_ucf_relevance_16_lst.pkl', 'wb') as fp:\n pickle.dump(relevance_16_lst, fp)\n\n # Obtaining the mAP for the results\n mAP_2 = get_mAP(relevance_2_lst)\n print(\"mAP_2 :: \", mAP_2)\n mAP_4 = get_mAP(relevance_4_lst)\n print(\"mAP_4 :: \", mAP_4)\n mAP_8 = get_mAP(relevance_8_lst)\n print(\"mAP_8 :: \", mAP_8)\n mAP_16 = get_mAP(relevance_16_lst)\n print(\"mAP_16 :: \", mAP_16)","sub_path":"QIK-Videos/Evaluate/UCF101/eval_dns.py","file_name":"eval_dns.py","file_ext":"py","file_size_in_byte":11103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"606132045","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 27 19:34:24 2014\n\n@author: pruvolo\n\"\"\"\nimport sys\nimport pygame\nfrom pygame.locals import *\nimport random\nimport math\nimport time\nimport wave\nimport pyaudio\nimport time\nsys.path.insert(0, '../lib')\n# import thinkdsp as td\n\n\n\nclass PyGameBrickBreakerView:\n \"\"\" renders the BrickBreakerModel to a pygame window \"\"\"\n def __init__(self,model,screen):\n self.model = model\n self.screen = screen\n \n def draw(self):\n pass\n\n\nclass PyGameKeyboardController:\n \"\"\" Manipulate game state based on keyboard input \"\"\"\n def __init__(self, model):\n self.model = model\n '''These are the state values:\n selection: picking a voice\n playback: allows playback after transformations\n '''\n self.mode = \"intro\"\n self.button = 'none'\n self.user_num = 0\n self.start_time = time.time()\n\n def handle_pygame_event(self, event):\n\n if self.mode == \"intro\":\n if event.type == KEYDOWN:\n if event.key == pygame.K_d:\n self.button = 'Start'\n print('Intro')\n sound = pygame.mixer.Sound(\"../poem/Intro.wav\")\n sound.play()\n self.mode = \"record\"\n self.start_time = time.time()\n\n if self.mode == \"record\":\n if event.type == KEYDOWN:\n if event.key == pygame.K_f:\n if self.button == 'none':\n pass\n else:\n print(\"start recording - press stop to terminate recording\")\n CHUNK = 1024 \n FORMAT = pyaudio.paInt16 #paInt8\n CHANNELS = 2 \n RATE = 44100 #sample rate\n RECORD_SECONDS = 20\n WAVE_OUTPUT_FILENAME = \"voice{0}.wav\".format(self.user_num)\n self.user_num = (self.user_num + 1) % 3\n\n p = pyaudio.PyAudio()\n\n stream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK) #buffer\n\n print(\"* recording\")\n\n frames = []\n\n done = False\n while(done == False):\n data = stream.read(CHUNK)\n frames.append(data)\n for newevent in pygame.event.get():\n if newevent.type == KEYDOWN and newevent.key == pygame.K_g:\n done = True\n\n print (\"finished recording\")\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n wf.close() \n\n self.mode = \"play\" \n self.start_time = time.time()\n\n\n if self.mode == \"play\":\n if event.type == pygame.MOUSEBUTTONDOWN:\n\n if event.button == 1: #left click\n poem = pygame.mixer.Sound(\"../poem/Pinar_Poem.wav\")\n poem.play()\n self.button = 'Pinar'\n print(self.button)\n self.start_time = time.time() \n\n if event.button == 3: #right click\n poem = pygame.mixer.Sound(\"../poem/Dimitar_Poem.wav\")\n poem.play()\n self.button = 'Dimitar'\n print(self.button)\n self.start_time = time.time()\n\n\n if event.type == KEYDOWN:\n\n if event.key == pygame.K_d:\n self.button = 'Start'\n print('Intro')\n sound = pygame.mixer.Sound(\"../poem/Intro.wav\")\n sound.play()\n self.mode = \"record\"\n self.start_time = time.time()\n\n if event.key == pygame.K_w:\n poem = pygame.mixer.Sound(\"../poem/voice0.wav\")\n poem.play()\n self.button = 'V1'\n print(self.button)\n self.start_time = time.time() \n\n if event.key == pygame.K_a:\n poem = pygame.mixer.Sound(\"../poem/voice1.wav\")\n poem.play()\n self.button = 'V2'\n print(self.button)\n self.start_time = time.time() \n\n if event.key == pygame.K_s:\n poem = pygame.mixer.Sound(\"../poem/voice2.wav\")\n poem.play()\n self.button = 'V3'\n print(self.button)\n self.start_time = time.time() \n\n if event.key == pygame.K_DOWN:\n poem = pygame.mixer.Sound(\"../poem/Dimitar_Poem.wav\")\n poem.play()\n self.button = 'Dimitar'\n print(self.button)\n self.start_time = time.time() \n\n if event.key == pygame.K_UP:\n poem = pygame.mixer.Sound(\"../poem/Pinar_Poem.wav\")\n poem.play()\n self.button = 'Pinar'\n print(self.button)\n self.start_time = time.time()\n\n if event.key == pygame.K_RIGHT:\n poem = pygame.mixer.Sound(\"../poem/Jee_Poem.wav\")\n poem.play()\n self.button = 'Jee'\n print(self.button)\n self.start_time = time.time() \n\n if event.key == pygame.K_LEFT:\n poem = pygame.mixer.Sound(\"../poem/Jiaying_Poem.wav\")\n poem.play()\n self.button = 'Jiaying'\n print(self.button)\n self.start_time = time.time() \n\n\n \n\n\n\n\nif __name__ == '__main__':\n pygame.mixer.pre_init(48000, 16, 1, 4096)\n pygame.mixer.init()\n pygame.init()\n\n size = (640,480)\n screen = pygame.display.set_mode(size)\n\n view = PyGameBrickBreakerView(None,screen)\n controller = PyGameKeyboardController(None)\n running = True\n start_time = time.time()\n while running:\n d_time = time.time() - controller.start_time\n\n if d_time > 45:\n controller.mode = \"intro\"\n\n for event in pygame.event.get():\n if event.type == QUIT:\n running = False\n controller.handle_pygame_event(event)\n start_time = time.time()\n time.sleep(.001)\n\n pygame.quit()","sub_path":"src/brick_breaker_section_1.py","file_name":"brick_breaker_section_1.py","file_ext":"py","file_size_in_byte":7260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"529726022","text":"# Purpose: Load raw text and excel behavioral data files so that they can be cleaned and transformed into formats that are conducive for loading into an SQLite or PostgreSQL database.\n# Brianne Sutton, PhD\n# June 2018\n\nimport os.path as op\nimport glob\nimport pandas as pd\nimport numpy as np\nimport re\nfrom itertools import dropwhile\nimport sys\n# wasn't recognizing the cwd for some reason. Explicitly adding eliminates the issue\nsys.path.append(op.expanduser('~/Documents/software/git_project_files/genius'))\nfrom locate_files import FoundFiles # local module\n\n\nclass ETL:\n \"\"\"Glimpse the structure of the data, so that intelligent choices for parsing, cleaning, merging, and loading to the DB can be made.\"\"\"\n\n def __init__(self, files):\n self._files = files\n self.base = op.commonpath(self._files)\n self.ext = files[0].strip().split('.')[-1] # should get the extension\n self.match = 'k' # Default for merging df's\n self.k = None\n self.v = None\n\n def __repr__(self):\n return('Goal of etl is to take multiple files, clean them, and prepare them for upload to a common dataframe or DB.', self._files)\n\n def __str__(self):\n return(self._files)\n\n # Take a look at an example textfile for the study to ensure that the correct columns are being culled.\n def preview_record(self):\n \"\"\"Get a feel for the data available in the raw file. This method is not the main parser and only samples a couple of the files (to make sure that one person's data and structure isn't an anomaly).\"\"\"\n if len(self._files) > 2:\n skip_length = int(len(self._files) / 3)\n else:\n skip_length = len(self._files)\n\n for j in range(0, len(self._files), skip_length):\n self.extract(self._files[j])\n\n def extract(self, input_file, params=''):\n \"\"\"Basic parsing for an individual file, not the study-wide df\"\"\"\n subj_base = op.dirname(input_file)\n subj = subj_base.split('/')[-1].split(' ')[0].replace('.', '_')\n # want to get the last numerical value that is not the extension\n timept = (input_file.split('/')[-1].split('.')[-2])[-1]\n subj_name = (subj + '_' + timept)\n #subj_name = '_'.join(input_file.split('/')[-1].replace('.','_').split('_')[:-1])\n clean_file_check = sorted(\n glob.glob(op.join(subj_base, subj_name + '_clean.csv')))\n\n if not clean_file_check:\n if params == '':\n # simple default to check and test\n vars_of_int = ['Pic', 'Prime', 'ACC', 'RT', 'RESP', 'CRESP','correctAnswer','movieFile1']\n else:\n #ADRIC - Is there a way to read the possible fields and have user input for the ones that they want to extract from the text file?\n vars_of_int = params\n\n if 'xls' in self.ext:\n cols = pd.read_excel(input_file, nrows=1).columns.tolist()\n keep_cols = []\n for col in cols:\n if col.strip().startswith('Unnamed'):\n pass\n else:\n keep_cols.append(col.strip())\n # , usecols = [keep_cols])\n table = pd.read_excel(input_file)\n elif 'txt' in self.ext:\n table = pd.read_csv(input_file, sep=\";|,|' '|'\\t'\", encoding='utf-16le',\n engine='python',skipinitialspace=True) # , encoding = 'utf-16' for E-Prime files\n temp_table = pd.DataFrame(table, dtype='str')\n temp_table = temp_table['*** Header Start ***'].str.split(\n ':', n=1, expand=True)\n ix = temp_table.loc[temp_table[0]=='*** Header End ***'].index[0]\n table = temp_table.iloc[(ix+1):,:]\n else:\n table = pd.read_csv(input_file, sep=\";|,|' '|'\\t'\", encoding='utf-16le',\n skipinitialspace=True) # , encoding = 'utf-16'\n\n # Initial cleaning steps\n df = pd.DataFrame(table)\n try:\n keep_cols\n except NameError:\n pass\n else:\n df = df[keep_cols]\n if len(pd.unique(df.iloc[:, 0])) > 1:\n print('Chopping')\n df = df.iloc[:-3, :]\n\n # Can't combine this with the import, because then the keep_cols may have extra entries\n df = df.dropna(axis=1, how='all')\n df['subj'] = subj_name # adds the subj\n print('Working with {}, who has {} lines of data'.format(subj, df.shape))\n\n if self.k is None:\n print(df.head(10))\n self.k = input('Which column header is the key? \\n').strip()\n self.v = input(\n 'Which column header matches the values? \\n').strip()\n if self.k.isdigit():\n print(df.columns.tolist())\n df.rename(columns={df.columns[int(self.k)]: 'k', df.columns[int(self.v)]: 'v'}, inplace=True)\n v_name = 'outcome_value'\n else:\n df.rename(columns={self.k: 'k',\n self.v: 'v'}, inplace=True)\n v_name = self.v\n\n if 'Prime' in df.k:\n # Both this and next line work with Priming #refactor\n df.mask((df.k == 'Prime') & (df.v == ''), inplace=True)\n # Both this and previous line work with Priming. #refactor\n df = df.dropna(how='any')\n\n # Strip whitespace, particularly from text files\n df = df.apply(lambda x: x.str.strip() if x.dtype == str else x)\n df = df.apply(lambda x: x.str.replace(\n '.', '_') if x.dtype == str else x)\n\n if 'txt' in self.ext:\n # Filter for interesting variables\n df = df[df['k'].str.contains(\n 'Pic|RT|ACC|RESP|CRESP|Prime|ImageOrder|sFile|iRate|movieFile1|correctAnswer')].reset_index(drop=True)\n print('Addressing data shaped: {}\\n'.format(df.shape))\n # May need to update search params. \"stims\" = values to pivot on.\n # Find the first stimulus presentation\n print(pd.unique(df.k.tolist()))\n stim = input('Which key are you looking for? (e.g., Pic) \\n').strip()\n stim_list = df.loc[df.k.str.contains(stim), 'v']\n # To get the padding of the list for the new, pivot column correct\n # Get the index for the first presentation\n first_ix = stim_list.index.tolist()[0]\n stim_labels = np.zeros(first_ix)\n trial_labels = np.zeros(first_ix)\n # Adapts the number of stim values to the number of matching characteristics that will be pivoted\n # Figure out how often the stimuli change\n rep_len = int(df.shape[0] / len(stim_list))\n print('Padding {} time(s), adding stim labels every {} rows'.format(\n len(stim_labels), rep_len))\n\n for s, sl in enumerate(stim_list):\n # number of repeated stim names\n add_reps = np.repeat('_' + sl.strip(), rep_len)\n # ever-growing list that will turn into the stim column\n stim_labels = np.append(stim_labels, add_reps)\n add_trial_reps = np.repeat(s, rep_len)\n trial_labels = np.append(trial_labels, add_trial_reps)\n\n # check for mismatches/dangling info at the end of a df\n num_nans = (df.shape[0] - len(stim_labels))\n if num_nans > 0:\n print('Padding final {} values'.format(num_nans))\n nans = np.repeat(\n 'nan', (df.shape[0] - len(stim_labels)))\n stim_labels = np.append(stim_labels, nans).tolist()\n trial_labels = np.append(trial_labels, nans).tolist()\n else:\n stim_labels = stim_labels[:df.shape[0]].tolist()\n trial_labels = trial_labels[:df.shape[0]].tolist()\n\n # adding descriptor columns\n df['stims'] = ((df['k'].map(str) + stim_labels).tolist())\n if stim == 'Pic':\n df['category'] = [x[1:3]\n for x in stim_labels] # subset of the stim label\n df['identifier'] = [x[3:] for x in stim_labels]\n elif 'mov' in stim:\n df['category'] = [x.split('_')[1] for x in stim_labels]\n df['identifier'] = stim_labels\n\n df['trial_num'] = trial_labels\n else:\n df['stims'] = df['k']\n df['category'] = df['k'].str.slice(start=0, stop=2)\n df['identifier'] = df['k'].str.slice(start=2)\n\n df.drop_duplicates(subset='stims', inplace=True)\n if not self.v.isdigit():\n df.rename(columns={'v': v_name}, inplace=True)\n\n # save cleaned version for others to use\n df_loc = op.join(subj_base, subj_name + '_clean.csv')\n df.to_csv(df_loc, index=False)\n else:\n df_loc = clean_file_check[0]\n print('Loading {}'.format(df_loc))\n df = pd.DataFrame(pd.read_csv(df_loc))\n return df, subj_name, df_loc\n\n # Loop extraction solution over all files\n def transform(self, match_key='subj'):\n \"\"\"Take the individual df's and merge them into the study-wide results.\"\"\"\n print('Match key(s) = {}'.format(match_key))\n print('Collecting dataframes.')\n df_dict = {}\n for s, sub in enumerate(self._files):\n [subj_df, subj, df_loc] = self.extract(sub)\n df_dict[subj] = subj_df\n\n # doesn't matter if it is the last entry or not;they're all merged\n df = subj_df.reset_index(drop=True)\n\n print('Merging {} dfs'.format(len(df_dict.keys())))\n # df = df_dict.values()[0]\n for df_k, df_v in df_dict.items():\n df_size = df.shape\n df = pd.merge(df, df_v.reset_index(drop=True), on=match_key,\n suffixes=('', '_y'), how='outer', copy=False)\n df = df.reset_index(drop=True)\n #select_col = [x for x in df.columns if (('ubj' in x) & ('_y' in x))]\n select_col = 'subj_y'\n change = (df[select_col].iloc[0] + '_values') # subj_name\n # moves the subj name to the column title, so that the data is easier to read\n df = df.rename(columns={'value_y': change}, copy=False)\n # limits memory usage a little; drops the \"unnecessary\" columns\n col_drop = [x for x in df.columns if x.endswith('_y')]\n df.drop(col_drop, axis=1, inplace=True)\n print('New df from {} => {}\\nmerged with {}\\nto create >> {} <<'.format(\n df_k, df_v.shape, df_size, df.shape))\n if df.shape[0] > 90000:\n df.to_csv(\n op.join(self.base, 'cleaned_partial_data.csv'), index=False)\n break\n print(df.head(7))\n chop = input('How many setup columns need to be removed? ').strip()\n df = df.iloc[:, int(chop):]\n df.to_csv(op.join(self.base, 'cleaned_data.csv'), index=False)\n print('Final dimensions for wide version are {}'.format(df.shape))\n\n df_long = subj_df.reset_index(drop=True)\n for df_k, df_v in df_dict.items():\n df_long = pd.concat([df_long, df_v], copy=False,\n sort=True).reset_index(drop=True)\n df_long.rename(columns={'v': self.v}).to_csv(\n op.join(self.base, 'cleaned_long_data.csv'), index=False)\n return df, df_long\n\n def db_load(self):\n pass\n\n\nclass ParseRaw:\n def __init__(self):\n pass\n\n def __repr__(self):\n pass\n\n def __str__(self):\n pass\n\n def objectify_raw(self):\n pass\n\n\nif __name__ == \"__main__\":\n # Locate the behavioral files to be extracted, cleaned, and transformed\n # Test cases\n ir = FoundFiles(\n 'IP*xls', 'Image Ratings', '/Users/bmohl/Dropbox (BrainStud)/BrainStud Team Folder/Subject Data')\n priming = FoundFiles(\n 'txt', 'priming', '/Users/bmohl/Dropbox (BrainStud)/BrainStud Team Folder/Subject Data')\n tasks = [ir, priming]\n# Build overarching loop for all class instances of the study\n for t in tasks:\n [base, file_list] = t.get_files()\n recs = ETL(sorted(file_list))\n rec1 = recs.preview_record()\n rec_df, trans_df = recs.transform('stims')\n","sub_path":"behav_etl.py","file_name":"behav_etl.py","file_ext":"py","file_size_in_byte":12808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"400890744","text":"# Copyright (c) 2013 Mirantis Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport flask\nfrom oslo_config import cfg\nfrom six.moves.urllib import parse\n\nfrom dashboard import vault\nfrom spectrometer.openstack.common import log as logging\n\n\nLOG = logging.getLogger(__name__)\n\n\nDEFAULTS = {\n 'review_nth': 5,\n}\n\nMETRIC_LABELS = {\n 'loc': 'Lines of code',\n 'commits': 'Commits',\n 'marks': 'Reviews',\n 'emails': 'Emails',\n}\n\nMETRIC_TO_RECORD_TYPE = {\n 'loc': 'commit',\n 'commits': 'commit',\n 'marks': 'mark',\n 'emails': 'email',\n}\n\nFILTER_PARAMETERS = ['release', 'project_type', 'module', 'company', 'user_id',\n 'metric', 'start_date', 'end_date', 'blueprint_id']\n\nDEFAULT_RECORDS_LIMIT = 10\nDEFAULT_STATIC_ACTIVITY_SIZE = 100\n\n\ndef get_default(param_name):\n if 'release' not in DEFAULTS:\n release = cfg.CONF.default_release\n if not release:\n runtime_storage_inst = vault.get_vault()['runtime_storage']\n releases = runtime_storage_inst.get_by_key('releases')\n if releases:\n release = releases[-1]['release_name']\n else:\n release = 'all'\n DEFAULTS['release'] = release.lower()\n DEFAULTS['metric'] = cfg.CONF.default_metric.lower()\n DEFAULTS['project_type'] = cfg.CONF.default_project_type.lower()\n\n if param_name in DEFAULTS:\n return DEFAULTS[param_name]\n else:\n return None\n\n\ndef get_parameter(kwargs, singular_name, plural_name=None, use_default=True):\n if singular_name in kwargs:\n p = kwargs[singular_name]\n else:\n p = flask.request.args.get(singular_name)\n if (not p) and plural_name:\n p = flask.request.args.get(plural_name)\n if p:\n return parse.unquote_plus(p).split(',')\n elif use_default:\n default = get_default(singular_name)\n return [default] if default else []\n else:\n return []\n\n\ndef get_single_parameter(kwargs, singular_name, use_default=True):\n param = get_parameter(kwargs, singular_name, use_default)\n if param:\n return param[0]\n else:\n return ''\n","sub_path":"dashboard/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"405543225","text":"\"\"\"trnin 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.conf.urls import url\nfrom django.urls import path,include,reverse_lazy\nfrom user import views\nimport course.views\nfrom messenger import views as msg\nfrom django.views.generic.base import TemplateView\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib.auth import views as auth_views\nfrom discuss import views as chat\n\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^login/$', auth_views.LoginView.as_view(template_name=\"registration/login.html\"), name=\"login\"),\n path('', course.views.index, name='Home'),\n path('index',course.views.index),\n path('password_reset/', auth_views.PasswordResetView.as_view(html_email_template_name='registration/password_reset_html_email.html'),name='password_reset'),\n path('',include('django.contrib.auth.urls')),\n\n path('register/',views.register,name='register'),\n path('profile/',views.view_profile,name='profile'),\n path('users/',views.getuser,name='getuser'),\n path('profile/password/',views.change_password,name='change_password'),\n path('profile/edit/',views.edit_profile,name='edit_profile'),\n url(r'^activate/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'),\n\n\n path('activate-mail/', TemplateView.as_view(template_name='registration/activate_mail_sent.html')),\n path('activated/', TemplateView.as_view(template_name='registration/activated.html')),\n\n url(r'^contact/$',msg.messages, name='contact'),\n path('blog/',course.views.blog,name='blog'),\n path('my_courses/',course.views.my_courses,name='my_courses'),\n url(r'^blog/(?P\\d+)/$',course.views.coursedesc,name='detail'),\n url(r'^blog/checkout/(?P\\d+)/$',course.views.checkout,name='checkout'),\n\n url(r'^course-info/(?P[-\\w]+)/$',course.views.coursehome,name='coursehome'),\n url(r'^course/(?P[-\\w]+)/$',course.views.playscorm,name='playscorm'),\n path('store_data/',course.views.store_data,name='store_data'),\n url(r'^discuss/(?P[-\\w]+)/$',chat.discuss,name='chat'),\n url(r'^getmessages/(?P[-\\w]+)/$',chat.messages,name='get_messages'),\n\n url(r'^post_messages/(?P[-\\w]+)/$',chat.postMessage,name='post_messages'),\n\n path('terms-of-service/',course.views.termsofservice,name='termsofservice'),\n path('about/',course.views.about,name='about'),\n url(r'^requirements/(?P[-\\w]+)/$',course.views.requirements,name='requirements'),\n url(r'^schedules/(?P[-\\w]+)/$',course.views.schedules,name='schedules'),\n url(r'^course_home/(?P[-\\w]+)/$',course.views.about_course,name='courseabout'),\n # url(r'^exam/(?P[-\\w]+)/$',course.views.exam,name='exam'),\n url(r'^progress/(?P[-\\w]+)/$',course.views.progress,name='progress'),\n # url(r'^add_question/(?P[-\\w]+)/$',course.views.add_question,name='add_question'),\n url(r'^messages_list/$',msg.messages_list,name='msg_list'),\n url(r'^send-message-to-admin/$',msg.messageToAdmin,name='message_to_admin'),\n url(r'^message/(?P\\d+)/$',msg.get_message,name='msg'),\n\n\n\n\n]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n","sub_path":"trnin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"109611300","text":"from __future__ import print_function\n\nimport copy\nimport os\nimport os.path as fp\nimport pickle\n\nimport pandas as pd\nimport spacy\nfrom educe.stac.annotation import DIALOGUE_ACTS\nfrom educe.stac.corpus import Reader\nfrom educe.stac.graph import Graph\nfrom educe.stac.learning import features as ft\nfrom educe.stac.learning.doc_vectorizer import DialogueActVectorizer, UNK\n\nfrom managers import get_train_games, get_test_games, get_valid_games, get_stac_data_path\nfrom m1.tools.utils import add_path_to_files, extract_corpus\n\nnlp = spacy.load('en')\n\n\ndef extract_single_features(inputs, dialogue_acts):\n def format_single_features(edu_id, vec):\n features = {'speaker_started_the_dialogue': vec['speaker_started_the_dialogue'],\n 'first_speaker_utterance': not vec['speaker_already_spoken_in_dialogue'],\n 'position_in_dialogue': vec['position_in_dialogue'],\n 'ends_with_bang': vec['ends_with_bang'],\n 'ends_with_qmark': vec['ends_with_qmark'],\n 'contains_possessives_nouns': (vec['lex_pronoun_pronoun_1'] or\n vec['lex_pronoun_pronoun_2'] or\n vec['lex_pronoun_pronoun_3'] or\n vec['lex_pronoun_pronoun_1poss'] or\n vec['lex_pronoun_pronoun_2poss'] or\n vec['lex_pronoun_pronoun_3poss']),\n 'contains_modal_modifiers': vec['lex_modifier_modal'] or vec['lex_modifier_negation'],\n 'contains_words_in_lexicons': (vec['lex_domain_ressource_sheep'] or\n vec['lex_domain_ressource_wood'] or\n vec['lex_domain_ressource_wheat'] or\n vec['lex_domain_ressource_ore'] or\n vec['lex_domain_ressource_clay']),\n 'contains_question_words': vec['is_question'],\n 'contains_player_name': vec['has_player_name_fuzzy'],\n 'contains_emoticons': vec['has_emoticons'],\n 'first_word': vec['word_first'],\n 'last_word': vec['word_last'],\n 'subject_lemmas': vec['lemma_subject'],\n 'dialogue_act': dialogue_acts[edu_id],\n }\n return features\n\n single_features = []\n for env in ft.mk_envs(inputs, \"discourse\"):\n doc = env.current.doc\n edus = [unit for unit in doc.units if ft.educe.stac.is_edu(unit)]\n for edu in edus:\n vec = ft.SingleEduKeys(env.inputs)\n vec.fill(env.current, edu)\n\n single_feature = format_single_features(edu.identifier(), vec)\n single_feature['text'] = list(map(str, nlp.tokenizer(edu.text().lower())))\n single_feature = pd.Series(single_feature)\n single_feature.name = edu.identifier()\n\n single_features.append(single_feature)\n return pd.DataFrame(single_features)\n\n\ndef extract_pair_features(inputs, games, path):\n def extract_links(path, games):\n links = set()\n\n game_folders = add_path_to_files(games, fp.join(get_stac_data_path(), path))\n\n for game_folder in game_folders:\n game_path, game_name = os.path.split(game_folder)\n\n game_corpus = Reader(game_path).slurp(doc_glob=game_name)\n for doc_key, doc_val in game_corpus.items():\n if doc_key.annotator == \"GOLD\" and doc_key.stage == \"discourse\":\n flat_graph = Graph().from_doc(game_corpus, doc_key).without_cdus(sloppy=True)\n\n for relation in flat_graph.relations():\n try:\n source, target = flat_graph.links(relation)\n source_id = source[2:]\n if source_id == 'ROOT':\n continue\n target_id = target[2:]\n relation = (source_id, target_id)\n links.add(relation)\n except KeyError:\n continue\n\n return links\n\n pair_features = []\n links = extract_links(path, games)\n\n for env in ft.mk_envs(inputs, \"discourse\"):\n for dia in ft._mk_high_level_dialogues(env.current):\n for source, target in dia.edu_pairs():\n if source.span > target.span or source.identifier() == 'ROOT':\n continue\n vec = ft._extract_pair(env, source, target)\n\n pair_feature = pd.Series({'distance': vec['num_edus_between'],\n 'same_speaker': vec['same_speaker'],\n 'linked': (source.identifier(), target.identifier()) in links})\n pair_feature.name = (source.identifier(), target.identifier())\n\n pair_features.append(pair_feature)\n return pd.DataFrame(pair_features)\n\n\ndef __transform(self, raw_documents):\n \"\"\"\n DO NOT USE.\n Only here to redefine the DialogueActVectorizer.transform method.\n \"\"\"\n for doc in raw_documents:\n for edu in self.instance_generator(doc):\n label = ft.clean_dialogue_act(edu.dialogue_act() or UNK)\n yield edu.identifier(), self.labelset_[label]\n\n\nDialogueActVectorizer.transform = __transform\n\nINPUTS = {}\n\n\ndef load_game(path, games):\n \"\"\"\n\n :param path:\n :param games:\n :return:\n \"\"\"\n if path in INPUTS:\n inputs = copy.deepcopy(INPUTS[path])\n else:\n if fp.isfile('data/inputs_{}.p'.format(path)):\n inputs = pickle.load(open('data/inputs_{}.p'.format(path), 'rb'))\n else:\n inputs = extract_corpus(path)\n pickle.dump(inputs, open('data/inputs_{}.p'.format(path), 'wb'), 2)\n INPUTS[path] = copy.deepcopy(inputs)\n\n for key in inputs.corpus.keys():\n if key.doc not in games:\n del inputs.corpus[key]\n\n dialogues = list(ft.mk_high_level_dialogues(inputs, \"discourse\"))\n labels = DIALOGUE_ACTS\n labtor = DialogueActVectorizer(lambda x: x.edus[1:], labels)\n dialogue_acts = {k: v for k, v in list(labtor.transform(dialogues))}\n\n single_features = extract_single_features(inputs, dialogue_acts)\n pair_features = extract_pair_features(inputs, games, path)\n\n return single_features, pair_features\n\n\ndef load_games(games):\n \"\"\"\n Loads EDUs features from given set type (train/valid/test).\n\n :return: Single features and pair features\n \"\"\"\n\n single_features = []\n pair_features = []\n\n for args in games.items():\n print(\"Loading {}\".format(args))\n sf, pf = load_game(*args)\n single_features.append(sf)\n pair_features.append(pf)\n\n # assert check_graphs_completeness(pair_features)\n\n return pd.concat(single_features), pd.concat(pair_features)\n\n\ndef load_features():\n \"\"\"\n Loads all the features based on config file games.yml.\n \"\"\"\n single_columns = ['set_type',\n 'text',\n 'speaker_started_the_dialogue',\n 'first_speaker_utterance',\n 'position_in_dialogue',\n 'ends_with_bang',\n 'ends_with_qmark',\n 'contains_possessives_nouns',\n 'contains_modal_modifiers',\n 'contains_words_in_lexicons',\n 'contains_question_words',\n 'contains_player_name',\n 'contains_emoticons',\n 'first_word',\n 'last_word',\n 'subject_lemmas',\n 'dialogue_act',\n ]\n single_index = ['edu']\n pair_columns = ['set_type',\n 'linked',\n 'distance',\n 'same_speaker']\n pair_index = ['source', 'target']\n\n set_types = ['train', 'valid', 'test']\n set_games = {'train': get_train_games,\n 'valid': get_valid_games,\n 'test': get_test_games}\n\n single_features = pd.DataFrame(columns=single_index + single_columns).set_index(single_index)\n pair_features = pd.DataFrame(columns=pair_index + pair_columns).set_index(pair_index)\n for set_type in set_types:\n games = set_games[set_type]()\n if len(games) > 0:\n single_feature, pair_feature = load_games(games)\n\n single_features = single_features.append(single_feature)\n single_features.loc[pd.isna(single_features['set_type']), 'set_type'] = set_type\n\n pair_features = pair_features.append(pair_feature)\n pair_features.loc[pd.isna(pair_features['set_type']), 'set_type'] = set_type\n\n return single_features, pair_features\n\n\nsingle_features, pair_features = load_features()\n\nsingle_features.to_pickle(\"data/single_features.p\", protocol=2)\npair_features.to_pickle(\"data/pair_features.p\", protocol=2)\n","sub_path":"m1/tools/corpus.py","file_name":"corpus.py","file_ext":"py","file_size_in_byte":9217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"67375120","text":"from django.shortcuts import render, get_object_or_404, HttpResponseRedirect\nfrom django.http import *\nfrom django.views.decorators.csrf import csrf_exempt\nimport pandas as pd\nfrom .models import *\nfrom apps.horario.models import *\nfrom apps.asistencias.forms import *\nfrom apps.asistencias.models import Asistencias\nimport json\n\n\ndef alumno_list(request):\n a = request.user.id\n materia = request.GET.get('materia')\n nomCurso = request.GET.get('nomCurso')\n listaalumno = Asistencias.objects.raw('SELECT max(horario.\"id\") AS id,curso.nombre , '\n 'lista_listado.\"id\" as idlista, alumno.nombres,'\n 'alumno.apellidos,current_date as hoy, materia.nombre as materia '\n 'FROM horario INNER JOIN curso ON horario.curso_id = curso.\"id\" '\n 'INNER JOIN lista_listado ON lista_listado.curso_id = curso.\"id\" '\n 'INNER JOIN alumno ON lista_listado.alumno_id = alumno.\"id\" '\n 'INNER JOIN silabo ON \"public\".horario.silabo_id= silabo.\"id\" '\n 'INNER JOIN materia ON silabo.materia_id = materia.\"id\" '\n 'WHERE horario.docente_id= %s and curso.nombre= %s '\n 'and materia.nombre = %s GROUP BY curso.nombre , lista_listado.\"id\",'\n 'alumno.nombres,alumno.apellidos,materia.nombre '\n 'order by alumno.apellidos asc ', [a, nomCurso, materia])\n contexto = {'listaalumno': listaalumno}\n\n return render(request, \"back-end/alumno/alumnoindex.html\", contexto)\ndef alumno_list2(request):\n p= 'Presente'\n f='Falta'\n a = request.user.id\n materia = request.GET.get('materia')\n fecha = request.GET.get('fecha')\n nomCurso = request.GET.get('nomCurso')\n listaalumno = Asistencias.objects.raw('SELECT alumno.nombres, alumno.apellidos, '\n 'asistencias_asistencias.\"Asistencia\" '\n 'AS \"id\",Case asistencias_asistencias.\"Asistencia\" WHEN 1 THEN %s WHEN 0 '\n 'THEN %s END as Asistencia, asistencias_asistencias.fecha, '\n 'curso.nombre AS curso, materia.nombre AS materia, horario.docente_id '\n 'FROM asistencias_asistencias '\n 'INNER JOIN lista_listado ON '\n '\"public\".asistencias_asistencias.\"Listado_id\" = \"public\".lista_listado.\"id\" '\n 'INNER JOIN alumno ON lista_listado.alumno_id = alumno.\"id\" '\n 'INNER JOIN curso ON lista_listado.curso_id = curso.\"id\" '\n 'INNER JOIN horario ON horario.curso_id = curso.\"id\" '\n 'AND asistencias_asistencias.\"Horario_id\" = horario.\"id\" '\n 'INNER JOIN silabo ON horario.silabo_id = silabo.\"id\" '\n 'INNER JOIN materia ON silabo.materia_id = materia.\"id\" '\n 'WHERE materia.nombre=%s AND curso.nombre = %s '\n 'AND asistencias_asistencias.fecha = %s AND horario.docente_id = %s '\n 'GROUP BY alumno.nombres, alumno.apellidos, '\n 'asistencias_asistencias.\"Asistencia\", '\n 'asistencias_asistencias.fecha,curso.nombre , '\n 'materia.nombre, horario.docente_id '\n 'order by alumno.apellidos asc', [p, f, materia, nomCurso, fecha, a])\n contexto = {'listaalumno': listaalumno}\n\n return render(request, \"back-end/alumno/alumnoindex2.html\", contexto)\ndef asistencia_list_fecha(request):\n a = request.user.id\n materia = request.GET.get('materia')\n nomCurso = request.GET.get('nomCurso')\n listaasistencia = Asistencias.objects.raw('SELECT asistencias_asistencias.fecha as id, curso.nombre, '\n 'materia.nombre as materia,horario.docente_id '\n 'FROM asistencias_asistencias '\n 'INNER JOIN lista_listado '\n 'ON asistencias_asistencias.\"Listado_id\" = lista_listado.\"id\" '\n 'INNER JOIN curso ON lista_listado.curso_id = curso.\"id\" '\n 'INNER JOIN horario ON horario.curso_id = curso.\"id\" '\n 'AND asistencias_asistencias.\"Horario_id\" = horario.\"id\" '\n 'INNER JOIN silabo ON horario.silabo_id = silabo.\"id\" '\n 'INNER JOIN materia ON silabo.materia_id = materia.\"id\" '\n 'WHERE materia.nombre = %s and curso.nombre= %s and '\n 'horario.docente_id =%s GROUP BY horario.docente_id,'\n 'asistencias_asistencias.fecha, \"public\".curso.nombre, '\n 'materia.nombre', [materia, nomCurso, a])\n contexto = {'listaasistencia': listaasistencia}\n return render(request, \"back-end/asistencia/asistenciaindex_fechas.html\", contexto)\ndef vista_asistencias(request):\n form = AsistenciasForm()\n if request.method == 'POST':\n form = AsistenciasForm(request.POST)\n return render(request, 'back-end/asistencia/asistencias_form.html', {'form': form})\n\ndef get_asistencias(request):\n materiaId = request.POST[\"materia_id\"]\n periodoId = request.POST[\"periodo_id\"]\n cursoId = request.POST[\"curso_id\"]\n desde = request.POST[\"desde\"]\n hasta = request.POST[\"hasta\"]\n data = transpose(materiaId, periodoId, cursoId, desde, hasta)\n if data:\n df = pd.DataFrame(data)\n df.fillna('0', inplace=True)\n pivot = pd.pivot_table(df, index=['Alumno'], values=['Asistencia'], columns=['Fecha'], aggfunc='mean')\n html2 = pivot.to_html(table_id='asistencia', classes='table table-striped table-bordered table-hover')\n response = {\"tablaHtml\":html2}\n else:\n response = {\"resp\": 'False'}\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\n\ndef transpose(materiaId, periodoId, cursoId, desde, hasta):\n asistencias = Asistencias.objects.filter(Horario__asignar__materia_id=materiaId, Listado__curso__id=cursoId,\n Listado__periodo_id=periodoId, fecha__range=[desde, hasta])\n data = [{'Alumno': a.Listado.alumno.apellidos+' '+a.Listado.alumno.nombres, 'Fecha': a.fecha,\n 'Asistencia': a.Asistencia} for a in asistencias]\n return data\n\n\n@csrf_exempt\ndef save_asistencia(request):\n data = {}\n fecha_hoy = date.today()\n if request.method == 'POST':\n datos = json.loads(request.POST['datos'])\n for sub in datos:\n if Asistencias.objects.filter(Horario_id=sub['horario'], Listado_id=sub['listado'], fecha=fecha_hoy):\n data['resp'] = False\n else:\n h = Horario.objects.get(pk=sub['horario'])\n h.asist_alum = 2\n h.save()\n n = Asistencias()\n n.Horario_id = sub['horario']\n n.Listado_id = sub['listado']\n n.fecha = fecha_hoy\n n.Asistencia = sub['asistencia']\n n.save()\n data['resp'] = True\n return HttpResponse(json.dumps(data), content_type=\"application/json\")","sub_path":"apps/asistencias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"468700939","text":"import secrets\nimport os\nfrom flask import url_for, current_app\nfrom flaskbase import mail\nfrom PIL import Image\nfrom flask_mail import Message\n\ndef pagination(page, pages_range):\n show_pages = []\n if len(pages_range)<5:\n return pages_range\n if page + 2 >= pages_range[-1]:\n n = pages_range[-1] - 4\n while n!=pages_range[-1]+1:\n show_pages.append(n)\n n+=1\n elif page - 2 <= 1:\n n = 1\n while n!=6:\n show_pages.append(n)\n n+=1\n else:\n n = page - 2\n while n!=page+3:\n show_pages.append(n)\n n+=1\n return show_pages\n\ndef save_picture(form_picture):\n random_hex = secrets.token_hex(8)\n _, f_ext = os.path.splitext(form_picture.filename)\n picture_fn = form_picture.filename\n if form_picture.filename != 'default.jpg':\n picture_fn = random_hex + f_ext\n picture_path = os.path.join(current_app.root_path, 'static/profile_pics', picture_fn)\n output_size = (125,125)\n i = Image.open(form_picture)\n i.thumbnail(output_size)\n i.save(picture_path)\n return picture_fn\n\ndef send_confirm_email(user):\n token = user.get_confirm_token()\n msg = Message(subject='Confirm Email', sender='noreply@demo.com', recipients=[user.email])\n msg.body = ''' To confirm your email, visit the following link:\n{}\n\nThis link will expire in an hour.\n '''.format(url_for('users.confirm_email',token=token, _external=True))\n mail.send(msg)\n\ndef send_reset_email(user):\n token = user.get_reset_token()\n msg = Message(subject='Password Reset Request', sender='noreply@demo.com', recipients=[user.email])\n msg.body = ''' To reset your password, visit the following link:\n{}\n\nIf you did not make this request then simple ignore this email and no changes will be made. This link will expire in 10 mins.\n '''.format(url_for('users.reset_token',token=token, _external=True))\n mail.send(msg)","sub_path":"flaskbase/users/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"227149808","text":"import curses\nimport config as c\nimport pygame as pg\nimport sys\nfrom pydub.utils import mediainfo\nimport _thread\nimport signal\nimport os\nsaved_positions = [0,0,0,0,0,0,0,0,0,0]\naction_state = \"saving\"\ntime_offset = 0\nshould_die = False\ndef setting(key):\n global action_state\n action_state = \"saving\"\ndef save(slot):\n global saved_positions\n saved_positions[slot] = (pg.mixer.music.get_pos()/1000) + time_offset\n stdscr.addstr(3, 0, \"Saved positions:\")\n stdscr.addstr(4, 0, str(saved_positions))\ndef loading(key):\n global action_state\n action_state = \"loading\"\ndef load(slot):\n global time_offset\n global is_playing\n pg.mixer.music.stop()\n pg.mixer.music.play(start=saved_positions[slot])\n time_offset = saved_positions[slot]\n is_playing = True\n stdscr.addstr(3, 0, \"Saved positions:\")\n stdscr.addstr(4, 0, str(saved_positions))\ndef pause_play(key):\n global is_playing\n if is_playing:\n pg.mixer.music.pause()\n stdscr.addstr(2, 0, \"Paused\")\n is_playing = False\n else:\n pg.mixer.music.unpause()\n stdscr.addstr(2, 0, \"Unpaused\")\n is_playing = True\ndef info(key):\n stdscr.addstr(2, 0, \"Saved positions:\")\n stdscr.addstr(3, 0, str(saved_positions))\n stdscr.addstr(4, 0, \"Current position (ms):\")\n stdscr.addstr(5, 0, str(pg.mixer.music.get_pos() + (time_offset * 1000)))\n stdscr.addstr(6, 0, \"Now playing: {7}\\n\\\nTotal length: {0}\\n\\\nControls:\\n\\\n Save: {1}\\n\\\n Load: {2}\\n\\\n Pause: {3}\\n\\\n Restart: {4}\\n\\\n Info: {5}\\n\\\n Jump: {6}\".format(length_, c.keybinds['set'], c.keybinds['load'], c.keybinds['pause'], \"Unimplemented\", c.keybinds['info'], c.keybinds['jump'], sys.argv[1]))\ndef jump(key):\n global time_offset\n global is_playing\n curses.nocbreak()\n curses.echo()\n stdscr.addstr(5, 5, \"Please type the target timestamp as a number of seconds.\")\n input = stdscr.getstr(6, 5)\n pg.mixer.music.stop()\n pg.mixer.music.play(start=float(input))\n time_offset = float(input)\n is_playing = True\n stdscr.addstr(7, 5, \"Done!\")\n curses.noecho()\n curses.cbreak()\ndef other_keys(key):\n try:\n int(key)\n if action_state == 'saving':\n save(int(key))\n stdscr.addstr(2, 0, \"Saving to slot \" + key + \".\")\n else:\n load(int(key))\n stdscr.addstr(2, 0, \"Loading from slot \" + key + \".\")\n except ValueError:\n stdscr.addstr(2, 0, \"No output for nonexistent command.\")\ndef finish_checker():\n global time_offset\n global other_thread\n other_thread = os.getpid()\n if should_die: _thread.exit()\n while True:\n if pg.mixer.music.get_pos() == -1:\n if c.should_loop:\n pg.mixer.music.stop()\n pg.mixer.music.play()\n stdscr.addstr(10, 0, \"Event: Looped\")\n time_offset = 0\n else:\n curses.nocbreak()\n stdscr.keypad(False)\n curses.echo()\n print(\"Song done, terminating.\")\n sys.exit(0)\ndef signal_handler(signal, frame):\n global should_die\n print(\"\\nKilling self...\")\n should_die = True\n import time\n pg.mixer.music.stop()\n os.kill(other_thread, 9)\n time.sleep(1)\n raise SystemExit\ntry:\n stdscr = curses.initscr()\n curses.cbreak()\n curses.noecho()\n stdscr.keypad(True)\n stdscr.clear()\n stdscr.scrollok(1)\n pg.mixer.init(int(mediainfo(sys.argv[1])['sample_rate']))\n pg.mixer.music.load(sys.argv[1])\n pg.mixer.music.play()\n pg.mixer.music.set_endevent(pg.USEREVENT + 1)\n global is_playing\n is_playing = True\n time_offset = 0\n global length_\n length_ = float(mediainfo(sys.argv[1])['duration']) * 1000\n _thread.start_new_thread(finish_checker, ())\n stdscr.addstr(0, 0, \"Now playing: {7}\\n\\\nTotal length: {0}\\n\\\nControls:\\n\\\n Save: {1}\\n\\\n Load: {2}\\n\\\n Pause: {3}\\n\\\n Restart: {4}\\n\\\n Info: {5}\\n\\\n Jump: {6}\".format(length_, c.keybinds['set'], c.keybinds['load'], c.keybinds['pause'], \"Unimplemented\", c.keybinds['info'], c.keybinds['jump'], sys.argv[1]))\n # signal.signal(signal.SIGINT, signal_handler)\n while True:\n current_key = stdscr.getkey()\n stdscr.clear()\n stdscr.addstr(0, 0, current_key)\n stdscr.addstr(1, 0, \"Command: \" + {\n c.keybinds['set']: \"Save\",\n c.keybinds['load']: \"Load\",\n c.keybinds['pause']: \"Pause/Play\",\n c.keybinds['restart']: \"Restart\",\n c.keybinds['info']: \"Info\",\n c.keybinds['jump']: \"Jump to time\"\n }.get(current_key, \"Unknown\"))\n {\n c.keybinds['set']: setting,\n c.keybinds['load']: loading,\n c.keybinds['pause']: pause_play,\n c.keybinds['restart']: pg.mixer.music.rewind,\n c.keybinds['info']: info,\n c.keybinds['jump']: jump\n }.get(current_key, other_keys)(current_key)\nfinally:\n should_die = True\n curses.nocbreak()\n stdscr.keypad(False)\n curses.echo()\n stdscr.clear()\n curses.noraw()\n curses.endwin()\n print(\"Something's gone wrong.\")\n print(\"Killing self...\")\n os.kill(other_thread, 9)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"166009483","text":"from typing import Callable, List, Optional, Tuple, Union\n\nfrom scipy.ndimage import zoom\n\nfrom PartSegCore.algorithm_describe_base import AlgorithmProperty\nfrom PartSegCore.image_transforming.transform_base import TransformBase\nfrom PartSegCore.roi_info import ROIInfo\nfrom PartSegImage import Image\n\n\nclass InterpolateImage(TransformBase):\n @classmethod\n def get_fields(cls):\n return [\"It can be very slow.\", AlgorithmProperty(\"scale\", \"Scale\", 1.0)]\n\n @classmethod\n def get_fields_per_dimension(cls, component_list: List[str]) -> List[Union[str, AlgorithmProperty]]:\n return [\n \"it can be very slow\",\n *[AlgorithmProperty(f\"scale_{i.lower()}\", f\"Scale {i}\", 1.0) for i in reversed(component_list)],\n ]\n\n @classmethod\n def get_name(cls):\n return \"Spline Interpolate\"\n\n @classmethod\n def transform(\n cls,\n image: Image,\n roi_info: Optional[ROIInfo],\n arguments: dict,\n callback_function: Optional[Callable[[str, int], None]] = None,\n ) -> Tuple[Image, Optional[ROIInfo]]:\n keys = [x for x in arguments if x.startswith(\"scale\")]\n keys_order = Image.axis_order.lower()\n scale_factor = [1.0] * len(keys_order)\n if len(keys) == 1 and keys[0] == \"scale\":\n for letter in image.get_dimension_letters().lower():\n scale_factor[keys_order.index(letter)] = arguments[\"scale\"]\n spacing = [x / arguments[\"scale\"] for x in image.spacing]\n else:\n # assume that all keys are in format scale_{}\n for key in keys:\n letter = key[-1]\n scale_factor[keys_order.index(letter)] = arguments[key]\n spacing = [\n x / arguments[f\"scale_{y}\"] for x, y in zip(image.spacing, image.get_dimension_letters().lower())\n ]\n array = zoom(image.get_data(), scale_factor, mode=\"mirror\")\n if image.mask is not None:\n mask = zoom(image.mask, scale_factor[:-1], mode=\"mirror\")\n else:\n mask = None\n return image.substitute(data=array, image_spacing=spacing, mask=mask), None\n\n @classmethod\n def calculate_initial(cls, image: Image):\n min_val = min(image.spacing)\n return {\n f\"scale_{letter}\": x / min_val for x, letter in zip(image.spacing, image.get_dimension_letters().lower())\n }\n","sub_path":"package/PartSegCore/image_transforming/interpolate_image.py","file_name":"interpolate_image.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"430560192","text":"# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# prompt_question:\r\n# Ask a question of your user. The user must provide a response that is in\r\n# you list of valid options\r\n#\r\n# prompt : A string that will be used to ask the user a question\r\n# valid_options : A list of string values you expect your user to respond with.\r\n# example usage:\r\n# a_topping = prompt_question(\"Would you like cheese on your pizza?\", ['yes', 'no'])\r\ndef prompt_question(prompt, valid_options):\r\n response = input(prompt)\r\n while not response.lower() in valid_options:\r\n print(\"Sorry, I did not understand your choice.\")\r\n response = input(prompt)\r\n return response.lower()\r\n\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# ask_command:\r\n# Ask your user for a command. The user must provide a response that is in\r\n# you list of valid options\r\n# prompt : A string that will be used to ask the user a question\r\n# valid_options : A list of string values you expect your user to respond with.\r\n#\r\n# example usage:\r\n# a_topping = prompt_question(\"What do you want to do?\", ['go', 'take', 'drop'])\r\ndef ask_command(prompt, valid_commands, no_arguments = ['status', 'help']):\r\n ask_again = True\r\n result = []\r\n while ask_again:\r\n # Get a response from the user and split the response into words\r\n response = input(prompt)\r\n words = response.split()\r\n\r\n # be safe against user accidents of just hitting the ENTER key\r\n if len(words) > 0:\r\n\r\n #check if the command is the list of valid commands\r\n if words[0].lower() not in valid_commands:\r\n print('\\tSorry, I don\\'t understand:\"', response, '\"')\r\n print('\\t\\t Your choices are:', valid_commands, \"\\n\")\r\n else:\r\n #if the command is valid, but they forgot an argument, try again.\r\n if len(words) < 2:\r\n # but check first if it was in the no argument list\r\n if words[0].lower() not in no_arguments:\r\n print('\\tThe command: \"', words[0], '\" requires an argument.\\n' )\r\n else:\r\n result = words\r\n ask_again = False\r\n else:\r\n # Otherwise we at least have two arguments! Now programmer gets to choose what to do.\r\n ask_again = False\r\n result = words\r\n # END WHILE LOOP\r\n #Return the command back to the user as a list (command will be index 0)\r\n # If the command was required then it will be in position 1\r\n return result\r\n#END OF FUNCTION\r\n\r\ndef has_a(player_inventory,item):\r\n if item in player_inventory.keys():\r\n current_count = player_inventory[item]\r\n if current_count > 0:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n#END OF THIS FUNCTION\r\n\r\ndef drop_item(player_inventory, room_inventory, item):\r\n if has_a(player_inventory, item):\r\n curr_count = player_inventory[item]\r\n player_inventory[item] = curr_count - 1\r\n\r\n if has_a(room_inventory, item):\r\n room_count = room_inventory[item]\r\n room_inventory[item] = room_count + 1\r\n\r\n else:\r\n room_inventory[item] = 1\r\n print(\"You dropped\", item)\r\n else:\r\n print(\"You don't have that\")\r\n print(\"\")\r\n\r\n#END OF FUNCION\r\ndef scrub_response(dirty_response):\r\n result = []\r\n result.append(dirty_response[0])\r\n\r\n if len(dirty_response) > 1:\r\n arg = dirty_response[1]\r\n if arg == 'fire':\r\n result.append(\"Fire Extinguisher\")\r\n else:\r\n result.append(dirty_response[1])\r\n return result\r\n\r\n#end\r\ndef take_item(player_inventory, room_inventory, item):\r\n if has_a(room_inventory, item):\r\n room_count = room_inventory[item]\r\n room_inventory[item] = room_count - 1\r\n if has_a(player_inventory, item):\r\n player_count = player_inventory[item]\r\n player_inventory[item] = player_count + 1\r\n print(\"You grab the\", item)\r\n else:\r\n player_inventory[item] = 1\r\n print(\"You grab the\", item)\r\n else:\r\n print(\"This room doesn't have that\")\r\n\r\n#END OF FUNCTIOn\r\n\r\ndef use_item(player_inventory, item):\r\n if has_a(player_inventory, item):\r\n print(\"You use your\",item)\r\n\r\n else:\r\n print(\"You do not posses a\", item)\r\n\r\n\r\n\r\n\r\ndef room_status(room_inventory):\r\n print(\"This room contains:\")\r\n empty = True\r\n\r\n for key in room_inventory.keys():\r\n if room_inventory[key] > 0:\r\n print(\"\\t\\t\\t\",room_inventory[key], key,)\r\n empty = False\r\n\r\n if empty == True:\r\n print(\"\\t\\t\\tnothing\")\r\n print(\"\")\r\n\r\n\r\n#END\r\n\r\ndef player_status(player_inventory):\r\n print(\"In your backpack you have:\")\r\n for key in player_inventory.keys():\r\n if player_inventory[key] > 0:\r\n print(\"\\t\\t\\t\",player_inventory[key],key)\r\n print(\"\")\r\n\r\n#END\r\n\r\ndef any_room(direction):\r\n if int(direction) in range(2, 18):\r\n next_room = int(direction)\r\n done_with_room = True\r\n\r\ndef help_function(commands):\r\n print('In this room, you can type:')\r\n print(commands)\r\n\r\ndef examine(description):\r\n print(description)\r\n\r\n","sub_path":"adventure_game/my_utils.py","file_name":"my_utils.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"100813424","text":"\ndata_path = 'fra.txt'\n\nlines = open(data_path).read().split('\\n')\n\nfInput = open(\"input.txt\", \"w+\")\nfOutput = open(\"output.txt\", \"w+\")\n\ninputTexts = []\noutputTexts = []\nfor line in lines:\n\n if line == '' or len(line) < 1:\n continue\n\n input_text, target_text = line.split('\\t')\n\n fInput.write(input_text + \"\\n\")\n fOutput.write(target_text + \"\\n\")\n\n #\n # inputTexts.append(input_text)\n # outputTexts.append(target_text)\n#\n# fInput.writelines(inputTexts)\n# fOutput.writelines(outputTexts)\n\nfInput.flush()\nfOutput.flush()","sub_path":"keras-examples/fra-eng/convert-data.py","file_name":"convert-data.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"526757576","text":"import wx, os\nFONTSIZE = 14\n\nclass TextDocPrintout( wx.Printout ):\n\n def __init__( self, text, title, margins ):\n wx.Printout.__init__( self, title )\n self.lines = text.split( '\\n' )\n self.margins = margins\n self.numPages = 1\n\n def HasPage( self, page ):\n return page <= self.numPages\n\n def GetPageInfo( self ):\n return ( 1, self.numPages, 1, self.numPages )\n\n def CalculateScale( self, dc ):\n ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()\n ppiScreenX, ppiScreenY = self.GetPPIScreen()\n logScale = float( ppiPrinterX )/float( ppiScreenX )\n pw, ph = self.GetPageSizePixels()\n dw, dh = dc.GetSize()\n scale = logScale * float( dw )/float( pw )\n dc.SetUserScale( scale, scale )\n self.logUnitsMM = float( ppiPrinterX )/( logScale*25.4 )\n\n def CalculateLayout( self, dc ):\n topLeft, bottomRight = self.margins\n dw, dh = dc.GetSize()\n self.x1 = topLeft.x * self.logUnitsMM\n self.y1 = topLeft.y * self.logUnitsMM\n self.x2 = ( dc.DeviceToLogicalXRel( dw) - bottomRight.x * self.logUnitsMM )\n self.y2 = ( dc.DeviceToLogicalYRel( dh ) - bottomRight.y * self.logUnitsMM )\n self.pageHeight = self.y2 - self.y1 - 2*self.logUnitsMM\n font = wx.Font( FONTSIZE, wx.TELETYPE, wx.NORMAL, wx.NORMAL )\n dc.SetFont( font )\n self.lineHeight = dc.GetCharHeight()\n self.linesPerPage = int( self.pageHeight/self.lineHeight )\n\n def OnPreparePrinting( self ):\n dc = self.GetDC()\n self.CalculateScale( dc )\n self.CalculateLayout( dc )\n self.numPages = len(self.lines) / self.linesPerPage\n if len(self.lines) % self.linesPerPage != 0:\n self.numPages += 1\n\n def OnPrintPage(self, page):\n dc = self.GetDC()\n self.CalculateScale(dc)\n self.CalculateLayout(dc)\n dc.SetPen(wx.Pen(\"black\", 0))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n r = wx.RectPP((self.x1, self.y1), (self.x2, self.y2))\n dc.DrawRectangleRect(r)\n dc.SetClippingRect(r)\n line = (page-1) * self.linesPerPage\n x = self.x1 + self.logUnitsMM\n y = self.y1 + self.logUnitsMM\n while line < (page * self.linesPerPage):\n dc.DrawText(self.lines[line], x, y)\n y += self.lineHeight\n line += 1\n if line >= len(self.lines):\n break\n return True\n\n","sub_path":"Printing.py","file_name":"Printing.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"422453739","text":"import sys\n\nimport numpy as np\nimport pytest\n\nfrom opytimizer.core import agent, function\nfrom opytimizer.optimizers import aiwpso\nfrom opytimizer.spaces import search\n\n\ndef test_aiwpso_hyperparams():\n hyperparams = {\n 'w': 2,\n 'w_min': 1,\n 'w_max': 3,\n 'c1': 1.7,\n 'c2': 1.7\n }\n\n new_aiwpso = aiwpso.AIWPSO(hyperparams=hyperparams)\n\n assert new_aiwpso.w == 2\n\n assert new_aiwpso.w_min == 1\n\n assert new_aiwpso.w_max == 3\n\n assert new_aiwpso.c1 == 1.7\n\n assert new_aiwpso.c2 == 1.7\n\n\ndef test_aiwpso_hyperparams_setter():\n new_aiwpso = aiwpso.AIWPSO()\n\n new_aiwpso.w_min = 0.5\n assert new_aiwpso.w_min == 0.5\n\n new_aiwpso.w_max = 2\n assert new_aiwpso.w_max == 2\n\n new_aiwpso.c1 = 1.5\n assert new_aiwpso.c1 == 1.5\n\n new_aiwpso.c2 = 1.5\n assert new_aiwpso.c2 == 1.5\n\n\ndef test_aiwpso_rebuild():\n new_aiwpso = aiwpso.AIWPSO()\n\n assert new_aiwpso.built == True\n\n\ndef test_aiwpso_compute_success():\n n_agents = 2\n\n search_space = search.SearchSpace(n_agents=n_agents, n_iterations=10,\n n_variables=2, lower_bound=[0, 0],\n upper_bound=[10, 10])\n\n new_aiwpso = aiwpso.AIWPSO()\n\n new_fitness = np.zeros(n_agents)\n\n new_aiwpso._compute_success(search_space.agents, new_fitness)\n\n assert new_aiwpso.w != 0\n\n\ndef test_aiwpso_evaluate():\n def square(x):\n return np.sum(x**2)\n\n new_function = function.Function(pointer=square)\n\n search_space = search.SearchSpace(n_agents=2, n_iterations=10,\n n_variables=2, lower_bound=[0, 0],\n upper_bound=[10, 10])\n\n new_aiwpso = aiwpso.AIWPSO()\n\n local_position = np.zeros((2, 2, 1))\n\n new_aiwpso._evaluate(search_space, new_function, local_position)\n\n assert search_space.best_agent.fit < sys.float_info.max\n\n\ndef test_aiwpso_run():\n def square(x):\n return np.sum(x**2)\n\n new_function = function.Function(pointer=square)\n\n new_aiwpso = aiwpso.AIWPSO()\n\n search_space = search.SearchSpace(n_agents=2, n_iterations=10,\n n_variables=2, lower_bound=[0, 0],\n upper_bound=[10, 10])\n\n history = new_aiwpso.run(search_space, new_function)\n\n assert len(history.agents) > 0\n assert len(history.best_agent) > 0\n","sub_path":"tests/opytimizer/optimizers/test_aiwpso.py","file_name":"test_aiwpso.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"273150721","text":"#!/usr/bin/env python\n\n'''\n \n GOAL:\n Make lists of files that contain\n - dome flats with same filter\n - sky flats with same filter\n Then combine and normalize the flats so they can be used to flatten image\n\n PROCEDURE:\n -User should move junk files to a junk subdirectory before starting\n - Junk files include initial bias frames pointing and other garbage frames\n - Use gethead to pull relevant header data\n - Overscan subtract and trim images (we assume these image names begin with 't r')\n - Combine flats according to flat type (dome vs sky) and filter\n\n EXAMPLE:\n In the directory containing all flats type in the command line:\n '/home/share/research/pythonCode/uat_HDIgroupflatfiles.py'(or whatever the path is to where this program is stored)\n\n \n INPUT/OUTPUT:\n Input: 'skyflat(type of filter)' or 'domeflat(type of filter)'\n -These contain trimmed image files grouped by filter grabbed from the i mage headers seen at the beginning of this code. \n Output: For combined flats --> 'cskyflat(type of filter).fits' or 'cdomeflat(t ype of filter).fits'.\n For normalized flats --> 'nskyflat(type of filter).fits' or 'ndomeflat (type of filter).fits'.\n\n REQUIRED MODULES:\n pyraf\n\n NOTES:\n in junkfile ftr flats still show. We changed the gethead requirements to only bring in files that start with tr but the ftr files will not go away! =(\n \n WRITTEN BY:\n Rose A. Finn\n EDITED BY:\n Natasha Collova, Tiffany Flood, and Kaitlyn Hoag 5/29/15\n Grant Boughton, Natasha Collova, and Sandy Spicer 6/3/16\n UPDATES:\n Now combines and normalizes the grouped flat files \n Input ex. = skyflatR\n Output ex. = cskyflatR.fits (combined sky flats in R band) & nskyflatR.fits (normalized sky flats in R band)\n \n'''\nimport glob\nimport os\nimport numpy as np\n\nimport ccdproc\nfrom astropy.io import fits\nimport astropy.units as u\nimport argparse\n\n'''\nfrom pyraf import iraf\niraf.noao()\niraf.imred()\niraf.ccdred() \n'''\n\nparser = argparse.ArgumentParser(description ='Groups images by filter and creates flatfield images')\nparser.add_argument('--filestring', dest='filestring', default='ztr', help='match string for input files (default = ztr, which gets ztr*.fits)')\nparser.add_argument('--siena', dest='siena', default=False,action='store_true', help='set this if reducing data from Siena STL11000M CCD')\nargs = parser.parse_args()\nfiles = sorted(glob.glob(args.filestring+'*.fits'))\nnfiles=len(files)\n\nif args.siena:\n print('running on Siena data - woo hoo!')\n os.system('gethead '+args.filestring+'*.fits IMAGETYP FILTER > tempflats')\nelse:\n print('running on HDI data - woo hoo!')\n print(('gethead '+args.filestring+'*f00.fits CMMTOBS > tempflats'))\n os.system('gethead '+args.filestring+'*f00.fits CMMTOBS > tempflats')\n\n# tempflats is the name of a \"junk file\" that contains the gethead information from all the flat images.\n# This file will be deleted after the information is read out in the future.\n\n# We assume that the flat images are trimmed and the file name starts with 'ztr'\ninfile=open('tempflats','r')\nfnames=[]\nfilter=[]\nftype=[] #skyflat or domeflat\n\n\nfor line in infile:\n t=line.split()\n fnames.append(t[0])\n ftype.append(t[1]+t[2])\n if len(t)> 4:\n if line.find('6620') > -1:\n filter.append('ha4')\n else:\n print('problem with determing filter!!!')\n print('probably got a multi-word entry for CMMTOBS')\n print(\"I'm storing the second word...\")\n print('filter = ',t[4].rstrip('\\n'))\n filter.append(t[4].rstrip('\\n'))\n else:\n filter.append(t[3].rstrip('\\n'))\ninfile.close()\nset_filter=set(filter)\nset_ftype=set(ftype)\narray_ftype=np.array(ftype)\narray_filter=np.array(filter)\n\n\n# create files that contain all flats taken in same filter\nflat_filelist = []\nfor f in set_ftype:\n print('####################################')\n print(\"flat type=\",f)\n print('####################################')\n for element in set_filter:\n ftype_filter = str(f)+str(element)\n flat_filelist.append(ftype_filter)\n print('grouping files for filter type = ',element)\n indices=np.where((array_ftype == f)&(array_filter == element))\n if len(indices[0]) > 0:\n outfile = open(ftype_filter,'w')\n for i in indices[0]:\n outfile.write(fnames[i]+'\\n')\n outfile.close()\n\nfor f in flat_filelist:\n print('filelist = ',f)\n flatimages = []\n try:\n filelist = open(f,'r')\n except IOError:\n print(('Problem opening file ',f))\n print('Hope that is ok...')\n continue\n for q in filelist: flatimages.append(q.rstrip())\n if len(flatimages) < 3:\n print('problem combining images from ',f)\n continue\n # combine flat images using average combine, scale by median, sigma clip\n flat = ccdproc.combine(flatimages,scale=np.median,method='average',sigma_clip=True,unit=u.adu)\n #med_flat = ccdproc.combine(flatimages, method='median')\n # normalize flat image by dividing by mean\n norm_flat = flat / np.mean(flat)\n print('writing fits')\n fits.writeto('n'+f+'.fits', norm_flat, overwrite=True)\n\n\n\n\n \n# clean up\nos.remove('tempflats') \n","sub_path":"python3/uat_HDIgroupflatfiles.py","file_name":"uat_HDIgroupflatfiles.py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"451431531","text":"from ctypes import (\r\n POINTER, Structure, Union, c_char, c_byte, c_long, c_longlong, c_short, c_size_t,\r\n c_ubyte, c_ulong, c_ulonglong, c_ushort, c_void_p, c_wchar, c_wchar_p, sizeof\r\n)\r\nfrom enum import IntEnum\r\n# ====================================================================================\r\nACCESS_MASK = DWORD = ULONG = c_ulong\r\nCCHAR = CHAR = c_char\r\nCSHORT = SHORT = c_short\r\nBOOLEAN = BYTE = c_byte\r\nHANDLE = HLOCAL = LPCVOID = PVOID = va_list = c_void_p\r\nKAFFINITY = ULONG_PTR = c_ulonglong if 8 == sizeof(c_void_p) else c_ulong\r\nLONG = KPRIORITY = NTSTATUS = c_long\r\nLONGLONG = c_longlong\r\nPWSTR = c_wchar_p\r\nSIZE_T = c_size_t\r\nUCHAR = c_ubyte\r\nULONGLONG = c_ulonglong\r\nUSHORT = WORD = c_ushort\r\nWCHAR = c_wchar\r\n# ====================================================================================\r\nPCHAR = PSTR = POINTER(CHAR)\r\nPULONG = POINTER(ULONG)\r\n# ====================================================================================\r\nclass CEnum(IntEnum):\r\n @classmethod\r\n def from_param(cls, self):\r\n if not isinstance(self, cls):\r\n raise TypeError\r\n return self\r\n\r\nclass CStruct(Structure):\r\n @property\r\n def size(self):\r\n return ULONG(sizeof(self))\r\n# ====================================================================================\r\nLOGICAL_PROCESSOR_RELATIONSHIP = IntEnum('LOGICAL_PROCESSOR_RELATIONSHIP', (\r\n 'RelationProcessorCore',\r\n 'RelationNumaNode',\r\n 'RelationCache',\r\n 'RelationProcessorPackage',\r\n 'RelationGroup',\r\n 'RelationAll', # 0xffff\r\n), start=0)\r\n\r\nPROCESSOR_CACHE_TYPE = IntEnum('PROCESSOR_CACHE_TYPE', (\r\n 'CacheUnified',\r\n 'CacheInstruction',\r\n 'CacheData',\r\n 'CacheTrace',\r\n), start=0)\r\n# ====================================================================================\r\nclass CACHE_DESCRIPTOR(Structure):\r\n _fields_ = (\r\n ('Level', BYTE),\r\n ('Associativity', BYTE),\r\n ('LineSize', WORD),\r\n ('Size', DWORD),\r\n ('_Type', DWORD),\r\n )\r\n @property\r\n def Type(self):\r\n return PROCESSOR_CACHE_TYPE(self._Type).name if self._Type else None\r\n\r\nclass CLIENT_ID(Structure):\r\n _fields_ = (\r\n ('UniqueProcess', HANDLE),\r\n ('UniqueThread', HANDLE),\r\n )\r\n\r\nclass GENERIC_MAPPING(Structure):\r\n _fields_ = (\r\n ('GenericRead', ACCESS_MASK),\r\n ('GenericWrite', ACCESS_MASK),\r\n ('GenericExecute', ACCESS_MASK),\r\n ('GenericAll', ACCESS_MASK)\r\n )\r\n\r\nclass GROUP_AFFINITY(Structure):\r\n _fields_ = (\r\n ('Mask', KAFFINITY),\r\n ('Group', USHORT),\r\n ('Reserved', USHORT * 3),\r\n )\r\n\r\nclass LARGE_INTEGER_UNION(Structure):\r\n _fields_ = (\r\n ('LowPart', ULONG),\r\n ('HighPart', LONG),\r\n )\r\n\r\nclass LARGE_INTEGER(Union):\r\n _fields_ = ( # LARGE_INTEGER = c_longlong\r\n ('u1', LARGE_INTEGER_UNION),\r\n ('u2', LARGE_INTEGER_UNION),\r\n ('QuadPart', LONGLONG),\r\n )\r\n\r\nclass NUMANODE(Structure):\r\n _fields_ = (\r\n ('NodeNumber', ULONG),\r\n )\r\n\r\nclass PROCESSORCORE(Structure):\r\n _fields_ = (\r\n ('Flags', BYTE),\r\n )\r\n\r\nclass TIME_FIELDS(Structure):\r\n _fields_ = (\r\n ('Year', CSHORT),\r\n ('Month', CSHORT),\r\n ('Day', CSHORT),\r\n ('Hour', CSHORT),\r\n ('Minute', CSHORT),\r\n ('Second', CSHORT),\r\n ('Milliseconds', CSHORT),\r\n ('Weekday', CSHORT),\r\n )\r\n\r\nclass UNICODE_STRING(Structure):\r\n _fields_ = (\r\n ('Length', USHORT),\r\n ('MaximumLength', USHORT),\r\n ('Buffer', PWSTR),\r\n )\r\nLSA_UNICODE_STRING = UNICODE_STRING\r\n\r\nclass OBJECT_NAME_INFORMATION(Structure):\r\n _fields_ = (\r\n ('Name', UNICODE_STRING),\r\n )\r\n","sub_path":"py/winnt/wintypes.py","file_name":"wintypes.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"145882260","text":"# Copyright 2017 Mycroft AI Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nINTRO:\nSpotify is a little different than some music services. The APIs encourage\na sort of network of music players. So this skill will act as a remote\ncontroller when another Spotify player is already running and it is invoked.\nOtherwise it begins playing the music locally using the Mycroft-controlled\nhardware. (Which, depending on the audio setup, might not be the main\nspeaker on the equipment.)\n\"\"\"\nfrom pprint import pformat\n\nimport re\nfrom mycroft.skills.core import MycroftSkill, intent_handler, \\\n intent_file_handler\nimport mycroft.client.enclosure.display_manager as DisplayManager\nfrom mycroft.util.parse import match_one\nfrom mycroft.util.log import LOG\nfrom mycroft.api import DeviceApi\nfrom padatious import IntentContainer\nfrom requests import HTTPError\nfrom adapt.intent import IntentBuilder\n\nimport time\nimport datetime\nfrom subprocess import Popen\nimport signal\nfrom socket import gethostname\n\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport random\n\n\ndef get_token(dev_cred):\n \"\"\" Get token with a single retry.\n Args:\n dev_cred: OAuth Credentials to fetch\n \"\"\"\n retry = False\n try:\n d = DeviceApi().get_oauth_token(dev_cred)\n except HTTPError as e:\n if e.response.status_code == 404: # Token doesn't exist\n raise\n if e.response.status_code == 401: # Device isn't paired\n raise\n else:\n retry = True\n if retry:\n d = DeviceApi().get_oauth_token(dev_cred)\n return d\n\n\nclass MycroftSpotifyCredentials(SpotifyClientCredentials):\n \"\"\" Credentials object renewing through the Mycroft backend.\"\"\"\n def __init__(self, dev_cred):\n self.dev_cred = dev_cred\n self.access_token = None\n self.expiration_time = None\n self.get_access_token()\n\n def get_access_token(self):\n if not self.access_token or time.time() > self.expiration_time:\n d = get_token(self.dev_cred)\n self.access_token = d['access_token']\n # get expiration time from message, if missing assume 1 hour\n self.expiration_time = d.get('expiration') or time.time() + 3600\n return self.access_token\n\n\nclass SpotifyConnect(spotipy.Spotify):\n \"\"\" Implement the Spotify Connect API.\n See: https://developer.spotify.com/web-api/\n\n This class extends the spotipy.Spotify class with Spotify Connect\n methods since the Spotipy module including these isn't released yet.\n \"\"\"\n def get_devices(self):\n \"\"\" Get a list of Spotify devices from the API.\n\n Returns:\n list of spotify devices connected to the user.\n \"\"\"\n try:\n # TODO: Cache for a brief time\n devices = self._get('me/player/devices')['devices']\n return devices\n except Exception as e:\n LOG.error(e)\n\n def status(self):\n \"\"\" Get current playback status (across the Spotify system) \"\"\"\n try:\n return self._get('me/player/currently-playing')\n except Exception as e:\n LOG.error(e)\n return None\n\n def is_playing(self, device=None):\n \"\"\" Get playback state, either across Spotify or for given device.\n Args:\n device (int): device id to check, if None playback on any device\n will be reported.\n\n Returns:\n True if specified device is playing\n \"\"\"\n try:\n status = self.status()\n if not status['is_playing'] or device is None:\n return status['is_playing']\n\n # Verify it is playing on the given device\n dev = self.get_device(device)\n return dev and dev['is_active']\n except:\n # Technically a 204 return from status() request means 'no track'\n return False # assume not playing\n\n def transfer_playback(self, device_id, force_play=True):\n \"\"\" Transfer playback to another device.\n Arguments:\n device_id (int): transfer playback to this device\n force_play (boolean): true if playback should start after\n transfer\n \"\"\"\n data = {\n 'device_ids': [device_id], # Doesn't allow more than one\n 'play': force_play\n }\n try:\n return self._put('me/player', payload=data)\n except Exception as e:\n LOG.error(e)\n\n def play(self, device, uris=None, context_uri=None):\n \"\"\" Start playback of tracks, albums or artist.\n\n Can play either a list of uris or a context_uri for things like\n artists and albums. Both uris and context_uri shouldn't be provided\n at the same time.\n\n Args:\n device (int): device id to start playback on\n uris (list): list of track uris to play\n context_uri (str): Spotify context uri for playing albums or\n artists.\n \"\"\"\n data = {}\n if uris:\n data['uris'] = uris\n elif context_uri:\n data['context_uri'] = context_uri\n path = 'me/player/play?device_id={}'.format(device)\n try:\n self._put(path, payload=data)\n except Exception as e:\n LOG.error(e)\n\n def pause(self, device):\n \"\"\" Pause user's playback on device.\n\n Arguments:\n device_id: device to pause\n \"\"\"\n LOG.debug('Pausing Spotify playback')\n try:\n self._put('me/player/pause?device_id={}'.format(device))\n except Exception as e:\n LOG.error(e)\n\n def next(self, device):\n \"\"\" Skip track.\n\n Arguments:\n device_id: device id for playback\n \"\"\"\n LOG.info('This was terrible, let\\'s play the next track')\n try:\n self._post('me/player/next?device_id={}'.format(device))\n except Exception as e:\n LOG.error(e)\n\n def prev(self, device):\n \"\"\" Move back in playlist.\n\n Arguments\n device_id: device target for playback\n \"\"\"\n LOG.debug('That was pretty good, let\\'s listen to that again')\n try:\n self._post('me/player/previous?device_id={}'.format(device))\n except Exception as e:\n LOG.error(e)\n\n def volume(self, device, volume):\n \"\"\" Set volume of device:\n\n Parameters:\n device: device id\n volume: volume in percent\n \"\"\"\n uri = 'me/player/volume?volume_percent={}&device_id={}'.format(volume,\n device)\n try:\n self._put(uri)\n except Exception as e:\n LOG.error(e)\n\n\nclass SpotifySkill(MycroftSkill):\n \"\"\"Spotify control through the Spotify Connect API.\"\"\"\n\n def __init__(self):\n super(SpotifySkill, self).__init__()\n self.index = 0\n self.spotify = None\n self.process = None\n self.device_name = None\n self.dev_id = None\n self.idle_count = 0\n self.ducking = False\n self.mouth_text = None\n\n self.__device_list = None\n self.__devices_fetched = 0\n self.OAUTH_ID = 1\n self.DEFAULT_VOLUME = 65\n self._playlists = None\n\n def launch_librespot(self):\n \"\"\" Launch the librespot binary for the Mark-1.\n TODO: Discovery mode\n \"\"\"\n platform = self.config_core.get('enclosure').get('platform', 'unknown')\n path = self.settings.get('librespot_path', None)\n if platform == 'mycroft_mark_1' and not path:\n path = 'librespot'\n\n if (path and self.device_name and\n 'user' in self.settings and 'password' in self.settings):\n # TODO: Error message when provided username/password don't work\n self.process = Popen([path, '-n', self.device_name,\n '-u', self.settings['user'],\n '-p', self.settings['password']])\n\n time.sleep(3) # give libreSpot time to start-up\n\n # Lower the volume since max volume sounds terrible on the Mark-1\n dev = self.device_by_name(self.device_name)\n if dev:\n self.spotify.volume(dev['id'], self.DEFAULT_VOLUME)\n\n def initialize(self):\n # Make sure the spotify login scheduled event is shutdown\n self.cancel_scheduled_event('SpotifyLogin')\n # Setup handlers for playback control messages\n self.add_event('mycroft.audio.service.next', self.next_track)\n self.add_event('mycroft.audio.service.prev', self.prev_track)\n self.add_event('mycroft.audio.service.pause', self.pause)\n self.add_event('mycroft.audio.service.resume', self.resume)\n\n # Check and then monitor for credential changes\n self.settings.set_changed_callback(self.on_websettings_changed)\n # Retry in 5 minutes\n self.schedule_repeating_event(self.on_websettings_changed,\n None, 5*60,\n name='SpotifyLogin')\n self.on_websettings_changed()\n\n def on_websettings_changed(self):\n # Only attempt to load credentials if the username has been set\n # will limit the accesses to the api.\n if not self.spotify and self.settings.get('user', None):\n try:\n self.load_credentials()\n except Exception:\n pass\n if self.spotify:\n self.cancel_scheduled_event('SpotifyLogin')\n if 'user' in self.settings and 'password' in self.settings:\n if self.process:\n self.stop_librespot()\n self.launch_librespot()\n\n def load_credentials(self):\n \"\"\" Retrieve credentials from the backend and connect to Spotify \"\"\"\n try:\n creds = MycroftSpotifyCredentials(self.OAUTH_ID)\n self.spotify = SpotifyConnect(client_credentials_manager=creds)\n except HTTPError:\n LOG.info('Couldn\\'t fetch credentials')\n self.spotify = None\n\n if self.spotify:\n # Spotfy connection worked, prepare for usage\n # TODO: Repeat occasionally on failures?\n # If not able to authorize, the method will be repeated after 60\n # seconds\n self.create_intents()\n # Should be safe to set device_name here since home has already\n # been connected\n self.device_name = DeviceApi().get().get('name')\n\n ######################################################################\n # Handle auto ducking when listener is started.\n\n def handle_listener_started(self, message):\n \"\"\" Handle auto ducking when listener is started. \"\"\"\n if self.spotify.is_playing():\n self.__pause()\n self.ducking = True\n\n # Start idle check\n self.idle_count = 0\n self.cancel_scheduled_event('IdleCheck')\n self.schedule_repeating_event(self.check_for_idle, None,\n 1, name='IdleCheck')\n\n def check_for_idle(self):\n \"\"\" Repeating event checking for end of auto ducking. \"\"\"\n if not self.ducking:\n self.cancel_scheduled_event('IdleCheck')\n return\n\n active = DisplayManager.get_active()\n if not active == '' or active == 'SpotifySkill':\n # No activity, start to fall asleep\n self.idle_count += 1\n\n if self.idle_count >= 5:\n # Resume playback after 5 seconds of being idle\n self.cancel_scheduled_event('IdleCheck')\n self.ducking = False\n self.resume()\n else:\n self.idle_count = 0\n\n ######################################################################\n # Mycroft display handling\n\n def start_monitor(self):\n \"\"\" Monitoring and current song display. \"\"\"\n # Clear any existing event\n self.stop_monitor()\n\n # Schedule a new one every 5 seconds to monitor/update display\n self.schedule_repeating_event(self._update_display,\n None, 5,\n name='MonitorSpotify')\n self.add_event('recognizer_loop:record_begin',\n self.handle_listener_started)\n\n def stop_monitor(self):\n # Clear any existing event\n self.cancel_scheduled_event('MonitorSpotify')\n\n def _update_display(self, message):\n # Checks once a second for feedback\n status = self.spotify.status() if self.spotify else {}\n\n if not status or not status.get('is_playing'):\n self.stop_monitor()\n self.mouth_text = None\n self.enclosure.mouth_reset()\n return\n\n # Get the current track info\n try:\n text = status['item']['artists'][0]['name'] + ': '\n except:\n text = \"\"\n try:\n text += status['item']['name']\n except:\n pass\n\n # Update the \"Now Playing\" display if needed\n if text != self.mouth_text:\n self.mouth_text = text\n self.enclosure.mouth_text(text)\n\n ######################################################################\n # Intent handling\n\n def create_intents(self):\n # Create intents for start playback handlers.\n self.register_intent_file('PlaySomeMusic.intent', self.play_something)\n self.register_intent_file('PlayAlbum.intent', self.play_album)\n self.register_intent_file('PlaySong.intent', self.play_song)\n\n # Play playlists\n self.register_intent_file('PlayPlaylist.intent', self.play_playlist)\n\n # TODO: REGRESSION: handling devices for all the above playing scenarios is going to require a second layer of logic for each one\n #self.register_intent_file('PlayOn.intent', self.play_playlist_on)\n @property\n def playlists(self):\n \"\"\" Playlists, cached for 5 minutes \"\"\"\n if not self.spotify:\n return [] # No connection, no playlists\n now = time.time()\n if not self._playlists or (now - self.__playlists_fetched > 5 * 60):\n self._playlists = {}\n playlists = self.spotify.current_user_playlists().get('items', [])\n for p in playlists:\n self._playlists[p['name']] = p\n self.__playlists_fetched = now\n return self._playlists\n\n @property\n def devices(self):\n \"\"\" Devices, cached for 60 seconds \"\"\"\n if not self.spotify:\n return [] # No connection, no devices\n now = time.time()\n if not self.__device_list or (now - self.__devices_fetched > 60):\n self.__device_list = self.spotify.get_devices()\n self.__devices_fetched = now\n return self.__device_list\n\n def device_by_name(self, name):\n \"\"\" Get a Spotify devices from the API\n\n Args:\n name (str): The device name (fuzzy matches)\n Returns:\n (dict) None or the matching device's description\n \"\"\"\n devices = self.devices\n if devices and len(devices) > 0:\n # Otherwise get a device with the selected name\n devices_by_name = {d['name']: d for d in devices}\n key, confidence = match_one(name, devices_by_name.keys())\n if confidence > 0.5:\n return devices_by_name[key]\n return None\n\n def get_default_device(self):\n \"\"\" Get preferred playback device \"\"\"\n if self.spotify:\n # When there is an active Spotify device somewhere, use it\n if (self.devices and len(self.devices) > 0 and\n self.spotify.is_playing()):\n for dev in self.devices:\n if dev['is_active']:\n return dev # Use this device\n\n # No playing device found, use the local Spotify instance\n dev = self.device_by_name(self.device_name)\n # if not check if a desktop spotify client is playing\n if not dev:\n dev = self.device_by_name(gethostname())\n # use first best device if none of the prioritized works\n if not dev and len(self.devices) > 0:\n dev = self.devices[0]\n if dev and not dev['is_active']:\n self.spotify.transfer_playback(dev['id'], False)\n return dev\n\n return None\n\n def get_best_playlist(self, playlist):\n \"\"\" Get best playlist matching the provided name\n\n Arguments:\n playlist (str): Playlist name\n\n Returns: (str) best match\n \"\"\"\n key, confidence = match_one(playlist, self.playlists.keys())\n if confidence > 0.5:\n return key\n else:\n return None\n\n def play_song(self, message):\n \"\"\"\n When the user wants to hear a song, optionally with artist and/or album information attached\n play the song \n play the song by \n play the song off \n play by off the album \n etc.\n\n Args:\n message (Dict): The utterance as interpreted by Padatious\n \"\"\"\n song = message.data.get('track')\n artist = message.data.get('artist')\n album = message.data.get('album')\n\n # workaround for Padatious training, as the most generic \"play {track}\"\n # is taking precedence over the play_something and play_playlist rules\n if song and not album:\n if song == 'spotify':\n self.continue_current_playlist(message)\n return\n m = re.match(self.translate('something_regex'),\n message.data['utterance'], re.M | re.I)\n if m:\n LOG.debug('play something detected, switching handler')\n self.play_something(message)\n return\n\n m = re.match(self.translate('playlist_regex'),\n message.data['utterance'], re.M | re.I)\n if m:\n LOG.debug('I\\'m in the play_song handler but I\\'ve seen'\n ' an utterance that contains \\'playlist.\\''\n ' I want to play the playlist ' + m.group(1) +\n '. Switching handlers.')\n message.data['playlist'] = m.group('playlist')\n self.play_playlist(message)\n return\n\n query = song\n LOG.info(\"I've been asked to play a particular song.\")\n LOG.info(\"\\tI think the song is: \" + song)\n if artist:\n query += ' artist:' + artist\n LOG.info(\"\\tI also think the artist is: \" + artist)\n\n if album:\n query += ' album:' + album\n LOG.info(\"\\tI also think the album is: \" + album)\n\n LOG.info(\"The query I want to send to Spotify is: '\" + query + \"'\")\n res = self.spotify.search(query, type='track')\n self.play(data=res, data_type='track')\n\n def play_album(self, message):\n \"\"\"\n When the user wants to hear an album, optionally with artist information attached\n Play the album by \n\n Args:\n message (Dict): The utterance as interpreted by Padatious\n \"\"\"\n album = message.data.get('album')\n artist = message.data.get('artist')\n query = album\n LOG.info(\"I've been asked to play a particular album.\")\n LOG.info(\"\\tI think the album is: \" + album)\n if artist:\n query += ' artist:' + artist\n LOG.info(\"\\tI also think the artist is: \" + artist)\n\n LOG.info(\"The query I want to send to Spotify is: '\" + query + \"'\")\n res = self.spotify.search(query, type='album')\n self.play(data=res, data_type='album')\n\n def play_something(self, message):\n \"\"\"\n When the user wants to hear something (optionally by an artist), but they don't know what\n play something\n play something by \n\n Args:\n message (Dict): The utterance as interpreted by Padatious\n \"\"\"\n LOG.info(\"I've been asked to play pretty much anything.\")\n artist = message.data.get('artist')\n genres = ['rap', 'dance', 'pop', 'hip hop', 'rock', 'trap', 'classic rock', 'metal', 'edm', 'techno', 'house']\n query = ''\n if artist:\n LOG.info(\"\\tBut it has to be by \" + artist)\n query = 'artist:' + artist\n res = self.spotify.search(query, type='artist')\n self.play(data=res, data_type='artist')\n else:\n genre = random.choice(genres)\n LOG.info(\"\\tI'm going to pick the genre \" + genre)\n query = 'genre:' + genre\n res = self.spotify.search(query, type='track')\n self.play(data=res, data_type='genre', genre_name = genre)\n\n\n def play_playlist(self, message):\n \"\"\" Play user playlist on default device. \"\"\"\n playlist = message.data.get('playlist')\n if not playlist or playlist == 'spotify':\n self.continue_current_playlist(message)\n elif self.playback_prerequisits_ok():\n dev = self.get_default_device()\n self.start_playlist_playback(dev, self.get_best_playlist(playlist))\n\n def continue_current_playlist(self, message):\n if self.playback_prerequisits_ok():\n dev = self.get_default_device()\n if dev:\n self.spotify_play(dev['id'])\n else:\n self.speak_dialog('NoDevicesAvailable')\n\n def playback_prerequisits_ok(self):\n \"\"\" Check that playback is possible, launch client if neccessary. \"\"\"\n if self.spotify is None:\n self.speak_dialog('NotAuthorized')\n return False\n\n if not self.process:\n self.launch_librespot()\n return True\n\n @intent_handler(IntentBuilder('').require('Play').require('Spotify'))\n def play_spotify(self, message):\n # Play anything\n if self.playback_prerequisits_ok():\n message.data['utterance'] = 'play spotify' # play anything!\n self.play_playlist(message)\n else:\n self.speak_dialog('NotAuthorized')\n\n def spotify_play(self, dev_id, uris=None, context_uri=None):\n \"\"\" Start spotify playback and catch any exceptions. \"\"\"\n try:\n LOG.info(u'spotify_play: {}'.format(dev_id))\n self.spotify.play(dev_id, uris, context_uri)\n self.start_monitor()\n self.dev_id = dev_id\n # self.show_notes()\n except spotipy.SpotifyException as e:\n # TODO: Catch other conditions?\n self.speak_dialog('NotAuthorized')\n except Exception as e:\n LOG.exception(e)\n self.speak_dialog('NotAuthorized')\n\n def start_playlist_playback(self, dev, playlist_name):\n LOG.info(u'Playlist: {}'.format(playlist_name))\n \n playlist = None\n if playlist_name:\n playlist = self.get_best_playlist(playlist_name)\n if not playlist:\n LOG.info(u'Playlists: {}'.format(self.playlists))\n if not self.playlists:\n return # different default action when no lists defined?\n playlist = self.get_best_playlist(self.playlists.keys()[0])\n \n if dev and playlist:\n LOG.info(u'playing {} using {}'.format(playlist, dev['name']))\n self.speak_dialog('listening_to_playlist', data={'playlist': playlist})\n time.sleep(2)\n pl = self.playlists[playlist]\n tracks = self.spotify.user_playlist_tracks(pl['owner']['id'], pl['id'])\n uris = [t['track']['uri'] for t in tracks['items']]\n self.spotify_play(dev['id'], uris=uris)\n # self.show_notes()\n elif dev:\n LOG.info(u'couldn\\'t find {}'.format(playlist))\n else:\n LOG.info('No spotify devices found')\n\n def play_playlist_on(self, message):\n \"\"\" Play playlist on specific device. \"\"\"\n if self.playback_prerequisits_ok():\n playlist = self.get_best_playlist(message.data.get('playlist'))\n dev = self.device_by_name(message.data.get('device'))\n if dev:\n # Assume we are about to act on this device,\n # transfer playback to it.\n if not dev['is_active']:\n self.spotify.transfer_playback(dev[\"id\"], False)\n self.start_playlist_playback(dev, playlist)\n\n def play(self, data, data_type='track', genre_name=None):\n \"\"\"\n Plays the provided data in the manner appropriate for 'data_type'\n If the type is 'genre' then genre_name should be specified to populate the output dialog\n\n A 'track' is played as just an individual track\n An 'album' queues up all the tracks contained in that album and starts with the first track\n A 'genre' expects data returned from self.spotify.search, and will use that genre to play a selection similar to it\n\n Args:\n data (Dict): Data returned by self.spotify.search\n data_type (String): The type of data contained in the passed-in object. 'track', 'album', or 'genre' are currently supported\n genre_name (String): If type is 'genre', also include the genre's name here, for output purposes\n \"\"\"\n dev = self.get_default_device()\n if dev is None:\n LOG.error(\"Unable to get a default device while trying to play something.\")\n self.speak_dialog('NoDevicesAvailable')\n else:\n try:\n if data_type is 'track':\n song = data['tracks']['items'][0]\n self.speak_dialog('listening_to_song_by', data={'tracks': song['name'], 'artist': song['artists'][0]['name']})\n time.sleep(2)\n self.spotify_play(dev['id'], uris=[song['uri']])\n elif data_type is 'artist':\n artist = data['artists']['items'][0]\n self.speak_dialog('listening_to_artist',\n data={'artist': artist['name']})\n time.sleep(2)\n self.spotify_play(dev['id'], context_uri=artist['uri'])\n elif data_type is 'album':\n album = data['albums']['items'][0]\n self.speak_dialog('listening_to_album_by', data={'album': album['name'], 'artist': album['artists'][0]['name']})\n time.sleep(2)\n self.spotify_play(dev['id'], context_uri=album['uri'])\n elif data_type is 'genre':\n items = data['tracks']['items']\n random.shuffle(items)\n uris = []\n for item in items:\n uris.append(item['uri'])\n self.speak_dialog('listening_to_genre', data={'genre': genre_name, 'track': items[0]['name'], 'artist': items[0]['artists'][0]['name']})\n time.sleep(2)\n self.spotify_play(dev['id'], uris=uris)\n except Exception as e:\n LOG.error(\"Unable to obtain the name, artist, and/or URI information while asked to play something. \" + str(e))\n\n def search(self, query, search_type=None):\n \"\"\" Search for an album, playlist or artist.\n Arguments:\n query: search query (album title, artist, etc.)\n search_type: weather to search for an 'album', 'artist',\n 'playlist', 'track', or 'genre'\n\n TODO: improve results of albums by checking artist\n \"\"\"\n if search_type is None:\n search_type = 'track'\n\n dev = self.get_default_device()\n if not dev:\n self.speak_dialog('NoDefaultDeviceAvailable')\n return\n\n res = None\n if search_type == 'album' and len(query.split('by')) > 1:\n title, artist = query.split('by')\n result = self.spotify.search(title, type=search_type)\n else:\n result = self.spotify.search(query, type=search_type)\n\n if search_type == 'album':\n if len(result['albums']['items']) > 0 and dev:\n album = result['albums']['items'][0]\n LOG.info(album)\n res = album\n elif search_type == 'artist':\n LOG.info(result['artists'])\n if len(result['artists']['items']) > 0:\n artist = result['artists']['items'][0]\n LOG.info(artist)\n res = artist\n elif search_type == 'genre':\n LOG.info(\"TODO! Genre\")\n else:\n LOG.info('ERROR')\n return\n\n #if res:\n # self.speak_dialog('listening_to', data={'tracks': res['name']})\n # time.sleep(2)\n # self.spotify_play(dev['id'], context_uri=res['uri'])\n #else:\n # self.speak_dialog('NoResults')\n return res\n\n def __pause(self):\n # if authorized and playback was started by the skill\n if self.spotify:\n LOG.info('Pausing Spotify...')\n self.spotify.pause(self.dev_id)\n\n def pause(self, message=None):\n \"\"\" Handler for playback control pause. \"\"\"\n self.ducking = False\n self.__pause()\n\n def resume(self, message=None):\n \"\"\" Handler for playback control resume. \"\"\"\n # if authorized and playback was started by the skill\n if self.spotify:\n LOG.info('Resume Spotify')\n if not self.dev_id:\n self.dev_id = self.get_default_device()\n self.spotify_play(self.dev_id)\n\n def next_track(self, message):\n \"\"\" Handler for playback control next. \"\"\"\n # if authorized and playback was started by the skill\n if self.spotify and self.dev_id:\n LOG.info('Next Spotify track')\n self.spotify.next(self.dev_id)\n self.start_monitor()\n\n def prev_track(self, message):\n \"\"\" Handler for playback control prev. \"\"\"\n # if authorized and playback was started by the skill\n if self.spotify and self.dev_id:\n LOG.info('Previous Spotify track')\n self.spotify.prev(self.dev_id)\n self.start_monitor()\n\n @intent_handler(IntentBuilder('').require('Spotify').require('Device'))\n def list_devices(self, message):\n \"\"\" List available devices. \"\"\"\n LOG.info(self)\n if self.spotify:\n devices = [d['name'] for d in self.spotify.get_devices()]\n if len(devices) == 1:\n self.speak(devices[0])\n elif len(devices) > 1:\n self.speak_dialog('AvailableDevices',\n {'devices': '. '.join(devices[:-1]) + '. ' +\n self.translate('And') + '. ' +\n devices[-1]})\n else:\n self.speak_dialog('NoDevicesAvailable')\n else:\n self.speak_dialog('NotAuthorized')\n\n @intent_handler(IntentBuilder('').require('Transfer').require('Spotify')\n .require('ToDevice'))\n def transfer_playback(self, message):\n \"\"\" Move playback from one device to another. \"\"\"\n if self.spotify and self.spotify.is_playing():\n dev = self.device_by_name(message.data['ToDevice'])\n if dev:\n self.spotify.transfer_playback(dev['id'])\n\n def show_notes(self):\n \"\"\" show notes, HA HA \"\"\"\n self.schedule_repeating_event(self._update_notes,\n datetime.datetime.now(), 2,\n name='dancing_notes')\n\n def display_notes(self):\n \"\"\" Start timer thread displaying notes on the display. \"\"\"\n pass\n\n def clear_display(self):\n \"\"\" Clear display. \"\"\"\n self.enclosure.mouth_display(img_code=\"HIAAAAAAAAAAAAAA\",\n refresh=False)\n self.enclosure.mouth_display(img_code=\"HIAAAAAAAAAAAAAA\",\n x=24, refresh=False)\n\n def draw_notes(self, index):\n \"\"\" Draw notes on display. \"\"\"\n\n notes = [['IIAEAOOHGAGEGOOHAA', 'IIAAACAHPDDADCDHPD'],\n ['IIAAACAHPDDADCDHPD', 'IIAEAOOHGAGEGOOHAA']]\n\n # draw notes\n for pos in range(4):\n self.enclosure.mouth_display(img_code=notes[index][pos % 2],\n x=pos * 8,\n refresh=False)\n\n def _update_notes(self):\n \"\"\" Repeating event updating the display. \"\"\"\n if self._should_display_notes():\n self.draw_notes(self.index)\n self.index = ((self.index + 1) % 2)\n\n def stop(self):\n \"\"\" Stop playback. \"\"\"\n if not self.spotify or not self.spotify.is_playing():\n self.dev_id = None\n return False\n\n dev = self.get_default_device()\n self.dev_id = dev['id']\n if self.dev_id:\n # self.remove_event('dancing_notes')\n self.pause(None)\n\n # Clear playing device id\n self.dev_id = None\n return True\n\n def stop_librespot(self):\n \"\"\" Send Terminate signal to librespot if it's running. \"\"\"\n if self.process and self.process.poll() is None:\n self.process.send_signal(signal.SIGTERM)\n self.process.communicate() # Communicate to remove zombie\n\n def shutdown(self):\n \"\"\" Remove the monitor at shutdown. \"\"\"\n self.cancel_scheduled_event('SpotifyLogin')\n self.stop_monitor()\n self.stop_librespot()\n\n # Do normal shutdown procedure\n super(SpotifySkill, self).shutdown()\n\n def _should_display_notes(self):\n _get_active = DisplayManager.get_active\n if _get_active() == '' or _get_active() == self.name:\n return True\n else:\n return False\n\n\ndef create_skill():\n return SpotifySkill()\n\n# WORKING COMMANDS:\n# play spotify\n# search spotify for the album nighthawks at the diner\n# list spotify devices\n# skip track\n# next track\n# pause\n# resume\n# pause music\n# resume music\n#\n# FAILING COMMANDS:\n# play tom waits on spotify\n# search spotify for nighthawks at the diner\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":35177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"538391390","text":"import urllib2\n\nimport json\nimport sys\n\ndef get_marathon_config(addr,app):\n r = urllib2.urlopen(addr)\n return r.read()\n\nif __name__ == '__main__':\n print(\"Run script.\")\n if len(sys.argv)<3:\n print(\"Run with marathon url and group param: get_config_py3.py \")\n exit()\n else:\n url = sys.argv[1]\n app = sys.argv[2]\n response = get_marathon_config(url,app)\n json_obj = json.loads(response)\n apps = json_obj['apps']\n theApp = [x for x in apps if x['id'] == app][0]\n tasks = theApp['tasks']\n hostAndPorts = [(x['host'],x['ports'][0]) for x in tasks]\n\n print('find nodes:',hostAndPorts)\n f = open(\"ssh_config\",'w')\n hostFile = open(\"hostfile\",\"w\")\n sysHostFilePart = open(\"sysHostFilePart\",\"w\")\n sysHostFilePart.write(\"\\n\")\n f.write(\"StrictHostKeyChecking no\\n\")\n index = 1\n for node in hostAndPorts:\n nodeName = \"node\"+str(index)\n f.write(\"HOST \"+nodeName+\"\\n\")\n f.write(\"\\t HostName \"+node[0]+\"\\n\")\n f.write(\"\\t Port \"+str(node[1])+\"\\n\")\n f.write(\"\\t User tutorial\\n\")\n sysHostFilePart.write(node[0]+\"\\t \"+nodeName+\"\\n\")\n hostFile.write(nodeName+\" slots=1\\n\")\n index+=1\n f.close()\n hostFile.close()\n sysHostFilePart.close()\n\n","sub_path":"get_config_py2.py","file_name":"get_config_py2.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"101887939","text":"__author__ = \"Christian Kongsgaard, Daniele Bigoni\"\n__license__ = 'MIT'\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# IMPORTS\n\n# Modules\nimport numpy as np\nfrom scipy import stats\n\n# RiBuild Modules\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# Sobol Sampling\n\n\ndef i4_bit_hi1(n):\n \"\"\" I4_BIT_HI1 returns the position of the high 1 bit base 2 in an integer.\n\n Example:\n\n N Binary BIT\n ---- -------- ----\n 0 0 0\n 1 1 1\n 2 10 2\n 3 11 2\n 4 100 3\n 5 101 3\n 6 110 3\n 7 111 3\n 8 1000 4\n 9 1001 4\n 10 1010 4\n 11 1011 4\n 12 1100 4\n 13 1101 4\n 14 1110 4\n 15 1111 4\n 16 10000 5\n 17 10001 5\n 1023 1111111111 10\n 1024 10000000000 11\n 1025 10000000001 11\n\n Licensing:\n\n This code is distributed under the GNU LGPL license.\n Modified: 22 February 2011\n\n Author:\n Original MATLAB version by John Burkardt.\n PYTHON version by Corrado Chisari\n\n :param n: The integer to be measured. n should be non-negative. If n is non-positive, the value will always be 0.\n :type n: int\n :return: BIT, the number of bits base 2.\n :rtype: int\n \"\"\"\n\n i = np.floor(n)\n bit = 0\n\n while True:\n if i <= 0:\n break\n else:\n bit += 1\n i = np.floor(i / 2.)\n\n return bit\n\n\ndef i4_bit_lo0(n):\n \"\"\"\n I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer.\n\n Example:\n\n N Binary BIT\n ---- -------- ----\n 0 0 1\n 1 1 2\n 2 10 1\n 3 11 3\n 4 100 1\n 5 101 2\n 6 110 1\n 7 111 4\n 8 1000 1\n 9 1001 2\n 10 1010 1\n 11 1011 3\n 12 1100 1\n 13 1101 2\n 14 1110 1\n 15 1111 5\n 16 10000 1\n 17 10001 2\n 1023 1111111111 1\n 1024 10000000000 1\n 1025 10000000001 1\n\n Licensing:\n\n This code is distributed under the GNU LGPL license.\n\n Modified: 22 February 2011\n\n Author:\n Original MATLAB version by John Burkardt.\n PYTHON version by Corrado Chisari\n\n :param n: The integer to be measured. N should be nonnegative.\n :type n: int\n :return: BIT, the position of the low 1 bit.\n :rtype: int\n \"\"\"\n\n bit = 0\n i = np.floor(n)\n\n while True:\n bit = bit + 1\n i2 = np.floor(i / 2.)\n\n if i == 2 * i2:\n break\n\n i = i2\n\n return bit\n\n\ndef i4_sobol_generate(m, n, skip):\n \"\"\"\n I4_SOBOL_GENERATE generates a Sobol dataset.\n\n Licensing:\n This code is distributed under the GNU LGPL license.\n\n Modified: 22 February 2011\n\n Author:\n Original MATLAB version by John Burkardt.\n PYTHON version by Corrado Chisari\n\n :param m: M, the spatial dimension.\n :type m: int\n :param n: N, the number of points to generate.\n :type n: int\n :param skip: SKIP, the number of initial points to skip.\n :type skip: int\n :return: R(M,N), the points.\n :rtype: float\n \"\"\"\n\n r = np.zeros((m, n))\n\n for j in range(1, n + 1):\n seed = skip + j - 2\n [r[0:m, j - 1], seed] = i4_sobol(m, seed)\n\n return r\n\n\ndef i4_sobol(dim_num, seed):\n \"\"\"\n I4_SOBOL generates a new quasirandom Sobol vector with each call.\n\n Discussion:\n The routine adapts the ideas of Antonov and Saleev.\n\n Licensing:\n This code is distributed under the GNU LGPL license.\n\n Modified: 22 February 2011\n\n Author:\n Original FORTRAN77 version by Bennett Fox.\n MATLAB version by John Burkardt.\n PYTHON version by Corrado Chisari\n\n Reference:\n\n Antonov, Saleev,\n USSR Computational Mathematics and Mathematical Physics,\n Volume 19, 1980, pages 252 - 256.\n\n Paul Bratley, Bennett Fox,\n Algorithm 659:\n Implementing Sobol's Quasirandom Sequence Generator,\n ACM Transactions on Mathematical Software,\n Volume 14, Number 1, pages 88-100, 1988.\n\n Bennett Fox,\n Algorithm 647:\n Implementation and Relative Efficiency of Quasirandom\n Sequence Generators,\n ACM Transactions on Mathematical Software,\n Volume 12, Number 4, pages 362-376, 1986.\n\n Ilya Sobol,\n USSR Computational Mathematics and Mathematical Physics,\n Volume 16, pages 236-242, 1977.\n\n Ilya Sobol, Levitan,\n The Production of Points Uniformly Distributed in a Multidimensional\n Cube (in Russian),\n Preprint IPM Akad. Nauk SSSR,\n Number 40, Moscow 1976.\n\n :param dim_num: DIM_NUM, the number of spatial dimensions. DIM_NUM must satisfy 1 <= DIM_NUM <= 40.\n :type dim_num: int\n :param seed: SEED, the \"seed\" for the sequence. This is essentially the index in the sequence of the quasirandom\n value to be generated.\tOn output, SEED has been set to the appropriate next value, usually simply SEED+1. If SEED\n is less than 0 on input, it is treated as though it were 0. An input value of 0 requests the first (0-th)\n element of the sequence.\n :type seed: int\n :return: QUASI(DIM_NUM), the next quasirandom vector.\n :rtype: float\n \"\"\"\n\n global atmost\n global dim_max\n global dim_num_save\n global initialized\n global lastq\n global log_max\n global maxcol\n global poly\n global recipd\n global seed_save\n global v\n\n if not 'initialized' in globals().keys():\n initialized = 0\n dim_num_save = -1\n\n if not initialized or dim_num != dim_num_save:\n initialized = 1\n dim_max = 40\n dim_num_save = -1\n log_max = 30\n seed_save = -1\n\n # Initialize (part of) V.\n\n v = np.zeros((dim_max, log_max))\n v[0:40, 0] = np.transpose([\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n\n v[2:40, 1] = np.transpose([\n 1, 3, 1, 3, 1, 3, 3, 1,\n 3, 1, 3, 1, 3, 1, 1, 3, 1, 3,\n 1, 3, 1, 3, 3, 1, 3, 1, 3, 1,\n 3, 1, 1, 3, 1, 3, 1, 3, 1, 3])\n\n v[3:40, 2] = np.transpose([\n 7, 5, 1, 3, 3, 7, 5,\n 5, 7, 7, 1, 3, 3, 7, 5, 1, 1,\n 5, 3, 3, 1, 7, 5, 1, 3, 3, 7,\n 5, 1, 1, 5, 7, 7, 5, 1, 3, 3])\n\n v[5:40, 3] = np.transpose([\n 1, 7, 9, 13, 11,\n 1, 3, 7, 9, 5, 13, 13, 11, 3, 15,\n 5, 3, 15, 7, 9, 13, 9, 1, 11, 7,\n 5, 15, 1, 15, 11, 5, 3, 1, 7, 9])\n\n v[7:40, 4] = np.transpose([\n 9, 3, 27,\n 15, 29, 21, 23, 19, 11, 25, 7, 13, 17,\n 1, 25, 29, 3, 31, 11, 5, 23, 27, 19,\n 21, 5, 1, 17, 13, 7, 15, 9, 31, 9])\n\n v[13:40, 5] = np.transpose([\n 37, 33, 7, 5, 11, 39, 63,\n 27, 17, 15, 23, 29, 3, 21, 13, 31, 25,\n 9, 49, 33, 19, 29, 11, 19, 27, 15, 25])\n\n v[19:40, 6] = np.transpose([\n 13,\n 33, 115, 41, 79, 17, 29, 119, 75, 73, 105,\n 7, 59, 65, 21, 3, 113, 61, 89, 45, 107])\n\n v[37:40, 7] = np.transpose([\n 7, 23, 39])\n\n # Set POLY.\n\n poly = [\n 1, 3, 7, 11, 13, 19, 25, 37, 59, 47,\n 61, 55, 41, 67, 97, 91, 109, 103, 115, 131,\n 193, 137, 145, 143, 241, 157, 185, 167, 229, 171,\n 213, 191, 253, 203, 211, 239, 247, 285, 369, 299]\n\n atmost = 2 ** log_max - 1\n\n # Find the number of bits in ATMOST.\n\n maxcol = i4_bit_hi1(atmost)\n\n # Initialize row 1 of V.\n\n v[0, 0:maxcol] = 1\n\n # Things to do only if the dimension changed.\n\n if dim_num != dim_num_save:\n\n # Check parameters.\n\n if dim_num < 1 or dim_max < dim_num:\n print('I4_SOBOL - Fatal error!')\n print('\tThe spatial dimension DIM_NUM should satisfy:')\n print('\t\t1 <= DIM_NUM <= %d' % dim_max)\n print('\tBut this input value is DIM_NUM = %d' % dim_num)\n return\n\n dim_num_save = dim_num\n\n # Initialize the remaining rows of V.\n\n for i in range(2, dim_num + 1):\n # The bits of the integer POLY(I) gives the form of polynomial I.\n # Find the degree of polynomial I from binary encoding.\n\n j = poly[i - 1]\n m = 0\n\n while True:\n j = np.floor(j / 2.)\n\n if j <= 0:\n break\n\n m = m + 1\n\n # Expand this bit pattern to separate components of the logical array INCLUD.\n\n j = poly[i - 1]\n includ = np.zeros(m)\n\n for k in range(m, 0, -1):\n j2 = np.floor(j / 2.)\n includ[k - 1] = (j != 2 * j2)\n j = j2\n\n # Calculate the remaining elements of row I as explained in Bratley and Fox, section 2.\n\n for j in range(m + 1, maxcol + 1):\n\n newv = v[i - 1, j - m - 1]\n l = 1\n for k in range(1, m + 1):\n l = 2 * l\n if includ[k - 1]:\n newv = np.bitwise_xor(int(newv), int(l * v[i - 1, j - k - 1]))\n v[i - 1, j - 1] = newv\n\n # Multiply columns of V by appropriate power of 2.\n\n l = 1\n for j in range(maxcol - 1, 0, -1):\n l = 2 * l\n v[0:dim_num, j - 1] = v[0:dim_num, j - 1] * l\n\n # RECIPD is 1/(common denominator of the elements in V).\n\n recipd = 1.0 / (2 * l)\n lastq = np.zeros(dim_num)\n\n seed = int(np.floor(seed))\n\n if seed < 0:\n seed = 0\n\n if seed == 0:\n l = 1\n lastq = np.zeros(dim_num)\n\n elif seed == seed_save + 1:\n # Find the position of the right-hand zero in SEED.\n\n l = i4_bit_lo0(seed)\n\n elif seed <= seed_save:\n\n seed_save = 0\n l = 1\n lastq = np.zeros(dim_num)\n\n for seed_temp in range(int(seed_save), int(seed)):\n l = i4_bit_lo0(seed_temp)\n for i in range(1, dim_num + 1):\n lastq[i - 1] = np.bitwise_xor(int(lastq[i - 1]), int(v[i - 1, l - 1]))\n\n l = i4_bit_lo0(seed)\n\n elif seed_save + 1 < seed:\n\n for seed_temp in range(int(seed_save + 1), int(seed)):\n l = i4_bit_lo0(seed_temp)\n for i in range(1, dim_num + 1):\n lastq[i - 1] = np.bitwise_xor(int(lastq[i - 1]), int(v[i - 1, l - 1]))\n\n l = i4_bit_lo0(seed)\n\n # Check that the user is not calling too many times!\n\n if maxcol < l:\n print('I4_SOBOL - Fatal error!')\n print('\tToo many calls!')\n print('\tMAXCOL = %d\\n' % maxcol)\n print('\tL =\t\t\t%d\\n' % l)\n return\n\n # Calculate the new components of QUASI.\n\n quasi = np.zeros(dim_num)\n for i in range(1, dim_num + 1):\n quasi[i - 1] = lastq[i - 1] * recipd\n lastq[i - 1] = np.bitwise_xor(int(lastq[i - 1]), int(v[i - 1, l - 1]))\n\n seed_save = seed\n seed = seed + 1\n\n return [quasi, seed]\n\n\ndef i4_uniform(a, b, seed):\n \"\"\"\n I4_UNIFORM returns a scaled pseudorandom I4.\n\n Discussion:\n The pseudorandom number will be scaled to be uniformly distributed\n between A and B.\n\n Licensing:\n This code is distributed under the GNU LGPL license.\n\n Modified: 22 February 2011\n\n Author:\n Original MATLAB version by John Burkardt.\n PYTHON version by Corrado Chisari\n\n Reference:\n Paul Bratley, Bennett Fox, Linus Schrage,\n A Guide to Simulation,\n Springer Verlag, pages 201-202, 1983.\n\n Pierre L'Ecuyer,\n Random Number Generation,\n in Handbook of Simulation,\n edited by Jerry Banks,\n Wiley Interscience, page 95, 1998.\n\n Bennett Fox,\n Algorithm 647:\n Implementation and Relative Efficiency of Quasirandom\n Sequence Generators,\n ACM Transactions on Mathematical Software,\n Volume 12, Number 4, pages 362-376, 1986.\n\n Peter Lewis, Allen Goodman, James Miller\n A Pseudo-Random Number Generator for the System/360,\n IBM Systems Journal,\n Volume 8, pages 136-143, 1969.\n\n :param a: A, the minimum acceptable values.\n :type a: int\n :param b: B, the maximum acceptable values.\n :type b: int\n :param seed: SEED, a seed for the random number generator.\n :type seed: int\n :return: C, the randomly chosen integer. SEED, the updated seed.\n :rtype: list\n \"\"\"\n\n if seed == 0:\n print('I4_UNIFORM - Fatal error!')\n print('\tInput SEED = 0!')\n\n seed = np.floor(seed)\n a = round(a)\n b = round(b)\n\n seed = np.mod(seed, 2147483647)\n\n if seed < 0:\n seed = seed + 2147483647\n\n k = np.floor(seed / 127773)\n\n seed = 16807 * (seed - k * 127773) - k * 2836\n\n if seed < 0:\n seed = seed + 2147483647\n\n r = seed * 4.656612875E-10\n\n # Scale R to lie between A-0.5 and B+0.5.\n\n r = (1.0 - r) * (min(a, b) - 0.5) + r * (max(a, b) + 0.5)\n\n # Use rounding to convert R to an integer between A and B.\n\n value = round(r)\n\n value = max(value, min(a, b))\n value = min(value, max(a, b))\n\n c = value\n\n return [int(c), int(seed)]\n\n\ndef prime_ge(n):\n \"\"\"\n PRIME_GE returns the smallest prime greater than or equal to N.\n\n Example:\n N \t\t PRIME_GE\n -10\t\t 2\n \t1\t\t 2\n \t2\t\t 2\n \t3\t\t 3\n \t4\t\t 5\n \t5\t\t 5\n \t6\t\t 7\n \t7\t\t 7\n \t8 11\n \t9 11\n 10 11\n\n Licensing:\n This code is distributed under the GNU LGPL license.\n\n Modified: 22 February 2011\n\n Author:\n Original MATLAB version by John Burkardt.\n PYTHON version by Corrado Chisari\n\n :param n: N, the number to be bounded.\n :type n: int\n :return: P, the smallest prime number that is greater than or equal to N.\n :rtype: int\n \"\"\"\n\n p = max(np.ceil(n), 2)\n\n while not isprime(p):\n p = p + 1\n\n return p\n\n\ndef isprime(n):\n \"\"\"\n IS_PRIME returns True if N is a prime number, False otherwise\n\n Licensing:\n This code is distributed under the GNU LGPL license.\n\n Modified: 22 February 2011\n\n Author:\n Corrado Chisari\n\n :param n: N, the number to be checked.\n :type n: int\n :return: True or false\n :rtype: bool\n \"\"\"\n\n if n != int(n) or n < 1:\n return False\n\n p = 2\n while p < n:\n if n % p == 0:\n return False\n p += 1\n return True\n\n\ndef sobol_generate(k, N, skip, leap):\n \"\"\"\n Skip and leap sobol sequence\n \n Reference:\n\n .. [1] Saltelli, A., Chan, K., Scott, E.M., \"Sensitivity Analysis\"\n \"\"\"\n\n # Generate sobol sequence\n samples = i4_sobol_generate(k, N * (leap + 1), skip).T\n\n # Remove leap values\n samples = samples[0:samples.shape[0]:(leap + 1), :]\n\n return samples\n\n\ndef scrambled_sobol_generate(k, N, skip, leap):\n \"\"\"\n Scramble function as in Owen (1997)\n \n Reference:\n\n .. [1] Saltelli, A., Chan, K., Scott, E.M., \"Sensitivity Analysis\"\n \"\"\"\n\n # Generate sobol sequence\n samples = sobol_generate(k, N, skip, leap)\n\n # Scramble the sequence\n for col in range(0, k):\n samples[:, col] = scramble(samples[:, col])\n\n return samples\n\n\ndef scramble(X):\n \"\"\"\n Scramble function as in Owen (1997)\n \n Reference:\n\n .. [1] Saltelli, A., Chan, K., Scott, E.M., \"Sensitivity Analysis\"\n \"\"\"\n\n N = len(X) - (len(X) % 2)\n\n idx = X[0:N].argsort()\n iidx = idx.argsort()\n\n # Generate binomial values and switch position for the second half of the array\n bi = stats.binom(1, 0.5).rvs(size=int(N / 2)).astype(bool)\n pos = stats.uniform.rvs(size=int(N / 2)).argsort()\n\n # Scramble the indexes\n tmp = idx[0:int(N / 2)][bi]\n idx[0:int(N / 2)][bi] = idx[int(N / 2):N][pos[bi]]\n idx[int(N / 2):N][pos[bi]] = tmp\n\n # Apply the scrambling\n X[0:N] = X[0:N][idx[iidx]]\n\n # Apply scrambling to sub intervals\n if N > 2:\n X[0:int(N / 2)] = scramble(X[0:int(N / 2)])\n X[int(N / 2):N] = scramble(X[int(N / 2):N])\n\n return X\n","sub_path":"delphin_6_automation/sampling/sobol_lib.py","file_name":"sobol_lib.py","file_ext":"py","file_size_in_byte":16379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"473057884","text":"# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014 Florian Bruhin (The Compiler) \n#\n# This file is part of qutebrowser.\n#\n# qutebrowser 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# qutebrowser 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 qutebrowser. If not, see .\n\n\"\"\"Setting options used for qutebrowser.\"\"\"\n\nimport re\nimport shlex\nimport base64\nimport codecs\nimport os.path\nimport sre_constants\n\nfrom PyQt5.QtCore import QUrl\nfrom PyQt5.QtGui import QColor, QFont\nfrom PyQt5.QtNetwork import QNetworkProxy\nfrom PyQt5.QtWidgets import QTabWidget, QTabBar\n\nfrom qutebrowser.commands import cmdutils\n\n\nSYSTEM_PROXY = object() # Return value for Proxy type\n\n\nclass ValidationError(ValueError):\n\n \"\"\"Exception raised when a value for a config type was invalid.\n\n Class attributes:\n section: Section in which the error occured (added when catching and\n re-raising the exception).\n option: Option in which the error occured.\n \"\"\"\n\n section = None\n option = None\n\n def __init__(self, value, msg):\n super().__init__(\"Invalid value '{}' - {}\".format(value, msg))\n\n\nclass ValidValues:\n\n \"\"\"Container for valid values for a given type.\n\n Attributes:\n values: A list with the allowed untransformed values.\n descriptions: A dict with value/desc mappings.\n \"\"\"\n\n def __init__(self, *vals):\n self.descriptions = {}\n self.values = []\n for v in vals:\n if isinstance(v, str):\n # Value without description\n self.values.append(v)\n else:\n # (value, description) tuple\n self.values.append(v[0])\n self.descriptions[v[0]] = v[1]\n\n def __contains__(self, val):\n return val in self.values\n\n def __iter__(self):\n return self.values.__iter__()\n\n\nclass BaseType:\n\n \"\"\"A type used for a setting value.\n\n Attributes:\n _none_ok: Whether to convert to None for an empty string.\n\n Class attributes:\n valid_values: Possible values if they can be expressed as a fixed\n string. ValidValues instance.\n typestr: The name of the type to appear in the config.\n \"\"\"\n\n typestr = None\n valid_values = None\n\n def __init__(self, none_ok=False):\n self._none_ok = none_ok\n\n def transform(self, value):\n \"\"\"Transform the setting value.\n\n This method can assume the value is indeed a valid value.\n\n The default implementation returns the original value.\n\n Args:\n value: The original string value.\n\n Return:\n The transformed value.\n \"\"\"\n if not value:\n return None\n else:\n return value\n\n def validate(self, value):\n \"\"\"Validate value against possible values.\n\n The default implementation checks the value against self.valid_values\n if it was defined.\n\n Args:\n value: The value to validate.\n method should be overridden.\n \"\"\"\n if not value and self._none_ok:\n return\n if self.valid_values is not None:\n if value not in self.valid_values:\n raise ValidationError(value, \"valid values: {}\".format(\n ', '.join(self.valid_values)))\n else:\n return\n else:\n raise NotImplementedError(\"{} does not implement validate.\".format(\n self.__class__.__name__))\n\n def complete(self):\n \"\"\"Return a list of possible values for completion.\n\n The default implementation just returns valid_values, but it might be\n useful to override this for special cases.\n\n Return:\n A list of (value, description) tuples or None.\n \"\"\"\n if self.valid_values is None:\n return None\n else:\n out = []\n for val in self.valid_values:\n try:\n desc = self.valid_values.descriptions[val]\n except KeyError:\n # Some values are self-explaining and don't need a\n # description.\n desc = \"\"\n out.append((val, desc))\n return out\n\n\nclass String(BaseType):\n\n \"\"\"Base class for a string setting (case-insensitive).\n\n Attributes:\n minlen: Minimum length (inclusive).\n maxlen: Maximum length (inclusive).\n forbidden: Forbidden chars in the string.\n \"\"\"\n\n typestr = 'string'\n\n def __init__(self, minlen=None, maxlen=None, forbidden=None,\n none_ok=False):\n super().__init__(none_ok)\n if minlen is not None and minlen < 1:\n raise ValueError(\"minlen ({}) needs to be >= 1!\".format(minlen))\n elif maxlen is not None and maxlen < 1:\n raise ValueError(\"maxlen ({}) needs to be >= 1!\".format(maxlen))\n elif maxlen is not None and minlen is not None and maxlen < minlen:\n raise ValueError(\"minlen ({}) needs to be <= maxlen ({})!\".format(\n minlen, maxlen))\n self.minlen = minlen\n self.maxlen = maxlen\n self.forbidden = forbidden\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n if self.forbidden is not None and any(c in value\n for c in self.forbidden):\n raise ValidationError(value, \"may not contain the chars \"\n \"'{}'\".format(self.forbidden))\n if self.minlen is not None and len(value) < self.minlen:\n raise ValidationError(value, \"must be at least {} chars \"\n \"long!\".format(self.minlen))\n if self.maxlen is not None and len(value) > self.maxlen:\n raise ValidationError(value, \"must be at most {} long!\".format(\n self.maxlen))\n\n\nclass List(BaseType):\n\n \"\"\"Base class for a (string-)list setting.\"\"\"\n\n typestr = 'string-list'\n\n def transform(self, value):\n if not value:\n return None\n else:\n return [v if v else None for v in value.split(',')]\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"list may not be empty!\")\n vals = self.transform(value)\n if None in vals:\n raise ValidationError(value, \"items may not be empty!\")\n\n\nclass Bool(BaseType):\n\n \"\"\"Base class for a boolean setting.\n\n Class attributes:\n _BOOLEAN_STATES: A dictionary of strings mapped to their bool meanings.\n \"\"\"\n\n typestr = 'bool'\n\n # Taken from configparser\n _BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,\n '0': False, 'no': False, 'false': False, 'off': False}\n\n valid_values = ValidValues('true', 'false')\n\n def transform(self, value):\n if not value:\n return None\n else:\n return Bool._BOOLEAN_STATES[value.lower()]\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n if value.lower() not in Bool._BOOLEAN_STATES:\n raise ValidationError(value, \"must be a boolean!\")\n\n\nclass BoolAsk(Bool):\n\n \"\"\"A yes/no/ask question.\"\"\"\n\n valid_values = ValidValues('true', 'false', 'ask')\n\n def transform(self, value):\n if value.lower() == 'ask':\n return 'ask'\n else:\n return super().transform(value)\n\n def validate(self, value):\n if value.lower() == 'ask':\n return\n else:\n super().validate(value)\n\n\nclass Int(BaseType):\n\n \"\"\"Base class for an integer setting.\n\n Attributes:\n minval: Minimum value (inclusive).\n maxval: Maximum value (inclusive).\n \"\"\"\n\n typestr = 'int'\n\n def __init__(self, minval=None, maxval=None, none_ok=False):\n super().__init__(none_ok)\n if maxval is not None and minval is not None and maxval < minval:\n raise ValueError(\"minval ({}) needs to be <= maxval ({})!\".format(\n minval, maxval))\n self.minval = minval\n self.maxval = maxval\n\n def transform(self, value):\n if not value:\n return None\n else:\n return int(value)\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n try:\n intval = int(value)\n except ValueError:\n raise ValidationError(value, \"must be an integer!\")\n if self.minval is not None and intval < self.minval:\n raise ValidationError(value, \"must be {} or bigger!\".format(\n self.minval))\n if self.maxval is not None and intval > self.maxval:\n raise ValidationError(value, \"must be {} or smaller!\".format(\n self.maxval))\n\n\nclass IntList(List):\n\n \"\"\"Base class for an int-list setting.\"\"\"\n\n typestr = 'int-list'\n\n def transform(self, value):\n vals = super().transform(value)\n return [int(v) if v is not None else None for v in vals]\n\n def validate(self, value):\n try:\n vals = self.transform(value)\n except ValueError:\n raise ValidationError(value, \"must be a list of integers!\")\n if None in vals and not self._none_ok:\n raise ValidationError(value, \"items may not be empty!\")\n\n\nclass Float(BaseType):\n\n \"\"\"Base class for an float setting.\n\n Attributes:\n minval: Minimum value (inclusive).\n maxval: Maximum value (inclusive).\n \"\"\"\n\n typestr = 'float'\n\n def __init__(self, minval=None, maxval=None, none_ok=False):\n super().__init__(none_ok)\n if maxval is not None and minval is not None and maxval < minval:\n raise ValueError(\"minval ({}) needs to be <= maxval ({})!\".format(\n minval, maxval))\n self.minval = minval\n self.maxval = maxval\n\n def transform(self, value):\n if not value:\n return None\n else:\n return float(value)\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n try:\n floatval = float(value)\n except ValueError:\n raise ValidationError(value, \"must be a float!\")\n if self.minval is not None and floatval < self.minval:\n raise ValidationError(value, \"must be {} or bigger!\".format(\n self.minval))\n if self.maxval is not None and floatval > self.maxval:\n raise ValidationError(value, \"must be {} or smaller!\".format(\n self.maxval))\n\n\nclass Perc(BaseType):\n\n \"\"\"Percentage.\n\n Attributes:\n minval: Minimum value (inclusive).\n maxval: Maximum value (inclusive).\n \"\"\"\n\n typestr = 'percentage'\n\n def __init__(self, minval=None, maxval=None, none_ok=False):\n super().__init__(none_ok)\n if maxval is not None and minval is not None and maxval < minval:\n raise ValueError(\"minval ({}) needs to be <= maxval ({})!\".format(\n minval, maxval))\n self.minval = minval\n self.maxval = maxval\n\n def transform(self, value):\n if not value:\n return\n else:\n return int(value[:-1])\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty\")\n if not value.endswith('%'):\n raise ValidationError(value, \"does not end with %\")\n try:\n intval = int(value[:-1])\n except ValueError:\n raise ValidationError(value, \"invalid percentage!\")\n if self.minval is not None and intval < self.minval:\n raise ValidationError(value, \"must be {}% or more!\".format(\n self.minval))\n if self.maxval is not None and intval > self.maxval:\n raise ValidationError(value, \"must be {}% or less!\".format(\n self.maxval))\n\n\nclass PercList(List):\n\n \"\"\"Base class for a list of percentages.\n\n Attributes:\n minval: Minimum value (inclusive).\n maxval: Maximum value (inclusive).\n \"\"\"\n\n typestr = 'perc-list'\n\n def __init__(self, minval=None, maxval=None, none_ok=False):\n super().__init__(none_ok)\n if maxval is not None and minval is not None and maxval < minval:\n raise ValueError(\"minval ({}) needs to be <= maxval ({})!\".format(\n minval, maxval))\n self.minval = minval\n self.maxval = maxval\n\n def transform(self, value):\n vals = super().transform(value)\n return [int(v[:-1]) if v is not None else None for v in vals]\n\n def validate(self, value):\n vals = super().transform(value)\n perctype = Perc(minval=self.minval, maxval=self.maxval)\n try:\n for val in vals:\n if val is None:\n if self._none_ok:\n continue\n else:\n raise ValidationError(value, \"items may not be empty!\")\n else:\n perctype.validate(val)\n except ValidationError:\n raise ValidationError(value, \"must be a list of percentages!\")\n\n\nclass PercOrInt(BaseType):\n\n \"\"\"Percentage or integer.\n\n Attributes:\n minperc: Minimum value for percentage (inclusive).\n maxperc: Maximum value for percentage (inclusive).\n minint: Minimum value for integer (inclusive).\n maxint: Maximum value for integer (inclusive).\n \"\"\"\n\n typestr = 'percentage-or-int'\n\n def __init__(self, minperc=None, maxperc=None, minint=None, maxint=None,\n none_ok=False):\n super().__init__(none_ok)\n if maxint is not None and minint is not None and maxint < minint:\n raise ValueError(\"minint ({}) needs to be <= maxint ({})!\".format(\n minint, maxint))\n if maxperc is not None and minperc is not None and maxperc < minperc:\n raise ValueError(\"minperc ({}) needs to be <= maxperc \"\n \"({})!\".format(minperc, maxperc))\n self.minperc = minperc\n self.maxperc = maxperc\n self.minint = minint\n self.maxint = maxint\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n if value.endswith('%'):\n try:\n intval = int(value[:-1])\n except ValueError:\n raise ValidationError(value, \"invalid percentage!\")\n if self.minperc is not None and intval < self.minperc:\n raise ValidationError(value, \"must be {}% or more!\".format(\n self.minperc))\n if self.maxperc is not None and intval > self.maxperc:\n raise ValidationError(value, \"must be {}% or less!\".format(\n self.maxperc))\n else:\n try:\n intval = int(value)\n except ValueError:\n raise ValidationError(value, \"must be integer or percentage!\")\n if self.minint is not None and intval < self.minint:\n raise ValidationError(value, \"must be {} or bigger!\".format(\n self.minint))\n if self.maxint is not None and intval > self.maxint:\n raise ValidationError(value, \"must be {} or smaller!\".format(\n self.maxint))\n\n\nclass Command(BaseType):\n\n \"\"\"Base class for a command value with arguments.\"\"\"\n\n typestr = 'command'\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n if value.split()[0] not in cmdutils.cmd_dict:\n raise ValidationError(value, \"must be a valid command!\")\n\n def complete(self):\n out = []\n for cmdname, obj in cmdutils.cmd_dict.items():\n out.append((cmdname, obj.desc))\n return out\n\n\nclass ColorSystem(BaseType):\n\n \"\"\"Color systems for interpolation.\"\"\"\n\n valid_values = ValidValues(('rgb', \"Interpolate in the RGB color system.\"),\n ('hsv', \"Interpolate in the HSV color system.\"),\n ('hsl', \"Interpolate in the HSL color system.\"))\n\n def validate(self, value):\n super().validate(value.lower())\n\n def transform(self, value):\n if not value:\n return None\n else:\n mapping = {\n 'rgb': QColor.Rgb,\n 'hsv': QColor.Hsv,\n 'hsl': QColor.Hsl,\n }\n return mapping[value.lower()]\n\n\nclass QtColor(BaseType):\n\n \"\"\"Base class for QColor.\"\"\"\n\n typestr = 'qcolor'\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n elif QColor.isValidColor(value):\n pass\n else:\n raise ValidationError(value, \"must be a valid color\")\n\n def transform(self, value):\n if not value:\n return None\n else:\n return QColor(value)\n\n\nclass CssColor(BaseType):\n\n \"\"\"Base class for a CSS color value.\"\"\"\n\n typestr = 'css-color'\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n if value.startswith('-'):\n # custom function name, won't validate.\n pass\n elif QColor.isValidColor(value):\n pass\n else:\n raise ValidationError(value, \"must be a valid color\")\n\n\nclass QssColor(CssColor):\n\n \"\"\"Base class for a color value.\n\n Class attributes:\n color_func_regexes: Valid function regexes.\n \"\"\"\n\n typestr = 'qss-color'\n\n color_func_regexes = [\n r'rgb\\([0-9]{1,3}%?, [0-9]{1,3}%?, [0-9]{1,3}%?\\)',\n r'rgba\\([0-9]{1,3}%?, [0-9]{1,3}%?, [0-9]{1,3}%?, [0-9]{1,3}%?\\)',\n r'hsv\\([0-9]{1,3}%?, [0-9]{1,3}%?, [0-9]{1,3}%?\\)',\n r'hsva\\([0-9]{1,3}%?, [0-9]{1,3}%?, [0-9]{1,3}%?, [0-9]{1,3}%?\\)',\n r'qlineargradient\\(.*\\)',\n r'qradialgradient\\(.*\\)',\n r'qconicalgradient\\(.*\\)',\n ]\n\n def validate(self, value):\n if not value:\n if self._none_ok:\n return\n else:\n raise ValidationError(value, \"may not be empty!\")\n elif any(re.match(r, value) for r in self.color_func_regexes):\n # QColor doesn't handle these, so we do the best we can easily\n pass\n elif QColor.isValidColor(value):\n pass\n else:\n raise ValidationError(value, \"must be a valid color\")\n\n\nclass Font(BaseType):\n\n \"\"\"Base class for a font value.\"\"\"\n\n typestr = 'font'\n font_regex = re.compile(r\"\"\"\n ^(\n (\n # style\n (?P